import en from './locales/en/ui.json' with { type: 'json' };
import fr from './locales/fr/ui.json' with { type: 'json' };
import type { Resource, ResourceLanguage } from 'i18next';

import { mergeResourceLanguages } from './mergeResourceLanguages.js';

export const uiI18nResources = {
  en: { ui: en },
  fr: { ui: fr },
} as const;

export type UiI18nResources = typeof uiI18nResources;

const isResourceLanguage = (value: unknown): value is ResourceLanguage => {
  return typeof value === 'object' && value != null;
};

const asResourceLanguage = (value: unknown): ResourceLanguage => {
  if (isResourceLanguage(value)) {
    return value;
  }
  return {};
};

/**
 * Returns i18next resources with the package-owned `ui` namespace registered.
 *
 * Applications should pass their resources through this helper before
 * initializing i18next. App-provided `ui` keys are deep-merged on top so
 * product-specific copy can override package defaults without dropping nested
 * shared UI keys such as common actions and table labels.
 */
export function withUiI18nResources(appResources: Resource = {}): Resource {
  const output: Resource = {};
  const packageResources = uiI18nResources as Resource;
  const locales = new Set([
    ...Object.keys(packageResources),
    ...Object.keys(appResources),
  ]);

  locales.forEach((locale) => {
    const packageLocale = asResourceLanguage(packageResources[locale]);
    const appLocale = asResourceLanguage(appResources[locale]);
    output[locale] = {
      ...packageLocale,
      ...appLocale,
      ui: mergeResourceLanguages(
        asResourceLanguage(packageLocale.ui),
        asResourceLanguage(appLocale.ui),
      ),
    };
  });

  return output;
}
