// 主题（亮/暗）管理：持久化到 localStorage，切换在 <html> 上加/去 .dark 类。
// 默认亮色（暗色为可选）。初始化在 applyInitialTheme（main 启动时调，先于渲染避免闪烁）。
import { useCallback, useEffect, useState } from "react";

export type Theme = "light" | "dark";

const KEY = "sdx-theme";

export function getStoredTheme(): Theme {
  const t = localStorage.getItem(KEY);
  return t === "dark" ? "dark" : "light"; // 默认亮色
}

function apply(theme: Theme): void {
  document.documentElement.classList.toggle("dark", theme === "dark");
}

// applyInitialTheme 在渲染前调用，依据存储值设好 .dark 类（避免首屏闪烁）。
export function applyInitialTheme(): void {
  apply(getStoredTheme());
}

// useTheme 暴露当前主题与切换函数（写 localStorage + 切 .dark 类）。
export function useTheme(): { theme: Theme; toggle: () => void; setTheme: (t: Theme) => void } {
  const [theme, setThemeState] = useState<Theme>(getStoredTheme);

  useEffect(() => {
    apply(theme);
    localStorage.setItem(KEY, theme);
  }, [theme]);

  const setTheme = useCallback((t: Theme) => setThemeState(t), []);
  const toggle = useCallback(() => setThemeState((t) => (t === "dark" ? "light" : "dark")), []);
  return { theme, toggle, setTheme };
}
