import { router } from '@inertiajs/react';
import { useEffect, useRef, useState } from 'react';
import type { ReactNode, RefObject } from 'react';
import { CategoryIcon } from '@/site/components/art/category-icon';
import { ButtonLink } from '@/site/components/ui/button';
import {
    ArrowRight,
    ChevronDown,
    Close,
    Menu,
} from '@/site/components/ui/icons';
import { SiteLink } from '@/site/components/ui/link';
import { useShared } from '@/site/hooks/use-shared';
import { useT } from '@/site/i18n';
import { cx } from '@/site/lib/cx';
import { subscribeScroll } from '@/site/lib/scroll-engine';
import type {
    Accent,
    AreaGroup,
    Nav,
    NavCategory,
    NavLink,
} from '@/site/types';
import { LanguageSwitcher } from './language-switcher';
import { Logo } from './logo';
import { TopBar } from './top-bar';

const MEGA_ID = 'site-mega-menu';

/**
 * Fixed site header: transparent over the hero, frosted once the page is
 * scrolled, tucked away while scrolling down. Holds the main navigation,
 * the treatments mega menu (desktop) and the full-screen menu (mobile).
 *
 * The two menu panels are rendered on first use, not on the server: they
 * hold some 80 links, which would otherwise add ~30 KB of HTML and a few
 * hundred DOM nodes to every page. Crawlers do not need them — every area
 * is linked from the footer and every treatment from /tedaviler and from
 * its area page.
 */
