import { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { localized } from './licensing.helpers';
import type { Bilingual } from './licensing.types';

/**
 * The component-facing bilingual reader — the twin of `useDateDisplayer()`.
 *
 * A hook rather than a bare `localized` import so the calling component is
 * subscribed to i18next: switching language re-renders it and every
 * backend-configured label flips with the rest of the UI. `useTranslation()`
 * with no instance argument resolves to the app's own <I18nextProvider>
 * (portal router.tsx, backoffice AppProviders.tsx), which is what makes this
 * work across two separate i18n instances.
 *
 * DISPLAY ONLY. Code that *matches* on a label — `.includes('nationality')`,
 * the vessel-picker regex in ConfigDrivenSection, the SUBCITY/WOREDA test in
 * AddressFormContent — must keep reading `value.en`, or the match breaks the
 * moment the user switches language.
 *
 * The returned function is stable per language, so it is safe — and required —
 * as a useMemo/useCallback dependency.
 */
export function useLocalized(): (value: Bilingual | undefined) => string {
  const { i18n } = useTranslation();
  return useCallback((value) => localized(value, i18n.language), [i18n.language]);
}
