import {
  cdcGpsfDashboardText,
  normalizeDashboardLanguage,
} from "./cdc-gpsf-dashboard-data";

const extras = {
  en: {
    totalPrimaryAgencies: "Total Primary Agencies",
    loadFailed: "Unable to load the dashboard.",
    exportChart: "Export chart",
    filter: "Filter",
    filterBy: "Filter by...",
    back: "Back",
    removeFilter: "Remove filter",
    noOptions: "No options available",
    clearAll: "Clear all",
    selectAll: "Select all",
    clearSelection: "Clear",
    month: "Month",
    filters: "Filters",
    viewAll: "View All",
    viewLess: "View Less",
    applyFilters: "Apply Filters",
  },
  kh: {
    totalPrimaryAgencies: "ស្ថាប័នទទួលបន្ទុកសរុប",
    loadFailed: "មិនអាចទាញយកផ្ទាំងគ្រប់គ្រងបានទេ។",
    exportChart: "នាំចេញក្រាហ្វ",
    filter: "តម្រង",
    filterBy: "តម្រងតាម...",
    back: "ត្រឡប់ក្រោយ",
    removeFilter: "លុបតម្រង",
    noOptions: "មិនមានជម្រើស",
    clearAll: "សម្អាតទាំងអស់",
    selectAll: "ជ្រើសរើសទាំងអស់",
    clearSelection: "សម្អាត",
    month: "ខែ",
    filters: "តម្រង",
    viewAll: "មើលទាំងអស់",
    viewLess: "មើលតិច",
    applyFilters: "អនុវត្តតម្រង",
  },
} as const;
export type DashboardModule = "pswg" | "ministry" | "cdc" | "cefp" | "cdcgpsf";
export type DashboardLabels = Record<
  keyof typeof cdcGpsfDashboardText.en | keyof typeof extras.en,
  string
>;
export function dashboardOwner(pathname: string): DashboardModule | null {
  const segment = pathname.split("/")[1];
  if (segment === "cdc-gpsf") return "cdcgpsf";
  return ["pswg", "ministry", "cdc", "cefp"].includes(segment)
    ? (segment as DashboardModule)
    : null;
}
export function dashboardPage(module: DashboardModule) {
  return ["pswg", "cdc", "cefp"].includes(module)
    ? "dashboard_working_group"
    : "dashboard";
}
export function dashboardTranslationKey(key: string) {
  if (key === "dashboard") return "page_title";
  return key.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
}
export function dashboardDefaults(language?: string): DashboardLabels {
  const lang = normalizeDashboardLanguage(language);
  return { ...cdcGpsfDashboardText[lang], ...extras[lang] };
}
export function resolveDashboardLabels(
  language: string,
  dictionary: Record<string, string>,
): DashboardLabels {
  return Object.fromEntries(
    Object.entries(dashboardDefaults(language)).map(([key, fallback]) => {
      const value = dictionary[dashboardTranslationKey(key)];
      return [
        key,
        typeof value === "string" && value.trim() ? value : fallback,
      ];
    }),
  ) as DashboardLabels;
}
export async function fetchDashboardDictionary(
  module: DashboardModule,
  language: string,
  signal?: AbortSignal,
  page = dashboardPage(module),
) {
  const base = (
    process.env.NEXT_PUBLIC_API_URL || "http://localhost:3001/api/v1"
  ).replace(/\/$/, "");
  const query = new URLSearchParams({
    module,
    page,
    language: normalizeDashboardLanguage(language) === "kh" ? "km" : "en",
  });
  const response = await fetch(base + "/translations/dictionary?" + query, {
    credentials: "include",
    cache: "no-store",
    signal,
  });
  if (!response.ok) throw new Error("Could not load dashboard translations");
  let value: unknown = await response.json();
  for (
    let depth = 0;
    depth < 5 && value && typeof value === "object";
    depth++
  ) {
    const record = value as Record<string, unknown>;
    if (record.translations && typeof record.translations === "object") {
      return Object.fromEntries(
        Object.entries(record.translations).filter(
          (entry): entry is [string, string] =>
            typeof entry[1] === "string" && !!entry[1].trim(),
        ),
      );
    }
    value = record.data;
  }
  return {};
}
