"use client";

import { ThemeProvider as NextThemesProvider, useTheme } from "next-themes";
import { useEffect } from "react";

function CrossSubdomainThemeCookie() {
  const { resolvedTheme } = useTheme();
  useEffect(() => {
    if (!resolvedTheme) return;
    // Cookie shared across *.klas.chat so sibling apps (e.g. dwg-counting) sync.
    document.cookie =
      `portal_theme=${resolvedTheme}; Path=/; Domain=.klas.chat; Max-Age=31536000; SameSite=Lax`;
  }, [resolvedTheme]);
  return null;
}

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  return (
    <NextThemesProvider
      attribute="class"
      defaultTheme="system"
      enableSystem
      disableTransitionOnChange
    >
      <CrossSubdomainThemeCookie />
      {children}
    </NextThemesProvider>
  );
}
