'use client';

import React, { useState, useRef, useEffect } from 'react';
import {
    motion,
    useScroll,
    useTransform,
    useSpring,
    useMotionValue,
    useMotionTemplate,
    AnimatePresence,
    useInView
} from 'framer-motion';
import {
    MessageSquare,
    FileText,
    CheckCircle2,
    Truck,
    Banknote,
    Package,
    Mail,
    User,
    ArrowUpRight,
    Sparkles,
    MapPin,
    BarChart3
} from 'lucide-react';

// --- DATA ---
const steps = [
    {
        id: 1,
        stage: 'capture',
        title: "Capture Inquiry",
        subtitle: "Unified Inbox",
        desc: "Centralize every lead from WhatsApp, Email, and Phone into one inbox. No more lost sticky notes.",
        icon: MessageSquare,
        color: "text-blue-400"
    },
    {
        id: 2,
        stage: 'qualify',
        title: "Qualify & Assign",
        subtitle: "Smart Routing",
        desc: "Auto-route inquiries to the right sales rep based on region or expertise. Speed to lead is everything.",
        icon: User,
        color: "text-indigo-400"
    },
    {
        id: 3,
        stage: 'quote',
        title: "Quote & Approve",
        subtitle: "Precision Pricing",
        desc: "Generate error-free technical quotes with locked-in margins. Managers approve with one click.",
        icon: FileText,
        color: "text-violet-400"
    },
    {
        id: 4,
        stage: 'purchase',
        title: "Purchase & Stock",
        subtitle: "Inventory AI",
        desc: "Smart procurement suggestions ensure you never overstock but always have what you need.",
        icon: Package,
        color: "text-fuchsia-400"
    },
    {
        id: 5,
        stage: 'dispatch',
        title: "Dispatch & Invoice",
        subtitle: "Logistics Flow",
        desc: "Scan-to-pack validation ensures 100% accuracy. Generate the E-Way bill and Invoice instantly.",
        icon: Truck,
        color: "text-emerald-400"
    },
    {
        id: 6,
        stage: 'cash',
        title: "Get Paid",
        subtitle: "Revenue Cycle",
        desc: "Automated payment reminders help you collect cash faster. Watch your bank balance grow.",
        icon: Banknote,
        color: "text-green-400"
    }
];

// --- UTILS & SHARED COMPONENTS ---

const GrainOverlay = () => (
    <div className="pointer-events-none fixed inset-0 z-50 opacity-[0.03] mix-blend-overlay"
        style={{ backgroundImage: 'url("data:image/svg+xml,%3Csvg viewBox=%220 0 200 200%22 xmlns=%22http://www.w3.org/2000/svg%22%3E%3Cfilter id=%22noiseFilter%22%3E%3CfeTurbulence type=%22fractalNoise%22 baseFrequency=%220.65%22 numOctaves=%223%22 stitchTiles=%22stitch%22/%3E%3C/filter%3E%3Crect width=%22100%25%22 height=%22100%25%22 filter=%22url(%23noiseFilter)%22 opacity=%221%22/%3E%3C/svg%3E")' }}
    />
);

const MeshGradientBackground = () => (
    <div className="absolute inset-0 overflow-hidden pointer-events-none">
        <div className="absolute top-[-20%] left-[-10%] w-[80%] h-[80%] bg-blue-500/10 rounded-full blur-[120px] animate-pulse" />
        <div className="absolute bottom-[-20%] right-[-10%] w-[80%] h-[80%] bg-indigo-500/10 rounded-full blur-[120px] animate-pulse delay-1000" />
        <div className="absolute top-[40%] left-[30%] w-[40%] h-[40%] bg-violet-500/10 rounded-full blur-[100px] animate-pulse delay-700" />
    </div>
);

// 3D Tilt Card Wrapper
const Card3D = ({ children, className = "" }: { children: React.ReactNode, className?: string }) => {
    const x = useMotionValue(0);
    const y = useMotionValue(0);
    const rotateX = useTransform(y, [-100, 100], [5, -5]);
    const rotateY = useTransform(x, [-100, 100], [-5, 5]);

    const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
        const rect = e.currentTarget.getBoundingClientRect();
        const centerX = rect.left + rect.width / 2;
        const centerY = rect.top + rect.height / 2;
        x.set(e.clientX - centerX);
        y.set(e.clientY - centerY);
    };

    const handleMouseLeave = () => {
        x.set(0);
        y.set(0);
    };

    return (
        <motion.div
            style={{ rotateX, rotateY, transformStyle: "preserve-3d" }}
            onMouseMove={handleMouseMove}
            onMouseLeave={handleMouseLeave}
            className={`relative perspective-1000 ${className}`}
        >
            {children}
        </motion.div>
    );
};

