import type { TranslationKey } from "./keys.js";

export type { TranslationKey };
export type Locale = "de" | "en";

type TranslationMap = Record<string, string>;

let _current: Locale = (localStorage.getItem("locale") as Locale) ?? "de";
const _cache = new Map<Locale, TranslationMap>();
const _listeners = new Set<() => void>();

async function _load(l: Locale): Promise<void> {
  if (_cache.has(l)) return;
  const res = await fetch(`/locales/${l}.json`);
  if (!res.ok) throw new Error(`Failed to load locale "${l}"`);
  _cache.set(l, await res.json());
}

export const locale = {
  get current(): Locale {
    return _current;
  },

  async init(): Promise<void> {
    await _load(_current);
    _listeners.forEach((fn) => fn());
  },

  async set(l: Locale): Promise<void> {
    await _load(l);
    _current = l;
    localStorage.setItem("locale", l);
    _listeners.forEach((fn) => fn());
  },

  t(key: TranslationKey): string {
    return _cache.get(_current)?.[key] ?? key;
  },

  subscribe(fn: () => void): () => void {
    _listeners.add(fn);
    return () => _listeners.delete(fn);
  },
};
