'use client';

import React, { useState, useRef, useCallback, useLayoutEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { useSectionTheme } from '../hooks/useSectionTheme';
import { useLenis } from './SmoothScroll';
import { steps } from '../constants/narrativeSteps';
import { StepCard } from './narrative/StepCard';
import { CaptureVisual } from './narrative/visuals/CaptureVisual';
import { QualifyVisual } from './narrative/visuals/QualifyVisual';
import { QuoteVisual } from './narrative/visuals/QuoteVisual';
import { PurchaseVisual } from './narrative/visuals/PurchaseVisual';
import { DispatchVisual } from './narrative/visuals/DispatchVisual';
import { CashVisual } from './narrative/visuals/CashVisual';
import { MessagingVisual } from './narrative/visuals/MessagingVisual';

gsap.registerPlugin(ScrollTrigger);

export const Narrative: React.FC = () => {
  const [activeStep, setActiveStep] = useState(0);
  const containerRef = useRef<HTMLDivElement>(null);
  const stepsRef = useRef<(HTMLDivElement | null)[]>([]);
  const themeRef = useSectionTheme('solutions');
  const lenis = useLenis();

  useLayoutEffect(() => {
    if (!lenis) return;

    const ctx = gsap.context(() => {
      // Calculate pin distance based on viewport height for longer snap duration
      const pinDistance = window.innerHeight * 1.2; // Pin for 120% of viewport height

      stepsRef.current.forEach((stepEl, index) => {
        if (!stepEl) return;

        ScrollTrigger.create({
          trigger: stepEl,
          start: "center center",
          end: `+=${pinDistance}`,
          pin: true,
          pinSpacing: true,
          anticipatePin: 1,
          onEnter: () => {
            setActiveStep(index);
          },
          onEnterBack: () => {
            setActiveStep(index);
          }
        });
      });

      // Refresh ScrollTrigger after setup
      ScrollTrigger.refresh();
    }, containerRef);

    const handleResize = () => {
      ScrollTrigger.refresh();
    };
    
    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
      ctx.revert();
    };
  }, [lenis]);

  const getVisualStage = useCallback((stepIndex: number) => {
    switch (stepIndex) {
      case 0: return 'capture';
      case 1: return 'qualify';
      case 2: return 'quote';
      case 3: return 'purchase';
      case 4: return 'dispatch';
      case 5: return 'cash';
      case 6: return 'messaging';
      default: return 'capture';
    }
  }, []);

  const currentStage = getVisualStage(activeStep);

  return (
    <section ref={themeRef} className="relative bg-transparent transition-colors duration-700">
       <div
         className={`
           w-full
           mt-10 mb-8
           px-4 md:px-14 lg:px-24
           ${/* Only absolute position on md+; relative on mobile */''}
           relative md:absolute md:top-0
         `}
       >
         <div
           className={`
             flex flex-col gap-4
             md:flex-row md:justify-between md:items-end
             md:gap-6
             w-full
             pr-0 md:pr-10 lg:pr-16
           `}
         >
           <h2 className="text-2xl sm:text-3xl md:text-4xl lg:text-5xl font-extrabold text-brand-blue dark:text-brand-blue/90 mb-3 md:mb-5 leading-tight text-left">
             KnowBuild <span className="text-brand-orange">connects</span>
             <br className="hidden md:block" />
             <span className="text-brand-teal">every step of your business</span>
           </h2>
           <p className="text-base sm:text-lg md:text-xl lg:text-2xl mb-6 text-slate-700 dark:text-slate-300 leading-relaxed font-medium text-left">
             From inquiry to invoice: sales get reminders, dispatch ships the right item,
             <br className="hidden sm:block" />
             and finance controls credit — automatically, <span className="font-bold">in perfect sync.</span>
           </p>
         </div>
       </div>
      <div ref={containerRef} className="max-w-7xl mx-auto pt-32 px-4 sm:px-6 lg:px-8 relative z-10">
        <div className="flex flex-col lg:flex-row items-start">
           
          {/* LEFT: Sticky Visuals */}
          <div className="hidden lg:flex lg:w-1/2 h-[600px] lg:h-screen sticky top-0 items-center justify-center px-6 lg:px-10">
            <div className="relative w-full max-w-md aspect-[4/5] flex items-center justify-center">
              {/* Glow Behind Card */}
              <div className="absolute inset-0 bg-brand-blue/20 dark:bg-brand-blue/10 blur-[100px] rounded-full scale-75 animate-pulse" />

              <AnimatePresence mode="wait">
                <motion.div
                  key={currentStage}
                  initial={{ opacity: 0, scale: 0.95, y: 20 }}
                  animate={{ opacity: 1, scale: 1, y: 0 }}
                  exit={{ opacity: 0, scale: 0.98, y: -20 }}
                  transition={{ duration: 0.35, ease: [0.25, 0.1, 0.25, 1] }}
                  className="w-full pt-20"
                >
                  {currentStage === 'capture' && <CaptureVisual />}
                  {currentStage === 'qualify' && <QualifyVisual />}
                  {currentStage === 'quote' && <QuoteVisual />}
                  {currentStage === 'purchase' && <PurchaseVisual />}
                  {currentStage === 'dispatch' && <DispatchVisual />}
                  {currentStage === 'cash' && <CashVisual />}
                  {currentStage === 'messaging' && <MessagingVisual />}
                </motion.div>
              </AnimatePresence>
            </div>
          </div>

          {/* RIGHT: Scrolling Text */}
          <div className="lg:w-1/2 py-20 lg:py-0">
            {steps.map((step, index) => (
              <div 
                key={step.id} 
                className='flex items-center justify-center h-screen py-20'
                ref={(el) => { stepsRef.current[index] = el; }}
              >
                <StepCard
                  step={step}
                  index={index}
                  isActive={activeStep === index}
                  onActivate={() => { /* Handled by GSAP */ }}
                />
              </div>
            ))}
            <div className="h-[200px] md:h-[300px] lg:h-[400px]" />
          </div>

        </div>
      </div>
    </section>
  );
};
