"use client";

import Image from "next/image";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useEffect, useRef, useState } from "react";
import { loanLinks, site } from "@/content/site";

export function SiteHeader() {
  const pathname = usePathname();
  return <HeaderContents key={pathname} pathname={pathname} />;
}
function HeaderContents({ pathname }: { pathname: string }) {
  const [mobileOpen, setMobileOpen] = useState(false);
  const [loanOpen, setLoanOpen] = useState(false);
  const header = useRef<HTMLElement>(null);
  const mobileButton = useRef<HTMLButtonElement>(null);
  const loanButton = useRef<HTMLButtonElement>(null);
  const loanPanel = useRef<HTMLUListElement>(null);
  useEffect(() => {
    const updateScrollState = () => {
      if (header.current)
        header.current.dataset.scrolled = String(window.scrollY > 0);
    };
    updateScrollState();
    window.addEventListener("scroll", updateScrollState, { passive: true });
    return () => window.removeEventListener("scroll", updateScrollState);
  }, []);
  useEffect(() => {
    const breakpoint = window.matchMedia("(min-width: 922px)");
    const reset = (event: MediaQueryListEvent) => {
      const nav = document.getElementById("site-navigation"),
        active = document.activeElement;
      setMobileOpen(false);
      setLoanOpen(false);
      if (!event.matches && nav?.contains(active))
        mobileButton.current?.focus();
      else if (event.matches && loanPanel.current?.contains(active))
        loanButton.current?.focus();
      else if (event.matches && active === mobileButton.current)
        nav?.querySelector("a")?.focus();
    };
    breakpoint.addEventListener("change", reset);
    return () => breakpoint.removeEventListener("change", reset);
  }, []);
  function close() {
    setMobileOpen(false);
    setLoanOpen(false);
  }
  return (
    <header
      ref={header}
      className="site-header"
      onKeyDown={(event) => {
        if (event.key !== "Escape") return;
        if (loanOpen) {
          setLoanOpen(false);
          loanButton.current?.focus();
        } else if (mobileOpen) {
          setMobileOpen(false);
          mobileButton.current?.focus();
        }
      }}
    >
      <div className="header-inner site-container">
        <Link
          href="/"
          aria-label="MaxCredit home"
          onClick={close}
          className="site-logo"
        >
          <Image
            src="/images/logo-250x47.webp"
            width={250}
            height={47}
            alt="MaxCredit"
            preload
          />
        </Link>
        <button
          ref={mobileButton}
          type="button"
          className="mobile-toggle"
          aria-label={mobileOpen ? "Close navigation" : "Open navigation"}
          aria-controls="site-navigation"
          aria-expanded={mobileOpen}
          onClick={() => {
            setMobileOpen(!mobileOpen);
            setLoanOpen(false);
          }}
        >
          <span className="mobile-toggle-icon" aria-hidden="true">
            <span />
            <span />
            <span />
          </span>
        </button>
        <nav
          id="site-navigation"
          aria-label="Main navigation"
          className={mobileOpen ? "main-navigation is-open" : "main-navigation"}
        >
          <ul className="nav-list">
            <li>
              <Link
                href="/"
                aria-current={pathname === "/" ? "page" : undefined}
                onClick={close}
              >
                Home
              </Link>
            </li>
            <li>
              <Link
                href="/about"
                aria-current={pathname === "/about" ? "page" : undefined}
                onClick={close}
              >
                About
              </Link>
            </li>
            <li
              className="loan-disclosure"
              onPointerEnter={(e) => {
                if (
                  e.pointerType === "mouse" &&
                  window.matchMedia("(min-width: 922px)").matches
                )
                  setLoanOpen(true);
              }}
              onPointerLeave={() => {
                if (
                  !loanPanel.current?.contains(document.activeElement) &&
                  document.activeElement !== loanButton.current
                )
                  setLoanOpen(false);
              }}
              onBlur={(e) => {
                if (!e.currentTarget.contains(e.relatedTarget))
                  setLoanOpen(false);
              }}
            >
              <button
                ref={loanButton}
                type="button"
                data-active={
                  loanLinks.some((link) => link.href === pathname) || undefined
                }
                aria-expanded={loanOpen}
                aria-controls="loan-navigation"
                onClick={() => setLoanOpen(!loanOpen)}
                onKeyDown={(e) => {
                  if (e.key === "ArrowDown") {
                    e.preventDefault();
                    setLoanOpen(true);
                    requestAnimationFrame(() =>
                      loanPanel.current?.querySelector("a")?.focus(),
                    );
                  }
                }}
              >
                Loan{" "}
                <svg
                  aria-hidden="true"
                  width="10"
                  height="7"
                  viewBox="0 0 10 7"
                >
                  <path d="m1 1 4 4 4-4" fill="none" stroke="currentColor" />
                </svg>
              </button>
              <ul
                ref={loanPanel}
                id="loan-navigation"
                className="loan-panel"
                hidden={!loanOpen}
              >
                {loanLinks.map((link) => (
                  <li key={link.href}>
                    <Link
                      href={link.href}
                      aria-current={pathname === link.href ? "page" : undefined}
                      onClick={close}
                    >
                      {link.label}
                    </Link>
                  </li>
                ))}
              </ul>
            </li>
            <li>
              <Link
                href="/contact"
                aria-current={pathname === "/contact" ? "page" : undefined}
                onClick={close}
              >
                Contact
              </Link>
            </li>
          </ul>
          <a className="header-apply" href={site.application} onClick={close}>
            Apply Now
          </a>
        </nav>
      </div>
    </header>
  );
}
