'use client';

/**
 * EN: I18n Provider wrapper component
 * VI: Component wrapper I18n Provider
 *
 * This component wraps the next-intl provider with our custom context
 */

import { NextIntlClientProvider } from 'next-intl';
import { I18nProvider as CustomI18nProvider } from '@/contexts/i18n-context';
import { useI18n } from '@/contexts/i18n-context';
import { useMemo } from 'react';
import enMessages from '@/i18n/messages/en.json';
import viMessages from '@/i18n/messages/vi.json';

/**
 * EN: Inner provider that uses the locale from context
 * VI: Provider bên trong sử dụng locale từ context
 */
function NextIntlProviderWrapper({ children }: { children: React.ReactNode }) {
  const { locale } = useI18n();

  // EN: Get messages based on locale - use static imports for immediate availability / VI: Lấy messages dựa trên locale - sử dụng static imports để có sẵn ngay
  const messages = useMemo(() => {
    return locale === 'vi' ? viMessages : enMessages;
  }, [locale]);

  // EN: Always render NextIntlClientProvider to ensure context exists / VI: Luôn render NextIntlClientProvider để đảm bảo context tồn tại
  return (
    <NextIntlClientProvider locale={locale} messages={messages}>
      {children}
    </NextIntlClientProvider>
  );
}

/**
 * EN: Main I18n Provider component
 * VI: Component I18n Provider chính
 */
export function I18nProvider({ children }: { children: React.ReactNode }) {
  return (
    <CustomI18nProvider>
      <NextIntlProviderWrapper>{children}</NextIntlProviderWrapper>
    </CustomI18nProvider>
  );
}
