'use client';

import { useEffect } from 'react';
import { useLocale } from 'next-intl';
import { useAuth } from '@/lib/hooks/useAuth';
import { usePathname, useRouter } from '@/i18n/navigation';
import type { AppLocale } from '@/i18n/routing';
import { isAppLocale } from '@/i18n/routing';

/** Redirect authenticated users to their saved profile language when it differs from the URL. */
export function LocaleSync() {
  const locale = useLocale();
  const router = useRouter();
  const pathname = usePathname();
  const { user, isAuthReady } = useAuth();

  useEffect(() => {
    if (!isAuthReady || !user?.language) return;

    const preferred = user.language;
    if (!isAppLocale(preferred) || preferred === locale) return;

    router.replace(pathname, { locale: preferred as AppLocale });
  }, [isAuthReady, user?.language, locale, pathname, router]);

  return null;
}
