'use client';
import { FunctionComponent, PropsWithChildren, useEffect } from 'react';
import { ThemeProvider as MuiThemeProvider, useColorScheme } from '@mui/material/styles';
import { AppRouterCacheProvider } from '@mui/material-nextjs/v16-appRouter';
import CssBaseline from '@mui/material/CssBaseline';
// @ts-ignore — stylis-plugin-rtl ships CJS without bundled TS declarations
import rtlPlugin from 'stylis-plugin-rtl';
import { COOKIE_NAMES, COLOR_SCHEME_COOKIE_OPTIONS } from '@/lib/cookies';
import { setClientCookie } from '@/lib/cookies/client';
import { APP_THEME_LTR, APP_THEME_RTL } from './theme';

/**
 * Writes the resolved color scheme to our cookie whenever MUI's state changes.
 * On a cookie-less first visit the server never learns the OS-resolved scheme
 * (tokens.css's `@media (prefers-color-scheme: dark)` fallback paints it, but
 * that's CSS-only — nothing tells the server) — this is what turns that visit
 * into a "returning visitor" with an explicit cookie next time, even before
 * the user ever manually toggles.
 */
function ColorSchemeCookieSync() {
  const { colorScheme } = useColorScheme();

  useEffect(() => {
    if (colorScheme === 'dark' || colorScheme === 'light') {
      setClientCookie(COOKIE_NAMES.COLOR_SCHEME, colorScheme, COLOR_SCHEME_COOKIE_OPTIONS);
    }
  }, [colorScheme]);

  return null;
}

interface AppThemeProviderProps extends PropsWithChildren {
  /** Text direction derived from the active locale. Defaults to 'ltr'. */
  dir?: 'ltr' | 'rtl';
  /**
   * Initial color-scheme mode passed from the server after reading our cookie.
   * 'dark' | 'light' when the cookie exists; 'system' on first ever visit so
   * the OS preference is respected before the user makes an explicit choice.
   */
  defaultMode?: 'light' | 'dark' | 'system';
}

const AppThemeProvider: FunctionComponent<AppThemeProviderProps> = ({
  children,
  dir = 'ltr',
  defaultMode = 'system',
}) => {
  const isRtl = dir === 'rtl';
  return (
    <AppRouterCacheProvider
      options={
        isRtl
          ? { key: 'muirtl', stylisPlugins: [rtlPlugin] }
          : { key: 'muiltr' }
      }
    >
      <MuiThemeProvider
        theme={isRtl ? APP_THEME_RTL : APP_THEME_LTR}
        defaultMode={defaultMode}
        disableTransitionOnChange
      >
        <CssBaseline enableColorScheme />
        <ColorSchemeCookieSync />
        {children}
      </MuiThemeProvider>
    </AppRouterCacheProvider>
  );
};

export default AppThemeProvider;