export function SiteHeader() {
    const { nav } = useShared();
    const t = useT();

    const headerRef = useRef<HTMLElement>(null);
    const triggerRef = useRef<HTMLButtonElement>(null);
    const dialogRef = useRef<HTMLDialogElement>(null);
    const closeTimer = useRef<number | undefined>(undefined);

    const [megaOpen, setMegaOpen] = useState(false);
    // Panels mount the first time they are needed and stay mounted afterwards.
    const [megaMounted, setMegaMounted] = useState(false);
    const [menuMounted, setMenuMounted] = useState(false);
    const [activeKey, setActiveKey] = useState(nav.categories[0]?.key ?? '');

    // Scroll state lives on the DOM node: no React render while scrolling.
    useEffect(() => {
        const header = headerRef.current;

        if (!header) {
            return;
        }

        let last = window.scrollY;

        return subscribeScroll((y) => {
            header.toggleAttribute('data-scrolled', y > 12);

            if (Math.abs(y - last) > 8) {
                header.toggleAttribute('data-hidden', y > last && y > 560);
                last = y;
            }
        });
    }, []);

    // Any visit closes the menus: "start" fires when a page is requested,
    // "navigate" when it is shown. Both are needed — a page already
    // prefetched on hover comes from the cache without a request, so on
    // "start" alone the menu stayed open over the new page and the visitor
    // could not tell that anything had happened. Prefetch requests fire
    // "start" too and are ignored: closing on them would shut the menu while
    // the pointer travels down the list.
    useEffect(() => {
        const close = () => {
            setMegaOpen(false);
            dialogRef.current?.close();
        };
        const offStart = router.on('start', (event) => {
            if (!event.detail.visit.prefetch) {
                close();
            }
        });
        const offNavigate = router.on('navigate', close);

        return () => {
            offStart();
            offNavigate();
        };
    }, []);

    useEffect(() => {
        if (!megaOpen) {
            return;
        }

        const onKeyDown = (event: KeyboardEvent) => {
            if (event.key === 'Escape') {
                setMegaOpen(false);
                triggerRef.current?.focus();
            }
        };

        const onPointerDown = (event: PointerEvent) => {
            if (!headerRef.current?.contains(event.target as Node)) {
                setMegaOpen(false);
            }
        };

        document.addEventListener('keydown', onKeyDown);
        document.addEventListener('pointerdown', onPointerDown);

        return () => {
            document.removeEventListener('keydown', onKeyDown);
            document.removeEventListener('pointerdown', onPointerDown);
        };
    }, [megaOpen]);

    const openMega = () => {
        window.clearTimeout(closeTimer.current);
        setMegaMounted(true);
        setMegaOpen(true);
    };

    const toggleMega = () => {
        setMegaMounted(true);
        setMegaOpen((open) => !open);
    };

    const openMenu = () => {
        setMenuMounted(true);
        dialogRef.current?.showModal();
    };

    // A short grace period lets the pointer travel from the trigger to the panel.
    const closeMegaSoon = () => {
        window.clearTimeout(closeTimer.current);
        closeTimer.current = window.setTimeout(() => setMegaOpen(false), 180);
    };

    const linkClass =
        'link-underline py-2 text-sm font-medium text-fg/85 transition-colors duration-300 hover:text-fg';

    return (
        <header
            ref={headerRef}
            data-mega={megaOpen ? '' : undefined}
            className={cx(
                // Position and the top bar sliding away: `.site-header` in site.css.
                'site-header stage-dark fixed inset-x-0 top-0 z-50 border-b border-transparent bg-transparent',
                'transition-[translate,background-color,border-color] duration-500 ease-out-expo',
                // Navy, unlike near-black, turns lavender when thinned over the light stage: kept dense.
                'data-[scrolled]:border-line data-[scrolled]:bg-ink/90 data-[scrolled]:backdrop-blur-xl',
                'data-[mega]:border-line data-[mega]:bg-ink',
            )}
            onMouseLeave={closeMegaSoon}
        >
            <TopBar />
            <div className="shell flex h-(--header-h) items-center justify-between gap-6">
                <Logo priority />

                <nav aria-label={t.common.mainNav} className="hidden lg:block">
                    <ul className="flex items-center gap-9">
                        <li>
                            <button
                                ref={triggerRef}
                                type="button"
                                aria-expanded={megaOpen}
                                aria-controls={MEGA_ID}
                                onClick={toggleMega}
                                onMouseEnter={openMega}
                                className={cx(
                                    linkClass,
                                    'inline-flex items-center gap-1.5',
                                )}
                            >
                                {nav.pages.treatments.label}
                                <ChevronDown
                                    className={cx(
                                        'size-4 transition-transform duration-500 ease-out-expo',
                                        megaOpen && 'rotate-180',
                                    )}
                                />
                            </button>
                        </li>
                        {pageLinks(nav).map((link) => (
                            <li key={link.url} onMouseEnter={closeMegaSoon}>
                                <SiteLink href={link.url} className={linkClass}>
                                    {link.label}
                                </SiteLink>
                            </li>
                        ))}
                    </ul>
                </nav>

                <div className="flex items-center gap-1 sm:gap-4">
                    <LanguageSwitcher variant="menu" />
                    {/* Wrapped: the button sets its own display, so hide the wrapper. */}
                    <div className="hidden sm:block">
                        <ButtonLink href={nav.pages.contact.url} arrow={false}>
                            {t.common.appointment}
                        </ButtonLink>
                    </div>
                    <button
                        type="button"
                        aria-haspopup="dialog"
                        aria-label={t.common.menu}
                        onClick={openMenu}
                        className="-me-2 grid size-11 place-items-center rounded-full lg:hidden"
                    >
                        <Menu className="size-6" />
                    </button>
                </div>
            </div>

            {megaMounted ? (
                <MegaMenu
                    nav={nav}
                    open={megaOpen}
                    activeKey={activeKey}
                    onActivate={setActiveKey}
                    onMouseEnter={openMega}
                />
            ) : null}

            <MobileMenu nav={nav} dialogRef={dialogRef} mounted={menuMounted} />
        </header>
    );
}

/** Top-level pages after "Tedaviler", in menu order (the blog once it has posts). */
function pageLinks(nav: Nav): NavLink[] {
    return [
        nav.pages.about,
        nav.pages.blog,
        nav.pages.faq,
        nav.pages.contact,
    ].filter((link): link is NavLink => link !== undefined);
}

