/**
 * Lightweight i18n system using Svelte stores.
 * Task 13: EN/RU localization with locale switcher and localStorage persistence.
 */

import { writable, derived } from 'svelte/store';
import en from './en.json';
import ru from './ru.json';

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

const LOCALE_KEY = 'dw_locale';

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

function getInitialLocale(): Locale {
	if (typeof localStorage !== 'undefined') {
		const stored = localStorage.getItem(LOCALE_KEY);
		if (stored === 'en' || stored === 'ru') return stored;
	}

	if (typeof navigator !== 'undefined') {
		const lang = navigator.language.toLowerCase();
		if (lang.startsWith('ru')) return 'ru';
	}

	return 'en';
}

export const locale = writable<Locale>(getInitialLocale());

// Persist locale changes to localStorage.
locale.subscribe((value) => {
	if (typeof localStorage !== 'undefined') {
		localStorage.setItem(LOCALE_KEY, value);
	}
});

/**
 * Look up a nested key like "dashboard.title" in the translation object.
 */
function getNestedValue(obj: Record<string, unknown>, path: string): string {
	const parts = path.split('.');
	let current: unknown = obj;
	for (const part of parts) {
		if (current === null || current === undefined || typeof current !== 'object') {
			return path;
		}
		current = (current as Record<string, unknown>)[part];
	}
	return typeof current === 'string' ? current : path;
}

/**
 * Derived store that returns a translation function.
 * Usage: $t('dashboard.title') or $t('projectDetail.deleteConfirmMessage', { name: 'my-app' })
 */
export const t = derived(locale, ($locale) => {
	const dict = translations[$locale] ?? translations.en;

	return (key: string, params?: Record<string, string>): string => {
		let result = getNestedValue(dict as Record<string, unknown>, key);

		// Fallback to English if key not found in current locale.
		if (result === key) {
			result = getNestedValue(translations.en as Record<string, unknown>, key);
		}

		// Replace {param} placeholders.
		if (params) {
			for (const [paramKey, paramValue] of Object.entries(params)) {
				result = result.replace(new RegExp(`\\{${paramKey}\\}`, 'g'), paramValue);
			}
		}

		return result;
	};
});

export function setLocale(newLocale: Locale): void {
	locale.set(newLocale);
}

export const availableLocales: readonly Locale[] = ['en', 'ru'] as const;
