'use client';

import { useState, useEffect, useRef } from 'react';
import { motion } from 'framer-motion';
import {
  UserPlus,
  Search,
  ShieldCheck,
  AlertTriangle,
  Users,
  Shield,
  ArrowRight,
  Database,
  Brain,
  ThumbsUp,
  BarChart3,
  CheckCircle2,
} from 'lucide-react';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { useAppStore } from '@/store/app-store';

// ─── Animated Counter ──────────────────────────────────────────────────────

function AnimatedCounter({ target, suffix = '' }: { target: number; suffix?: string }) {
  const [count, setCount] = useState(0);
  const ref = useRef<HTMLDivElement>(null);
  const hasAnimated = useRef(false);

  useEffect(() => {
    const observer = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting && !hasAnimated.current) {
          hasAnimated.current = true;
          const duration = 1500;
          const startTime = performance.now();
          const animate = (currentTime: number) => {
            const elapsed = currentTime - startTime;
            const progress = Math.min(elapsed / duration, 1);
            // Ease-out cubic
            const eased = 1 - Math.pow(1 - progress, 3);
            setCount(Math.floor(eased * target));
            if (progress < 1) {
              requestAnimationFrame(animate);
            }
          };
          requestAnimationFrame(animate);
        }
      },
      { threshold: 0.3 }
    );
    if (ref.current) observer.observe(ref.current);
    return () => observer.disconnect();
  }, [target]);

  return (
    <div ref={ref} className="text-3xl sm:text-4xl font-bold">
      {count.toLocaleString()}{suffix}
    </div>
  );
}

// ─── Steps Data ────────────────────────────────────────────────────────────

const steps = [
  {
    number: 1,
    title: 'Create an Account',
    description: 'Sign up for free to start reporting and tracking scams. Your account lets you submit reports, bookmark suspicious entities, and track your activity across the platform.',
    icon: UserPlus,
    gradient: 'from-emerald-500 to-emerald-600',
  },
  {
    number: 2,
    title: 'Search Before You Pay',
    description: 'Enter any phone number, bKash number, or Facebook profile to check if it\'s been reported. Our database instantly shows you risk assessments and related scam reports.',
    icon: Search,
    gradient: 'from-teal-500 to-teal-600',
  },
  {
    number: 3,
    title: 'Review Risk Assessment',
    description: 'Each entity has a risk level based on community reports and evidence. Risk scores are calculated from multiple factors including report count, evidence, and community verification.',
    icon: ShieldCheck,
    gradient: 'from-cyan-500 to-cyan-600',
  },
  {
    number: 4,
    title: 'Report a Scam',
    description: 'If you\'ve been scammed, report it with details and evidence to warn others. Include phone numbers, bKash accounts, and screenshots to help the community stay safe.',
    icon: AlertTriangle,
    gradient: 'from-amber-500 to-amber-600',
  },
  {
    number: 5,
    title: 'Community Verification',
    description: 'Other users can upvote and verify reports, building trust in the data. Reports with multiple verifications and evidence are marked with higher confidence levels.',
    icon: Users,
    gradient: 'from-orange-500 to-orange-600',
  },
  {
    number: 6,
    title: 'Stay Protected',
    description: 'Use our AI detector and safety tips to avoid future scams. Our AI-powered text analysis can detect common scam patterns targeting Bangladesh residents.',
    icon: Shield,
    gradient: 'from-red-500 to-red-600',
  },
];

// ─── Feature Highlights ────────────────────────────────────────────────────

const features = [
  {
    icon: Database,
    title: 'Real-time Database',
    description: 'Our scam database updates in real-time as new reports come in',
    color: 'text-emerald-500',
    bg: 'bg-emerald-500/10',
    border: 'border-emerald-500/20',
  },
  {
    icon: Brain,
    title: 'AI-Powered Detection',
    description: 'Our AI analyzes suspicious messages to detect potential scams',
    color: 'text-teal-500',
    bg: 'bg-teal-500/10',
    border: 'border-teal-500/20',
  },
  {
    icon: ThumbsUp,
    title: 'Community Driven',
    description: 'Reports are verified by the community through upvotes and evidence',
    color: 'text-cyan-500',
    bg: 'bg-cyan-500/10',
    border: 'border-cyan-500/20',
  },
  {
    icon: BarChart3,
    title: 'Risk Scoring',
    description: 'Each entity is scored based on multiple factors for accurate risk assessment',
    color: 'text-amber-500',
    bg: 'bg-amber-500/10',
    border: 'border-amber-500/20',
  },
];

// ─── Stats ─────────────────────────────────────────────────────────────────

