const storageKey = "sound-signal-theme"; const themes = new Set(["dark", "light"]); function savedTheme() { try { const value = window.localStorage.getItem(storageKey); return themes.has(value) ? value : "dark"; } catch { return "dark"; } } function applyTheme(theme, button) { document.documentElement.dataset.theme = theme; if (!button) return; const nextTheme = theme === "dark" ? "light" : "dark"; button.textContent = nextTheme === "light" ? "☀ Light mode" : "☾ Dark mode"; button.setAttribute("aria-label", "Switch to " + nextTheme + " mode"); button.setAttribute("aria-pressed", String(theme === "light")); } function installThemeToggle() { const button = document.querySelector(".theme-toggle") ?? document.createElement("button"); if (!button.isConnected) { button.className = "theme-toggle"; button.type = "button"; document.body.append(button); } applyTheme(savedTheme(), button); button.addEventListener("click", () => { const nextTheme = document.documentElement.dataset.theme === "dark" ? "light" : "dark"; try { window.localStorage.setItem(storageKey, nextTheme); } catch {} applyTheme(nextTheme, button); }); } applyTheme(savedTheme()); if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", installThemeToggle, { once: true }); } else { installThemeToggle(); }