import CurrencySelector from '@/components/CurrencySelector';
import CookieBanner from '@/components/platform/CookieBanner';
import { cn } from '@/lib/utils';
import { Link } from '@inertiajs/react';
import { AnimatePresence, motion } from 'framer-motion';
import {
    BarChart3,
    BookOpen,
    ChevronDown,
    CreditCard,
    Landmark,
    Menu,
    Moon,
    PiggyBank,
    Sun,
    UserCheck,
    Users,
    X,
} from 'lucide-react';
import { useEffect, useRef, useState } from 'react';

interface PlatformLayoutProps {
    children: React.ReactNode;
}

const productItems = [
    {
        icon: Landmark,
        label: 'Overview',
        desc: 'The complete MFI operating system',
        href: '/product',
    },
    {
        icon: CreditCard,
        label: 'Loan Management',
        desc: 'Full lifecycle, top-ups, restructuring',
        href: '/product/loans',
    },
    {
        icon: PiggyBank,
        label: 'Savings Management',
        desc: 'Voluntary, compulsory, fixed deposits',
        href: '/product/savings',
    },
    {
        icon: Users,
        label: 'Client & Groups',
        desc: 'KYC, credit scoring, group lending',
        href: '/product/clients',
    },
    {
        icon: BookOpen,
        label: 'Accounting & Finance',
        desc: 'Double-entry GL, reconciliation, budgeting',
        href: '/product/accounting',
    },
    {
        icon: UserCheck,
        label: 'HR & Payroll',
        desc: 'Employees, attendance, leave, payroll',
        href: '/product/hr',
    },
    {
        icon: BarChart3,
        label: 'Analytics & Reports',
        desc: 'Role dashboards, custom report builder',
        href: '/product/reports',
    },
];

const footerLinks: Record<string, { label: string; href: string }[]> = {
    Platform: [
        { label: 'Loan Management', href: '/product/loans' },
        { label: 'Savings Management', href: '/product/savings' },
        { label: 'Client & Groups', href: '/product/clients' },
        { label: 'Accounting & Finance', href: '/product/accounting' },
        { label: 'HR & Payroll', href: '/product/hr' },
        { label: 'Analytics & Reports', href: '/product/reports' },
    ],
    Company: [
        { label: 'About Us', href: '/about' },
        { label: 'Our Manifesto', href: '/manifesto' },
        { label: 'Careers', href: '/careers' },
        { label: 'Press', href: '/press' },
        { label: 'Customers', href: '/customers' },
        { label: 'Case Studies', href: '/case-studies' },
    ],
    Support: [
        { label: 'Help Centre', href: '/help' },
        { label: 'Tutorials', href: '/tutorials' },
        { label: 'FAQ', href: '/faq' },
        { label: 'Contact Us', href: '/support' },
        { label: 'Privacy Policy', href: '/privacy' },
        { label: 'Terms & Conditions', href: '/terms' },
    ],
};

