import { Head, Link, useForm, usePage } from '@inertiajs/react';
import { ChevronDown, Facebook, Linkedin, Mail, MapPin, Menu, Phone, X } from 'lucide-react';
import { type PropsWithChildren, useEffect, useRef, useState } from 'react';

interface SubLink {
    label: string;
    href: string;
}

interface NavLink {
    label: string;
    href: string;
    sub?: SubLink[];
}

const navLinks: NavLink[] = [
    { label: 'Home', href: '/' },
    {
        label: 'About',
        href: '/about',
        sub: [
            { label: 'About ABEC', href: '/about' },
            { label: 'Governance', href: '/about/governance' },
        ],
    },
    { label: 'Programs', href: '/programs' },
    { label: 'Research', href: '/research' },
    { label: 'Members', href: '/members' },
];

function Logo({ logoUrl, size = 'md' }: { logoUrl?: string; size?: 'sm' | 'md' | 'lg' }) {
    const h = size === 'sm' ? 'h-7' : size === 'lg' ? 'h-12' : 'h-8';

    if (logoUrl) {
        return (
            <div className="flex items-center gap-2.5">
                <img
                    src={logoUrl}
                    alt="ABEC Africa"
                    className={`${h} w-auto object-contain flex-shrink-0`}
                />
                <div>
                    <div className="text-[#1b265c] font-black text-sm tracking-[0.1em] uppercase leading-none">ABEC</div>
                    <div className="text-[#555e8a] text-[9px] tracking-[0.12em] uppercase leading-none mt-0.5">
                        African Biomedical Engineering Consortium
                    </div>
                </div>
            </div>
        );
    }

    return (
        <div className="flex items-center gap-2.5">
            <div className="w-8 h-8 bg-[#1b265c] flex items-center justify-center flex-shrink-0">
                <span className="text-white text-xs font-black tracking-tighter">A</span>
            </div>
            <div>
                <div className="text-[#1b265c] font-black text-sm tracking-[0.12em] uppercase leading-none">ABEC</div>
                <div className="text-[#555e8a] text-[9px] tracking-[0.15em] uppercase leading-none mt-0.5">
                    African Biomedical Engineering Consortium
                </div>
            </div>
        </div>
    );
}

