import { createContext, useContext, useMemo, useState } from 'react';
import type { ReactNode } from 'react';
import { getContentPack } from '../content/pack';
import type { ContentPack } from '../engine/types';
import { loadLocale, saveLocale } from './types';
import type { Locale } from './types';
import { uiStrings } from './ui';
import type { UIStrings } from './ui';

interface I18nValue {
  readonly locale: Locale;
  readonly t: UIStrings;
  /** Content-Pack in der aktuellen Sprache. */
  readonly pack: ContentPack;
  readonly setLocale: (locale: Locale) => void;
}

const I18nContext = createContext<I18nValue | null>(null);

/** Stellt Sprache, UI-Wörterbuch und lokalisierten Content-Pack bereit. */
export function I18nProvider({ children }: { readonly children: ReactNode }): JSX.Element {
  const [locale, setLocaleState] = useState<Locale>(() => loadLocale());

  const value = useMemo<I18nValue>(
    () => ({
      locale,
      t: uiStrings(locale),
      pack: getContentPack(locale),
      setLocale: (next: Locale) => {
        saveLocale(next);
        setLocaleState(next);
      },
    }),
    [locale],
  );

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

/** Zugriff auf Sprache, Wörterbuch und Content-Pack. */
export function useI18n(): I18nValue {
  const ctx = useContext(I18nContext);
  if (!ctx) {
    throw new Error('useI18n muss innerhalb von <I18nProvider> verwendet werden.');
  }
  return ctx;
}
