"use client";

import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import type { NavItemCms } from "@/lib/cms";
import type { HeaderStyle } from "@/lib/theme";
import { LogoMark } from "./artwork";

export function Navbar({
  brand,
  nav,
  header,
}: {
  brand: string;
  nav: NavItemCms[];
  header?: HeaderStyle;
}) {
  const sticky = header?.sticky ?? true;
  const headerBg = header?.background || undefined;
  const headerHeight = header?.height || undefined;
  const pathname = usePathname();
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(false);

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

  // Close the mobile menu whenever the route changes (compare in effect body
  // so we only call setState when the value actually changed).
  const lastPathname = useRef(pathname);
  useEffect(() => {
    if (lastPathname.current !== pathname) {
      lastPathname.current = pathname;
      setOpen(false);
    }
  }, [pathname]);

  return (
    <header
      className={`z-50 transition-all duration-300 ${
        sticky ? "sticky top-0" : "relative"
      } ${
        scrolled ? "shadow-[0_10px_30px_-18px_rgba(14,59,59,0.35)]" : ""
      }`}
    >
      <div
        style={
          headerBg || headerHeight
            ? {
                backgroundColor: headerBg,
                height: headerHeight,
              }
            : undefined
        }
        className={`mx-auto flex h-[4.5rem] w-full max-w-6xl items-center justify-between px-6 transition-all duration-300 lg:px-10 ${
          headerBg
            ? ""
            : scrolled
              ? "bg-white/95 backdrop-blur-md"
              : "bg-transparent"
        }`}
      >
        <Link
          href="/"
          className="animate-fade-up flex items-center gap-2.5"
          aria-label={`${brand} — home`}
        >
          <LogoMark className="h-8 w-8 text-teal" />
          <span className="font-display text-[1.35rem] font-bold tracking-tight">
            {brand.split(" ").length > 1 ? (
              <>
                <span className="text-ink">{brand.split(" ")[0]}</span>
                <span className="text-teal">
                  &nbsp;{brand.split(" ").slice(1).join(" ")}
                </span>
              </>
            ) : (
              <span className="text-ink">{brand}</span>
            )}
          </span>
        </Link>

        {/* Desktop nav */}
        <nav
          className="animate-fade-up absolute left-1/2 hidden -translate-x-1/2 items-center gap-8 lg:flex [animation-delay:120ms]"
          aria-label="Main"
        >
          {nav.map((item) => {
            const active =
              item.href === "/"
                ? pathname === "/"
                : pathname.startsWith(item.href);
            return (
              <Link
                key={item.href}
                href={item.href}
                aria-current={active ? "page" : undefined}                data-active={active ? "true" : undefined}
                className={`nav-link text-[0.9rem] font-medium transition-colors ${
                  active ? "text-amber-dark" : "text-ink-soft hover:text-ink"
                }`}>
                {item.label}
              </Link>
            );
          })}
        </nav>

        {/* Desktop CTA */}
        <div className="animate-fade-up hidden items-center gap-5 [animation-delay:150ms] lg:flex">
          <Link href="/contact" className="btn btn-teal !px-6 !py-2.5">
            Get Started
          </Link>
        </div>

        {/* Mobile toggle */}
        <button
          type="button"
          onClick={() => setOpen((v) => !v)}
          className="flex h-11 w-11 flex-col items-center justify-center gap-[6px] lg:hidden"
          aria-expanded={open}
          aria-label={open ? "Close menu" : "Open menu"}
        >
          <span
            className={`h-[2px] w-6 rounded-full bg-ink transition-transform duration-300 ${
              open ? "translate-y-[8px] rotate-45" : ""
            }`}
          />
          <span
            className={`h-[2px] w-6 rounded-full bg-ink transition-opacity duration-300 ${
              open ? "opacity-0" : ""
            }`}
          />
          <span
            className={`h-[2px] w-6 rounded-full bg-ink transition-transform duration-300 ${
              open ? "-translate-y-[8px] -rotate-45" : ""
            }`}
          />
        </button>
      </div>

      {/* Mobile menu */}
      <div
        className={`overflow-hidden bg-white transition-[max-height] duration-300 lg:hidden ${
          open ? "max-h-[30rem] shadow-[0_20px_40px_-24px_rgba(14,59,59,0.4)]" : "max-h-0"
        }`}
      >
        <nav className="flex flex-col px-6 py-6" aria-label="Mobile">
          {nav.map((item) => {
            const active =
              item.href === "/"
                ? pathname === "/"
                : pathname.startsWith(item.href);
            return (
              <Link
                key={item.href}
                href={item.href}
                className={`border-b border-linen py-4 font-display text-2xl transition-colors ${
                  active ? "text-amber-dark" : "text-ink"
                }`}
              >
                {item.label}
              </Link>
            );
          })}
          <Link href="/contact" className="btn btn-teal mt-6 self-start">
            Get Started
          </Link>
        </nav>
      </div>
    </header>
  );
}
