"use client";

import { useEffect } from "react";
import { useThemeStore } from "@/stores/theme";

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const mode = useThemeStore((s) => s.mode);

  // Sync dark class based on mode + system preference
  useEffect(() => {
    const applyDarkClass = (isDark: boolean) => {
      if (isDark) {
        document.documentElement.classList.add("dark");
      } else {
        document.documentElement.classList.remove("dark");
      }
    };

    if (mode === "dark") {
      applyDarkClass(true);
      return;
    }

    if (mode === "light") {
      applyDarkClass(false);
      return;
    }

    // mode === "system" — follow OS preference
    const mql = window.matchMedia("(prefers-color-scheme: dark)");
    applyDarkClass(mql.matches);

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

  return <>{children}</>;
}
