/**
 * earth-now.co
 * Author:  Simon-Pierre Boucher
 * Contact: contact@spboucher.ai
 * File:    apps/web/lib/i18n.tsx
 * Purpose: Tiny client-side locale context (fr/en) — provider + useI18n hook, UI strings only (metric text comes from the API)
 */

"use client";

import { createContext, useContext, type ReactNode } from "react";
import type { Locale } from "./api";
import { getMessages, type MessageKey } from "./messages";

interface I18nContextValue {
  locale: Locale;
  setLocale: (locale: Locale) => void;
  t: (key: MessageKey) => string;
}

const I18nContext = createContext<I18nContextValue | null>(null);

export function I18nProvider({
  locale,
  setLocale,
  children,
}: {
  locale: Locale;
  setLocale: (locale: Locale) => void;
  children: ReactNode;
}) {
  const messages = getMessages(locale);
  const value: I18nContextValue = {
    locale,
    setLocale,
    t: (key) => messages[key],
  };
  return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
}

export function useI18n(): I18nContextValue {
  const ctx = useContext(I18nContext);
  if (ctx === null) throw new Error("useI18n must be used inside <I18nProvider>");
  return ctx;
}
