'use client';

import React, { useState, useRef, useEffect } from 'react';
import {
    motion,
    useScroll,
    useTransform,
    useSpring,
    useMotionValue,
    useMotionTemplate,
    AnimatePresence
} from 'framer-motion';
import {
    UserCheck,
    ShieldCheck,
    Truck,
    FileText,
    ShoppingCart,
    Wallet,
    Bell,
    ArrowRight,
    Sparkles,
    Zap
} from 'lucide-react';

// --- TYPES ---
interface Feature {
    id: number;
    icon: React.ElementType;
    title: string;
    desc: string;
    accentColor: string; // Hex or RGB for coloring
    gradient: string; // Tailwind gradient class
}

// --- DATA ---
const features: Feature[] = [
    {
        id: 1,
        icon: UserCheck,
        title: "Sales Accountability",
        desc: "Track every lead. Never lose sight of your pipeline.",
        accentColor: "#a855f7",
        gradient: "from-violet-500 to-fuchsia-500"
    },
    {
        id: 2,
        icon: ShieldCheck,
        title: "Credit Control",
        desc: "Monitor and manage credit limits in real-time.",
        accentColor: "#06b6d4",
        gradient: "from-cyan-500 to-blue-500"
    },
    {
        id: 3,
        icon: Truck,
        title: "Auto Dispatch",
        desc: "Error-free deliveries with intelligent routing.",
        accentColor: "#10b981",
        gradient: "from-emerald-500 to-teal-500"
    },
    {
        id: 4,
        icon: FileText,
        title: "E-Invoicing",
        desc: "Automated invoice generation and delivery.",
        accentColor: "#f97316",
        gradient: "from-orange-500 to-amber-500"
    },
    {
        id: 5,
        icon: ShoppingCart,
        title: "Smart Alerts",
        desc: "Proactive Procurement recommendations.",
        accentColor: "#ec4899",
        gradient: "from-pink-500 to-rose-500"
    },
    {
        id: 6,
        icon: Wallet,
        title: "Finance Module",
        desc: "Real-time cash flow and financial intelligence.",
        accentColor: "#6366f1",
        gradient: "from-indigo-500 to-purple-500"
    },
    {
        id: 7,
        icon: Bell,
        title: "Auto Reminders",
        desc: "Intelligent nudges that keep your team on track.",
        accentColor: "#ef4444",
        gradient: "from-red-500 to-orange-500"
    }
];

// --- UTILS ---

