/* i18n — lightweight translation registry.

   Usage from any component:
     window.T("nav.dashboard", "Dashboard")  // fallback if key missing
     window.T("kpi.totalVolume")             // falls back to the key itself

   Switching locale:
     window.setLocale("it")
     window.setLocale("en")
   Components that need to re-render on locale change call useLocale().

   Supported locales: Italian (default) + English. Missing keys fall back
   to the EN dictionary, then the caller-supplied fallback, then the key. */

const I18N_DICT = {
  en: {
    /* Navy strip + mobile header */
    "navy.saldo":         "Balance",
    "navy.fido":          "Credit",
    "navy.disponibilita": "Available",
    "navy.tweaks":        "Tweaks",
    "navy.menu":          "Menu",
    "navy.mute":          "Mute notifications",
    "navy.muted":         "Notifications muted",
    "navy.switchBrand":   "Switch brand",

    /* Host nav (White Label menu items) */
    "host.dashboard":  "Dashboard",
    "host.players":    "Players",
    "host.listaUtenti":"Users",
    "host.sportCoupons":"Sport coupons",
    "host.deposit":    "Deposit",
    "host.rete":       "Network",
    "host.payments":   "Payments",
    "host.bonus":      "Bonus campaigns",
    "host.report":     "Reports",
    "host.voucher":    "Voucher",
    "host.settings":   "Settings",
    "host.commission": "Commissions",
    "host.cms":        "CMS",
    "host.depositsList":  "Deposits",
    "host.withdrawsList": "Withdraws",
    "host.messaggi":   "Messages",

    /* Report dropdown (host menu) */
    "report.bonusRetention":     "Bonus Retention",
    "report.conversion":         "Conversion",
    "report.players":            "Players Report",
    "report.betting":            "Betting",
    "report.betType":            "Bet type",
    "report.daily":              "Daily Report",
    "report.transactions":       "Transactions",
    "report.creditTransactions": "Credit Transactions",
    "report.withdrawalRequests": "My withdrawal requests",
    "report.commissions":        "Commissions",
    "report.providerCosts":      "Provider Costs",
    "report.netWin":             "NetWin",
    "report.dailyPerformance":   "Daily Performance",
    "report.summary":            "Summary",
    "report.business":           "Business report",

    /* PayBO subnav + section groups */
    "sub.overview":       "Overview",
    "sub.dashboard":      "Dashboard",
    "sub.activity":       "Activity log",
    "sub.payments":       "Payments",
    "sub.transactions":   "Transactions",
    "sub.deposits":       "Deposits",
    "sub.withdrawals":    "Withdrawals",
    "sub.methods":        "Payment methods",
    "sub.players":        "Players",
    "sub.finance":        "Finance",
    "sub.reports":        "Reports",
    "sub.platform":       "Platform",
    "sub.settingsPage":   "Settings",
    "sub.development":    "Development",
    "sub.hostGroup":      "White Label host",
    "sub.payboGroup":     "PayBO sections",

    /* Common actions */
    "btn.save":           "Save changes",
    "btn.cancel":         "Cancel",
    "btn.delete":         "Delete",
    "btn.edit":           "Edit",
    "btn.add":            "Add",
    "btn.export":         "Export",
    "btn.exportCSV":      "Export CSV",
    "btn.clearAll":       "Clear all",
    "btn.enableAll":      "Enable for all",
    "btn.disableAll":     "Disable for all",
    "btn.refresh":        "Refresh",
    "btn.close":          "Close",
    "btn.back":           "Back",
    "btn.viewAll":        "View all",
    "btn.message":        "Message",
    "btn.suspend":        "Suspend account",
    "btn.reactivate":     "Reactivate account",
    "btn.manualDeposit":  "Manual deposit",
    "btn.manualWithdraw": "Manual withdraw",
    "btn.changeLevel":    "Change level",
    "btn.overrideLimits": "Override limits",
    "btn.toggleAutoApprove":"Toggle auto-approve",
    "btn.addPlayer":      "Add player",
    "btn.addMethod":      "Add method",
    "btn.deleteMethod":   "Delete method",
    "btn.addBrand":       "Add brand",
    "btn.editPlayer":     "Edit player",

    /* Common labels + filter facets */
    "lbl.status":         "Status",
    "lbl.enabled":        "Enabled",
    "lbl.disabled":       "Disabled",
    "lbl.all":            "All",
    "lbl.allBrands":      "All brands",
    "lbl.allLevels":      "All levels",
    "lbl.allCountries":   "All countries",
    "lbl.allCurrencies":  "All currencies",
    "lbl.allKinds":       "All kinds",
    "lbl.allActions":     "All actions",
    "lbl.allRoles":       "All roles",
    "lbl.allStates":      "All states",
    "lbl.allMethods":     "All methods",
    "lbl.brand":          "Brand",
    "lbl.method":         "Method",
    "lbl.country":        "Country",
    "lbl.currency":       "Currency",
    "lbl.level":          "Level",
    "lbl.kyc":            "KYC",
    "lbl.role":           "Role",
    "lbl.state":          "State",
    "lbl.active":         "Active",
    "lbl.suspended":      "Suspended",
    "lbl.restricted":     "Restricted methods",
    "lbl.kind":           "Kind",
    "lbl.action":         "Action",
    "lbl.actor":          "Actor",
    "lbl.operator":       "Operator",
    "lbl.minAmount":      "Min amount",
    "lbl.maxAmount":      "Max amount",
    "lbl.amountRange":    "Amount range",
    "lbl.type":           "Type",
    "lbl.environment":    "Environment",
    "lbl.search":         "Search",

    /* Reports KPIs */
    "kpi.totalVolume":    "Total volume",
    "kpi.transactions":   "Transactions",
    "kpi.avgBasket":      "Avg basket",
    "kpi.approvalRate":   "Approval rate",
    "kpi.activePlayers":  "Active (7d)",
    "kpi.depositLTV":     "Deposit LTV",
    "kpi.feesCollected":  "Fees collected",
    "kpi.netPosition":    "Net position (14d)",

    /* Page titles */
    "page.reports":       "Reports & analytics",
    "page.accounts":      "Accounts",
    "page.methods":       "Payment methods",
    "page.activity":      "Activity feed",
    "page.devCto":        "Development · CTO briefing",
    "page.settings":      "Settings",
    "page.dashboard":     "Dashboard",

    /* Reports tab labels */
    "rpt.overview":       "Overview",
    "rpt.players":        "Players",
    "rpt.methods":        "Methods",
    "rpt.brands":         "Brands",
    "rpt.cashflow":       "Cashflow",
    "rpt.geography":      "Geography",
    "rpt.ops":            "Ops & Queue",
    "rpt.fees":           "Fees",
    "rpt.risk":           "Risk",
    "rpt.currencies":     "Currencies",

    /* Tweaks panel */
    "tweaks.title":       "Tweaks",
    "tweaks.navPattern":  "Navigation pattern",
    "tweaks.accent":      "Accent color",
    "tweaks.density":     "Density",
    "tweaks.language":    "Language",

    /* Languages */
    "lang.en":            "English",
    "lang.it":            "Italiano",
  },

  it: {
    /* Navy strip */
    "navy.saldo":         "Saldo",
    "navy.fido":          "Fido",
    "navy.disponibilita": "Disponibilità",
    "navy.tweaks":        "Tweaks",
    "navy.menu":          "Menu",
    "navy.mute":          "Silenzia notifiche",
    "navy.muted":         "Notifiche silenziate",
    "navy.switchBrand":   "Cambia brand",

    /* Host nav */
    "host.dashboard":  "Dashboard",
    "host.players":    "Players",
    "host.listaUtenti":"Lista utenti",
    "host.sportCoupons":"Coupon sportivi",
    "host.deposit":    "Deposito",
    "host.rete":       "Rete Commerciale",
    "host.payments":   "Payments",
    "host.bonus":      "Promozioni Bonus",
    "host.report":     "Report",
    "host.voucher":    "Voucher",
    "host.settings":   "Impostazioni",
    "host.commission": "Commissioni",
    "host.cms":        "CMS",
    "host.depositsList":  "Deposits",
    "host.withdrawsList": "Withdraws",
    "host.messaggi":   "Messaggi",

    /* Report dropdown (host menu) */
    "report.bonusRetention":     "Bonus Retention",
    "report.conversion":         "Conversion",
    "report.players":            "Report giocatori",
    "report.betting":            "Report scommesse",
    "report.betType":            "Tipo di scommessa",
    "report.daily":              "Report giornaliero",
    "report.transactions":       "Transazioni",
    "report.creditTransactions": "Transazioni Fido",
    "report.withdrawalRequests": "Le mie richieste di prelievo",
    "report.commissions":        "Commissioni",
    "report.providerCosts":      "Costi Skin",
    "report.netWin":             "NetWin",
    "report.dailyPerformance":   "Rendimento Giornaliero",
    "report.summary":            "Riepilogo",
    "report.business":           "Business report",

    /* PayBO subnav */
    "sub.overview":       "Panoramica",
    "sub.dashboard":      "Dashboard",
    "sub.activity":       "Log attività",
    "sub.payments":       "Pagamenti",
    "sub.transactions":   "Transazioni",
    "sub.deposits":       "Depositi",
    "sub.withdrawals":    "Prelievi",
    "sub.methods":        "Metodi di pagamento",
    "sub.players":        "Giocatori",
    "sub.finance":        "Finanza",
    "sub.reports":        "Report",
    "sub.platform":       "Piattaforma",
    "sub.settingsPage":   "Impostazioni",
    "sub.development":    "Sviluppo",
    "sub.hostGroup":      "White Label host",
    "sub.payboGroup":     "Sezioni PayBO",

    /* Common actions */
    "btn.save":           "Salva modifiche",
    "btn.cancel":         "Annulla",
    "btn.delete":         "Elimina",
    "btn.edit":           "Modifica",
    "btn.add":            "Aggiungi",
    "btn.export":         "Esporta",
    "btn.exportCSV":      "Esporta CSV",
    "btn.clearAll":       "Pulisci tutto",
    "btn.enableAll":      "Abilita per tutti",
    "btn.disableAll":     "Disabilita per tutti",
    "btn.refresh":        "Aggiorna",
    "btn.close":          "Chiudi",
    "btn.back":           "Indietro",
    "btn.viewAll":        "Vedi tutto",
    "btn.message":        "Messaggio",
    "btn.suspend":        "Sospendi account",
    "btn.reactivate":     "Riattiva account",
    "btn.manualDeposit":  "Deposito manuale",
    "btn.manualWithdraw": "Prelievo manuale",
    "btn.changeLevel":    "Cambia livello",
    "btn.overrideLimits": "Override limiti",
    "btn.toggleAutoApprove":"Commuta auto-approvazione",
    "btn.addPlayer":      "Aggiungi giocatore",
    "btn.addMethod":      "Aggiungi metodo",
    "btn.deleteMethod":   "Elimina metodo",
    "btn.addBrand":       "Aggiungi brand",
    "btn.editPlayer":     "Modifica giocatore",

    /* Labels */
    "lbl.status":         "Stato",
    "lbl.enabled":        "Abilitato",
    "lbl.disabled":       "Disabilitato",
    "lbl.all":            "Tutti",
    "lbl.allBrands":      "Tutti i brand",
    "lbl.allLevels":      "Tutti i livelli",
    "lbl.allCountries":   "Tutti i paesi",
    "lbl.allCurrencies":  "Tutte le valute",
    "lbl.allKinds":       "Tutti i tipi",
    "lbl.allActions":     "Tutte le azioni",
    "lbl.allRoles":       "Tutti i ruoli",
    "lbl.allStates":      "Tutti gli stati",
    "lbl.allMethods":     "Tutti i metodi",
    "lbl.brand":          "Brand",
    "lbl.method":         "Metodo",
    "lbl.country":        "Paese",
    "lbl.currency":       "Valuta",
    "lbl.level":          "Livello",
    "lbl.kyc":            "KYC",
    "lbl.role":           "Ruolo",
    "lbl.state":          "Stato",
    "lbl.active":         "Attivo",
    "lbl.suspended":      "Sospeso",
    "lbl.restricted":     "Metodi limitati",
    "lbl.kind":           "Tipo",
    "lbl.action":         "Azione",
    "lbl.actor":          "Attore",
    "lbl.operator":       "Operatore",
    "lbl.minAmount":      "Importo min",
    "lbl.maxAmount":      "Importo max",
    "lbl.amountRange":    "Intervallo importo",
    "lbl.type":           "Tipo",
    "lbl.environment":    "Ambiente",
    "lbl.search":         "Cerca",

    /* KPIs */
    "kpi.totalVolume":    "Volume totale",
    "kpi.transactions":   "Transazioni",
    "kpi.avgBasket":      "Carrello medio",
    "kpi.approvalRate":   "Tasso di approvazione",
    "kpi.activePlayers":  "Attivi (7g)",
    "kpi.depositLTV":     "LTV depositi",
    "kpi.feesCollected":  "Commissioni raccolte",
    "kpi.netPosition":    "Posizione netta (14g)",

    /* Pages */
    "page.reports":       "Report e analisi",
    "page.accounts":      "Account",
    "page.methods":       "Metodi di pagamento",
    "page.activity":      "Feed attività",
    "page.devCto":        "Sviluppo · Briefing CTO",
    "page.settings":      "Impostazioni",
    "page.dashboard":     "Dashboard",

    /* Reports tab labels */
    "rpt.overview":       "Panoramica",
    "rpt.players":        "Giocatori",
    "rpt.methods":        "Metodi",
    "rpt.brands":         "Brand",
    "rpt.cashflow":       "Flusso di cassa",
    "rpt.geography":      "Geografia",
    "rpt.ops":            "Ops & Coda",
    "rpt.fees":           "Commissioni",
    "rpt.risk":           "Rischio",
    "rpt.currencies":     "Valute",

    /* Tweaks */
    "tweaks.title":       "Tweaks",
    "tweaks.navPattern":  "Schema di navigazione",
    "tweaks.accent":      "Colore accento",
    "tweaks.density":     "Densità",
    "tweaks.language":    "Lingua",

    /* Languages */
    "lang.en":            "English",
    "lang.it":            "Italiano",
  },
};

