import {useQuery} from '@tanstack/react-query';
import {type ReactNode, useEffect} from 'react';
import {getPreferences} from '@/client';
import {useUser} from '@/contexts';
import i18n from '@/lib/i18n';

/**
 * Syncs the user's server-side language preference to i18n after login.
 * This ensures the API-stored preference takes precedence over browser detection.
 */
export function LanguageProvider({children}: {children: ReactNode}) {
  const {isAuthenticated} = useUser();

  const {data: preferences} = useQuery({
    queryKey: ['userPreferences'],
    queryFn: async () => {
      const resp = await getPreferences();
      return resp.data?.data ?? null;
    },
    enabled: isAuthenticated,
    staleTime: 5 * 60 * 1000,
    retry: false,
  });

  useEffect(() => {
    if (preferences?.language && preferences.language !== i18n.language) {
      i18n.changeLanguage(preferences.language);
    }
  }, [preferences]);

  return children;
}
