"use client"; import { useEffect, useState } from "react"; export const THEME_STORAGE_KEY = "leistungsbilanz:theme"; type Theme = "light" | "dark"; function applyTheme(theme: Theme) { document.documentElement.setAttribute("data-bs-theme", theme); } export function ThemeToggle() { const [theme, setTheme] = useState("light"); // The inline script in layout.tsx already applied the persisted/system // theme before hydration; read it back so the toggle starts in sync // instead of flashing to "light" first. useEffect(() => { const current = document.documentElement.getAttribute("data-bs-theme"); setTheme(current === "dark" ? "dark" : "light"); }, []); useEffect(() => { function handleStorage(event: StorageEvent) { if ( event.key === THEME_STORAGE_KEY && (event.newValue === "dark" || event.newValue === "light") ) { setTheme(event.newValue); applyTheme(event.newValue); } } window.addEventListener("storage", handleStorage); return () => window.removeEventListener("storage", handleStorage); }, []); function toggleTheme() { const next: Theme = theme === "dark" ? "light" : "dark"; setTheme(next); applyTheme(next); try { localStorage.setItem(THEME_STORAGE_KEY, next); } catch { // Private browsing or disabled storage: theme still applies for // this page load, just without persistence across reloads. } } return ( ); }