// the deskbar's look menu picks a palette and light, dark or following the system. both are
// saved, and Window.astro's head script applies them. the menus are plain popovers, this only
// puts focus in them when they open so ↑↓ work.

import { DEFAULT_PALETTE, THEMES } from "../lib/themes";
import { focusIn } from "./menukeys";

for (const menu of document.querySelectorAll<HTMLElement>("#leaf-menu, #look-menu")) {
  menu.addEventListener("toggle", (e) => (e as ToggleEvent).newState === "open" && focusIn(menu));
}

const menu = document.querySelector<HTMLElement>("#look-menu");
const btn = document.querySelector<HTMLElement>("[data-look-btn]");
if (menu && btn) setup(menu, btn);

function setup(menu: HTMLElement, btn: HTMLElement) {
  const root = document.documentElement;
  const mark = () => {
    const palette = root.dataset.palette ?? DEFAULT_PALETTE;
    const pick = root.dataset.themePick ?? "auto";
    menu.querySelectorAll<HTMLElement>("[data-palette-pick]").forEach((b) => b.toggleAttribute("aria-current", b.dataset.palettePick === palette));
    menu.querySelectorAll<HTMLElement>("[data-theme-set]").forEach((b) => b.toggleAttribute("aria-current", b.dataset.themeSet === pick));
    btn.title = `${palette}, ${THEMES.find((t) => t.pick === pick)?.label ?? pick}`;
    btn.setAttribute("aria-label", `look: ${btn.title}`);
  };
  const save = (key: string, value: string | undefined) => {
    if (value) localStorage.setItem(key, value);
    else localStorage.removeItem(key);
    window.dispatchEvent(new Event("hydrant-theme"));
    mark();
  };
  mark();
  // the menu stays open, so both halves can be picked while the page changes behind it
  menu.addEventListener("click", (e) => {
    const b = (e.target as HTMLElement).closest<HTMLElement>("button");
    if (b?.dataset.palettePick) save("hydrant-palette", b.dataset.palettePick === DEFAULT_PALETTE ? undefined : b.dataset.palettePick);
    if (b?.dataset.themeSet) save("hydrant-theme", b.dataset.themeSet === "auto" ? undefined : b.dataset.themeSet);
  });
  addEventListener("storage", mark);
}

export {};