const stats = [
  { label: 'Reports Filed', value: 1050, suffix: '+', icon: AlertTriangle, color: 'text-emerald-500', bg: 'bg-emerald-500/10' },
  { label: 'Money Protected', value: 250, suffix: 'K+ ৳', icon: Shield, color: 'text-teal-500', bg: 'bg-teal-500/10' },
  { label: 'Active Users', value: 320, suffix: '+', icon: Users, color: 'text-cyan-500', bg: 'bg-cyan-500/10' },
  { label: 'Entities Tracked', value: 580, suffix: '+', icon: Search, color: 'text-amber-500', bg: 'bg-amber-500/10' },
];

// ─── Main Component ────────────────────────────────────────────────────────

export function HowItWorksPage() {
  const navigate = useAppStore((s) => s.navigate);

  return (
    <div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8 py-8 sm:py-12">
      {/* ─── Hero Section ──────────────────────────────────────────────────── */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        className="text-center mb-16 sm:mb-20"
      >
        <Badge variant="outline" className="mb-4 border-emerald-500/30 text-emerald-600 dark:text-emerald-400 bg-emerald-500/5">
          <ShieldCheck className="h-3.5 w-3.5 mr-1" />
          Step-by-Step Guide
        </Badge>
        <h1 className="text-3xl sm:text-4xl lg:text-5xl font-bold mb-4 leading-tight">
          How{' '}
          <span className="bg-gradient-to-r from-emerald-500 via-teal-500 to-cyan-500 bg-clip-text text-transparent">
            ScamChecker BD
          </span>{' '}
          Works
        </h1>
        <p className="text-lg text-muted-foreground max-w-2xl mx-auto leading-relaxed">
          A step-by-step guide to protecting yourself from scams in Bangladesh.
          Our community-powered platform helps you stay safe from fraud.
        </p>
      </motion.div>

      {/* ─── Step-by-Step Process ──────────────────────────────────────────── */}
      <div className="relative mb-16 sm:mb-20">
        {/* Vertical connector line - desktop only */}
        <div className="hidden lg:block absolute left-8 top-0 bottom-0 w-0.5 bg-gradient-to-b from-emerald-500/40 via-teal-500/40 via-amber-500/40 to-red-500/40" />

        <div className="space-y-8 lg:space-y-12">
          {steps.map((step, idx) => {
            const Icon = step.icon;
            return (
              <motion.div
                key={step.number}
                initial={{ opacity: 0, y: 20 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: idx * 0.08, duration: 0.4 }}
                className="relative flex flex-col lg:flex-row gap-4 lg:gap-8"
              >
                {/* Number indicator + Icon */}
                <div className="flex items-center lg:items-start gap-4 shrink-0">
                  {/* Large numbered circle */}
                  <div className={`relative flex items-center justify-center h-16 w-16 rounded-2xl bg-gradient-to-br ${step.gradient} shadow-lg shrink-0`}>
                    <span className="text-2xl font-bold text-white">{step.number}</span>
                    {/* Pulse ring for active step */}
                    {idx === 0 && (
                      <div className="absolute inset-0 rounded-2xl bg-gradient-to-br from-emerald-500 to-emerald-600 animate-ping opacity-20" />
                    )}
                  </div>
                  {/* Icon in gradient circle */}
                  <div className="hidden lg:flex items-center justify-center h-12 w-12 rounded-xl bg-card border border-border shadow-sm shrink-0 card-themed">
                    <Icon className="h-5 w-5 text-emerald-500" />
                  </div>
                </div>

                {/* Content */}
                <div className="flex-1 lg:pt-2">
                  <Card className="border-border/50 hover:border-emerald-500/20 transition-colors duration-300 card-themed">
                    <CardContent className="p-5 sm:p-6">
                      <div className="flex items-center gap-3 mb-2 lg:hidden">
                        <div className={`p-2 rounded-lg bg-gradient-to-br ${step.gradient}`}>
                          <Icon className="h-4 w-4 text-white" />
                        </div>
                        <h3 className="text-xl font-bold">{step.title}</h3>
                      </div>
                      <h3 className="text-xl font-bold mb-2 hidden lg:block">{step.title}</h3>
                      <p className="text-muted-foreground leading-relaxed">
                        {step.description}
                      </p>
                    </CardContent>
                  </Card>
                </div>
              </motion.div>
            );
          })}
        </div>
      </div>

      {/* ─── Feature Highlights ────────────────────────────────────────────── */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.3, duration: 0.5 }}
        className="mb-16 sm:mb-20"
      >
        <div className="text-center mb-10">
          <Badge variant="outline" className="mb-3 border-teal-500/30 text-teal-600 dark:text-teal-400 bg-teal-500/5">
            <CheckCircle2 className="h-3.5 w-3.5 mr-1" />
            Platform Features
          </Badge>
          <h2 className="text-2xl sm:text-3xl font-bold mb-3">
            Powered by{' '}
            <span className="bg-gradient-to-r from-teal-500 to-emerald-500 bg-clip-text text-transparent">
              Smart Technology
            </span>
          </h2>
          <p className="text-muted-foreground max-w-lg mx-auto">
            Our platform combines cutting-edge technology with community intelligence to keep you safe.
          </p>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 sm:gap-6">
          {features.map((feature, idx) => {
            const FeatureIcon = feature.icon;
            return (
              <motion.div
                key={feature.title}
                initial={{ opacity: 0, y: 15 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{ delay: 0.4 + idx * 0.08, duration: 0.4 }}
              >
                <Card className={`h-full border ${feature.border} hover:shadow-lg hover:shadow-emerald-500/5 transition-all duration-300 group card-themed`}>
                  <CardContent className="p-6">
                    <div className={`p-3 rounded-xl ${feature.bg} w-fit mb-4 group-hover:scale-110 transition-transform duration-300`}>
                      <FeatureIcon className={`h-6 w-6 ${feature.color}`} />
                    </div>
                    <h3 className="text-lg font-bold mb-2">{feature.title}</h3>
                    <p className="text-muted-foreground text-sm leading-relaxed">
                      {feature.description}
                    </p>
                  </CardContent>
                </Card>
              </motion.div>
            );
          })}
        </div>
      </motion.div>

      {/* ─── Statistics Section ────────────────────────────────────────────── */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.5, duration: 0.5 }}
        className="mb-16 sm:mb-20"
      >
        <div className="text-center mb-10">
          <Badge variant="outline" className="mb-3 border-cyan-500/30 text-cyan-600 dark:text-cyan-400 bg-cyan-500/5">
            <BarChart3 className="h-3.5 w-3.5 mr-1" />
            By The Numbers
          </Badge>
          <h2 className="text-2xl sm:text-3xl font-bold">
            Making a{' '}
            <span className="bg-gradient-to-r from-cyan-500 to-emerald-500 bg-clip-text text-transparent">
              Real Impact
            </span>
          </h2>
        </div>

        <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
          {stats.map((stat, idx) => {
            const StatIcon = stat.icon;
            return (
              <motion.div
                key={stat.label}
                initial={{ opacity: 0, scale: 0.95 }}
                animate={{ opacity: 1, scale: 1 }}
                transition={{ delay: 0.6 + idx * 0.08, duration: 0.4 }}
              >
                <Card className="text-center border-border/50 hover:border-emerald-500/20 transition-colors duration-300 group card-themed">
                  <CardContent className="p-5 sm:p-6">
                    <div className={`p-2.5 rounded-xl ${stat.bg} w-fit mx-auto mb-3 group-hover:scale-110 transition-transform duration-300`}>
                      <StatIcon className={`h-5 w-5 ${stat.color}`} />
                    </div>
                    <AnimatedCounter target={stat.value} suffix={stat.suffix} />
                    <p className="text-sm text-muted-foreground mt-1">{stat.label}</p>
                  </CardContent>
                </Card>
              </motion.div>
            );
          })}
        </div>
      </motion.div>

      {/* ─── CTA Section ──────────────────────────────────────────────────── */}
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.6, duration: 0.5 }}
      >
        <Card className="border-0 bg-gradient-to-br from-emerald-600 to-teal-600 text-white overflow-hidden">
          <CardContent className="p-8 sm:p-12 text-center relative">
            {/* Background decorative elements */}
            <div className="absolute top-0 right-0 w-64 h-64 bg-white/5 rounded-full -translate-y-1/2 translate-x-1/2" />
            <div className="absolute bottom-0 left-0 w-48 h-48 bg-white/5 rounded-full translate-y-1/2 -translate-x-1/2" />

            <div className="relative z-10">
              <Shield className="h-12 w-12 mx-auto mb-4 opacity-90" />
              <h2 className="text-2xl sm:text-3xl font-bold mb-3">
                Ready to Stay Safe?
              </h2>
              <p className="text-emerald-100 max-w-lg mx-auto mb-8 leading-relaxed">
                Start protecting yourself today. Search our database before making any transaction,
                or report a scam to help protect others in Bangladesh.
              </p>
              <div className="flex flex-col sm:flex-row items-center justify-center gap-3">
                <Button
                  size="lg"
                  onClick={() => navigate('search')}
                  className="h-12 px-8 text-base bg-white text-emerald-700 hover:bg-emerald-50 shadow-lg rounded-xl font-semibold"
                >
                  <Search className="h-5 w-5" />
                  Search Database
                </Button>
                <Button
                  size="lg"
                  variant="outline"
                  onClick={() => navigate('report')}
                  className="h-12 px-8 text-base border-white/30 text-white hover:bg-white/10 rounded-xl font-semibold"
                >
                  <AlertTriangle className="h-5 w-5" />
                  Report a Scam
                </Button>
              </div>
            </div>
          </CardContent>
        </Card>
      </motion.div>
    </div>
  );
}
