import { useEffect, useRef } from 'react';
import { Check, ChevronDown } from '@/site/components/ui/icons';
import { useShared } from '@/site/hooks/use-shared';
import { useT } from '@/site/i18n';
import { cx } from '@/site/lib/cx';
import { flags } from '@/site/lib/flags';
import type { Alternate } from '@/site/types';

type LanguageSwitcherProps = {
    /**
     * `menu`: a compact button that opens a list (header).
     * `inline`: every language side by side (footer, mobile menu).
     */
    variant?: 'menu' | 'inline';
    className?: string;
};

/**
 * Links to the current page in every language, each with the flag of its
 * country. They are plain <a> elements on purpose: switching language is a
 * full page load (new <html lang>, fonts and dictionary) and the links stay
 * crawlable with their hreflang (docs/I18N.md §3, docs/SEO.md §6).
 *
 * The menu is a native <details>: it opens without JavaScript; the script
 * only adds closing on Escape, on a click elsewhere and when focus leaves.
 */
export function LanguageSwitcher({
    variant = 'inline',
    className,
}: LanguageSwitcherProps) {
    const { alternates, locale } = useShared();
    const t = useT();
    const ref = useRef<HTMLDetailsElement>(null);

    useEffect(() => {
        const details = ref.current;

        if (!details) {
            return;
        }

        const close = () => details.removeAttribute('open');

        const onPointerDown = (event: PointerEvent) => {
            if (!details.contains(event.target as Node)) {
                close();
            }
        };

        const onKeyDown = (event: KeyboardEvent) => {
            if (event.key === 'Escape' && details.open) {
                close();
                details.querySelector('summary')?.focus();
            }
        };

        const onFocusOut = (event: FocusEvent) => {
            if (!details.contains(event.relatedTarget as Node | null)) {
                close();
            }
        };

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

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

    if (alternates.length < 2) {
        return null;
    }

    const current =
        alternates.find((alternate) => alternate.code === locale) ??
        alternates[0];

    if (variant === 'inline') {
        return (
            <nav aria-label={t.common.language} className={className}>
                <ul className="flex flex-wrap items-center gap-2">
                    {alternates.map((alternate) => (
                        <li key={alternate.code}>
                            <LanguageLink
                                alternate={alternate}
                                current={alternate.code === locale}
                                className="border-line data-[current]:border-line-strong rounded-full border px-3.5 py-2"
                            />
                        </li>
                    ))}
                </ul>
            </nav>
        );
    }

    return (
        <nav aria-label={t.common.language} className={className}>
            <details ref={ref} className="group relative">
                <summary className="text-fg/85 hover:text-fg flex cursor-pointer list-none items-center gap-2 rounded-full py-2 ps-2 pe-1.5 text-xs font-semibold tracking-[0.14em] transition-colors duration-300 [&::-webkit-details-marker]:hidden">
                    <Flag code={current.flag} />
                    <span aria-hidden="true">{current.short}</span>
                    <span className="sr-only">
                        {t.common.languageCurrent(current.name)}
                    </span>
                    <ChevronDown className="ease-out-expo size-3.5 transition-transform duration-500 group-open:rotate-180" />
                </summary>

                <ul className="lang-menu border-line bg-ink-2 absolute end-0 top-full z-10 mt-2 min-w-44 rounded-md border p-1.5 shadow-2xl">
                    {alternates.map((alternate) => (
                        <li key={alternate.code}>
                            <LanguageLink
                                alternate={alternate}
                                current={alternate.code === locale}
                                className="hover:bg-ink-3 rounded-sm px-3 py-2.5"
                                check
                            />
                        </li>
                    ))}
                </ul>
            </details>
        </nav>
    );
}

function LanguageLink({
    alternate,
    current,
    className,
    check = false,
}: {
    alternate: Alternate;
    current: boolean;
    className?: string;
    /** Mark the current language with a check at the end of the row. */
    check?: boolean;
}) {
    return (
        <a
            href={alternate.url}
            hrefLang={alternate.code}
            lang={alternate.code}
            aria-current={current ? 'true' : undefined}
            data-current={current ? '' : undefined}
            className={cx(
                'flex items-center gap-3 text-sm transition-colors duration-300',
                current ? 'text-fg' : 'text-fg/70 hover:text-fg',
                className,
            )}
        >
            <Flag code={alternate.flag} />
            <span className="grow">{alternate.name}</span>
            {check && current ? (
                <Check className="text-accent-fg size-4" />
            ) : null}
        </a>
    );
}

/** The flag of a country, drawn at a fixed 3:2 size; nothing for an unknown code. */
function Flag({ code }: { code: string }) {
    const Svg = flags[code];

    return Svg ? (
        <Svg
            aria-hidden="true"
            className="ring-line-strong h-3.5 w-[1.3125rem] shrink-0 rounded-[2px] ring-1"
        />
    ) : null;
}