type AreaRun = { group: AreaGroup | null; categories: NavCategory[] };

/**
 * The areas as the menus list them: one after another, the areas of a
 * named group (medical aesthetics, the other areas) together under its
 * name — docs/DECISIONS.md K37. The server sends them in that order.
 */
function areaRuns(nav: Nav): AreaRun[] {
    const runs: AreaRun[] = [];

    for (const category of nav.categories) {
        const last = runs.at(-1);

        if (category.group !== null && last?.group?.key === category.group) {
            last.categories.push(category);

            continue;
        }

        runs.push({
            group:
                nav.groups.find((group) => group.key === category.group) ??
                null,
            categories: [category],
        });
    }

    return runs;
}

/** One row of the areas list: an area, or a department of several areas. */
type AreaEntry = {
    /** What the mega menu shows on hover: the area's key, or `group:` + the department's. */
    key: string;
    name: string;
    url: string;
    icon: string;
    accent: Accent;
    /** Treatments in it. */
    count: number;
};

const areaEntry = (category: NavCategory): AreaEntry => ({
    key: category.key,
    name: category.name,
    url: category.url,
    icon: category.icon,
    accent: category.accent,
    count: category.treatments.length,
});

const departmentEntry = (
    group: AreaGroup,
    areas: NavCategory[],
): AreaEntry => ({
    key: `group:${group.key}`,
    name: group.name,
    url: group.url ?? areas[0].url,
    icon: group.icon ?? areas[0].icon,
    accent: group.accent ?? areas[0].accent,
    count: areas.reduce((sum, area) => sum + area.treatments.length, 0),
});

/**
 * The areas of a menu, as two sections (docs/DECISIONS.md K37): the main
 * departments — hair, dental, medical aesthetics, men's health — as rows
 * of equal rank, medical aesthetics with its own areas set in under it;
 * then, under a rule and a heading, the other areas.
 */
function AreaList({
    nav,
    row,
    nested,
    heading,
}: {
    nav: Nav;
    /** The link of one row. */
    row: (entry: AreaEntry) => ReactNode;
    /** Classes of the list of a department's areas (indent and rule). */
    nested: string;
    /** Classes of the "other areas" heading. */
    heading: string;
}) {
    const item = (entry: AreaEntry, children?: ReactNode) => (
        <li key={entry.key} data-accent={entry.accent}>
            {row(entry)}
            {children}
        </li>
    );

    return (
        <ul>
            {areaRuns(nav).map(({ group, categories }) => {
                if (group?.kind === 'department') {
                    return item(
                        departmentEntry(group, categories),
                        <ul aria-label={group.name} className={nested}>
                            {categories.map((area) => item(areaEntry(area)))}
                        </ul>,
                    );
                }

                if (group?.kind === 'others') {
                    return (
                        <li
                            key={group.key}
                            className="border-line mt-4 border-t pt-4"
                        >
                            <p
                                className={cx(
                                    'text-eyebrow text-soft pb-2 font-semibold uppercase',
                                    heading,
                                )}
                            >
                                {group.name}
                            </p>
                            <ul aria-label={group.name}>
                                {categories.map((area) =>
                                    item(areaEntry(area)),
                                )}
                            </ul>
                        </li>
                    );
                }

                return categories.map((area) => item(areaEntry(area)));
            })}
        </ul>
    );
}

type MegaMenuProps = {
    nav: Nav;
    open: boolean;
    activeKey: string;
    onActivate: (key: string) => void;
    onMouseEnter: () => void;
};

