import { createContext, useContext, useEffect, useMemo, useState, type ReactNode } from "react";
import { isRtl, type Locale } from "@/lib/clinic/locale";
import { DICTS, tPath } from "./index";
import type { Dict } from "./en";

type I18nValue = {
  locale: Locale;
  dir: "rtl" | "ltr";
  dict: Dict;
  setLocale: (locale: Locale) => void;
  t: (path: string) => string;
};

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

export function I18nProvider({ initial, copy = {}, children }: { initial: Locale; copy?: Record<string, Record<string, string>>; children: ReactNode }) {
  const [locale, setLocaleState] = useState<Locale>(initial);

  useEffect(() => {
    document.documentElement.lang = locale;
    document.documentElement.dir = isRtl(locale) ? "rtl" : "ltr";
    document.title = DICTS[locale].metaTitle;
    try {
      localStorage.setItem("aurelia.locale", locale);
      document.cookie = `aurelia_locale=${locale};path=/;max-age=31536000;samesite=lax`;
    } catch {
      /* ignore private mode */
    }
  }, [locale]);

  const value = useMemo<I18nValue>(() => {
    const dict = DICTS[locale];
    return {
      locale,
      dir: isRtl(locale) ? "rtl" : "ltr",
      dict,
      setLocale: setLocaleState,
      t: (path: string) => copy[locale]?.[path] || tPath(dict, path),
    };
  }, [locale, copy]);

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

export function useI18n(): I18nValue {
  const ctx = useContext(I18nContext);
  if (!ctx) throw new Error("useI18n outside provider");
  return ctx;
}
