'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { buttonStyles } from '@/components/ui/Button';
import { ArrowRightIcon, MenuIcon, XIcon } from '@/components/ui/icons';
import { cn } from '@/lib/cn';
import type { NavItem } from '@/lib/site';

function isActive(pathname: string, href: string): boolean {
  return pathname === href || pathname.startsWith(`${href}/`);
}

/**
 * Header navigation: desktop link row plus the mobile disclosure menu. Client-side only for
 * aria-current and the menu state; everything else in the header is server-rendered.
 */
export function SiteNav({ items }: { items: readonly NavItem[] }) {
  const pathname = usePathname();
  const [open, setOpen] = useState(false);
  const [lastPath, setLastPath] = useState(pathname);
  const toggleRef = useRef<HTMLButtonElement>(null);

  // Close the menu whenever the route changes (incl. back/forward), without an effect.
  if (pathname !== lastPath) {
    setLastPath(pathname);
    setOpen(false);
  }

  useEffect(() => {
    if (!open) return;
    const root = document.documentElement;
    const previousOverflow = root.style.overflow;
    root.style.overflow = 'hidden';
    const onKey = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        setOpen(false);
        toggleRef.current?.focus();
      }
    };
    // The panel is hidden at lg+, so close it if the viewport grows while it is open.
    const desktop = window.matchMedia('(min-width: 64rem)');
    const onResize = () => desktop.matches && setOpen(false);
    document.addEventListener('keydown', onKey);
    desktop.addEventListener('change', onResize);
    return () => {
      root.style.overflow = previousOverflow;
      document.removeEventListener('keydown', onKey);
      desktop.removeEventListener('change', onResize);
    };
  }, [open]);

  return (
    <>
      <nav aria-label="Main" className="hidden lg:block">
        <ul className="flex items-center gap-1">
          {items.map((item) => {
            const active = isActive(pathname, item.href);
            return (
              <li key={item.href}>
                <Link
                  href={item.href}
                  aria-current={active ? 'page' : undefined}
                  className={cn(
                    'relative inline-flex min-h-11 items-center rounded-lg px-3.5 text-[0.9375rem] font-medium transition-colors',
                    active ? 'text-fg' : 'text-muted hover:bg-white/[0.05] hover:text-fg',
                  )}
                >
                  {item.label}
                  {active && (
                    <span
                      aria-hidden="true"
                      className="absolute inset-x-3.5 -bottom-px h-0.5 rounded-full bg-[linear-gradient(90deg,var(--color-violet),var(--color-cyan))]"
                    />
                  )}
                </Link>
              </li>
            );
          })}
        </ul>
      </nav>

      <button
        ref={toggleRef}
        type="button"
        className="inline-flex size-12 items-center justify-center rounded-xl border border-line-strong/70 bg-raised/70 text-fg transition-colors hover:border-violet-soft lg:hidden"
        aria-expanded={open}
        aria-controls="mobile-menu"
        onClick={() => setOpen((value) => !value)}
      >
        <span className="sr-only">{open ? 'Close menu' : 'Open menu'}</span>
        {open ? <XIcon className="size-6" /> : <MenuIcon className="size-6" />}
      </button>

      <div
        id="mobile-menu"
        hidden={!open}
        className="glass fixed inset-x-0 top-16 bottom-0 z-40 overflow-y-auto border-t border-line/70 lg:hidden"
      >
        <nav aria-label="Mobile" className="container-page flex flex-col gap-6 py-6 motion-safe:animate-rise">
          <ul className="flex flex-col divide-y divide-line/60 border-y border-line/60">
            {items.map((item) => {
              const active = isActive(pathname, item.href);
              return (
                <li key={item.href}>
                  <Link
                    href={item.href}
                    aria-current={active ? 'page' : undefined}
                    onClick={() => setOpen(false)}
                    className={cn(
                      'flex min-h-14 items-center justify-between font-display text-lg font-semibold',
                      active ? 'text-cyan' : 'text-fg',
                    )}
                  >
                    {item.label}
                    <ArrowRightIcon className="size-5 text-subtle" />
                  </Link>
                </li>
              );
            })}
          </ul>
          <Link href="/pilot" onClick={() => setOpen(false)} className={buttonStyles({ size: 'lg', fullWidth: true })}>
            Join the pilot
            <ArrowRightIcon />
          </Link>
          <p className="text-center text-sm text-subtle">No app. No sign-up. No wagering.</p>
        </nav>
      </div>
    </>
  );
}
