/* Light/dark theme toggle. Applies early to avoid flash; persists to localStorage;
   respects prefers-color-scheme on first visit. */
(function () {
  const KEY = "rgp-theme";
  const root = document.documentElement;
  const pref = () => (window.matchMedia && matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
  const current = () => localStorage.getItem(KEY) || pref();
  root.setAttribute("data-theme", current());

  function bind() {
    const btn = document.querySelector("[data-theme-toggle]");
    if (!btn || btn.dataset.bound) return;
    btn.dataset.bound = "1";
    const sync = () => btn.setAttribute("aria-pressed", root.getAttribute("data-theme") === "dark");
    sync();
    btn.addEventListener("click", () => {
      const t = root.getAttribute("data-theme") === "dark" ? "light" : "dark";
      root.setAttribute("data-theme", t);
      localStorage.setItem(KEY, t);
      sync();
    });
  }
  document.addEventListener("DOMContentLoaded", bind);
  document.addEventListener("partials:loaded", bind);
})();
