// #region I18nModule [C:3] [TYPE Module] [SEMANTICS i18n, localization, store, locale, translation]
// @BRIEF Centralized internationalization management using Svelte 5 runes with Russian and English locale support persisted in LocalStorage.
// @RELATION DEPENDS_ON -> [EXT:frontend:LocaleEn]
// @RELATION DEPENDS_ON -> [EXT:frontend:LocaleRu]
// @UX_STATE: locale.current — 'ru' | 'en' (reactive atom)
// @UX_STATE: t — translation dictionary (reactive derived via Proxy)
// @UX_FEEDBACK: locale change → localStorage persistence via $effect
// @INVARIANT: Locale must be either 'ru' or 'en'.
// @INVARIANT: Persistence is handled via LocalStorage.
// @RATIONALE Migrated from Svelte 4 stores (writable/derived) to Svelte 5 runes ($state/$derived/$effect).
//            Subscribe method preserved for backward compat with $t.xxx template syntax.
//            t is a Proxy to support both subscribe (templates) and direct key access (model files).

// [SECTION: IMPORTS]
// Domain-split locale files (INV_7: each file < 400 lines)
import enApiKeys from './locales/en/api-keys.json';
import enCommon from './locales/en/common.json';
import enNav from './locales/en/nav.json';
import enHealth from './locales/en/health.json';
import enLlm from './locales/en/llm.json';
import enSettings from './locales/en/settings.json';
import enGit from './locales/en/git.json';
import enDashboard from './locales/en/dashboard.json';
import enProfile from './locales/en/profile.json';
import enReports from './locales/en/reports.json';
import enDatasets from './locales/en/datasets.json';
import enDatasetReview from './locales/en/dataset_review.json';
import enTasks from './locales/en/tasks.json';
import enDebug from './locales/en/debug.json';
import enAdmin from './locales/en/admin.json';
import enTranslate from './locales/en/translate.json';
import enValidation from './locales/en/validation.json';
import enAssistant from './locales/en/assistant.json';
import enAuth from './locales/en/auth.json';
import enMapper from './locales/en/mapper.json';
import enMigration from './locales/en/migration.json';
import enStorage from './locales/en/storage.json';
import enMaintenance from './locales/en/maintenance.json';
import enConnections from './locales/en/connections.json';

import ruApiKeys from './locales/ru/api-keys.json';
import ruCommon from './locales/ru/common.json';
import ruNav from './locales/ru/nav.json';
import ruHealth from './locales/ru/health.json';
import ruLlm from './locales/ru/llm.json';
import ruSettings from './locales/ru/settings.json';
import ruGit from './locales/ru/git.json';
import ruDashboard from './locales/ru/dashboard.json';
import ruProfile from './locales/ru/profile.json';
import ruReports from './locales/ru/reports.json';
import ruDatasets from './locales/ru/datasets.json';
import ruDatasetReview from './locales/ru/dataset_review.json';
import ruTasks from './locales/ru/tasks.json';
import ruDebug from './locales/ru/debug.json';
import ruAdmin from './locales/ru/admin.json';
import ruTranslate from './locales/ru/translate.json';
import ruValidation from './locales/ru/validation.json';
import ruAssistant from './locales/ru/assistant.json';
import ruAuth from './locales/ru/auth.json';
import ruMapper from './locales/ru/mapper.json';
import ruMigration from './locales/ru/migration.json';
import ruStorage from './locales/ru/storage.json';
import ruMaintenance from './locales/ru/maintenance.json';
import ruConnections from './locales/ru/connections.json';

// Merge domain objects into locale dictionaries
const en = {
	api_keys: enApiKeys,
	common: enCommon,
	nav: enNav,
	health: enHealth,
	llm: enLlm,
	settings: enSettings,
	git: enGit,
	dashboard: enDashboard,
	profile: enProfile,
	reports: enReports,
	datasets: enDatasets,
	dataset_review: enDatasetReview,
	tasks: enTasks,
	debug: enDebug,
	admin: enAdmin,
	translate: enTranslate,
	validation: enValidation,
	assistant: enAssistant,
	auth: enAuth,
	mapper: enMapper,
	migration: enMigration,
	storage: enStorage,
	maintenance: enMaintenance,
	connections: enConnections,
};