const ScrambleText = ({ text, isActive }: { text: string; isActive: boolean }) => {
    const [display, setDisplay] = useState(text);
    const chars = "!@#$%^&*()_+~`|}{[]:;?><,./-=";

    useEffect(() => {
        if (!isActive) {
            setDisplay(text);
            return;
        }

        let iterations = 0;
        const interval = setInterval(() => {
            setDisplay(
                text
                    .split("")
                    .map((letter, index) => {
                        if (index < iterations) {
                            return text[index];
                        }
                        return chars[Math.floor(Math.random() * chars.length)];
                    })
                    .join("")
            );

            if (iterations >= text.length) {
                clearInterval(interval);
            }

            iterations += 1 / 2; // Speed control
        }, 30);

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

    return <span>{display}</span>;
};

const MagneticButton = ({ children, className = "" }: { children: React.ReactNode; className?: string }) => {
    const ref = useRef<HTMLDivElement>(null);
    const x = useMotionValue(0);
    const y = useMotionValue(0);

    const mouseX = useSpring(x, { stiffness: 150, damping: 15, mass: 0.1 });
    const mouseY = useSpring(y, { stiffness: 150, damping: 15, mass: 0.1 });

    const handleMouseMove = (e: React.MouseEvent<HTMLDivElement>) => {
        if (!ref.current) return;
        const { clientX, clientY } = e;
        const { left, top, width, height } = ref.current.getBoundingClientRect();
        const centerX = left + width / 2;
        const centerY = top + height / 2;
        x.set((clientX - centerX) * 0.5);
        y.set((clientY - centerY) * 0.5);
    };

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

    return (
        <motion.div
            ref={ref}
            onMouseMove={handleMouseMove}
            onMouseLeave={handleMouseLeave}
            style={{ x: mouseX, y: mouseY }}
            className={className}
        >
            {children}
        </motion.div>
    );
};

// --- BACKGROUND ---

const AuroraBackground = ({ activeColor }: { activeColor: string }) => {
    return (
        <div className="absolute inset-0 overflow-hidden pointer-events-none">
            <div className="absolute inset-0 bg-white dark:bg-slate-950 transition-colors duration-700" />

            {/* Primary Glow that follows active state */}
            <motion.div
                animate={{
                    background: `radial-gradient(circle at 50% 50%, ${activeColor}40 0%, transparent 70%)`,
                }}
                transition={{ duration: 1.5 }}
                className="absolute top-[-20%] left-[-10%] w-[600px] h-[600px] md:w-[800px] md:h-[800px] lg:w-[900px] lg:h-[900px] rounded-full blur-[120px] mix-blend-multiply dark:mix-blend-screen opacity-60 dark:opacity-40"
            />

            {/* Secondary Ambient Glows */}
            <motion.div
                animate={{
                    y: [0, -50, 0],
                    scale: [1, 1.1, 1],
                }}
                transition={{ duration: 10, repeat: Infinity, ease: "easeInOut" }}
                className="absolute bottom-[-10%] right-[-10%] w-[500px] h-[500px] md:w-[650px] md:h-[650px] lg:w-[750px] lg:h-[750px] bg-blue-100 dark:bg-blue-900/20 rounded-full blur-[100px] mix-blend-multiply dark:mix-blend-screen"
            />

            {/* Grain Overlay */}
            <div
                className="absolute inset-0 opacity-[0.05] mix-blend-overlay"
                style={{
                    backgroundImage: `url("data:image/svg+xml,%3Csvg viewBox='0 0 200 200' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='noiseFilter'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.65' numOctaves='3' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23noiseFilter)'/%3E%3C/svg%3E")`,
                }}
            />
        </div>
    );
};

import { useSectionTheme } from '../hooks/useSectionTheme';

// --- MAIN COMPONENT ---

export const SecondBrain: React.FC = () => {
    const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);
    const containerRef = useRef<HTMLDivElement>(null);
    const themeRef = useSectionTheme('mindset');

    // Smooth mouse following for the card
    const mouseX = useSpring(0, { stiffness: 500, damping: 30 });
    const mouseY = useSpring(0, { stiffness: 500, damping: 30 });

    useEffect(() => {
        const handleMouseMove = (e: MouseEvent) => {
            // Only track if within container (optional, but keeps it cleaner)
            if (containerRef.current) {
                const rect = containerRef.current.getBoundingClientRect();
                // Check if mouse is roughly inside or near
                if (e.clientY >= rect.top && e.clientY <= rect.bottom) {
                    mouseX.set(e.clientX - rect.left);
                    mouseY.set(e.clientY - rect.top);
                }
            }
        };

        window.addEventListener('mousemove', handleMouseMove);
        return () => window.removeEventListener('mousemove', handleMouseMove);
    }, [mouseX, mouseY]);

    const activeFeature = hoveredIndex !== null ? features[hoveredIndex] : features[0];

    return (
        <section
            ref={(node) => {
                // @ts-ignore
                containerRef.current = node;
                // @ts-ignore
                themeRef.current = node;
            }}
            className="relative w-full min-h-[600px] md:min-h-[700px] lg:min-h-[800px] flex items-center justify-center overflow-hidden py-12 md:py-16 lg:py-20"
        >
            {/* Replaced AuroraBackground with Global Theme 'mindset' */}


            <div className="relative z-10 w-full max-w-5xl mx-auto px-4 sm:px-6 md:px-8 flex flex-col md:flex-row items-start justify-between gap-8 md:gap-10 lg:gap-12">

                {/* LEFT: Header & Context */}
                <div className="w-full md:w-1/3 flex flex-col items-start">
                    <MagneticButton className="mb-8 cursor-default">
                        <div className="inline-flex items-center gap-2 px-4 py-2 rounded-full 
                            bg-white/80 dark:bg-white/5 border border-slate-200 dark:border-white/10 backdrop-blur-md 
                            shadow-sm dark:shadow-[0_0_15px_rgba(255,255,255,0.05)] transition-colors duration-300">
                            <Sparkles className="w-3.5 h-3.5 text-slate-600 dark:text-white/70" />
                            <span className="text-xs font-bold text-slate-800 dark:text-white/80 tracking-widest uppercase">The Second Brain for Your Business</span>
                        </div>
                    </MagneticButton>

                    <motion.h2
                        initial={{ opacity: 0, y: 20 }}
                        whileInView={{ opacity: 1, y: 0 }}
                        viewport={{ once: true }}
                        className="text-4xl sm:text-5xl md:text-5xl lg:text-6xl font-black text-slate-900 dark:text-white leading-[0.9] tracking-tight mb-6 md:mb-8 transition-colors duration-300"
                    >
                        Always On.<br />
                        <span className="text-2xl sm:text-3xl md:text-3xl lg:text-4xl font-black text-slate-600 dark:text-white/40 leading-[0.9] tracking-tight transition-colors duration-300">Always Working.</span>
                    </motion.h2>

                    <motion.p
                        initial={{ opacity: 0 }}
                        whileInView={{ opacity: 1 }}
                        viewport={{ once: true }}
                        transition={{ delay: 0.2 }}
                        className="text-slate-600 dark:text-white/60 text-base sm:text-lg font-medium leading-relaxed max-w-xs transition-colors duration-300"
                    >
                        Intelligent automation that runs in the background, keeping your business synchronized and efficient.
                    </motion.p>
                    <div className="flex items-center justify-center w-full mt-8 pr-12">
                    <motion.div
                        animate={{
                            scale: [1, 1.05, 1],
                            rotate: [0, 2, -2, 0],
                        }}
                        transition={{
                            duration: 4,
                            repeat: Infinity,
                            ease: "easeInOut"
                        }}
                        className="flex-shrink-0 relative"
                    >
                        <div className="relative w-32 h-32 sm:w-40 sm:h-40 md:w-44 md:h-44 lg:w-48 lg:h-48">
                            {/* Brain Container */}
                            <div className="mb-6 relative">
                                <img
                                    src="https://knowbuildwebsiteassets.s3.ap-south-1.amazonaws.com/knowbuild-logo-gif.gif"
                                    alt="knowbuild"
                                    className="w-full h-full object-contain mix-blend-multiply dark:mix-blend-screen"
                                    style={{
                                        filter: 'contrast(1.1) brightness(0.95)',
                                    }}
                                />
                            </div>

                            {/* Glow effect around brain */}
                            <motion.div
                                className="absolute inset-0 rounded-full blur-xl"
                                style={{
                                    background: 'radial-gradient(circle, rgba(249, 115, 22, 0.3) 0%, rgba(14, 165, 233, 0.3) 50%, transparent 100%)'
                                }}
                                animate={{
                                    scale: [1, 1.2, 1],
                                    opacity: [0.4, 0.6, 0.4],
                                }}
                                transition={{
                                    duration: 3,
                                    repeat: Infinity,
                                    ease: "easeInOut"
                                }}
                            />
                        </div>
                    </motion.div>
                    </div>
                  
                </div>

                {/* RIGHT: Interactive List */}
                <div className="w-full md:w-2/3 pl-0 md:pl-12 relative">
                    <div className="flex flex-col">
                        {features.map((feature, index) => (
                            <React.Fragment key={feature.id}>
                                <motion.div
                                    initial={{ opacity: 0, x: 50 }}
                                    whileInView={{ opacity: 1, x: 0 }}
                                    viewport={{ once: true }}
                                    transition={{ delay: index * 0.05 }}
                                    onMouseEnter={() => setHoveredIndex(index)}
                                    onMouseLeave={() => setHoveredIndex(null)}
                                    // Mobile touch behavior
                                    onTouchStart={() => setHoveredIndex(index)}
                                    className="group relative py-4 md:py-6 border-b border-slate-200 dark:border-white/10 cursor-pointer flex items-center justify-between transition-colors duration-300"
                                >
                                    <div className="flex items-center gap-6">
                                        <span className={`
                                            text-sm font-mono transition-colors duration-300
                                            ${hoveredIndex === index ? 'text-slate-900 dark:text-white' : 'text-slate-400 dark:text-white/20'}
                                        `}>
                                            0{index + 1}
                                        </span>
                                        <h3 className={`
                                            text-xl sm:text-2xl md:text-3xl lg:text-4xl font-bold tracking-tight transition-all duration-300
                                            ${hoveredIndex === index ? 'text-slate-900 dark:text-white translate-x-2' : 'text-slate-600 dark:text-white/40'}
                                        `}>
                                            {hoveredIndex === index ? (
                                                <ScrambleText text={feature.title} isActive={true} />
                                            ) : (
                                                feature.title
                                            )}
                                        </h3>
                                    </div>

                                    <motion.div
                                        animate={{
                                            opacity: hoveredIndex === index ? 1 : 0,
                                            x: hoveredIndex === index ? 0 : -10
                                        }}
                                        className="text-slate-900 dark:text-white/80"
                                    >
                                        <ArrowRight className="w-6 h-6" />
                                    </motion.div>
                                </motion.div>

                                {/* Mobile Details Expansion */}
                                <AnimatePresence>
                                    {hoveredIndex === index && (
                                        <motion.div
                                            initial={{ height: 0, opacity: 0 }}
                                            animate={{ height: 'auto', opacity: 1 }}
                                            exit={{ height: 0, opacity: 0 }}
                                            className="md:hidden overflow-hidden"
                                        >
                                            <div className="pb-6 pt-2 text-slate-600 dark:text-white/60 text-sm font-medium leading-relaxed border-b border-slate-200 dark:border-white/5 transition-colors duration-300">
                                                <div className="flex items-center gap-3 mb-3">
                                                    <div className={`p-2 rounded-lg bg-gradient-to-br ${feature.gradient}`}>
                                                        {React.createElement(feature.icon, { size: 16, className: "text-white" })}
                                                    </div>
                                                    <span className="text-slate-900 dark:text-white text-xs font-bold uppercase tracking-wider">Feature Details</span>
                                                </div>
                                                {feature.desc}
                                            </div>
                                        </motion.div>
                                    )}
                                </AnimatePresence>
                            </React.Fragment>
                        ))}
                    </div>
                </div>

                {/* FLOATING GLASS CARD (Desktop Only - visible on hover) */}
                <AnimatePresence>
                    {hoveredIndex !== null && (
                        <motion.div
                            initial={{ opacity: 0, scale: 0.8 }}
                            animate={{ opacity: 1, scale: 1 }}
                            exit={{ opacity: 0, scale: 0.8 }}
                            transition={{ type: "spring", stiffness: 400, damping: 30 }}
                            style={{
                                left: mouseX,
                                top: mouseY,
                                position: 'absolute',
                                pointerEvents: 'none',
                                zIndex: 50,
                                x: -0, // Offset to not cover cursor
                                y: 20
                            }}
                            className="hidden md:block fixed w-[280px] lg:w-[320px] rounded-[24px] overflow-hidden shadow-2xl shadow-black/5 dark:shadow-black/30"
                        >
                            {/* Glassmorphism Styles */}
                            <div className="absolute inset-0 bg-white/80 dark:bg-slate-900/60 backdrop-blur-xl transition-colors duration-300" />
                            <div className="absolute inset-0 border border-white/40 dark:border-white/10 rounded-[24px]" />
                            <div className="absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-slate-900/10 dark:via-white/30 to-transparent" />

                            <div className="relative p-6 flex flex-col gap-4">
                                <div className={`
                                    w-12 h-12 rounded-2xl flex items-center justify-center
                                    bg-gradient-to-br ${features[hoveredIndex].gradient}
                                    shadow-lg shadow-slate-900/5 dark:shadow-black/20
                                `}>
                                    {React.createElement(features[hoveredIndex].icon, {
                                        className: "w-6 h-6 text-white"
                                    })}
                                </div>

                                <div>
                                    <h4 className="text-slate-900 dark:text-white font-bold text-xl mb-2 transition-colors duration-300">
                                        {features[hoveredIndex].title}
                                    </h4>
                                    <p className="text-slate-600 dark:text-white/60 text-sm leading-relaxed transition-colors duration-300">
                                        {features[hoveredIndex].desc}
                                    </p>
                                </div>
                            </div>
                        </motion.div>
                    )}
                </AnimatePresence>
            </div>
        </section>
    );
};
