import { EN, TH, type MessageKey } from "@/lib/i18n/messages"

/**
 * Saying something in the reader's language.
 *
 * Pure, like the dictionary it reads, so a client component may take both.
 */

export const LOCALES = ["en", "th"] as const

export type Locale = (typeof LOCALES)[number]

export function isLocale(value: unknown): value is Locale {
  return (
    typeof value === "string" && (LOCALES as readonly string[]).includes(value)
  )
}

/**
 * What each language calls itself, in itself.
 *
 * Never "English / Thai" in English. Somebody who cannot read the interface is
 * exactly the person reaching for this control, and a switcher labelled in the
 * language they cannot read is a switcher they cannot find.
 */
export const LANGUAGE_NAMES: Record<Locale, string> = {
  en: "English",
  th: "ไทย",
}

const DICTIONARIES: Record<Locale, Record<MessageKey, string>> = {
  en: EN,
  th: TH,
}

export type Translate = (
  key: MessageKey,
  values?: Record<string, string | number>,
) => string

/**
 * `{name}` is replaced and nothing else is.
 *
 * No plurals: Thai has no plural form, and an English count reads the same
 * either way once the number is in the sentence. No dates or numbers either,
 * because those go through `toLocaleDateString` where the reader's language is
 * one argument among several and the timezone matters more.
 */
export function translator(locale: Locale): Translate {
  const dictionary = DICTIONARIES[locale]
  return (key, values) => {
    const message = dictionary[key]
    if (!values) return message
    return message.replace(/\{(\w+)\}/g, (whole, name: string) =>
      name in values ? String(values[name]) : whole,
    )
  }
}
