"use client";

import Link from "./site-link";
import { usePathname } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { mainNavigation } from "../lib/site";
import { whatsappUrl } from "../lib/whatsapp";
import { PortalIcon } from "./portal-icon";
import { PortalLogo } from "./portal-logo";

export function SiteHeader() {
  const pathname = usePathname();
  const [open, setOpen] = useState(false);
  const menuToggle = useRef<HTMLButtonElement>(null);
  const mobileMenu = useRef<HTMLDialogElement>(null);

  useEffect(() => {
    document.body.dataset.menuOpen = open ? "true" : "false";
    const dialog = mobileMenu.current;
    if (open && dialog && !dialog.open) dialog.showModal();
    if (!open && dialog?.open) dialog.close();
    return () => {
      delete document.body.dataset.menuOpen;
    };
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const breakpoint = window.matchMedia("(min-width: 901px)");
    function closeOnDesktop() { if (breakpoint.matches) setOpen(false); }
    breakpoint.addEventListener("change", closeOnDesktop);
    return () => breakpoint.removeEventListener("change", closeOnDesktop);
  }, [open]);

  return (
    <>
      <a className="skip-link" href="#conteudo-principal">
        Pular para o conteúdo
      </a>
      <header className="site-header">
        <div className="shell site-header__inner">
          <Link className="brand" href="/" aria-label="Portal Distribuidora — início">
            <PortalLogo />
          </Link>

          <nav className="desktop-nav" aria-label="Navegação principal">
            {mainNavigation.map((item) => (
              <Link
                key={item.href}
                href={item.href}
                aria-current={pathname === item.href ? "page" : undefined}
                data-active={pathname === item.href || (item.href.startsWith("/solucoes/") && pathname.startsWith("/solucoes/")) || (item.href === "/produtos" && (pathname.startsWith("/produto/") || pathname.startsWith("/produtos/") || pathname.startsWith("/marcas"))) || undefined}
                onClick={() => setOpen(false)}
              >
                {item.label}
              </Link>
            ))}
          </nav>

          <div className="header-actions">
            <a className="button button--primary button--compact desktop-cta" data-cta="header_whatsapp" href={whatsappUrl("Olá, Portal! Vim pelo site e quero solicitar um orçamento de materiais elétricos.")} target="_blank" rel="noopener noreferrer">
              <PortalIcon name="chat" /> Cotar no WhatsApp
            </a>
            <button
              ref={menuToggle}
              data-track-id="menu_abrir" className="menu-toggle"
              type="button"
              aria-expanded={open}
              aria-controls="mobile-menu"
              onClick={() => setOpen((value) => !value)}
            >
              <span className="sr-only">{open ? "Fechar menu" : "Abrir menu"}</span>
              <span aria-hidden="true">{open ? "×" : "Menu"}</span>
            </button>
          </div>
        </div>

        <dialog
          ref={mobileMenu}
          id="mobile-menu"
          className="mobile-menu"
          aria-label="Menu principal"
          onKeyDown={(event) => {
            if (event.key !== "Tab") return;
            const controls = mobileMenu.current?.querySelectorAll<HTMLElement>("button, a[href]");
            if (!controls?.length) return;
            const first = controls[0];
            const last = controls[controls.length - 1];
            if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
            else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
          }}
          onCancel={() => setOpen(false)}
          onClose={() => { setOpen(false); menuToggle.current?.focus(); }}
        >
          <div className="shell mobile-menu__heading"><PortalLogo /><button type="button" onClick={() => setOpen(false)} data-track-id="menu_fechar" aria-label="Fechar menu">Fechar <span aria-hidden="true">×</span></button></div>
          <nav className="shell" aria-label="Navegação móvel">
            {mainNavigation.map((item) => (
              <Link key={item.href} href={item.href} aria-current={pathname === item.href ? "page" : undefined} onClick={() => setOpen(false)}>
                {item.label} <span aria-hidden="true">↗</span>
              </Link>
            ))}
            <Link href="/contato" onClick={() => setOpen(false)}>Contato <span aria-hidden="true">↗</span></Link>
            <a className="button button--primary" data-cta="menu_whatsapp" href={whatsappUrl("Olá, Portal! Quero solicitar um orçamento de materiais elétricos.")} target="_blank" rel="noopener noreferrer" onClick={() => setOpen(false)}>Solicitar orçamento no WhatsApp ↗</a>
            <Link className="button button--ghost-light" href="/orcamento" onClick={() => setOpen(false)}>
              Organizar minha lista de materiais
            </Link>
            <a className="mobile-menu__phone" href="tel:+556232907222">
              Ligar para (62) 3290-7222
            </a>
          </nav>
        </dialog>
      </header>
    </>
  );
}