// Bento Grid Style Container
const BentoContainer = ({ children, className = "" }: { children: React.ReactNode, className?: string }) => (
    <div className={`
    relative overflow-hidden rounded-3xl 
    bg-white/5 dark:bg-slate-900/40 backdrop-blur-2xl 
    border border-white/10 dark:border-white/5
    shadow-[inset_0_1px_0_0_rgba(255,255,255,0.1)]
    ${className}
  `}>
        {children}
    </div>
);

// --- VISUALS ---

const CaptureVisual = () => (
    <Card3D className="w-full max-w-md">
        <BentoContainer className="p-6 h-[400px] flex flex-col">
            <div className="flex items-center justify-between mb-8">
                <div className="flex items-center gap-2">
                    <div className="w-2 h-2 rounded-full bg-red-500 animate-pulse" />
                    <span className="text-xs font-mono uppercase tracking-widest text-slate-500 dark:text-slate-400">Live Feed</span>
                </div>
                <Sparkles size={14} className="text-slate-400 opacity-50" />
            </div>

            <div className="space-y-4 relative z-10">
                {[1, 2, 3].map((i) => (
                    <motion.div
                        key={i}
                        initial={{ x: -50, opacity: 0, rotateX: 20 }}
                        animate={{ x: 0, opacity: 1, rotateX: 0 }}
                        transition={{ delay: i * 0.15, type: "spring", stiffness: 100 }}
                        whileHover={{ scale: 1.02, x: 5 }}
                        className="group p-4 rounded-2xl bg-white/40 dark:bg-white/5 border border-white/20 dark:border-white/5 backdrop-blur-md shadow-sm hover:shadow-md transition-all cursor-default"
                    >
                        <div className="flex justify-between items-start mb-2">
                            <div className="flex items-center gap-2">
                                <div className={`p-1.5 rounded-lg ${i === 1 ? 'bg-green-500/10 text-green-600 dark:text-green-400' : 'bg-blue-500/10 text-blue-600 dark:text-blue-400'}`}>
                                    {i === 1 ? <MessageSquare size={14} /> : <Mail size={14} />}
                                </div>
                                <span className="text-xs font-bold text-slate-700 dark:text-slate-200">Inquiry #{2040 + i}</span>
                            </div>
                            <span className="text-[10px] text-slate-400">2m ago</span>
                        </div>
                        <p className="text-sm text-slate-600 dark:text-slate-400 line-clamp-2 group-hover:text-slate-900 dark:group-hover:text-white transition-colors">
                            "Looking for a quote on the industrial valves for our new plant..."
                        </p>
                    </motion.div>
                ))}
            </div>

            {/* Decorative Glow */}
            <div className="absolute bottom-0 left-1/2 -translate-x-1/2 w-32 h-32 bg-blue-500/20 blur-[60px] rounded-full pointer-events-none" />
        </BentoContainer>
    </Card3D>
);

const QualifyVisual = () => (
    <Card3D className="w-full max-w-md">
        <BentoContainer className="p-8 h-[400px] flex flex-col justify-center relative">
            {/* Background Grid */}
            <div className="absolute inset-0 bg-[linear-gradient(rgba(255,255,255,0.05)_1px,transparent_1px),linear-gradient(90deg,rgba(255,255,255,0.05)_1px,transparent_1px)] bg-[size:20px_20px] [mask-image:radial-gradient(ellipse_at_center,black,transparent)]" />

            <div className="relative z-10 flex flex-col items-center gap-8">
                {/* Source Node */}
                <motion.div
                    initial={{ scale: 0 }} animate={{ scale: 1 }}
                    className="w-16 h-16 rounded-2xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700 flex items-center justify-center shadow-xl z-20"
                >
                    <User size={24} className="text-slate-600 dark:text-slate-300" />
                </motion.div>

                {/* Animated Path */}
                <div className="h-16 w-0.5 bg-slate-200 dark:bg-slate-800 relative overflow-hidden">
                    <motion.div
                        animate={{ y: [0, 64] }}
                        transition={{ duration: 1.5, repeat: Infinity, ease: "linear" }}
                        className="absolute top-0 left-0 w-full h-1/2 bg-gradient-to-b from-transparent to-indigo-500"
                    />
                </div>

                {/* Target Node */}
                <motion.div
                    initial={{ scale: 0.8, opacity: 0 }}
                    animate={{ scale: 1, opacity: 1 }}
                    transition={{ delay: 0.5 }}
                    className="w-full p-4 rounded-2xl bg-indigo-500/10 border border-indigo-500/20 backdrop-blur-md flex items-center gap-4"
                >
                    <div className="w-12 h-12 rounded-full bg-indigo-500 flex items-center justify-center shadow-lg shadow-indigo-500/30">
                        <CheckCircle2 size={20} className="text-white" />
                    </div>
                    <div>
                        <div className="text-sm font-bold text-slate-900 dark:text-white">Assigned to Rahul</div>
                        <div className="text-xs text-indigo-600 dark:text-indigo-300">North Region Expert</div>
                    </div>
                </motion.div>
            </div>
        </BentoContainer>
    </Card3D>
);

