import { derived } from 'svelte/store';
import { language } from '$lib/stores/global';
import { en } from './en';
import { pt } from './pt';

export type Language = 'en' | 'pt';
export type TranslationKey = keyof typeof en;

const translations = { en, pt };

export const t = derived(language, ($lang) => {
	return (key: TranslationKey, params?: Record<string, string | number>): string => {
		let text = translations[$lang][key] || translations.en[key] || key;

		if (params) {
			Object.entries(params).forEach(([k, v]) => {
				text = text.replace(`{${k}}`, String(v));
			});
		}

		return text;
	};
});

export function setLanguage(lang: Language) {
	language.set(lang);
}
