import { useEffect, useState } from "react";
import { useThemeStore, type ColorMode } from "@/stores/theme";
import { themes, getThemeById, type ThemeDefinition } from "./theme-config";

/**
 * Convenience hook wrapping the Zustand theme store.
 *
 * Returns the current theme definition, mode, resolved effective mode
 * (accounting for system preference), and setters.
 */
export function useTheme() {
  const { mode, setMode } = useThemeStore();

  const [effectiveMode, setEffectiveMode] = useState<"light" | "dark">("light");

  useEffect(() => {
    if (mode !== "system") {
      setEffectiveMode(mode);
      return;
    }

    const mql = window.matchMedia("(prefers-color-scheme: dark)");
    setEffectiveMode(mql.matches ? "dark" : "light");

    const handler = (e: MediaQueryListEvent) =>
      setEffectiveMode(e.matches ? "dark" : "light");
    mql.addEventListener("change", handler);
    return () => mql.removeEventListener("change", handler);
  }, [mode]);

  const currentTheme: ThemeDefinition = getThemeById("default");

  return {
    /** Current mode setting (light | dark | system) */
    mode,
    /** Resolved mode after considering system preference */
    effectiveMode,
    /** Full theme definition for the active theme */
    currentTheme,
    /** All available theme definitions */
    themes,
    /** Set the color mode */
    setMode,
  };
}

export type { ThemeDefinition, ColorMode };