const QuoteVisual = () => (
    <Card3D className="w-full max-w-md">
        <BentoContainer className="h-[400px] flex flex-col relative group">
            <div className="h-1.5 w-full bg-gradient-to-r from-violet-500 to-fuchsia-500" />

            <div className="p-8 flex-1 flex flex-col">
                <div className="flex justify-between items-start mb-8">
                    <div>
                        <h3 className="text-3xl font-bold text-slate-900 dark:text-white tracking-tight">₹ 4.5L</h3>
                        <p className="text-xs text-slate-500 uppercase tracking-widest mt-1">Total Value</p>
                    </div>
                    <div className="w-10 h-10 rounded-full bg-slate-100 dark:bg-slate-800 flex items-center justify-center">
                        <FileText size={18} className="text-slate-600 dark:text-slate-300" />
                    </div>
                </div>

                <div className="space-y-3 flex-1">
                    {[1, 2, 3].map((i) => (
                        <div key={i} className="flex items-center gap-3 py-2 border-b border-dashed border-slate-200 dark:border-slate-700/50">
                            <div className="w-1.5 h-1.5 rounded-full bg-slate-300 dark:bg-slate-600" />
                            <div className="h-2 bg-slate-200 dark:bg-slate-700 rounded w-2/3" />
                            <div className="h-2 bg-slate-200 dark:bg-slate-700 rounded w-1/4 ml-auto" />
                        </div>
                    ))}
                </div>

                <motion.div
                    initial={{ scale: 1.5, opacity: 0, rotate: -10 }}
                    animate={{ scale: 1, opacity: 1, rotate: -5 }}
                    className="self-end mt-4 px-6 py-2 bg-green-500 text-white font-bold text-lg rounded-lg shadow-lg shadow-green-500/30 rotate-[-5deg]"
                >
                    APPROVED
                </motion.div>
            </div>
        </BentoContainer>
    </Card3D>
);

const PurchaseVisual = () => (
    <Card3D className="w-full max-w-md">
        <BentoContainer className="p-6 h-[400px] flex flex-col justify-between">
            <div className="flex justify-between items-center">
                <h3 className="text-lg font-bold text-slate-900 dark:text-white">Inventory</h3>
                <BarChart3 size={18} className="text-slate-400" />
            </div>

            <div className="space-y-6 my-auto">
                {/* Stock Bar 1 */}
                <div className="space-y-2">
                    <div className="flex justify-between text-xs">
                        <span className="text-slate-500 dark:text-slate-400">Steel Pipes</span>
                        <span className="text-green-500 font-mono">450 units</span>
                    </div>
                    <div className="h-2 w-full bg-slate-100 dark:bg-slate-800 rounded-full overflow-hidden">
                        <motion.div
                            initial={{ width: 0 }} animate={{ width: "80%" }} transition={{ duration: 1, delay: 0.2 }}
                            className="h-full bg-green-500 rounded-full"
                        />
                    </div>
                </div>

                {/* Stock Bar 2 (Low) */}
                <div className="space-y-2">
                    <div className="flex justify-between text-xs">
                        <span className="text-slate-500 dark:text-slate-400">Valves Type-A</span>
                        <span className="text-red-500 font-mono animate-pulse">12 units (Low)</span>
                    </div>
                    <div className="h-2 w-full bg-slate-100 dark:bg-slate-800 rounded-full overflow-hidden">
                        <motion.div
                            initial={{ width: 0 }} animate={{ width: "15%" }} transition={{ duration: 1, delay: 0.4 }}
                            className="h-full bg-red-500 rounded-full"
                        />
                    </div>
                </div>
            </div>

            <motion.div
                initial={{ y: 20, opacity: 0 }}
                animate={{ y: 0, opacity: 1 }}
                className="bg-fuchsia-500/10 border border-fuchsia-500/20 p-4 rounded-xl flex items-center gap-4"
            >
                <div className="p-2 bg-fuchsia-500 rounded-lg text-white">
                    <Package size={16} />
                </div>
                <div>
                    <div className="text-sm font-bold text-slate-900 dark:text-white">Auto-Reorder</div>
                    <div className="text-xs text-fuchsia-600 dark:text-fuchsia-400">PO #9921 Generated</div>
                </div>
            </motion.div>
        </BentoContainer>
    </Card3D>
);

