'use client';

import { useState, useEffect, useRef, type ReactNode } from 'react';
import { Cigarette, Leaf, Heart, Trophy, DollarSign, TrendingDown, CheckCircle, type LucideIcon } from 'lucide-react';
import { cn } from '@/lib/utils';

interface DemoScreen {
  id: string;
  title: string;
  subtitle: string;
  description: string;
  Icon: LucideIcon;
  iconBg: string;
  iconColor: string;
  content: ReactNode;
}

const DEMO_SCREENS: DemoScreen[] = [
  {
    id: 'logging',
    title: 'Log Your Usage',
    subtitle: 'Track daily consumption with ease',
    description: 'Quick tap or scroll to log your nicotine and marijuana use. See real-time trends and weekly comparisons to stay motivated on your journey.',
    Icon: Cigarette,
    iconBg: 'bg-gradient-to-br from-red-500/20 to-orange-500/20',
    iconColor: 'text-red-400',
    content: (
      <div className="space-y-4">
        <div className="flex justify-between items-center p-3 rounded-xl bg-white/5 border border-white/10">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-lg bg-red-500/20 flex items-center justify-center">
              <Cigarette className="h-4 w-4 text-red-400" />
            </div>
            <span className="font-medium">Nicotine</span>
          </div>
          <div className="text-2xl font-bold">3</div>
        </div>
        <div className="flex justify-between items-center p-3 rounded-xl bg-white/5 border border-white/10">
          <div className="flex items-center gap-3">
            <div className="w-8 h-8 rounded-lg bg-green-500/20 flex items-center justify-center">
              <Leaf className="h-4 w-4 text-green-400" />
            </div>
            <span className="font-medium">Marijuana</span>
          </div>
          <div className="text-2xl font-bold">0</div>
        </div>
        <div className="text-center text-xs text-muted-foreground mt-4">
          <TrendingDown className="h-4 w-4 inline mr-1 text-green-400" />
          Down 40% from last week
        </div>
      </div>
    ),
  },
  {
    id: 'health',
    title: 'Health Recovery',
    subtitle: 'Watch your body heal',
    description: 'Track your health milestones from the first 20 minutes to years of recovery. See real-time progress as your body repairs itself.',
    Icon: Heart,
    iconBg: 'bg-gradient-to-br from-teal-500/20 to-cyan-500/20',
    iconColor: 'text-teal-400',
    content: (
      <div className="space-y-3">
        <div className="space-y-1">
          <div className="flex justify-between text-xs">
            <span>Blood Pressure Normalizes</span>
            <CheckCircle className="h-3 w-3 text-green-400" />
          </div>
          <div className="h-2 rounded-full bg-white/10 overflow-hidden">
            <div className="h-full w-full bg-gradient-to-r from-teal-500 to-cyan-400 rounded-full" />
          </div>
        </div>
        <div className="space-y-1">
          <div className="flex justify-between text-xs">
            <span>Oxygen Levels Rise</span>
            <CheckCircle className="h-3 w-3 text-green-400" />
          </div>
          <div className="h-2 rounded-full bg-white/10 overflow-hidden">
            <div className="h-full w-full bg-gradient-to-r from-teal-500 to-cyan-400 rounded-full" />
          </div>
        </div>
        <div className="space-y-1">
          <div className="flex justify-between text-xs">
            <span>Circulation Improves</span>
            <span className="text-yellow-400">1 week to go</span>
          </div>
          <div className="h-2 rounded-full bg-white/10 overflow-hidden">
            <div className="h-full w-3/4 bg-gradient-to-r from-teal-500 to-cyan-400 rounded-full" />
          </div>
        </div>
        <div className="space-y-1">
          <div className="flex justify-between text-xs">
            <span>Heart Attack Risk Drops</span>
            <span className="text-muted-foreground">2 weeks to go</span>
          </div>
          <div className="h-2 rounded-full bg-white/10 overflow-hidden">
            <div className="h-full w-1/2 bg-gradient-to-r from-teal-500 to-cyan-400 rounded-full" />
          </div>
        </div>
      </div>
    ),
  },
  {
    id: 'achievements',
    title: 'Achievements',
    subtitle: 'Celebrate every milestone',
    description: 'Unlock badges as you reach new goals. From your First Step to becoming a Monthly Master, every achievement is worth celebrating.',
    Icon: Trophy,
    iconBg: 'bg-gradient-to-br from-yellow-500/20 to-amber-500/20',
    iconColor: 'text-yellow-400',
    content: (
      <div className="grid grid-cols-3 gap-2">
        {[
          { name: 'First Step', unlocked: true },
          { name: 'Hat Trick', unlocked: true },
          { name: 'Week Warrior', unlocked: true },
          { name: 'Fighter', unlocked: false },
          { name: 'Monthly Master', unlocked: false },
          { name: 'Goal Crusher', unlocked: false },
        ].map((badge) => (
          <div
            key={badge.name}
            className={`aspect-square rounded-xl flex flex-col items-center justify-center p-2 text-center ${
              badge.unlocked
                ? 'bg-gradient-to-br from-yellow-500/30 to-amber-600/20 border border-yellow-500/50'
                : 'bg-white/5 border border-white/10 opacity-50'
            }`}
          >
            <Trophy
              className={`h-5 w-5 mb-1 ${badge.unlocked ? 'text-yellow-400' : 'text-muted-foreground'}`}
            />
            <span className="text-[10px] leading-tight">{badge.name}</span>
          </div>
        ))}
      </div>
    ),
  },
  {
    id: 'savings',
    title: 'Money Saved',
    subtitle: 'Track your financial wins',
    description: 'See exactly how much money you save by cutting back. Watch your savings grow daily and set goals for what to do with your extra cash.',
    Icon: DollarSign,
    iconBg: 'bg-gradient-to-br from-emerald-500/20 to-green-500/20',
    iconColor: 'text-emerald-400',
    content: (
      <div className="text-center space-y-4">
        <div className="w-16 h-16 rounded-2xl bg-emerald-500/20 flex items-center justify-center mx-auto">
          <DollarSign className="h-8 w-8 text-emerald-400" />
        </div>
        <div>
          <div className="text-4xl font-black text-emerald-400">$127.50</div>
          <div className="text-sm text-muted-foreground">saved this month</div>
        </div>
        <div className="grid grid-cols-2 gap-2 text-xs">
          <div className="p-2 rounded-lg bg-white/5 border border-white/10">
            <div className="font-bold">$4.25</div>
            <div className="text-muted-foreground">per day</div>
          </div>
          <div className="p-2 rounded-lg bg-white/5 border border-white/10">
            <div className="font-bold">$1,530</div>
            <div className="text-muted-foreground">per year</div>
          </div>
        </div>
      </div>
    ),
  },
];

