"use client";

import { createContext, useContext, useEffect, type ReactNode } from "react";

import { getLocaleOption, type SupportedLocale } from "@/lib/i18n-config";
import {
  translate,
  translateStaticUiText,
  type TranslationKey,
} from "@/lib/i18n-dictionaries";

type TranslationValues = Record<string, string | number>;

type I18nContextValue = {
  locale: SupportedLocale;
  t: (key: TranslationKey, values?: TranslationValues) => string;
  tr: (source: string) => string;
};

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

export function I18nProvider({
  children,
  locale,
}: {
  children: ReactNode;
  locale: SupportedLocale;
}) {
  const value: I18nContextValue = {
    locale,
    t: (key, values) => translate(locale, key, values),
    tr: (source) => translateStaticUiText(locale, source),
  };

  useEffect(() => {
    document.documentElement.lang = getLocaleOption(locale).htmlLang;
  }, [locale]);

  return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
}

export function useI18n() {
  const value = useContext(I18nContext);

  if (!value) {
    throw new Error("useI18n must be used inside I18nProvider");
  }

  return value;
}