const DispatchVisual = () => (
    <Card3D className="w-full max-w-md">
        <BentoContainer className="h-[400px] relative">
            {/* Map Background */}
            <div className="absolute inset-0 opacity-30 dark:opacity-20 bg-[url('https://upload.wikimedia.org/wikipedia/commons/e/ec/World_map_blank_without_borders.svg')] bg-cover bg-center mix-blend-multiply dark:mix-blend-screen grayscale" />

            <div className="absolute inset-0 flex flex-col justify-between p-8 z-10">
                <div className="flex justify-between">
                    <div className="flex flex-col items-center">
                        <MapPin size={24} className="text-slate-400 mb-1" />
                        <span className="text-xs font-bold text-slate-900 dark:text-white">MUMBAI</span>
                    </div>
                    <div className="flex flex-col items-center">
                        <MapPin size={24} className="text-slate-400 mb-1" />
                        <span className="text-xs font-bold text-slate-900 dark:text-white">BLR</span>
                    </div>
                </div>

                {/* Truck Path */}
                <div className="absolute top-1/2 left-8 right-8 h-0.5 bg-slate-300 dark:bg-slate-700 border-t border-dashed border-slate-400">
                    <motion.div
                        animate={{ x: ["0%", "100%"] }}
                        transition={{ duration: 3, repeat: Infinity, ease: "linear" }}
                        className="absolute top-1/2 -translate-y-1/2 -translate-x-1/2 text-emerald-500"
                    >
                        <Truck size={32} className="drop-shadow-[0_4px_8px_rgba(16,185,129,0.4)]" />
                    </motion.div>
                </div>

                <div className="mt-auto bg-white/80 dark:bg-slate-800/80 backdrop-blur-md p-4 rounded-xl border border-white/20 dark:border-white/10 flex items-center justify-between">
                    <div>
                        <div className="text-xs text-slate-500 uppercase">Status</div>
                        <div className="text-sm font-bold text-emerald-600 dark:text-emerald-400">In Transit</div>
                    </div>
                    <div className="text-right">
                        <div className="text-xs text-slate-500 uppercase">ETA</div>
                        <div className="text-sm font-bold text-slate-900 dark:text-white">2 Days</div>
                    </div>
                </div>
            </div>
        </BentoContainer>
    </Card3D>
);

const CashVisual = () => (
    <Card3D className="w-full max-w-md">
        <BentoContainer className="h-[400px] flex flex-col items-center justify-center p-8 text-center relative overflow-hidden">
            <div className="absolute inset-0 bg-green-500/5" />

            <motion.div
                initial={{ scale: 0.8, opacity: 0 }}
                animate={{ scale: 1, opacity: 1 }}
                className="w-24 h-24 rounded-full bg-gradient-to-br from-green-400 to-emerald-600 flex items-center justify-center shadow-[0_0_40px_rgba(34,197,94,0.4)] mb-6"
            >
                <CheckCircle2 size={48} className="text-white" />
            </motion.div>

            <h3 className="text-4xl font-bold text-slate-900 dark:text-white mb-2">₹ 4,50,000</h3>
            <div className="px-4 py-1 rounded-full bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400 text-xs font-bold uppercase tracking-widest">
                Payment Received
            </div>

            {/* Confetti */}
            {[...Array(20)].map((_, i) => (
                <motion.div
                    key={i}
                    initial={{ y: 0, opacity: 1 }}
                    animate={{ y: -200, x: (Math.random() - 0.5) * 200, opacity: 0 }}
                    transition={{ duration: 2, repeat: Infinity, delay: Math.random() * 2 }}
                    className="absolute bottom-0 w-2 h-2 bg-green-400 rounded-full"
                    style={{ left: `${Math.random() * 100}%` }}
                />
            ))}
        </BentoContainer>
    </Card3D>
);

