import type { Metadata } from "next";

import enAdminUsers from "@/i18n/locales/en/adminUsers.json";
import enAudit from "@/i18n/locales/en/audit.json";
import enAuth from "@/i18n/locales/en/auth.json";
import enConfig from "@/i18n/locales/en/config.json";
import enDashboard from "@/i18n/locales/en/dashboard.json";
import enDraws from "@/i18n/locales/en/draws.json";
import enJackpot from "@/i18n/locales/en/jackpot.json";
import enPlayers from "@/i18n/locales/en/players.json";
import enReconcile from "@/i18n/locales/en/reconcile.json";
import enReports from "@/i18n/locales/en/reports.json";
import enRisk from "@/i18n/locales/en/risk.json";
import enSettlement from "@/i18n/locales/en/settlement.json";
import enCommon from "@/i18n/locales/en/common.json";
import enTickets from "@/i18n/locales/en/tickets.json";
import enWallet from "@/i18n/locales/en/wallet.json";
import enAgents from "@/i18n/locales/en/agents.json";
import enSettlementCenter from "@/i18n/locales/en/settlementCenter.json";

const EN_FLAT: Record<string, Record<string, unknown>> = {
  dashboard: enDashboard,
  players: enPlayers,
  draws: enDraws,
  tickets: enTickets,
  settlement: enSettlement,
  reconcile: enReconcile,
  reports: enReports,
  audit: enAudit,
  adminUsers: enAdminUsers,
  adminRoles: enAdminUsers,
  wallet: enWallet,
  risk: enRisk,
  jackpot: enJackpot,
  config: enConfig,
  common: enCommon,
  auth: enAuth,
  agents: enAgents,
  settlementCenter: enSettlementCenter,
};

function getByPath(obj: Record<string, unknown>, path: string): string | undefined {
  const parts = path.split(".");
  let cur: unknown = obj;
  for (const part of parts) {
    if (cur == null || typeof cur !== "object") {
      return undefined;
    }
    cur = (cur as Record<string, unknown>)[part];
  }
  return typeof cur === "string" ? cur : undefined;
}

/** SSR 默认英文标题；客户端由 {@link AdminDocumentTitle} 按用户语言覆盖。 */
export function buildPageMetadata(ns: string, key: string): Metadata {
  const bundle = EN_FLAT[ns];
  const title = bundle ? getByPath(bundle as Record<string, unknown>, key) : undefined;

  return {
    title: title ?? key,
  };
}
