"use client";

import Link from "next/link";
import { useEffect, useRef } from "react";
import { ButtonLink } from "@/components/ui/Button";
import { ArrowRight, ChevronDown, Close } from "@/components/ui/Icons";
import { Logo } from "@/components/ui/Logo";
import { getServiceSummary, industryCatalog, serviceGroups } from "@/content/catalog";
import { routes } from "@/lib/routes";

const FOCUSABLE = 'a[href], button:not([disabled]), summary, [tabindex]:not([tabindex="-1"])';

export function MobileNav({ open, onClose }: { open: boolean; onClose: () => void }) {
  const dialogRef = useRef<HTMLDivElement>(null);
  const closeButtonRef = useRef<HTMLButtonElement>(null);
  const onCloseRef = useRef(onClose);

  useEffect(() => {
    onCloseRef.current = onClose;
  }, [onClose]);

  useEffect(() => {
    if (!open) return;
    const previouslyFocused = document.activeElement as HTMLElement | null;
    const root = document.documentElement;
    const previousOverflow = root.style.overflow;
    root.style.overflow = "hidden";
    closeButtonRef.current?.focus();

    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.preventDefault();
        onCloseRef.current();
        return;
      }
      if (event.key !== "Tab" || !dialogRef.current) return;
      const focusable = Array.from(dialogRef.current.querySelectorAll<HTMLElement>(FOCUSABLE)).filter(
        (el) => el.offsetParent !== null,
      );
      if (focusable.length === 0) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };

    document.addEventListener("keydown", onKey);
    return () => {
      root.style.overflow = previousOverflow;
      document.removeEventListener("keydown", onKey);
      previouslyFocused?.focus();
    };
  }, [open]);

  if (!open) return null;

  const linkClass = "flex min-h-12 items-center justify-between border-b border-line text-lg tracking-[-0.01em]";

  return (
    <div
      ref={dialogRef}
      role="dialog"
      aria-modal="true"
      aria-label="Site menu"
      className="mobile-sheet fixed inset-0 z-[60] flex flex-col bg-paper lg:hidden"
    >
      <div className="container-page flex h-16 shrink-0 items-center justify-between border-b border-line">
        <Link href={routes.home} onClick={onClose} aria-label="Axidys Media home" className="-m-1 rounded-sm p-1">
          <Logo />
        </Link>
        <button
          ref={closeButtonRef}
          type="button"
          onClick={onClose}
          aria-label="Close menu"
          className="inline-flex size-11 items-center justify-center rounded-md hover:bg-paper-deep"
        >
          <Close size={22} />
        </button>
      </div>

      <nav aria-label="Mobile" className="container-page flex-1 overflow-y-auto pb-8 pt-2">
        <details className="group border-b border-line" open>
          <summary className="flex min-h-14 cursor-pointer items-center justify-between text-lg tracking-[-0.01em]">
            Services
            <ChevronDown size={18} className="transition-transform duration-300 group-open:rotate-180" />
          </summary>
          <div className="space-y-6 pb-6">
            {serviceGroups.map((group) => (
              <div key={group.label}>
                <p className="text-label uppercase text-muted">{group.label}</p>
                <ul className="mt-2">
                  {group.slugs.map((slug) => (
                    <li key={slug}>
                      <Link href={routes.service(slug)} onClick={onClose} className="flex min-h-11 items-center text-ink-soft">
                        {getServiceSummary(slug).name}
                      </Link>
                    </li>
                  ))}
                </ul>
              </div>
            ))}
          </div>
        </details>

        <details className="group border-b border-line">
          <summary className="flex min-h-14 cursor-pointer items-center justify-between text-lg tracking-[-0.01em]">
            Industries
            <ChevronDown size={18} className="transition-transform duration-300 group-open:rotate-180" />
          </summary>
          <ul className="pb-4">
            {industryCatalog.map((industry) => (
              <li key={industry.href}>
                <Link href={industry.href} onClick={onClose} className="flex min-h-11 items-center text-ink-soft">
                  {industry.title}
                </Link>
              </li>
            ))}
          </ul>
        </details>

        {[
          { label: "How We Work", href: routes.howWeWork },
          { label: "Resources", href: routes.resources },
          { label: "About", href: routes.about },
          { label: "Contact", href: routes.contact },
        ].map((link) => (
          <Link key={link.href} href={link.href} onClick={onClose} className={linkClass}>
            {link.label}
            <ArrowRight size={16} />
          </Link>
        ))}
      </nav>

      <div className="container-page shrink-0 border-t border-line py-4">
        <ButtonLink href={routes.audit} size="lg" className="w-full">
          Get a Growth Audit
        </ButtonLink>
      </div>
    </div>
  );
}
