'use client';

import Link from 'next/link';
import { usePathname } from 'next/navigation';
import { useEffect, useRef, useState } from 'react';
import { BookOpenIcon, BriefcaseIcon, CompassIcon, MenuIcon, ScaleIcon, SearchIcon, XIcon } from './Icons';
import { AccountLink } from './AccountWidgets';

const LINKS = [
  { href: '/practice-areas/', label: 'Practice areas', Icon: ScaleIcon },
  { href: '/methodology/', label: 'How we rank', Icon: BookOpenIcon },
  { href: '/search/', label: 'Search', Icon: SearchIcon },
] as const;

const isActive = (path: string | null, href: string) => !!path && (path === href || path.startsWith(href));

/** Desktop links with an active underline, plus a mobile sheet that closes on navigation, Escape and outside clicks */
export function HeaderNav() {
  const path = usePathname();
  const [open, setOpen] = useState(false);
  const panel = useRef<HTMLDivElement>(null);
  const toggle = useRef<HTMLButtonElement>(null);

  useEffect(() => setOpen(false), [path]);
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => {
      if (e.key === 'Escape') {
        setOpen(false);
        toggle.current?.focus();
      }
    };
    const onClick = (e: MouseEvent) => {
      const t = e.target as Node;
      if (!panel.current?.contains(t) && !toggle.current?.contains(t)) setOpen(false);
    };
    document.addEventListener('keydown', onKey);
    document.addEventListener('mousedown', onClick);
    return () => {
      document.removeEventListener('keydown', onKey);
      document.removeEventListener('mousedown', onClick);
    };
  }, [open]);

  return (
    <>
      <nav aria-label="Main" className="ml-auto hidden items-center gap-1 text-sm font-medium md:flex">
        {LINKS.filter((l) => l.href !== '/search/').map(({ href, label }) => {
          const active = isActive(path, href);
          return (
            <Link
              key={href}
              href={href}
              aria-current={active ? 'page' : undefined}
              className={`relative rounded-md px-3 py-2 transition-colors hover:bg-sunken hover:text-ink ${active ? 'text-ink after:absolute after:inset-x-3 after:-bottom-[0.6rem] after:h-0.5 after:rounded-full after:bg-ledger' : 'text-ink-2'}`}
            >
              {label}
            </Link>
          );
        })}
        <AccountLink />
        <Link href="/for-lawyers/" aria-current={isActive(path, '/for-lawyers/') ? 'page' : undefined} className="btn btn-quiet btn-sm ml-2">
          <BriefcaseIcon className="h-4 w-4 text-ledger" />
          For lawyers
        </Link>
      </nav>

      <button
        ref={toggle}
        type="button"
        className="btn btn-ghost btn-icon ml-auto md:hidden"
        aria-expanded={open}
        aria-controls="mobile-nav"
        aria-label={open ? 'Close menu' : 'Open menu'}
        onClick={() => setOpen((o) => !o)}
      >
        {open ? <XIcon className="h-5 w-5" /> : <MenuIcon className="h-5 w-5" />}
      </button>

      {open && (
        <div ref={panel} id="mobile-nav" className="pop-in absolute inset-x-0 top-full z-40 border-b border-rule bg-surface shadow-lg md:hidden">
          <nav aria-label="Mobile" className="mx-auto max-w-6xl space-y-1 px-4 py-3">
            {[...LINKS, { href: '/for-lawyers/', label: 'For lawyers', Icon: BriefcaseIcon }, { href: '/about/', label: 'About Justice Choice', Icon: CompassIcon }].map(({ href, label, Icon }) => {
              const active = isActive(path, href);
              return (
                <Link
                  key={href}
                  href={href}
                  aria-current={active ? 'page' : undefined}
                  className={`flex items-center gap-3 rounded-lg px-3 py-3 text-[0.95rem] font-medium transition-colors ${active ? 'bg-ledger-soft text-ledger' : 'text-ink-2 hover:bg-sunken hover:text-ink active:bg-ledger-soft'}`}
                >
                  <Icon className="h-5 w-5" />
                  {label}
                </Link>
              );
            })}
            <AccountLink className="w-full px-3 py-3 text-[0.95rem]" />
          </nav>
        </div>
      )}
    </>
  );
}