// --- MAIN COMPONENT ---

export const Narrative: React.FC = () => {
    const [activeStep, setActiveStep] = useState(0);
    const containerRef = useRef(null);
    const { scrollYProgress } = useScroll({ target: containerRef });

    const getVisualStage = (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';
            default: return 'capture';
        }
    };

    const currentStage = getVisualStage(activeStep);

    return (
        <section ref={containerRef} className="relative bg-slate-50 dark:bg-[#0B1220] transition-colors duration-700">
            <GrainOverlay />
            <MeshGradientBackground />

            <div className="max-w-7xl mx-auto 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">
                        <AnimatePresence mode="wait">
                            <motion.div
                                key={currentStage}
                                initial={{ opacity: 0, scale: 0.95, y: 20, filter: "blur(10px)" }}
                                animate={{ opacity: 1, scale: 1, y: 0, filter: "blur(0px)" }}
                                exit={{ opacity: 0, scale: 1.05, y: -20, filter: "blur(10px)" }}
                                transition={{ duration: 0.5, ease: [0.22, 1, 0.36, 1] }}
                                className="w-full flex justify-center"
                            >
                                {currentStage === 'capture' && <CaptureVisual />}
                                {currentStage === 'qualify' && <QualifyVisual />}
                                {currentStage === 'quote' && <QuoteVisual />}
                                {currentStage === 'purchase' && <PurchaseVisual />}
                                {currentStage === 'dispatch' && <DispatchVisual />}
                                {currentStage === 'cash' && <CashVisual />}
                            </motion.div>
                        </AnimatePresence>
                    </div>

                    {/* RIGHT: Scrolling Text */}
                    <div className="lg:w-1/2 py-20 lg:py-0">
                        {steps.map((step, index) => (
                            <StepCard
                                key={step.id}
                                step={step}
                                index={index}
                                isActive={activeStep === index}
                                onActivate={() => setActiveStep(index)}
                            />
                        ))}
                        <div className="h-[200px] md:h-[300px] lg:h-[400px]" />
                    </div>

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

const StepCard = ({ step, index, isActive, onActivate }: { step: any, index: number, isActive: boolean, onActivate: () => void }) => {
    const ref = useRef(null);
    const isInView = useInView(ref, { margin: "-50% 0px -50% 0px" });

    useEffect(() => {
        if (isInView) onActivate();
    }, [isInView, onActivate]);

    return (
        <div
            ref={ref}
            className={`min-h-[500px] md:min-h-[600px] lg:min-h-[700px] flex items-center justify-center lg:justify-start transition-opacity duration-500 ${isActive ? 'opacity-100' : 'opacity-20'}`}
        >
            <div className="relative max-w-lg">
                <div className="flex items-center gap-4 mb-6">
                    <span className="font-mono text-xs text-slate-400 dark:text-slate-500 uppercase tracking-widest">0{index + 1}</span>
                    <div className={`h-px w-12 ${isActive ? 'bg-slate-900 dark:bg-white' : 'bg-slate-300 dark:bg-slate-700'} transition-colors duration-500`} />
                    <span className={`font-mono text-xs uppercase tracking-widest ${isActive ? 'text-slate-900 dark:text-white' : 'text-slate-400 dark:text-slate-500'} transition-colors duration-500`}>
                        {step.subtitle}
                    </span>
                </div>

                {/* Mask Reveal Title */}
                <div className="overflow-hidden mb-6">
                    <motion.h3
                        initial={{ y: "100%" }}
                        animate={{ y: isActive ? 0 : "100%" }}
                        transition={{ duration: 0.8, ease: [0.22, 1, 0.36, 1] }}
                        className="text-5xl md:text-7xl font-bold text-slate-900 dark:text-white leading-[0.9] tracking-tighter"
                    >
                        {step.title}
                    </motion.h3>
                </div>

                <p className="text-lg md:text-xl text-slate-600 dark:text-slate-400 leading-relaxed max-w-md">
                    {step.desc}
                </p>

                {/* Mobile Visual Placeholder */}
                <div className="lg:hidden mt-8">
                    <div className="p-4 rounded-xl bg-slate-100 dark:bg-slate-800 border border-slate-200 dark:border-slate-700">
                        <span className="text-xs text-slate-500">Visual for {step.title}</span>
                    </div>
                </div>
            </div>
        </div>
    );
};
