"use client";

import { createContext, useContext } from "react";
import { FA_FALLBACK } from "@/context/fa-fallback";

export const TranslationMapContext = createContext<Record<string, string>>({});

/** برای SSR وقتی Context هنوز در دسترس نیست */
let globalTranslationMap: Record<string, string> = {};

export const setGlobalTranslationMap = (map: Record<string, string> | undefined) => {
  if (map && Object.keys(map).length > 0) {
    globalTranslationMap = map;
  }
};

export const useTranslationMap = () => useContext(TranslationMapContext);

/** ترجمه پایدار SSR/CSR + fallback فارسی */
export const useT = () => {
  const ctx = useTranslationMap();
  const map = Object.keys(ctx).length > 0 ? ctx : globalTranslationMap;
  return (key: string) => {
    if (!key) return "";
    const raw = map[key] ?? globalTranslationMap[key] ?? FA_FALLBACK[key] ?? key;
    // رشته خالی از API باعث mismatch با fallback می‌شود
    return raw === "" ? FA_FALLBACK[key] ?? key : raw;
  };
};
