"use client";

import Image from "next/image";
import Link from "next/link";
import { useEffect, useState, type ReactNode } from "react";
import { navLinks } from "@/data/nav";

type SiteChromeProps = {
  eyebrow: string;
  children: ReactNode;
};

export function SiteChrome({ eyebrow, children }: SiteChromeProps) {
  const [menuOpen, setMenuOpen] = useState(false);

  useEffect(() => {
    if (!menuOpen) return;

    const onKeyDown = (event: KeyboardEvent) => {
      if (event.key === "Escape") setMenuOpen(false);
    };

    document.addEventListener("keydown", onKeyDown);
    const previousOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    return () => {
      document.removeEventListener("keydown", onKeyDown);
      document.body.style.overflow = previousOverflow;
    };
  }, [menuOpen]);

  return (
    <div className="app-shell">
      <p className="watermark">{eyebrow}</p>

      <header className="brand-header">
        <div className="brand-header__row">
          <Link href="/" className="brand-header__identity">
            <Image
              src="/img/logo.png"
              alt="اک"
              width={100}
              height={67}
              className="brand-logo"
              priority
            />
            <h1 className="brand-name">اک، روایت امروز بلوط</h1>
          </Link>

          <button
            type="button"
            className={`hamburger${menuOpen ? " is-open" : ""}`}
            aria-label={menuOpen ? "بستن منو" : "باز کردن منو"}
            aria-expanded={menuOpen}
            aria-controls="site-menu"
            onClick={() => setMenuOpen((open) => !open)}
          >
            <span />
            <span />
            <span />
          </button>
        </div>
      </header>

      {menuOpen ? (
        <>
          <div
            className="menu-backdrop is-open"
            onClick={() => setMenuOpen(false)}
            aria-hidden="true"
          />
          <nav id="site-menu" className="side-menu is-open">
            <ul className="side-menu__list">
              {navLinks.map((link) => (
                <li key={link.href}>
                  <Link href={link.href} onClick={() => setMenuOpen(false)}>
                    {link.label}
                  </Link>
                </li>
              ))}
            </ul>
          </nav>
        </>
      ) : null}

      {children}
    </div>
  );
}
