'use client';

import { useLayoutEffect, useState } from 'react';
import { usePathname } from 'next/navigation';
import { ThemeProvider } from 'next-themes';
import { useAppDispatch } from '@/hooks/useRedux';
import { setTheme as setReduxTheme } from '@/store/slices/themeSlice';
import { applySessionFlowLightTheme, isSessionFlow } from '@/utils/sessionFlow';

export function AppThemeProvider({ children }: { children: React.ReactNode }) {
  const pathname = usePathname();
  const dispatch = useAppDispatch();
  const [forceLight, setForceLight] = useState(() => isSessionFlow());

  useLayoutEffect(() => {
    const inSessionFlow = isSessionFlow();
    setForceLight(inSessionFlow);

    if (inSessionFlow) {
      applySessionFlowLightTheme();
      dispatch(setReduxTheme('light'));
    }
  }, [pathname, dispatch]);

  return (
    <ThemeProvider
      attribute="class"
      defaultTheme="dark"
      enableSystem={false}
      disableTransitionOnChange={false}
      forcedTheme={forceLight ? 'light' : undefined}
    >
      {children}
    </ThemeProvider>
  );
}