function MegaMenu({
    nav,
    open,
    activeKey,
    onActivate,
    onMouseEnter,
}: MegaMenuProps) {
    const t = useT();

    return (
        <div
            id={MEGA_ID}
            hidden={!open}
            onMouseEnter={onMouseEnter}
            className="mega-panel border-line bg-ink absolute inset-x-0 top-full hidden max-h-[calc(100dvh-var(--header-h))] overflow-y-auto border-b lg:block"
        >
            <div className="shell grid grid-cols-12 gap-10 py-10">
                <div className="col-span-4">
                    <p className="text-eyebrow text-soft mb-4 px-3 font-semibold uppercase">
                        {t.header.departments}
                    </p>
                    <AreaList
                        nav={nav}
                        nested="border-line ms-[1.625rem] border-s ps-2"
                        heading="px-3"
                        row={(entry) => {
                            const active = entry.key === activeKey;

                            return (
                                <SiteLink
                                    href={entry.url}
                                    onMouseEnter={() => onActivate(entry.key)}
                                    onFocus={() => onActivate(entry.key)}
                                    className={cx(
                                        'group flex items-center gap-4 rounded-md px-3 py-2 transition-colors duration-300',
                                        active
                                            ? 'bg-ink-3 text-fg'
                                            : 'text-fg/70 hover:text-fg',
                                    )}
                                >
                                    <CategoryIcon
                                        name={entry.icon}
                                        className={cx(
                                            'size-7 shrink-0 transition-colors duration-300',
                                            active
                                                ? 'text-accent'
                                                : 'text-soft',
                                        )}
                                    />
                                    <span className="grow font-medium">
                                        {entry.name}
                                    </span>
                                    <span className="text-soft text-xs tabular-nums">
                                        {entry.count}
                                    </span>
                                </SiteLink>
                            );
                        }}
                    />
                    <SiteLink
                        href={nav.pages.treatments.url}
                        className="text-accent-fg mt-5 inline-flex items-center gap-2 px-3 text-sm font-medium"
                    >
                        <span className="link-underline">
                            {t.header.allTreatments}
                        </span>
                        <ArrowRight className="size-4" />
                    </SiteLink>
                </div>

                <div className="border-line col-span-8 border-s ps-10">
                    {/* A department of several areas: its promise and its areas. */}
                    {nav.groups.map((group) =>
                        group.kind === 'department' ? (
                            <div
                                key={group.key}
                                hidden={`group:${group.key}` !== activeKey}
                                data-accent={group.accent ?? undefined}
                            >
                                <p className="font-display text-display-4">
                                    {group.name}
                                </p>
                                {group.tagline ? (
                                    <p className="text-soft mt-2 max-w-xl">
                                        {group.tagline}
                                    </p>
                                ) : null}
                                <ul
                                    aria-label={t.header.departmentAreas(
                                        group.name,
                                    )}
                                    className="mt-7 grid grid-cols-2 gap-x-10 xl:grid-cols-3"
                                >
                                    {nav.categories
                                        .filter(
                                            (area) => area.group === group.key,
                                        )
                                        .map((area) => (
                                            <li
                                                key={area.key}
                                                data-accent={area.accent}
                                            >
                                                <SiteLink
                                                    href={area.url}
                                                    className="text-fg/75 hover:text-accent-fg flex items-center gap-3 py-2 text-sm transition-colors duration-300"
                                                >
                                                    <CategoryIcon
                                                        name={area.icon}
                                                        className="size-5 shrink-0 text-accent"
                                                    />
                                                    <span className="grow">
                                                        {area.name}
                                                    </span>
                                                    <span className="text-soft text-xs tabular-nums">
                                                        {area.treatments.length}
                                                    </span>
                                                </SiteLink>
                                            </li>
                                        ))}
                                </ul>
                            </div>
                        ) : null,
                    )}
                    {nav.categories.map((category) => (
                        <div
                            key={category.key}
                            hidden={category.key !== activeKey}
                            data-accent={category.accent}
                        >
                            <p className="font-display text-display-4">
                                {category.name}
                            </p>
                            <p className="text-soft mt-2 max-w-xl">
                                {category.tagline}
                            </p>
                            <ul
                                aria-label={t.header.areaTreatments(
                                    category.name,
                                )}
                                className="mt-7 columns-2 gap-x-10 xl:columns-3"
                            >
                                {category.treatments.map((treatment) => (
                                    <li
                                        key={treatment.key}
                                        className="break-inside-avoid"
                                    >
                                        <SiteLink
                                            href={treatment.url}
                                            className="text-fg/75 hover:text-accent-fg block py-1.5 text-sm transition-colors duration-300"
                                        >
                                            {treatment.name}
                                        </SiteLink>
                                    </li>
                                ))}
                            </ul>
                        </div>
                    ))}
                </div>
            </div>
        </div>
    );
}