// Phone mockup component
function PhoneMockup({ activeScreen }: { activeScreen: number }) {
  return (
    <div className="relative">
      {/* Phone frame glow */}
      <div className="absolute inset-0 bg-gradient-to-br from-primary/30 to-purple-500/30 rounded-[3rem] blur-2xl opacity-50" />

      {/* Phone frame */}
      <div className="relative w-[280px] sm:w-[320px] aspect-[9/16] rounded-[2.5rem] overflow-hidden border-4 border-white/10 bg-background shadow-2xl shadow-black/30">
        {/* Notch */}
        <div className="absolute top-0 left-1/2 -translate-x-1/2 w-24 h-6 bg-black rounded-b-2xl z-20" />

        {/* Screen content with crossfade */}
        <div className="absolute inset-0 p-4 pt-10">
          {/* Screen header */}
          <div className="text-center mb-4">
            <h3 className="text-lg font-bold">{DEMO_SCREENS[activeScreen].title}</h3>
            <p className="text-xs text-muted-foreground">
              {DEMO_SCREENS[activeScreen].subtitle}
            </p>
          </div>

          {/* Crossfade content */}
          <div className="relative h-[calc(100%-5rem)]">
            {DEMO_SCREENS.map((screen, index) => (
              <div
                key={screen.id}
                className={cn(
                  "absolute inset-0 transition-opacity duration-500 motion-reduce:transition-none",
                  activeScreen === index ? "opacity-100 z-10" : "opacity-0 z-0"
                )}
              >
                {screen.content}
              </div>
            ))}
          </div>
        </div>

        {/* Bottom gradient overlay */}
        <div className="absolute bottom-0 left-0 right-0 h-20 bg-gradient-to-t from-background to-transparent pointer-events-none" />
      </div>
    </div>
  );
}

// Feature description card for scroll sections
function FeatureCard({ screen, isActive }: { screen: DemoScreen; isActive: boolean }) {
  const Icon = screen.Icon;

  return (
    <div
      className={cn(
        "p-6 sm:p-8 rounded-2xl transition-all duration-500 motion-reduce:transition-none",
        isActive
          ? "bg-primary/10 border border-primary/30 scale-100 opacity-100"
          : "bg-white/5 border border-white/10 scale-[0.98] opacity-60"
      )}
    >
      <div className="flex items-start gap-4">
        <div className={cn(
          "w-12 h-12 rounded-xl flex items-center justify-center shrink-0",
          screen.iconBg
        )}>
          <Icon className={cn("h-6 w-6", screen.iconColor)} />
        </div>
        <div className="flex-1">
          <h3 className="text-xl font-bold mb-2">{screen.title}</h3>
          <p className="text-muted-foreground leading-relaxed">
            {screen.description}
          </p>
        </div>
      </div>
    </div>
  );
}

