/**
 * Design Lab — header interactions (clone of ktbysa.net behavior)
 */
(() => {
  const header = document.getElementById("siteHeader");
  const menuToggle = document.getElementById("menuToggle");
  const siteNav = document.getElementById("siteNav");
  const moreMenu = document.getElementById("hdrMoreMenu");
  const moreBtn = document.getElementById("hdrMoreBtn");
  const darkToggle = document.getElementById("darkToggle");
  const THEME_KEY = "kutby-dl-theme";

  function setDark(on) {
    document.documentElement.classList.toggle("dark", on);
    try {
      localStorage.setItem(THEME_KEY, on ? "dark" : "light");
    } catch (_) {}
    if (darkToggle) {
      darkToggle.setAttribute(
        "aria-label",
        on ? "تبديل إلى الوضع النهاري" : "تبديل الوضع الليلي"
      );
    }
  }

  try {
    const saved = localStorage.getItem(THEME_KEY);
    if (saved === "dark") setDark(true);
  } catch (_) {}

  darkToggle?.addEventListener("click", () => {
    setDark(!document.documentElement.classList.contains("dark"));
  });

  function closeMore() {
    moreMenu?.classList.remove("is-open");
    moreBtn?.setAttribute("aria-expanded", "false");
  }

  moreBtn?.addEventListener("click", (e) => {
    e.stopPropagation();
    const open = moreMenu.classList.toggle("is-open");
    moreBtn.setAttribute("aria-expanded", open ? "true" : "false");
  });

  document.addEventListener("click", (e) => {
    if (!e.target.closest("#hdrMoreMenu")) closeMore();
  });

  menuToggle?.addEventListener("click", () => {
    const open = siteNav.classList.toggle("active");
    menuToggle.setAttribute("aria-expanded", open ? "true" : "false");
    closeMore();
  });

  siteNav?.querySelectorAll("a").forEach((link) => {
    link.addEventListener("click", () => {
      siteNav.classList.remove("active");
      menuToggle?.setAttribute("aria-expanded", "false");
      closeMore();
    });
  });

  window.addEventListener(
    "scroll",
    () => {
      header?.classList.toggle("is-scrolled", window.scrollY > 8);
    },
    { passive: true }
  );

  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape") {
      closeMore();
      siteNav?.classList.remove("active");
      menuToggle?.setAttribute("aria-expanded", "false");
    }
  });
})();
