"use client";

import React, { useState, useEffect, useCallback, useMemo } from "react";
import {
    X,
    ChevronRight,
    ChevronLeft,
    ChevronDown,
    Linkedin,
    Facebook,
    Instagram,
    User,
} from "lucide-react";
import { LinkItem, Column } from "./Header"; // keep as you had

// --- Data Structure (kept same as your original) ---
type PanelContent = { title: string; sections: Column[] };

const sideMenuData: { [key: string]: PanelContent } = {
    who_we_are: {
        title: "Who We Are",
        sections: [
            {
                title: "Our Organization",
                links: [
                    { text: "Overview", href: "/overview" },
                    { text: "Our History", href: "/our-history" },
                    { text: "Our Mission & Vision", href: "/mision-vision" },
                    { text: "Leadership", href: "/leadership" },
                    { text: "Our Experts", href: "/our-exeprts" },
                    { text: "Award & Recognitions", href: "/award-recognations" },
                    { text: "Clients & Feedback", href: "/clients-feedback" },
                    { text: "Portfolio", href: "/portfolio" },
                ],
            } as Column,
            {
                title: "Our Projects",
                links: [
                    { text: "Sudarshan 2.O", href: "/overview" },
                    { text: "Tree Stethosccope", href: "/mision-vision" },
                    { text: "M.E.R.A 1.0", href: "/mera" },
                ],
            } as Column,
            {
                title: "Impact",
                links: [
                    { text: "11 Rupey Me Graduate", href: "/rupeyme-graduate" },
                    { text: "The Art of Living", href: "/artof-living" },
                    { text: "Green Galaxy", href: "/green-galaxy" },
                    { text: "Digital Awareness", href: "/digital-awareness" },
                ],
            } as Column,
        ],
    },

    what_we_do: {
        title: "What We Do",
        sections: [
            {
                title: "Capabilities",
                links: [
                    { text: "Application Development and Maintenance", href: "#market" },
                    { text: "Cybersecurity", href: "#policy" },
                    { text: "Artificial Intelligence", href: "#forecasting" },
                    { text: "Robotics", href: "#forecasting" },
                    { text: "Consulting", href: "#forecasting" },
                    { text: "Digital Marketing", href: "#forecasting" },
                    { text: "Learning", href: "#forecasting" },
                    { text: "Broadcasting", href: "#forecasting" },
                    { text: "Cloud", href: "#forecasting" },
                    { text: "Deep Space Exploration", href: "#forecasting" },
                    { text: "Research", href: "#forecasting" },
                    { text: "IoT and Digital Engineering", href: "#forecasting" },
                    { text: "Data & Analytics", href: "#forecasting" },
                    { text: "Branding", href: "#forecasting" },
                ],
            } as Column,
            {
                title: "Industries",
                links: [
                    { text: "Education", href: "#strategy" },
                    { text: "Aerospace & Defence", href: "#risk" },
                    { text: "Agriculture", href: "#digital" },
                    { text: "Software", href: "#digital" },
                    { text: "Communications Services", href: "#digital" },
                    { text: "Banking & Finance", href: "#digital" },
                    { text: "Information Services & Publishing", href: "#digital" },
                    { text: "E-Commerce & Logistics", href: "#digital" },
                    { text: "Media and Entertainment", href: "#digital" },
                    { text: "Healthcare", href: "#digital" },
                    { text: "Security", href: "#digital" },
                    {
                        text: "Consumer Packaged Goods and Distribution",
                        href: "#digital",
                    },
                ],
            } as Column,
            {
                title: "Products",
                links: [
                    { text: "Panther Speaks", href: "#strategy" },
                    { text: "Suhagini Spices", href: "#risk" },
                ],
            } as Column,
            {
                title: "Platforms",
                links: [
                    { text: "Wimraw Institute", href: "#strategy" },
                    { text: "Jhumle", href: "#risk" },
                    { text: "NCSI", href: "#digital" },
                    { text: "Web Expert", href: "#digital" },
                    { text: "NECI", href: "#digital" },
                    { text: "Black Cat News Network", href: "#digital" },
                    { text: "Oibuild", href: "#digital" },
                    { text: "Oifind", href: "#digital" },
                    { text: "Oiearn", href: "#digital" },
                    { text: "Wimraw Cloud", href: "#digital" },
                    { text: "Aasiqui", href: "#digital" },
                ],
            } as Column,
        ],
    },

    for_you: {
        title: "For You",
        sections: [
            {
                title: "Careers",
                links: [
                    { text: "Work@ Wimraw", href: "#market" },
                    { text: "Apprenticeship & Internships", href: "#policy" },
                    { text: "Research Fellowship", href: "#forecasting" },
                ],
            } as Column,
            {
                title: "Opportunities",
                links: [
                    { text: "Corporate Collaboration", href: "#strategy" },
                    { text: "CSR", href: "#risk" },
                ],
            } as Column,
        ],
    },

    for_press: {
        title: "For Press",
        sections: [
            {
                title: "Press",
                links: [
                    { text: "Events", href: "#market" },
                    { text: "Press Releases", href: "#policy" },
                    { text: "Stories", href: "#forecasting" },
                    { text: "Media Resources", href: "#strategy" },
                ],
            } as Column,
        ],
    },
};

