// Tiny typed i18n — no library. en.ts is the source of truth; de.ts mirrors
// its shape (compiler-enforced via Dict). Components call useT() and read
// nested keys with full autocomplete: t.live.todayHeading.
import { en, type Dict } from './en';
import { de } from './de';
import { useLocaleStore, type Locale } from '@/stores/localeStore';
import { kickoffDay, kickoffTime, relativeKickoff } from '@/lib/format';

export type { Dict } from './en';

const dicts: Record<Locale, Dict> = { en, de };

/** Reactive dictionary for components — re-renders on locale switch. */
export function useT(): Dict {
  return dicts[useLocaleStore((s) => s.locale)];
}

/** Non-hook access (event handlers, module-level helpers). */
export function getDict(): Dict {
  return dicts[useLocaleStore.getState().locale];
}

/** "{n} of {total}" interpolation. */
export function fmt(tpl: string, vars: Record<string, string | number>): string {
  return tpl.replace(/\{(\w+)\}/g, (m, k: string) => (k in vars ? String(vars[k]) : m));
}

export interface Plural {
  one: string;
  other: string;
}

/** English/German share the one/other cardinal split. */
export function plural(p: Plural, n: number): string {
  return fmt(n === 1 ? p.one : p.other, { n });
}

/** Split a template around {placeholders} so React nodes (e.g. glossary <Term>
 *  chips) can be spliced in: fmtSplit("a {x} b") → ["a ", {key:"x"}, " b"]. */
export function fmtSplit(tpl: string): (string | { key: string })[] {
  const out: (string | { key: string })[] = [];
  const re = /\{(\w+)\}/g;
  let last = 0;
  for (let m = re.exec(tpl); m; m = re.exec(tpl)) {
    if (m.index > last) out.push(tpl.slice(last, m.index));
    out.push({ key: m[1]! });
    last = m.index + m[0].length;
  }
  if (last < tpl.length) out.push(tpl.slice(last));
  return out;
}

/** Locale-bound date formatters + the dictionary, in one hook. */
export function useFormat(): {
  t: Dict;
  locale: Locale;
  kickoffTime: (iso: string) => string;
  kickoffDay: (iso: string) => string;
  relativeKickoff: (iso: string) => string;
} {
  const locale = useLocaleStore((s) => s.locale);
  const t = dicts[locale];
  return {
    t,
    locale,
    kickoffTime: (iso) => kickoffTime(iso, locale),
    kickoffDay: (iso) => kickoffDay(iso, locale),
    relativeKickoff: (iso) => relativeKickoff(iso, locale, { inMinutes: t.common.inMinutes, todayAt: t.common.todayAt }),
  };
}