type MobileMenuProps = {
    nav: Nav;
    dialogRef: RefObject<HTMLDialogElement | null>;
    /** Whether the menu has been opened at least once (its content renders from then on). */
    mounted: boolean;
};

/**
 * Full-screen menu for small screens, built on a native <dialog>: focus is
 * trapped, Esc closes it and the page behind is inert — all by the browser.
 */
function MobileMenu({ nav, dialogRef, mounted }: MobileMenuProps) {
    const t = useT();
    const close = () => dialogRef.current?.close();

    return (
        <dialog
            ref={dialogRef}
            aria-label={t.common.menu}
            className="menu-dialog stage-dark m-0 h-dvh max-h-none w-screen max-w-none overflow-y-auto p-0 lg:hidden"
        >
            {mounted ? <MobileMenuContent nav={nav} onClose={close} /> : null}
        </dialog>
    );
}

function MobileMenuContent({
    nav,
    onClose,
}: {
    nav: Nav;
    onClose: () => void;
}) {
    const t = useT();

    return (
        <>
            <div className="shell flex min-h-full flex-col pb-10">
                <div className="flex h-(--header-h) shrink-0 items-center justify-between">
                    <Logo />
                    <button
                        type="button"
                        aria-label={t.common.close}
                        onClick={onClose}
                        className="-me-2 grid size-11 place-items-center rounded-full"
                    >
                        <Close className="size-6" />
                    </button>
                </div>

                <nav aria-label={t.common.mainNav} className="mt-6 grow">
                    <details className="group border-line border-b" open>
                        <summary className="font-display text-display-4 flex cursor-pointer list-none items-center justify-between py-4 [&::-webkit-details-marker]:hidden">
                            {nav.pages.treatments.label}
                            <ChevronDown className="text-soft ease-out-expo size-6 transition-transform duration-500 group-open:rotate-180" />
                        </summary>
                        <p className="text-eyebrow text-soft pt-1 pb-2 font-semibold uppercase">
                            {t.header.departments}
                        </p>
                        <AreaList
                            nav={nav}
                            nested="border-line ms-3 border-s ps-4"
                            heading=""
                            row={(entry) => (
                                <SiteLink
                                    href={entry.url}
                                    className="text-fg/85 flex items-center gap-4 py-2.5"
                                >
                                    <CategoryIcon
                                        name={entry.icon}
                                        className="size-6 shrink-0 text-accent"
                                    />
                                    <span className="grow">{entry.name}</span>
                                    <span className="text-soft text-xs tabular-nums">
                                        {entry.count}
                                    </span>
                                </SiteLink>
                            )}
                        />
                        <SiteLink
                            href={nav.pages.treatments.url}
                            className="text-accent-fg mt-2 mb-5 inline-flex items-center gap-2 py-2 text-sm font-medium"
                        >
                            {t.header.allTreatments}
                            <ArrowRight className="size-4" />
                        </SiteLink>
                    </details>

                    <ul>
                        {pageLinks(nav).map((link) => (
                            <li key={link.url} className="border-line border-b">
                                <SiteLink
                                    href={link.url}
                                    className="font-display text-display-4 block py-4"
                                >
                                    {link.label}
                                </SiteLink>
                            </li>
                        ))}
                    </ul>
                </nav>

                <div className="mt-10 flex flex-col gap-6">
                    <ButtonLink href={nav.pages.contact.url} size="lg">
                        {t.common.appointmentLong}
                    </ButtonLink>
                    <LanguageSwitcher />
                </div>
            </div>
        </>
    );
}
