/* global React */
const THEME_KEY = "aur.theme";

function applyTheme(theme) {
  document.documentElement.dataset.ui = theme === "light" ? "light" : "dark";
  try { localStorage.setItem(THEME_KEY, theme); } catch (_) {}
}

function ThemeToggle({ lang }) {
  const [theme, setTheme] = React.useState(() => (localStorage.getItem(THEME_KEY) || "dark"));
  React.useEffect(() => { applyTheme(theme); }, [theme]);
  const light = theme === "light";
  const label = lang === "de" ? (light ? "Dunkel" : "Hell") : (light ? "Dark" : "Light");
  return (
    <button type="button" className="theme-toggle" onClick={() => setTheme(light ? "dark" : "light")}
      title={label} aria-label={label}>
      {light ? (
        <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round">
          <path d="M20.5 14.2A8.5 8.5 0 1 1 9.8 3.5a6.8 6.8 0 0 0 10.7 10.7z" />
        </svg>
      ) : (
        <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round">
          <circle cx="12" cy="12" r="4.2" />
          <path d="M12 2.6v2M12 19.4v2M4.6 12h-2M21.4 12h-2M6.2 6.2 4.8 4.8M19.2 19.2l-1.4-1.4M17.8 6.2l1.4-1.4M4.8 19.2l1.4-1.4" />
        </svg>
      )}
    </button>
  );
}

applyTheme(localStorage.getItem(THEME_KEY) || "dark");
window.ThemeToggle = ThemeToggle;
window.applyTheme = applyTheme;
