"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useState } from "react";
import { Logo } from "@/components/logo";
import { Icon } from "@/components/icons";
import { Button } from "@/components/ui";
import { primaryNav, site, type NavItem } from "@/content/site";

function isActive(pathname: string, href: string) {
  const base = href.split("#")[0];
  if (base === "/") return pathname === "/";
  return pathname === base || pathname.startsWith(`${base}/`);
}

export function SiteHeader() {
  const pathname = usePathname();
  const [open, setOpen] = useState(false);
  const [scrolled, setScrolled] = useState(false);
  const [expanded, setExpanded] = useState<string | null>(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 8);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Close the mobile menu whenever the route changes (React's recommended
  // "adjust state during render" pattern — no effect needed).
  const [lastPath, setLastPath] = useState(pathname);
  if (pathname !== lastPath) {
    setLastPath(pathname);
    setOpen(false);
    setExpanded(null);
  }

  useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => {
      document.body.style.overflow = "";
    };
  }, [open]);

  return (
    <header
      className={`sticky top-0 z-50 border-b transition-colors ${
        scrolled
          ? "border-ink-100 bg-cream/90 backdrop-blur"
          : "border-transparent bg-cream"
      }`}
    >
      <div className="container-page flex h-18 items-center justify-between gap-4 py-3">
        <Logo />

        <nav aria-label="Primary" className="hidden lg:block">
          <ul className="flex items-center gap-1">
            {primaryNav
              .filter((item) => item.label !== "Home")
              .map((item) => (
                <li key={item.label} className="group relative">
                  <Link
                    href={item.href}
                    className={`flex items-center gap-1 rounded-full px-3.5 py-2 text-sm font-medium transition-colors ${
                      isActive(pathname, item.href)
                        ? "text-brand-700"
                        : "text-ink-600 hover:text-ink-900"
                    }`}
                  >
                    {item.label}
                    {item.children && (
                      <Icon
                        name="chevron-down"
                        className="h-3.5 w-3.5 transition-transform group-hover:rotate-180"
                      />
                    )}
                  </Link>

                  {item.children && (
                    <div className="invisible absolute left-0 top-full z-50 w-72 translate-y-1 pt-2 opacity-0 transition-all group-hover:visible group-hover:translate-y-0 group-hover:opacity-100 group-focus-within:visible group-focus-within:translate-y-0 group-focus-within:opacity-100">
                      <div className="overflow-hidden rounded-2xl border border-ink-100 bg-white p-2 shadow-lift">
                        {item.children.map((child) => (
                          <Link
                            key={child.href}
                            href={child.href}
                            className="block rounded-xl px-3 py-2.5 transition-colors hover:bg-brand-50"
                          >
                            <span className="block text-sm font-semibold text-ink-900">
                              {child.label}
                            </span>
                            {child.description && (
                              <span className="mt-0.5 block text-xs text-ink-500">
                                {child.description}
                              </span>
                            )}
                          </Link>
                        ))}
                      </div>
                    </div>
                  )}
                </li>
              ))}
          </ul>
        </nav>

        <div className="hidden items-center gap-3 lg:flex">
          <a
            href={site.contact.phoneHref}
            className="inline-flex items-center gap-2 text-sm font-semibold text-ink-700 transition-colors hover:text-brand-700"
          >
            <Icon name="phone" className="h-4 w-4 text-brand-600" />
            {site.contact.phoneLocal}
          </a>
          <Button href="/request-quote" withArrow>
            Request a Quote
          </Button>
        </div>

        <button
          type="button"
          onClick={() => setOpen((v) => !v)}
          aria-expanded={open}
          aria-controls="mobile-menu"
          aria-label={open ? "Close menu" : "Open menu"}
          className="grid h-10 w-10 place-items-center rounded-xl border border-ink-200 bg-white text-ink-800 lg:hidden"
        >
          <Icon name={open ? "close" : "menu"} className="h-5 w-5" />
        </button>
      </div>

      {/* Mobile menu */}
      <div
        id="mobile-menu"
        className={`lg:hidden ${open ? "block" : "hidden"} border-t border-ink-100 bg-cream`}
      >
        <nav aria-label="Mobile" className="container-page max-h-[calc(100vh-4.5rem)] overflow-y-auto py-4">
          <ul className="flex flex-col gap-1">
            {primaryNav.map((item) => (
              <MobileItem
                key={item.label}
                item={item}
                pathname={pathname}
                expanded={expanded === item.label}
                onToggle={() =>
                  setExpanded((cur) => (cur === item.label ? null : item.label))
                }
              />
            ))}
          </ul>
          <div className="mt-5 flex flex-col gap-3 border-t border-ink-100 pt-5">
            <a
              href={site.contact.phoneHref}
              className="inline-flex items-center gap-2 text-sm font-semibold text-ink-800"
            >
              <Icon name="phone" className="h-4 w-4 text-brand-600" />
              {site.contact.phone}
            </a>
            <Button href="/request-quote" withArrow className="w-full">
              Request a Quote
            </Button>
          </div>
        </nav>
      </div>
    </header>
  );
}

function MobileItem({
  item,
  pathname,
  expanded,
  onToggle,
}: {
  item: NavItem;
  pathname: string;
  expanded: boolean;
  onToggle: () => void;
}) {
  const active = isActive(pathname, item.href);
  if (!item.children) {
    return (
      <li>
        <Link
          href={item.href}
          className={`block rounded-xl px-3 py-3 text-[15px] font-medium ${
            active ? "bg-brand-50 text-brand-700" : "text-ink-700"
          }`}
        >
          {item.label}
        </Link>
      </li>
    );
  }
  return (
    <li>
      <div className="flex items-center">
        <Link
          href={item.href}
          className={`flex-1 rounded-xl px-3 py-3 text-[15px] font-medium ${
            active ? "bg-brand-50 text-brand-700" : "text-ink-700"
          }`}
        >
          {item.label}
        </Link>
        <button
          type="button"
          onClick={onToggle}
          aria-expanded={expanded}
          aria-label={`Toggle ${item.label} submenu`}
          className="grid h-10 w-10 place-items-center rounded-xl text-ink-500"
        >
          <Icon
            name="chevron-down"
            className={`h-4 w-4 transition-transform ${expanded ? "rotate-180" : ""}`}
          />
        </button>
      </div>
      {expanded && (
        <ul className="mb-1 ml-3 flex flex-col gap-0.5 border-l border-ink-100 pl-3">
          {item.children.map((child) => (
            <li key={child.href}>
              <Link
                href={child.href}
                className="block rounded-lg px-3 py-2.5 text-sm text-ink-600"
              >
                {child.label}
              </Link>
            </li>
          ))}
        </ul>
      )}
    </li>
  );
}
