"use client"

import * as React from "react"

import { translator, type Locale, type Translate } from "@/lib/i18n"

/**
 * The reader's language, handed down once from the server.
 *
 * A context and not a prop threaded through every component, because the
 * language is the one thing every leaf needs and nothing in between cares
 * about. The shell reads it from the signed-in person and puts it here; a
 * client component asks `useT()` and never asks who is reading.
 *
 * There is no default and no fallback locale. A component rendered outside the
 * provider throws, which happens once, in development, on the first render of
 * whoever forgot it. Falling back to English would instead ship a Thai screen
 * with English words on it to somebody who cannot read them.
 */

const LocaleContext = React.createContext<Locale | null>(null)

export function LocaleProvider({
  locale,
  children,
}: {
  locale: Locale
  children: React.ReactNode
}) {
  return (
    <LocaleContext.Provider value={locale}>{children}</LocaleContext.Provider>
  )
}

export function useLocale(): Locale {
  const locale = React.useContext(LocaleContext)
  if (!locale) {
    throw new Error(
      "useLocale outside a LocaleProvider. The shell provides it; a screen that renders without the shell has to provide its own.",
    )
  }
  return locale
}

export function useT(): Translate {
  const locale = useLocale()
  return React.useMemo(() => translator(locale), [locale])
}
