import { useEffect, useState } from 'react';
import i18n from 'i18next';

/**
 * Translations of the application's own strings, keyed by their English text exactly
 * like Laravel's JSON translations (__('Save changes')). They come from the same files
 * the server reads: each module's lang/<locale>.json and the application's lang/,
 * which resources/js/app.tsx registers before the first render.
 */
export const LARAVEL_NAMESPACE = 'laravel';

const catalogs = new Map<string, Record<string, string>>();

export function registerTranslations(
  locale: string,
  messages: Record<string, string>,
): void {
  catalogs.set(locale, { ...catalogs.get(locale), ...messages });
}

export function translationResources(): Record<
  string,
  Record<string, Record<string, string>>
> {
  return Object.fromEntries(
    [...catalogs].map(([locale, messages]) => [
      locale,
      { [LARAVEL_NAMESPACE]: messages },
    ]),
  );
}

function replace(text: string, replacements: Record<string, string | number>) {
  return Object.entries(replacements).reduce(
    (result, [key, value]) => result.replaceAll(`:${key}`, String(value)),
    text,
  );
}

/**
 * Translate an English string, like Laravel's __(): `__('Welcome, :name', { name })`.
 * Missing translations fall back to the English text.
 */
export function __(
  key: string,
  replacements: Record<string, string | number> = {},
): string {
  const text = i18n.isInitialized
    ? i18n.t(key, {
        ns: LARAVEL_NAMESPACE,
        keySeparator: false,
        nsSeparator: false,
        defaultValue: key,
      })
    : key;

  return replace(String(text), replacements);
}

/**
 * __() for components: they re-render once translations load and whenever the
 * language changes. It listens to i18next directly, so it also works in components
 * rendered before the I18nProvider has initialized it.
 */
export function useTrans() {
  const [, setLanguage] = useState(() => i18n.language);

  useEffect(() => {
    const update = () => setLanguage(i18n.language);
    i18n.on('initialized', update);
    i18n.on('languageChanged', update);

    return () => {
      i18n.off('initialized', update);
      i18n.off('languageChanged', update);
    };
  }, []);

  return __;
}
