/**
 * Reactive i18n module using Svelte 5 $state rune.
 * Locale changes automatically propagate to all components using t().
 */

import en from './en.json';
import ru from './ru.json';

export type Locale = 'en' | 'ru';

const translations: Record<Locale, Record<string, any>> = { en, ru };

function detectLocale(): Locale {
	if (typeof localStorage !== 'undefined') {
		const saved = localStorage.getItem('locale') as Locale | null;
		if (saved && saved in translations) return saved;
	}
	if (typeof navigator !== 'undefined') {
		const lang = navigator.language.slice(0, 2);
		if (lang in translations) return lang as Locale;
	}
	return 'en';
}

let currentLocale = $state<Locale>(detectLocale());

export function getLocale(): Locale {
	return currentLocale;
}

export function setLocale(locale: Locale) {
	currentLocale = locale;
	if (typeof localStorage !== 'undefined') {
		localStorage.setItem('locale', locale);
	}
}

export function initLocale() {
	// No-op: locale is auto-detected at module load via $state.
	// Kept for backward compatibility with existing onMount calls.
}

/**
 * Get a translated string by dot-separated key.
 * Falls back to English if key not found in current locale.
 * Reactive: re-evaluates when currentLocale changes.
 */
export function t(key: string, fallback?: string): string {
	return resolve(translations[currentLocale], key)
		?? resolve(translations.en, key)
		?? fallback
		?? key;
}

function resolve(obj: any, path: string): string | undefined {
	const parts = path.split('.');
	let current = obj;
	for (const part of parts) {
		if (current == null || typeof current !== 'object') return undefined;
		current = current[part];
	}
	return typeof current === 'string' ? current : undefined;
}