export function DemoSection() {
  const [activeScreen, setActiveScreen] = useState(0);
  const [isPaused, setIsPaused] = useState(false);
  const sectionRefs = useRef<(HTMLDivElement | null)[]>([]);

  // Timer-based rotation for mobile
  useEffect(() => {
    if (isPaused) return;

    // Only run timer on mobile (will be hidden on lg+)
    const interval = setInterval(() => {
      setActiveScreen((prev) => (prev + 1) % DEMO_SCREENS.length);
    }, 4000);

    return () => clearInterval(interval);
  }, [isPaused]);

  // Intersection Observer for desktop scroll spy
  useEffect(() => {
    const observers: IntersectionObserver[] = [];

    sectionRefs.current.forEach((ref, index) => {
      if (!ref) return;

      const observer = new IntersectionObserver(
        (entries) => {
          entries.forEach((entry) => {
            if (entry.isIntersecting) {
              setActiveScreen(index);
            }
          });
        },
        {
          threshold: 0.5,
          rootMargin: '-20% 0px -30% 0px',
        }
      );

      observer.observe(ref);
      observers.push(observer);
    });

    return () => {
      observers.forEach((observer) => observer.disconnect());
    };
  }, []);

  return (
    <section
      id="demo"
      aria-labelledby="demo-heading"
      className="relative"
    >
      {/* Background accents - contained to avoid overflow issues */}
      <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute top-1/2 left-0 w-96 h-96 bg-primary/10 rounded-full blur-[120px] -translate-y-1/2" />
        <div className="absolute top-1/2 right-0 w-96 h-96 bg-purple-500/10 rounded-full blur-[120px] -translate-y-1/2" />
      </div>

      <div className="container mx-auto max-w-6xl relative z-10 px-4">
        {/* Section Header */}
        <div className="text-center py-20">
          <h2
            id="demo-heading"
            className="text-3xl sm:text-4xl font-bold mb-4"
          >
            See It In{' '}
            <span className="bg-gradient-to-r from-primary via-purple-500 to-pink-500 bg-clip-text text-transparent">
              Action
            </span>
          </h2>
          <p className="text-muted-foreground max-w-2xl mx-auto">
            A quick look at how QuitTraq helps you track progress and stay motivated.
          </p>
        </div>

        {/* Desktop: Split Sticky Scroll Layout */}
        <div className="hidden lg:flex lg:gap-16 lg:items-start">
          {/* Sticky Phone Column */}
          <div className="w-1/2 sticky top-24 flex items-center justify-center py-8">
            <PhoneMockup activeScreen={activeScreen} />
          </div>

          {/* Scrolling Content Column */}
          <div className="w-1/2">
            {DEMO_SCREENS.map((screen, index) => (
              <div
                key={screen.id}
                ref={(el) => { sectionRefs.current[index] = el; }}
                className={cn(
                  "min-h-[70vh] flex items-center py-8",
                  index === 0 && "pt-0",
                  index === DEMO_SCREENS.length - 1 && "min-h-[50vh]"
                )}
              >
                <FeatureCard screen={screen} isActive={activeScreen === index} />
              </div>
            ))}
          </div>
        </div>

        {/* Mobile: Original Stacked Layout with Timer */}
        <div className="lg:hidden pb-20">
          <div className="flex flex-col items-center gap-12">
            {/* Phone Mockup */}
            <div
              className="relative"
              onMouseEnter={() => setIsPaused(true)}
              onMouseLeave={() => setIsPaused(false)}
              onTouchStart={() => setIsPaused(true)}
              onTouchEnd={() => setIsPaused(false)}
            >
              <PhoneMockup activeScreen={activeScreen} />
            </div>

            {/* Description and indicators */}
            <div className="w-full max-w-md text-center">
              <div className="space-y-4">
                {/* Screen descriptions as buttons */}
                {DEMO_SCREENS.map((screen, index) => (
                  <button
                    key={screen.id}
                    onClick={() => setActiveScreen(index)}
                    className={cn(
                      "w-full text-left p-4 rounded-xl transition-all duration-300",
                      activeScreen === index
                        ? "bg-primary/10 border border-primary/30"
                        : "hover:bg-white/5 border border-transparent"
                    )}
                  >
                    <h4
                      className={cn(
                        "font-semibold mb-1",
                        activeScreen === index ? "text-primary" : "text-foreground"
                      )}
                    >
                      {screen.title}
                    </h4>
                    <p className="text-sm text-muted-foreground">{screen.subtitle}</p>
                  </button>
                ))}
              </div>

              {/* Dot indicators */}
              <div className="flex justify-center gap-2 mt-6">
                {DEMO_SCREENS.map((_, index) => (
                  <button
                    key={index}
                    onClick={() => setActiveScreen(index)}
                    className={cn(
                      "w-2 h-2 rounded-full transition-all",
                      activeScreen === index
                        ? "w-6 bg-primary"
                        : "bg-white/20 hover:bg-white/40"
                    )}
                    aria-label={`Go to screen ${index + 1}`}
                  />
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