/* --- runtime API -------------------------------------------------- */

(function setupI18n(){
  const KEY = "pb-locale";
  let current = pbStore.get(KEY, "it") || "it";
  // Fall back to IT for any stored preference we no longer ship (e.g. "fr").
  if (!I18N_DICT[current]) current = "it";
  window.__LOCALE__ = current;

  window.getLocale = () => window.__LOCALE__;

  window.setLocale = (locale) => {
    if (!I18N_DICT[locale]) return;
    window.__LOCALE__ = locale;
    pbStore.set(KEY, locale);
    document.documentElement.setAttribute("lang", locale);
    window.dispatchEvent(new Event("localechange"));
  };
  document.documentElement.setAttribute("lang", current);

  window.T = (key, fallback) => {
    const dict = I18N_DICT[window.__LOCALE__] || I18N_DICT.en;
    if (dict[key] != null) return dict[key];
    if (I18N_DICT.en[key] != null) return I18N_DICT.en[key];
    return fallback != null ? fallback : key;
  };

  window.AVAILABLE_LOCALES = [
    { id: "it", label: "Italiano", flag: "🇮🇹" },
    { id: "en", label: "English",  flag: "🇬🇧" },
  ];
})();

/* React hook — components call this to re-render when the locale flips */
const useLocale = () => {
  const [, bump] = React.useState(0);
  React.useEffect(() => {
    const fn = () => bump(v => v + 1);
    window.addEventListener("localechange", fn);
    return () => window.removeEventListener("localechange", fn);
  }, []);
  return window.__LOCALE__;
};
window.useLocale = useLocale;
