// src/app/components/admin/blocks/ResultsSection.tsx

'use client';

import { motion } from 'framer-motion';
import { useInView } from 'react-intersection-observer';
import { useState, useEffect, useRef } from 'react';
import { TrendingUp, Users, Globe, Award, BarChart, Target, Zap, Star, LucideIcon } from 'lucide-react';
import { ResultsSectionProps, ResultStat } from '@/lib/page-builder/types';

// Default stats data
const defaultStats: ResultStat[] = [
  {
    icon: 'TrendingUp',
    value: 40,
    suffix: '+',
    label: 'Average Domain Authority',
    description: 'Premium website quality'
  },
  {
    icon: 'Globe',
    value: 50,
    suffix: '+',
    label: 'Average Domain Rating',
    description: 'High-authority platforms'
  },
  {
    icon: 'Users',
    value: 5000,
    suffix: '+',
    label: 'Successful Publications',
    description: 'Happy clients worldwide'
  },
  {
    icon: 'Award',
    value: 98,
    suffix: '%',
    label: 'Client Satisfaction Rate',
    description: 'Proven track record'
  }
];

// Icon mapping
const iconMap: Record<string, LucideIcon> = {
  TrendingUp: TrendingUp,
  Users: Users,
  Globe: Globe,
  Award: Award,
  BarChart: BarChart,
  Target: Target,
  Zap: Zap,
  Star: Star
};

const getIconComponent = (iconName: string): LucideIcon => {
  return iconMap[iconName] || TrendingUp;
};

// Counter Component
const Counter = ({ 
  value, 
  suffix, 
  start, 
  duration = 2000 
}: { 
  value: number; 
  suffix: string; 
  start: boolean;
  duration?: number;
}) => {
  const [count, setCount] = useState(0);
  const animationRef = useRef<NodeJS.Timeout | undefined>(undefined);

  useEffect(() => {
    // Jab start false ho to kuch mat karo
    if (!start) return;

    // Counter ko reset karo aur fresh start do
    setCount(0);
    const steps = 60;
    const stepValue = value / steps;
    let currentStep = 0;

    animationRef.current = setInterval(() => {
      currentStep++;
      setCount(Math.min(Math.floor(stepValue * currentStep), value));

      if (currentStep >= steps) {
        if (animationRef.current) {
          clearInterval(animationRef.current);
        }
      }
    }, duration / steps);

    return () => {
      if (animationRef.current) {
        clearInterval(animationRef.current);
      }
    };
    // 'count' dependency array mein NAHI hoga — warna har setState par
    // effect dobara chalega aur interval reset hota rehega
  }, [start, value, duration]);

  return (
    <span className="bg-linear-to-r from-blue-600 to-cyan-600 bg-clip-text text-transparent">
      {count}{suffix}
    </span>
  );
};

export default function ResultsSection(props: ResultsSectionProps) {
  const {
    id,
    className = '',
    title = 'Proven',
    highlightedText = 'Results',
    description = 'Real numbers that showcase the quality and impact of our premium guest posting services',
    stats = defaultStats,
    showStats = true,
    animationDuration = 2000,
  } = props;

  const [counterStarted, setCounterStarted] = useState(false);

  const { ref, inView } = useInView({
    triggerOnce: true,
    threshold: 0.1,
    onChange: (inViewState) => {
      if (inViewState && !counterStarted) {
        setCounterStarted(true);
      }
    }
  });

  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: {
        staggerChildren: 0.2
      }
    }
  };

  const itemVariants = {
    hidden: { y: 50, opacity: 0 },
    visible: {
      y: 0,
      opacity: 1,
      transition: {
        type: "spring" as const,
        stiffness: 100,
        damping: 15
      }
    },
    hover: {
      y: -5,
      scale: 1.02,
      transition: {
        type: "spring" as const,
        stiffness: 400,
        damping: 25
      }
    }
  };

  return (
    <section id={id} className={`py-24 bg-linear-to-br from-slate-50 via-white to-blue-50/20 relative overflow-hidden ${className}`}>
      {/* Background Elements */}
      <div className="absolute top-0 left-0 w-72 h-72 bg-blue-100/10 rounded-full blur-3xl"></div>
      <div className="absolute bottom-0 right-0 w-96 h-96 bg-purple-100/10 rounded-full blur-3xl"></div>
      
      <div className="relative max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
        {/* Section Header */}
        <motion.div
          ref={ref}
          initial={{ opacity: 0, y: 40 }}
          animate={inView ? { opacity: 1, y: 0 } : {}}
          transition={{ duration: 0.8 }}
          className="text-center mb-20"
        >
          <motion.h2
            initial={{ opacity: 0, y: 30 }}
            animate={inView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: 0.8, delay: 0.3 }}
            className="text-5xl md:text-6xl font-bold text-gray-900 mb-6"
          >
            {title}
            <span className="bg-linear-to-r from-blue-600 to-cyan-600 bg-clip-text text-transparent ml-4">
              {highlightedText}
            </span>
          </motion.h2>
          
          <motion.p
            initial={{ opacity: 0, y: 20 }}
            animate={inView ? { opacity: 1, y: 0 } : {}}
            transition={{ duration: 0.8, delay: 0.4 }}
            className="text-xl text-gray-600 max-w-3xl mx-auto leading-relaxed font-light"
          >
            {description}
          </motion.p>
        </motion.div>

        {/* Animated Stats Counters */}
        {showStats && (
          <motion.div
            variants={containerVariants}
            initial="hidden"
            animate={inView ? "visible" : "hidden"}
            className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-8"
          >
            {stats.map((stat) => {
              const IconComponent = getIconComponent(stat.icon);
              return (
                <motion.div
                  key={stat.label}
                  variants={itemVariants}
                  whileHover="hover"
                  className="text-center p-8 bg-white rounded-3xl shadow-lg border border-gray-100 hover:shadow-2xl transition-all duration-500"
                >
                  <motion.div
                    whileHover={{ scale: 1.1, rotate: 5 }}
                    className="w-16 h-16 bg-linear-to-r from-blue-600 to-cyan-600 rounded-2xl flex items-center justify-center mx-auto mb-6 shadow-lg"
                  >
                    <IconComponent className="h-8 w-8 text-white" />
                  </motion.div>
                  
                  <div className="text-5xl font-bold text-gray-900 mb-3">
                    <Counter 
                      value={stat.value} 
                      suffix={stat.suffix} 
                      start={counterStarted}
                      duration={animationDuration}
                    />
                  </div>
                  
                  <h3 className="text-lg font-semibold text-gray-800 mb-2">
                    {stat.label}
                  </h3>
                  
                  <p className="text-gray-500 text-sm">
                    {stat.description}
                  </p>
                </motion.div>
              );
            })}
          </motion.div>
        )}
      </div>
    </section>
  );
}