export const THEME_STORAGE_KEY = "mocker_theme";
const LEGACY_THEME_KEY = "alpingo_theme";

function readThemeStorage() {
  try {
    let v = localStorage.getItem(THEME_STORAGE_KEY);
    if (!v) {
      const legacy = localStorage.getItem(LEGACY_THEME_KEY);
      if (legacy) {
        localStorage.setItem(THEME_STORAGE_KEY, legacy);
        v = legacy;
      }
    }
    return v;
  } catch {
    return null;
  }
}

export function getSiteTheme() {
  try {
    return readThemeStorage() === "light" ? "light" : "dark";
  } catch {
    return "dark";
  }
}

export function applySiteTheme(theme) {
  const t = theme === "light" ? "light" : "dark";
  document.documentElement.setAttribute("data-theme", t);
  document.documentElement.style.colorScheme = t;
  const meta = document.querySelector('meta[name="theme-color"]');
  if (meta) meta.setAttribute("content", t === "light" ? "#ffffff" : "#181f2e");
}

export function setSiteTheme(theme) {
  const t = theme === "light" ? "light" : "dark";
  try {
    localStorage.setItem(THEME_STORAGE_KEY, t);
  } catch {
    /* ignore */
  }
  applySiteTheme(t);
  window.dispatchEvent(new CustomEvent("mocker:theme", { detail: { theme: t } }));
}

export function initSiteTheme() {
  applySiteTheme(getSiteTheme());
}

export function themeToggleButtonHtml(ariaLabel, className = "") {
  const extra = className ? ` ${className}` : "";
  return `
    <button type="button" data-theme-toggle class="site-theme-toggle k-btn k-btn--icon btn-site-icon${extra}" aria-label="${ariaLabel}" title="${ariaLabel}">
      <svg class="site-theme-toggle__icon site-theme-toggle__icon--dark h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 12.79A9 9 0 1111.21 3 7 7 0 0021 12.79z"/></svg>
      <svg class="site-theme-toggle__icon site-theme-toggle__icon--light h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m8.66-13.66l-.71.71M4.05 19.95l-.71.71M21 12h-1M4 12H3m16.66 5.66l-.71-.71M4.05 4.05l-.71-.71M12 7a5 5 0 100 10 5 5 0 000-10z"/></svg>
    </button>`;
}

export function updateThemeToggleUi(root = document) {
  const light = getSiteTheme() === "light";
  root.querySelectorAll("[data-theme-toggle]").forEach((btn) => {
    btn.setAttribute("aria-pressed", light ? "true" : "false");
  });
}

export function bindThemeToggle(root = document) {
  root.querySelectorAll("[data-theme-toggle]").forEach((btn) => {
    if (btn.dataset.themeBound) return;
    btn.dataset.themeBound = "1";
    btn.addEventListener("click", () => {
      setSiteTheme(getSiteTheme() === "light" ? "dark" : "light");
    });
  });
  updateThemeToggleUi(root);
}