export default function PlatformLayout({ children }: PlatformLayoutProps) {
    const [scrolled, setScrolled] = useState(false);
    const [isDark, setIsDark] = useState(false);
    const [productOpen, setProductOpen] = useState(false);
    const [mobileOpen, setMobileOpen] = useState(false);
    const hoverTimeout = useRef<ReturnType<typeof setTimeout> | null>(null);

    useEffect(() => {
        const stored = localStorage.getItem('uf-theme');
        const dark = stored === 'dark';
        setIsDark(dark);
        document.documentElement.classList.toggle('dark', dark);
    }, []);

    useEffect(() => {
        const onScroll = () => setScrolled(window.scrollY > 16);
        window.addEventListener('scroll', onScroll, { passive: true });
        return () => window.removeEventListener('scroll', onScroll);
    }, []);

    const toggleDark = () => {
        const next = !isDark;
        setIsDark(next);
        document.documentElement.classList.toggle('dark', next);
        localStorage.setItem('uf-theme', next ? 'dark' : 'light');
    };

    const openMenu = () => {
        if (hoverTimeout.current) clearTimeout(hoverTimeout.current);
        setProductOpen(true);
    };
    const closeMenu = () => {
        hoverTimeout.current = setTimeout(() => setProductOpen(false), 140);
    };

    return (
        <div className="pf-page-bg text-foreground min-h-screen">
            {/* ── Navbar ──────────────────────────────────────────────── */}
            <header
                className={cn(
                    'fixed inset-x-0 top-0 z-50 transition-all duration-300',
                    scrolled
                        ? 'pf-nav-glass border-border/60 border-b shadow-sm'
                        : 'bg-transparent',
                )}
            >
                <div className="pf-container">
                    <div className="flex h-16 items-center justify-between">
                        {/* Logo */}
                        <Link
                            href="/"
                            className="group flex items-center gap-2.5"
                        >
                            <img
                                src="/images/logo.png"
                                alt="Upepo Finance"
                                className="h-8 w-8 object-contain transition-transform group-hover:scale-105"
                            />
                            <span className="font-display text-foreground text-sm font-semibold tracking-tight">
                                Upepo Finance
                            </span>
                        </Link>

                        {/* Desktop nav */}
                        <nav className="hidden items-center gap-1 md:flex">
                            <div
                                className="relative"
                                onMouseEnter={openMenu}
                                onMouseLeave={closeMenu}
                            >
                                <button className="text-muted-foreground hover:bg-accent hover:text-accent-foreground flex items-center gap-1.5 rounded-xl px-3.5 py-2 text-sm font-medium transition-all">
                                    Product
                                    <ChevronDown
                                        className={cn(
                                            'text-primary/60 h-3.5 w-3.5 transition-transform duration-200',
                                            productOpen && 'rotate-180',
                                        )}
                                    />
                                </button>

                                <AnimatePresence>
                                    {productOpen && (
                                        <motion.div
                                            initial={{
                                                opacity: 0,
                                                y: 6,
                                                scale: 0.98,
                                            }}
                                            animate={{
                                                opacity: 1,
                                                y: 0,
                                                scale: 1,
                                            }}
                                            exit={{
                                                opacity: 0,
                                                y: 6,
                                                scale: 0.98,
                                            }}
                                            transition={{
                                                duration: 0.15,
                                                ease: [0.16, 1, 0.3, 1],
                                            }}
                                            className="border-border bg-popover shadow-foreground/5 absolute top-full left-1/2 mt-2 w-[330px] -translate-x-1/2 overflow-hidden rounded-2xl border p-1.5 shadow-xl"
                                        >
                                            <div className="mb-1 px-3 pt-2 pb-1.5">
                                                <span className="text-muted-foreground/70 text-[10px] font-semibold tracking-widest uppercase">
                                                    Platform Modules
                                                </span>
                                            </div>
                                            {productItems.map((item) => (
                                                <Link
                                                    key={item.label}
                                                    href={item.href}
                                                    className="group hover:bg-accent/30 flex items-start gap-3 rounded-xl p-2.5 transition-colors"
                                                >
                                                    <div className="pf-icon-box mt-0.5 h-8 w-8 rounded-xl">
                                                        <item.icon className="h-4 w-4" />
                                                    </div>
                                                    <div>
                                                        <p className="text-foreground group-hover:text-primary text-sm font-semibold">
                                                            {item.label}
                                                        </p>
                                                        <p className="text-muted-foreground text-xs">
                                                            {item.desc}
                                                        </p>
                                                    </div>
                                                </Link>
                                            ))}
                                        </motion.div>
                                    )}
                                </AnimatePresence>
                            </div>

                            {[
                                ['Pricing', '/pricing'],
                                ['Support', '/support'],
                            ].map(([label, href]) => (
                                <Link
                                    key={label}
                                    href={href}
                                    className="text-muted-foreground hover:bg-accent hover:text-accent-foreground rounded-xl px-3.5 py-2 text-sm font-medium transition-all"
                                >
                                    {label}
                                </Link>
                            ))}
                        </nav>

                        {/* Right actions */}
                        <div className="hidden items-center gap-2 md:flex">
                            <CurrencySelector />
                            <button
                                onClick={toggleDark}
                                aria-label="Toggle theme"
                                className="text-muted-foreground hover:bg-accent hover:text-accent-foreground rounded-xl p-2 transition-colors"
                            >
                                {isDark ? (
                                    <Sun className="h-4 w-4" />
                                ) : (
                                    <Moon className="h-4 w-4" />
                                )}
                            </button>
                            <Link
                                href="/login"
                                className="text-muted-foreground hover:bg-accent hover:text-accent-foreground rounded-xl px-4 py-2 text-sm font-medium transition-colors"
                            >
                                Sign In
                            </Link>
                            <Link
                                href="/get-started"
                                className="pf-btn px-5 py-2 text-sm"
                            >
                                Get Started
                            </Link>
                        </div>

                        {/* Mobile toggles */}
                        <div className="flex items-center gap-2 md:hidden">
                            <CurrencySelector className="px-2" />
                            <button
                                onClick={toggleDark}
                                className="text-muted-foreground hover:bg-accent hover:text-accent-foreground rounded-xl p-2"
                            >
                                {isDark ? (
                                    <Sun className="h-4 w-4" />
                                ) : (
                                    <Moon className="h-4 w-4" />
                                )}
                            </button>
                            <button
                                onClick={() => setMobileOpen(!mobileOpen)}
                                className="text-muted-foreground hover:bg-accent hover:text-accent-foreground rounded-xl p-2"
                            >
                                {mobileOpen ? (
                                    <X className="h-5 w-5" />
                                ) : (
                                    <Menu className="h-5 w-5" />
                                )}
                            </button>
                        </div>
                    </div>
                </div>
            </header>

            {/* Mobile drawer */}
            <AnimatePresence>
                {mobileOpen && (
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        transition={{ duration: 0.26, ease: [0.16, 1, 0.3, 1] }}
                        onClick={() => setMobileOpen(false)}
                        className="fixed inset-0 z-[60] bg-black/30 backdrop-blur-sm"
                    />
                )}
            </AnimatePresence>
            <AnimatePresence>
                {mobileOpen && (
                    <motion.div
                        initial={{ opacity: 0, x: '100%' }}
                        animate={{ opacity: 1, x: 0 }}
                        exit={{ opacity: 0, x: '100%' }}
                        transition={{ duration: 0.26, ease: [0.16, 1, 0.3, 1] }}
                        className="pf-glass border-border fixed inset-y-0 right-0 z-[70] w-80 overflow-y-auto !rounded-none border-l"
                    >
                        <div className="flex h-full flex-col px-6 py-6">
                            <div className="border-border mb-8 flex items-center justify-between border-b pb-5">
                                <div className="flex items-center gap-2.5">
                                    <img
                                        src="/images/logo.png"
                                        alt="Upepo Finance"
                                        className="h-8 w-8 object-contain"
                                    />
                                    <span className="font-display text-foreground text-sm font-semibold">
                                        Upepo Finance
                                    </span>
                                </div>
                                <button
                                    onClick={() => setMobileOpen(false)}
                                    className="text-muted-foreground hover:text-foreground"
                                >
                                    <X className="h-5 w-5" />
                                </button>
                            </div>

                            <div className="flex-1 space-y-0.5">
                                <p className="text-muted-foreground/60 mb-2 text-[10px] font-semibold tracking-widest uppercase">
                                    Platform
                                </p>
                                {productItems.map((item) => (
                                    <Link
                                        key={item.label}
                                        href={item.href}
                                        onClick={() => setMobileOpen(false)}
                                        className="text-muted-foreground hover:bg-accent hover:text-accent-foreground flex items-center gap-3 rounded-xl px-3 py-2.5 text-sm font-medium transition-colors"
                                    >
                                        <div className="pf-icon-box h-7 w-7 rounded-lg">
                                            <item.icon className="h-3.5 w-3.5" />
                                        </div>
                                        {item.label}
                                    </Link>
                                ))}
                                <div className="border-border mt-3 space-y-0.5 border-t pt-3">
                                    {[
                                        ['Pricing', '/pricing'],
                                        ['Support', '/support'],
                                    ].map(([label, href]) => (
                                        <Link
                                            key={label}
                                            href={href}
                                            onClick={() => setMobileOpen(false)}
                                            className="text-muted-foreground hover:bg-accent hover:text-accent-foreground block rounded-xl px-3 py-2.5 text-sm font-medium transition-colors"
                                        >
                                            {label}
                                        </Link>
                                    ))}
                                </div>
                            </div>

                            <div className="border-border mt-8 space-y-3 border-t pt-6">
                                <Link
                                    href="/login"
                                    onClick={() => setMobileOpen(false)}
                                    className="border-border text-muted-foreground hover:border-primary/40 hover:text-foreground block w-full rounded-xl border py-2.5 text-center text-sm font-medium transition-colors"
                                >
                                    Sign In
                                </Link>
                                <Link
                                    href="/get-started"
                                    onClick={() => setMobileOpen(false)}
                                    className="pf-btn block w-full py-2.5 text-center text-sm"
                                >
                                    Get Started Free
                                </Link>
                            </div>
                        </div>
                    </motion.div>
                )}
            </AnimatePresence>

            <main>{children}</main>

            <CookieBanner />

            {/* ── Footer ──────────────────────────────────────────────── */}
            <footer className="bg-panel text-panel-foreground">
                <div className="pf-divider opacity-20" />
                <div className="pf-container py-16">
                    <div className="grid grid-cols-1 gap-12 md:grid-cols-4">
                        {/* Brand */}
                        <div>
                            <Link
                                href="/"
                                className="mb-5 flex items-center gap-2.5"
                            >
                                <img
                                    src="/images/logo.png"
                                    alt="Upepo Finance"
                                    className="h-8 w-8 object-contain"
                                />
                                <span className="font-display text-panel-foreground text-base font-semibold">
                                    Upepo Finance
                                </span>
                            </Link>
                            <p className="text-panel-foreground/70 mb-6 text-sm leading-relaxed">
                                The enterprise operating system
                                <br />
                                for East African lending institutions.
                            </p>

                            {/* Live status */}
                            <div className="mb-4 flex items-center gap-2">
                                <div className="pf-live" />
                                <span className="text-panel-foreground/70 text-xs">
                                    All systems operational
                                </span>
                            </div>

                            {/* Social */}
                            <div className="flex items-center gap-2">
                                {[
                                    {
                                        d: 'M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-4.714-6.231-5.401 6.231H2.744l7.737-8.835L1.254 2.25H8.08l4.253 5.622 5.911-5.622zm-1.161 17.52h1.833L7.084 4.126H5.117z',
                                        vb: '0 0 24 24',
                                    },
                                    {
                                        d: 'M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433a2.062 2.062 0 01-2.063-2.065 2.064 2.064 0 112.063 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z',
                                        vb: '0 0 24 24',
                                    },
                                    {
                                        d: 'M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12',
                                        vb: '0 0 24 24',
                                    },
                                ].map((icon, i) => (
                                    <a
                                        key={i}
                                        href="#"
                                        className="border-panel-foreground/15 bg-panel-foreground/8 hover:border-lime/50 hover:bg-lime/10 hover:text-lime flex h-8 w-8 items-center justify-center rounded-xl border transition-all"
                                    >
                                        <svg
                                            className="text-panel-foreground/55 h-3.5 w-3.5"
                                            viewBox={icon.vb}
                                            fill="currentColor"
                                        >
                                            <path d={icon.d} />
                                        </svg>
                                    </a>
                                ))}
                            </div>
                        </div>

                        {/* Link columns */}
                        {Object.entries(footerLinks).map(([title, links]) => (
                            <div key={title}>
                                <p className="text-panel-foreground/65 mb-4 text-[10px] font-semibold tracking-widest uppercase">
                                    {title}
                                </p>
                                <ul className="space-y-2.5">
                                    {links.map((link) => (
                                        <li key={link.label}>
                                            <Link
                                                href={link.href}
                                                className="text-panel-foreground/60 hover:text-lime text-sm transition-colors"
                                            >
                                                {link.label}
                                            </Link>
                                        </li>
                                    ))}
                                </ul>
                            </div>
                        ))}
                    </div>

                    <div className="border-panel-foreground/10 mt-16 flex flex-col items-center justify-between gap-4 border-t pt-8 md:flex-row">
                        <p className="text-panel-foreground/50 text-xs">
                            © {new Date().getFullYear()} Upepo Finance. All
                            rights reserved.
                        </p>
                        <div className="flex items-center gap-6">
                            {[
                                { label: 'Privacy Policy', href: '/privacy' },
                                {
                                    label: 'Terms & Conditions',
                                    href: '/terms',
                                },
                                { label: 'Cookie Policy', href: '/cookies' },
                            ].map((link) => (
                                <Link
                                    key={link.label}
                                    href={link.href}
                                    className="text-panel-foreground/50 hover:text-lime text-xs transition-colors"
                                >
                                    {link.label}
                                </Link>
                            ))}
                        </div>
                    </div>
                </div>
            </footer>
        </div>
    );
}
