"use client";

import { SessionProvider } from "next-auth/react";
import type { ReactNode } from "react";
import { useEffect } from "react";

export default function Providers({ children }: { children: ReactNode }) {
  useEffect(() => {
    if (typeof document === "undefined") return;
    const root = document.documentElement;
    const applyTheme = () => {
      try {
        const saved = window.localStorage.getItem("theme");
        if (saved === "dark" || saved === "light") {
          root.dataset.theme = saved;
        }
      } catch {
        // ignore
      }
    };
    applyTheme();
    const handler = () => applyTheme();
    window.addEventListener("storage", handler);
    return () => window.removeEventListener("storage", handler);
  }, []);

  return <SessionProvider>{children}</SessionProvider>;
}