const panelOrder = ["sidenav", "who_we_are", "what_we_do", "for_you", "for_press"];
const panelCount = panelOrder.length;

// ----------------------
// SubCollapseItem (Accordion subsection)
// ----------------------
interface SubCollapseItemProps {
    section: Column;
    isActive: boolean;
    onToggle: () => void;
}
const SubCollapseItem: React.FC<SubCollapseItemProps> = ({ section, isActive, onToggle }) => {
    const contentRef = React.useRef<HTMLUListElement>(null);
    const [contentHeight, setContentHeight] = useState("0px");

    useEffect(() => {
        if (contentRef.current) {
            setContentHeight(isActive ? `${contentRef.current.scrollHeight}px` : "0px");
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [isActive]);

    return (
        <li className="border-b border-white/5">
            <button
                type="button"
                onClick={(e) => {
                    e.preventDefault();
                    onToggle();
                }}
                className="w-full flex justify-between items-center text-lg font-medium py-4 text-white hover:text-indigo-400 transition-colors"
            >
                <span>{section.title}</span>
                <ChevronDown size={20} className={`transition-transform duration-300 ${isActive ? "rotate-180" : "rotate-0"}`} />
            </button>

            <div className="overflow-hidden transition-[max-height] duration-300 ease-in-out" style={{ maxHeight: contentHeight }}>
                <ul ref={contentRef} className="pl-4 pb-4 space-y-1">
                    {section.links.map((link) => (
                        <li key={link.text}>
                            <a href={link.href} className="block py-2 text-base text-white/80 hover:text-indigo-300 transition-colors">
                                {link.text}
                            </a>
                        </li>
                    ))}
                </ul>
            </div>
        </li>
    );
};

// ----------------------
// Main Sidenav Panel
// ----------------------
interface SideMenuPanelProps {
    panelId: string;
    onNavigate: (targetId: string) => void;
    onClose: () => void;
}

const MainSidenavPanel: React.FC<SideMenuPanelProps> = ({ onNavigate, onClose }) => (
    // NOTE: use w-screen so each panel is exactly 100vw
    <div id="sidenav" className="flex-shrink-0 w-screen flex flex-col h-full">
        <div className="flex justify-end items-center p-4 border-b border-white/5 h-20 flex-shrink-0">
            <button onClick={onClose} className="p-2 text-2xl text-white hover:text-indigo-400 transition-transform duration-300 transform hover:rotate-90" aria-label="Close menu">
                <X size={28} />
            </button>
        </div>

        <div className="flex-grow overflow-y-auto p-6 space-y-10">
            <nav className="space-y-0">
                {panelOrder.slice(1).map((id) => {
                    const item = sideMenuData[id];
                    if (!item) return null;
                    return (
                        // use button to avoid hash navigation side effects
                        <button
                            type="button"
                            key={id}
                            onClick={() => onNavigate(id)}
                            className="w-full flex justify-between items-center text-xl font-medium py-4 text-white/90 hover:text-indigo-400 transition-colors border-b border-white/5"
                        >
                            <span>{item.title}</span>
                            <ChevronRight size={20} className="text-indigo-400" />
                        </button>
                    );
                })}

                <a href="/signin" onClick={onClose} className="flex justify-between items-center text-xl font-medium py-4 text-white/90 hover:text-indigo-400 transition-colors border-b border-white/5">
                    <span>Sign In</span>
                    <ChevronRight size={20} className="text-indigo-400" />
                </a>
            </nav>

            <div className="flex justify-center mt-10 gap-5">
                <a href="#" className="w-10 h-10 flex justify-center items-center bg-white rounded-full text-indigo-700 hover:bg-indigo-700 hover:text-white transition-colors">
                    <Linkedin size={20} />
                </a>
                <a href="#" className="w-10 h-10 flex justify-center items-center bg-white rounded-full text-indigo-700 hover:bg-indigo-700 hover:text-white transition-colors">
                    <Facebook size={20} />
                </a>
                <a href="#" className="w-10 h-10 flex justify-center items-center bg-white rounded-full text-indigo-700 hover:bg-indigo-700 hover:text-white transition-colors">
                    <Instagram size={20} />
                </a>
            </div>
        </div>
    </div>
);

// ----------------------
// SubMenuPanel
// ----------------------
const SubMenuPanel: React.FC<SideMenuPanelProps> = ({ panelId, onNavigate, onClose }) => {
    const panelData = sideMenuData[panelId];
    const [openSection, setOpenSection] = useState<string | null>(null);

    useEffect(() => {
        setOpenSection(null);
    }, [panelId]);

    const handleToggle = (title: string) => {
        setOpenSection((prev) => (prev === title ? null : title));
    };

    if (!panelData || !panelData.sections || panelData.sections.length === 0) {
        return (
            <div id={panelId} className="flex-shrink-0 w-screen flex flex-col h-full bg-red-900">
                <div className="flex items-center p-4 border-b border-white/5 h-20 flex-shrink-0">
                    <button onClick={() => onNavigate("sidenav")} className="flex items-center text-lg text-white/90 hover:text-indigo-400 transition-colors p-2 -ml-2" aria-label="Back to main menu">
                        <ChevronLeft size={20} className="mr-2" /> Back
                    </button>
                </div>
                <div className="p-6 text-xl font-bold text-red-300">🚨 ERROR: Data failed to load for {panelId.toUpperCase()}</div>
            </div>
        );
    }

    return (
        <div id={panelId} className="flex-shrink-0 w-screen flex flex-col h-full">
            <div className="flex items-center p-4 border-b border-white/5 h-20 flex-shrink-0">
                <button onClick={() => onNavigate("sidenav")} className="flex items-center text-lg text-white/90 hover:text-indigo-400 transition-colors p-2 -ml-2" aria-label="Back to main menu">
                    <ChevronLeft size={20} className="mr-2" /> Back
                </button>
            </div>

            <div className="flex-grow overflow-y-auto p-6">
                <div className="text-2xl font-bold mb-6 text-white uppercase tracking-wider border-b border-white/5 pb-4">
                    <span className="inline-flex items-center">
                        {panelData.title}
                        <ChevronRight size={20} className="ml-2 text-indigo-400" />
                    </span>
                </div>

                <nav className="mt-4">
                    <ul className="space-y-0 divide-y divide-white/5">
                        {panelData.sections.map((section) => (
                            <SubCollapseItem key={section.title} section={section} isActive={openSection === section.title} onToggle={() => handleToggle(section.title)} />
                        ))}
                    </ul>
                </nav>
            </div>
        </div>
    );
};

// ----------------------
// MobileSidenav (MAIN)
// ----------------------
interface MobileSidenavProps {
    isOpen: boolean;
    onClose: () => void;
}

const MobileSidenav: React.FC<MobileSidenavProps> = ({ isOpen, onClose }) => {
    const [currentPanelId, setCurrentPanelId] = useState<string>("sidenav");

    const currentPanelIndex = useMemo(() => panelOrder.findIndex((id) => id === currentPanelId), [currentPanelId]);

    // translate in vw so it's exact 1 panel per 100vw
    const translateXValue = useMemo(() => `translateX(-${currentPanelIndex * 100}vw)`, [currentPanelIndex]);

    useEffect(() => {
        if (isOpen) {
            setCurrentPanelId("sidenav");
        }
    }, [isOpen]);

    const handleNavigate = useCallback((targetId: string) => {
        setCurrentPanelId(targetId);
    }, []);

    const gradientStyle = "linear-gradient(251deg, rgba(2, 0, 36, 1) 0%, rgba(74, 0, 224, 1) 100%)";

    return (
        <div
            // Outer wrapper (full screen). We toggle whole menu on/off with translate-x.
            className={`fixed top-0 left-0 w-full h-screen z-[1050] text-white transition-transform duration-300 ease-in-out transform ${isOpen ? "translate-x-0" : "-translate-x-full"}`}
            style={{
                background: gradientStyle,
                transitionTimingFunction: "cubic-bezier(0.7, 0, 0.3, 1)",
                overflow: "hidden",
            }}
        >
            <div
                // Sliding wrapper: width = panelCount * 100vw. Each child is w-screen (100vw).
                className="flex h-full transition-transform duration-300 ease-in-out"
                style={{
                    width: `${panelCount * 100}vw`, // e.g. 5 * 100vw = 500vw
                    transform: translateXValue,
                    transitionTimingFunction: "cubic-bezier(0.7, 0, 0.3, 1)",
                }}
            >
                <MainSidenavPanel panelId="sidenav" onNavigate={handleNavigate} onClose={onClose} />
                {panelOrder.slice(1).map((id) => (
                    <SubMenuPanel key={id} panelId={id} onNavigate={handleNavigate} onClose={onClose} />
                ))}
            </div>
        </div>
    );
};

export default MobileSidenav;