function Nav() {
    const { url, props } = usePage();
    const logoUrl = props.settings?.logo_url as string | undefined;
    const [open, setOpen] = useState(false);
    const [scrolled, setScrolled] = useState(false);

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

    useEffect(() => {
        setOpen(false);
    }, [url]);

    const [openDropdown, setOpenDropdown] = useState<string | null>(null);
    const dropdownRef = useRef<HTMLDivElement>(null);

    const isActive = (href: string) =>
        href === '/' ? url === '/' : url.startsWith(href);

    useEffect(() => {
        function handleClick(e: MouseEvent) {
            if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
                setOpenDropdown(null);
            }
        }
        document.addEventListener('mousedown', handleClick);
        return () => document.removeEventListener('mousedown', handleClick);
    }, []);

    return (
        <header
            className={`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${
                scrolled
                    ? 'bg-white/96 backdrop-blur-sm border-b border-[#d0d4ec] shadow-sm'
                    : 'bg-white border-b border-[#d0d4ec]'
            }`}
        >
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
                <div className="flex items-center justify-between h-16 lg:h-20">
                    {/* Logo */}
                    <Link href="/" className="flex items-center gap-3 group">
                        <Logo logoUrl={logoUrl} />
                    </Link>

                    {/* Desktop nav */}
                    <nav className="hidden lg:flex items-center gap-8" ref={dropdownRef}>
                        {navLinks.map((link) =>
                            link.sub ? (
                                <div key={link.href} className="relative">
                                    <button
                                        onClick={() => setOpenDropdown(openDropdown === link.href ? null : link.href)}
                                        className={`flex items-center gap-1 text-xs tracking-[0.18em] uppercase font-semibold transition-colors pb-0.5 ${
                                            isActive(link.href)
                                                ? 'text-[#df2548] border-b-2 border-[#df2548]'
                                                : 'text-[#1b265c] hover:text-[#df2548]'
                                        }`}
                                    >
                                        {link.label}
                                        <ChevronDown size={10} className="mt-0.5" />
                                    </button>
                                    {openDropdown === link.href && (
                                        <div className="absolute top-full left-0 mt-2 bg-white border border-[#d0d4ec] shadow-lg min-w-44 z-50">
                                            {link.sub.map((sub) => (
                                                <Link
                                                    key={sub.href}
                                                    href={sub.href}
                                                    onClick={() => setOpenDropdown(null)}
                                                    className={`block px-5 py-3 text-xs tracking-[0.15em] uppercase font-semibold border-b border-[#d0d4ec] last:border-0 transition-colors ${
                                                        url === sub.href
                                                            ? 'text-[#df2548] bg-[#f9f7f4]'
                                                            : 'text-[#1b265c] hover:text-[#df2548] hover:bg-[#f9f7f4]'
                                                    }`}
                                                >
                                                    {sub.label}
                                                </Link>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            ) : (
                                <Link
                                    key={link.href}
                                    href={link.href}
                                    className={`text-xs tracking-[0.18em] uppercase font-semibold transition-colors pb-0.5 ${
                                        isActive(link.href)
                                            ? 'text-[#df2548] border-b-2 border-[#df2548]'
                                            : 'text-[#1b265c] hover:text-[#df2548]'
                                    }`}
                                >
                                    {link.label}
                                </Link>
                            ),
                        )}
                    </nav>

                    {/* CTA + mobile toggle */}
                    <div className="flex items-center gap-3">
                        <Link
                            href="/join"
                            className="hidden lg:inline-flex items-center h-9 px-5 bg-[#df2548] text-white text-xs font-semibold tracking-[0.15em] uppercase hover:bg-[#c01e3d] transition-colors"
                        >
                            Join ABEC
                        </Link>
                        <Link
                            href="/portal"
                            className="hidden lg:inline-flex items-center h-9 px-4 border border-[#1b265c] text-[#1b265c] text-xs font-semibold tracking-[0.15em] uppercase hover:bg-[#1b265c] hover:text-white transition-colors"
                        >
                            #MyABEC
                        </Link>
                        <button
                            onClick={() => setOpen(!open)}
                            className="lg:hidden p-2 text-[#1b265c] hover:text-[#df2548] transition-colors"
                            aria-label="Toggle menu"
                        >
                            {open ? <X size={20} /> : <Menu size={20} />}
                        </button>
                    </div>
                </div>
            </div>

            {/* Mobile menu */}
            {open && (
                <div className="lg:hidden bg-white border-t border-[#d0d4ec]">
                    <div className="max-w-7xl mx-auto px-4 py-6 flex flex-col gap-4">
                        {navLinks.map((link) =>
                            link.sub ? (
                                <div key={link.href} className="border-b border-[#d0d4ec]">
                                    <div className={`text-sm tracking-[0.15em] uppercase font-semibold py-2 ${isActive(link.href) ? 'text-[#df2548]' : 'text-[#1b265c]'}`}>
                                        {link.label}
                                    </div>
                                    <div className="pl-4 pb-2 flex flex-col gap-2">
                                        {link.sub.map((sub) => (
                                            <Link
                                                key={sub.href}
                                                href={sub.href}
                                                className={`text-xs tracking-[0.15em] uppercase font-semibold py-1 ${
                                                    url === sub.href ? 'text-[#df2548]' : 'text-[#555e8a]'
                                                }`}
                                            >
                                                {sub.label}
                                            </Link>
                                        ))}
                                    </div>
                                </div>
                            ) : (
                                <Link
                                    key={link.href}
                                    href={link.href}
                                    className={`text-sm tracking-[0.15em] uppercase font-semibold py-2 border-b border-[#d0d4ec] ${
                                        isActive(link.href) ? 'text-[#df2548]' : 'text-[#1b265c]'
                                    }`}
                                >
                                    {link.label}
                                </Link>
                            ),
                        )}
                        <Link
                            href="/join"
                            className="mt-2 inline-flex items-center justify-center h-11 px-6 bg-[#df2548] text-white text-xs font-semibold tracking-[0.15em] uppercase"
                        >
                            Join ABEC
                        </Link>
                        <Link
                            href="/portal"
                            className="inline-flex items-center justify-center h-11 px-6 border border-[#1b265c] text-[#1b265c] text-xs font-semibold tracking-[0.15em] uppercase"
                        >
                            #MyABEC Portal
                        </Link>
                    </div>
                </div>
            )}
        </header>
    );
}

function FooterNewsletter() {
    const { data, setData, post, processing, wasSuccessful, reset } = useForm({ email: '', name: '' });

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        post('/newsletter/subscribe', { onSuccess: () => reset() });
    };

    return (
        <div>
            <h4 className="text-white/40 text-[10px] tracking-[0.2em] uppercase font-semibold mb-5">
                Stay Updated
            </h4>
            {wasSuccessful ? (
                <p className="text-[#D4A843] text-sm">You're subscribed. Thank you.</p>
            ) : (
                <form onSubmit={handleSubmit} className="space-y-3">
                    <p className="text-white/50 text-sm leading-relaxed">
                        Get updates on programs, research, and events from the ABEC network.
                    </p>
                    <input
                        type="email"
                        required
                        value={data.email}
                        onChange={(e) => setData('email', e.target.value)}
                        placeholder="Your email address"
                        className="w-full bg-white/10 border border-white/20 text-white placeholder:text-white/30 text-sm px-3 py-2 focus:outline-none focus:border-[#D4A843]"
                    />
                    <button
                        type="submit"
                        disabled={processing}
                        className="w-full bg-[#df2548] hover:bg-[#c41e3a] text-white text-xs font-bold tracking-[0.12em] uppercase px-4 py-2.5 transition-colors disabled:opacity-50"
                    >
                        {processing ? 'Subscribing...' : 'Subscribe'}
                    </button>
                </form>
            )}
        </div>
    );
}

function Footer() {
    const { props } = usePage();
    const logoUrl = props.settings?.logo_url as string | undefined;

    return (
        <footer
            style={{
                background: 'linear-gradient(135deg, #111113 0%, #1C1C1E 40%, #1b265c 100%)',
            }}
            className="text-white"
        >
            <div className="border-b border-white/10">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-16">
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-12">
                        {/* Brand */}
                        <div className="lg:col-span-1">
                            <div className="flex items-center gap-3 mb-6">
                                {logoUrl ? (
                                    <img
                                        src={logoUrl}
                                        alt="ABEC Africa"
                                        className="h-10 w-auto object-contain brightness-0 invert"
                                    />
                                ) : (
                                    <>
                                        <div className="w-10 h-10 bg-white/10 border border-white/20 flex items-center justify-center">
                                            <span className="text-white text-sm font-black tracking-tighter">A</span>
                                        </div>
                                        <div>
                                            <div className="text-white font-black text-sm tracking-[0.12em] uppercase">ABEC</div>
                                            <div className="text-white/50 text-[9px] tracking-[0.1em] uppercase mt-0.5">
                                                Est. 2012, Incorporated 2020
                                            </div>
                                        </div>
                                    </>
                                )}
                            </div>
                            <p className="text-white/60 text-sm leading-relaxed">
                                Promoting and Sharing Excellence in Biomedical Engineering to Improve the Health and Wealth of Africa.
                            </p>
                            <div className="flex gap-3 mt-6">
                                <a
                                    href="https://www.facebook.com/abec.africa"
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="w-8 h-8 bg-white/10 hover:bg-[#df2548] flex items-center justify-center transition-colors"
                                    aria-label="Facebook"
                                >
                                    <Facebook size={14} />
                                </a>
                                <a
                                    href="https://www.linkedin.com/company/abec-african-biomedical-engineering-consortium/"
                                    target="_blank"
                                    rel="noopener noreferrer"
                                    className="w-8 h-8 bg-white/10 hover:bg-[#df2548] flex items-center justify-center transition-colors"
                                    aria-label="LinkedIn"
                                >
                                    <Linkedin size={14} />
                                </a>
                            </div>
                        </div>

                        {/* Navigation */}
                        <div>
                            <h4 className="text-white/40 text-[10px] tracking-[0.2em] uppercase font-semibold mb-5">
                                Navigation
                            </h4>
                            <ul className="space-y-3">
                                {[
                                    { label: 'Home', href: '/' },
                                    { label: 'About ABEC', href: '/about' },
                                    { label: 'Governance', href: '/about/governance' },
                                    { label: 'Our Programs', href: '/programs' },
                                    { label: 'Research', href: '/research' },
                                    { label: 'Member Directory', href: '/members' },
                                    { label: 'Join the Consortium', href: '/join' },
                                    { label: 'Contact', href: '/contact' },
                                ].map((link) => (
                                    <li key={link.href}>
                                        <Link
                                            href={link.href}
                                            className="text-white/60 text-sm hover:text-white transition-colors"
                                        >
                                            {link.label}
                                        </Link>
                                    </li>
                                ))}
                            </ul>
                        </div>

                        {/* Newsletter */}
                        <FooterNewsletter />

                        {/* Contact */}
                        <div>
                            <h4 className="text-white/40 text-[10px] tracking-[0.2em] uppercase font-semibold mb-5">
                                Contact
                            </h4>
                            <ul className="space-y-4">
                                <li className="flex gap-3">
                                    <MapPin size={14} className="text-[#df2548] flex-shrink-0 mt-0.5" />
                                    <span className="text-white/60 text-sm leading-relaxed">
                                        Mbaguta Cell, Ruharo
                                        <br />
                                        Mbarara City, Uganda
                                        <br />
                                        P.O. Box 1807, Mbarara
                                    </span>
                                </li>
                                <li className="flex gap-3 items-center">
                                    <Mail size={14} className="text-[#df2548] flex-shrink-0" />
                                    <a
                                        href="mailto:abec.uganda@gmail.com"
                                        className="text-white/60 text-sm hover:text-white transition-colors"
                                    >
                                        abec.uganda@gmail.com
                                    </a>
                                </li>
                                <li className="flex gap-3 items-center">
                                    <Phone size={14} className="text-[#df2548] flex-shrink-0" />
                                    <a
                                        href="tel:+256759542376"
                                        className="text-white/60 text-sm hover:text-white transition-colors"
                                    >
                                        +256 759 542 376
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>

            {/* Bottom bar */}
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-5">
                <div className="flex flex-col sm:flex-row items-center justify-between gap-3">
                    <p className="text-white/30 text-xs tracking-wide">
                        &copy; {new Date().getFullYear()} African Biomedical Engineering Consortium. All rights reserved.
                    </p>
                    <a
                        href="https://www.buildal.net"
                        target="_blank"
                        rel="noopener noreferrer"
                        className="text-white/25 text-xs hover:text-white/50 transition-colors"
                    >
                        Site by Buildal
                    </a>
                </div>
            </div>
        </footer>
    );
}

const ORGANIZATION_LD = {
    '@context': 'https://schema.org',
    '@type': 'Organization',
    '@id': 'https://abecafrica.org/#organization',
    name: 'African Biomedical Engineering Consortium',
    alternateName: 'ABEC Africa',
    url: 'https://abecafrica.org',
    logo: 'https://abecafrica.org/images/abec-logo.png',
    foundingDate: '2020',
    description:
        'ABEC Africa is a pan-African body promoting and sharing excellence in biomedical engineering to improve the health and wealth of Africa. 19+ member institutions across 10+ African countries.',
    address: {
        '@type': 'PostalAddress',
        streetAddress: 'Mbaguta Cell, Ruharo',
        addressLocality: 'Mbarara City',
        addressRegion: 'Western Uganda',
        postalCode: '1807',
        addressCountry: 'UG',
    },
    contactPoint: {
        '@type': 'ContactPoint',
        telephone: '+256-759-542-376',
        email: 'abec.uganda@gmail.com',
        contactType: 'general enquiries',
        availableLanguage: 'English',
    },
    sameAs: [
        'https://www.facebook.com/abec.africa',
        'https://www.linkedin.com/company/abec-african-biomedical-engineering-consortium/',
    ],
    areaServed: 'Africa',
    knowsAbout: ['Biomedical Engineering', 'Biomedical Research', 'Healthcare Technology', 'Medical Devices'],
};

const WEBSITE_LD = {
    '@context': 'https://schema.org',
    '@type': 'WebSite',
    '@id': 'https://abecafrica.org/#website',
    url: 'https://abecafrica.org',
    name: 'ABEC Africa',
    description: 'African Biomedical Engineering Consortium — membership, research, and programs.',
    publisher: { '@id': 'https://abecafrica.org/#organization' },
    potentialAction: {
        '@type': 'SearchAction',
        target: { '@type': 'EntryPoint', urlTemplate: 'https://abecafrica.org/members?search={search_term_string}' },
        'query-input': 'required name=search_term_string',
    },
    inLanguage: 'en-GB',
};

function GoogleAnalytics() {
    const { props } = usePage();
    const gaId = (props.settings as Record<string, string> | undefined)?.google_analytics_id;

    useEffect(() => {
        if (!gaId) return;
        const script = document.createElement('script');
        script.src = `https://www.googletagmanager.com/gtag/js?id=${gaId}`;
        script.async = true;
        document.head.appendChild(script);
        script.onload = () => {
            (window as any).dataLayer = (window as any).dataLayer || [];
            function gtag(...args: any[]) { (window as any).dataLayer.push(args); }
            gtag('js', new Date());
            gtag('config', gaId);
        };
    }, [gaId]);

    return null;
}

export default function PublicLayout({ children }: PropsWithChildren) {
    return (
        <div className="min-h-screen flex flex-col bg-white">
            <Head>
                <script
                    head-key="org-ld"
                    type="application/ld+json"
                    dangerouslySetInnerHTML={{ __html: JSON.stringify([ORGANIZATION_LD, WEBSITE_LD]) }}
                />
            </Head>
            <GoogleAnalytics />
            <Nav />
            <main className="flex-1 pt-16 lg:pt-20">{children}</main>
            <Footer />
        </div>
    );
}