const ru = {
	api_keys: ruApiKeys,
	common: ruCommon,
	nav: ruNav,
	health: ruHealth,
	llm: ruLlm,
	settings: ruSettings,
	git: ruGit,
	dashboard: ruDashboard,
	profile: ruProfile,
	reports: ruReports,
	datasets: ruDatasets,
	dataset_review: ruDatasetReview,
	tasks: ruTasks,
	debug: ruDebug,
	admin: ruAdmin,
	translate: ruTranslate,
	validation: ruValidation,
	assistant: ruAssistant,
	auth: ruAuth,
	mapper: ruMapper,
	migration: ruMigration,
	storage: ruStorage,
	maintenance: ruMaintenance,
	connections: ruConnections,
};

const translationsMap = { ru, en };
type Locale = keyof typeof translationsMap;

/**
 * @purpose Determines the starting locale.
 * @returns {Locale}
 */
const getInitialLocale = (): Locale => {
  if (typeof localStorage !== 'undefined') {
    const saved = localStorage.getItem('locale');
    if (saved === 'ru' || saved === 'en') return saved as Locale;
  }
  return 'ru';
};

// ── Reactive State (Svelte 5 Runes) ───────────────────────────
let _locale = $state<Locale>(getInitialLocale());

// ── Subscriber Tracking (for backward compat with $t.xxx syntax) ─
const _localeSubs = new Set<(v: Locale) => void>();
const _tSubs = new Set<(v: any) => void>();

// ── Derived Translation Value ──────────────────────────────────
const _tValue = $derived.by(() => translationsMap[_locale] || translationsMap.ru);

// ── Explicit notifier (replaces $effect to avoid effect_orphan in tests) ──
// @RATIONALE Module-level $effect causes effect_orphan when vitest imports this
//            file outside a Svelte component context. Explicit _notifyAll() called
//            from locale.setter achieves the same persistence + subscriber update
//            without relying on the Svelte runtime.
function _notifyAll(): void {
  if (typeof localStorage !== 'undefined') {
    localStorage.setItem('locale', _locale);
  }
  _localeSubs.forEach((fn) => fn(_locale));
  _tSubs.forEach((fn) => fn(_tValue));
}

// ── Exports ────────────────────────────────────────────────────

// #region locale:Reactive [TYPE Function]
/**
 * @purpose Holds the current active locale string.
 * @side_effect Writes to LocalStorage on change (via $effect).
 *             Supports .subscribe() for backward compat with Svelte 4 store syntax.
 */
export const locale = {
  get current() { return _locale; },
  set current(v: Locale) {
    _locale = v;
    _notifyAll();
  },
  subscribe(fn: (v: Locale) => void) {
    fn(_locale);
    _localeSubs.add(fn);
    return () => { _localeSubs.delete(fn); };
  }
};
// #endregion locale:Reactive

// #region t:Reactive [TYPE Function]
// @RELATION BINDS_TO -> [locale:Reactive]
/**
 * @purpose Reactive translation dictionary.
 *             Uses Proxy to support both .subscribe() (for Svelte $t template syntax)
 *             and direct key access (e.g., t.dashboard?.load_failed in model files).
 */
export const t = new Proxy({} as any, {
  get(_target, prop) {
    if (prop === 'subscribe') {
      return (fn: (v: any) => void) => {
        fn(_tValue);
        _tSubs.add(fn);
        return () => { _tSubs.delete(fn); };
      };
    }
    if (prop === 'current') {
      return _tValue;
    }
    return (_tValue as any)[prop];
  }
});
// #endregion t:Reactive

/**
 * @purpose Get current translation dictionary directly (for model .svelte.ts files).
 *           Replaces `get(tStore)` pattern from svelte/store.
 */
export function getT(): any {
  return _tValue;
}

// #region _:Function [TYPE Function]
/**
 * @purpose Get translation by key path.
 * @param key - Translation key path (e.g., 'nav.dashboard')
 * @returns Translation string or key if not found
 */
export function _(key: string): string {
  const keys = key.split('.');
  let value: any = _tValue;

  for (const k of keys) {
    if (value && typeof value === 'object' && k in value) {
      value = value[k];
    } else {
      return key; // Return key if translation not found
    }
  }

  return typeof value === 'string' ? value : key;
}
// #endregion _:Function

// #endregion I18nModule
