'use client';

import React from 'react';

import {
  type AppLocale,
  persistAppLocale,
  readBrowserAppLocale,
} from '@/lib/i18n/core';

type AppI18nContextValue = {
  locale: AppLocale;
  setLocale: (locale: AppLocale) => void;
};

const AppI18nContext = React.createContext<AppI18nContextValue | null>(null);

export function AppI18nProvider({
  initialLocale,
  children,
}: {
  initialLocale: AppLocale;
  children: React.ReactNode;
}) {
  const [locale, setLocaleState] = React.useState<AppLocale>(initialLocale);

  React.useEffect(() => {
    const browserLocale = readBrowserAppLocale();
    if (browserLocale !== locale) {
      setLocaleState(browserLocale);
      return;
    }
    persistAppLocale(locale);
  }, []);

  React.useEffect(() => {
    persistAppLocale(locale);
  }, [locale]);

  const value = React.useMemo<AppI18nContextValue>(
    () => ({
      locale,
      setLocale: setLocaleState,
    }),
    [locale]
  );

  return <AppI18nContext.Provider value={value}>{children}</AppI18nContext.Provider>;
}

export function useAppI18n(): AppI18nContextValue {
  const value = React.useContext(AppI18nContext);
  if (!value) {
    throw new Error('useAppI18n must be used within AppI18nProvider');
  }
  return value;
}
