'use client';

import React from 'react';

import {
  type PortalLocale,
  persistPortalLocale,
  readBrowserPortalLocale,
} from '@/lib/i18n/core';

type PortalI18nContextValue = {
  locale: PortalLocale;
  setLocale: (locale: PortalLocale) => void;
};

const PortalI18nContext = React.createContext<PortalI18nContextValue | null>(null);

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

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

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

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

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

export function usePortalI18n(): PortalI18nContextValue {
  const value = React.useContext(PortalI18nContext);
  if (!value) {
    throw new Error('usePortalI18n must be used within PortalI18nProvider');
  }
  return value;
}
