import { useCallback, useMemo } from "react";
import type { TransactionKind } from "./shared/types";

type Locale = "en" | "fr";

const translations = {
  en: {
    "app.name": "Crédit Mabligop",
    "common.loading": "Loading...",
    "common.loadingChats": "Loading messages...",
    "common.loadingChat": "Loading conversation...",
    "common.loadingLobby": "Entering agency setup...",
    "common.notice": "Notice:",
    "common.online": "online",
    "common.offline": "offline",
    "common.dummy": "Assisted customer",
    "common.player": "Customer",
    "common.banker": "Advisor",
    "common.bank": "Bank",
    "common.from": "From",
    "common.to": "To",
    "common.guest": "Guest",
    "common.you": "You",
    "common.join": "Join",
    "common.continue": "Continue",
    "common.retryNow": "Retry now",
    "common.transactions": "Transactions",
    "common.send": "Send",
    "common.reset": "Reset",
    "common.cancel": "Cancel",
    "common.done": "Done",
    "common.exit": "Exit",
    "common.save": "Save",
    "common.load": "Load",
    "common.noReason": "No reason provided",
    "entry.subtitle": "Open or access an agency.",
    "entry.heroBadge": "Mobile banking companion",
    "entry.landingTitle": "Access your agency.",
    "entry.landingBody":
      "Use your agency code to sign in, or open a new agency if you are the advisor in charge.",
    "entry.landingFooter": "Real-time balances, transfers, and approvals for Crédit Mabligop agencies.",
    "entry.metricRealtimeValue": "Live",
    "entry.metricRealtimeLabel": "Transfers and balances stay synchronized.",
    "entry.metricSupervisedValue": "Advisor-led",
    "entry.metricSupervisedLabel": "Agencies stay under advisor control.",
    "entry.primaryEyebrow": "Customer access",
    "entry.secondaryEyebrow": "Advisor access",
    "entry.accessAgency": "Access an agency",
    "entry.accessAgencyHint":
      "Enter your agency code, identify yourself, and recover an existing profile if needed.",
    "entry.openAgency": "Open an agency",
    "entry.openAgencyHint":
      "Launch a supervised agency, invite customers, and approve assisted-profile recovery.",
    "entry.joinStepTitle": "Identify your agency.",
    "entry.joinStepSubtitle":
      "Enter the agency code shared by your advisor to view the available customer access options.",
    "entry.createStepTitle": "Open a new agency.",
    "entry.createStepSubtitle":
      "Create an advisor-controlled space for balances, transfers, approvals, and assisted customers.",
    "entry.joinTitle": "Agency access",
    "entry.joinDescription": "Use your agency code to retrieve available customer profiles.",
    "entry.sessionCode": "Agency code",
    "entry.previewLabel": "Agency found",
    "entry.agencyCodeValue": "Agency code: {code}",
    "entry.previewCustomers": "{count} customer profiles currently registered.",
    "entry.newPlayer": "Join as a new customer",
    "entry.newCustomerDescription":
      "Create a fresh customer profile and enter the agency immediately.",
    "entry.joinAsCustomer": "Join agency",
    "entry.playerName": "Customer name",
    "entry.takeoverTitle": "Recover an existing profile",
    "entry.recoverCustomerDescription":
      "Request access to an assisted customer profile. An advisor must approve the recovery.",
    "entry.alreadyConnected": "This customer profile is already connected.",
    "entry.dummyId": "Dummy ID (select later)",
    "entry.selectDummy": "Select an assisted customer",
    "entry.yourNameOptional": "Your name (optional)",
    "entry.requestTakeover": "Request advisor approval",
    "entry.noDummies": "No assisted customer profiles are available yet.",
    "entry.takeoverPending": "Waiting for an advisor to approve your recovery request.",
    "entry.createTitle": "Advisor profile",
    "entry.createDescription":
      "The first profile created becomes the advisor supervising this agency.",
    "entry.bankerName": "Advisor name",
    "entry.advisorName": "Advisor name",
    "entry.openVault": "Open agency",
    "entry.linkAccessExisting": "Access an existing agency instead",
    "entry.linkOpenNew": "Open a new agency instead",
    "entry.alert.enterCode": "Enter an agency code",
    "entry.alert.enterAdvisorName": "Enter an advisor name",
    "entry.alert.sessionNotFound": "Agency not found",
    "entry.alert.selectDummy": "Select an assisted customer",
    "entry.alert.takeoverFailed": "Unable to request takeover. Please try again.",
    "lobby.title": "Agency setup",
    "lobby.code": "Agency code: {code}",
    "lobby.startGame": "Open agency",
    "lobby.addDummyTitle": "Add an assisted customer",
    "lobby.addDummySubtitle":
      "Create a supervised customer profile for someone without the mobile app.",
    "lobby.enterDummyName": "Enter an assisted customer name",
    "lobby.addDummyButton": "Create assisted customer",
    "lobby.heroAdvisor":
      "Finalize customer access, review recoveries, and open the agency when everything is ready.",
    "lobby.heroCustomer":
      "Your advisor is preparing the agency. You will enter as soon as the agency opens.",
    "lobby.customers": "Customers",
    "lobby.assisted": "Assisted",
    "lobby.rosterTitle": "Agency roster",
    "lobby.waitingTitle": "Waiting for agency opening",
    "lobby.waitingBody":
      "Transfers, balances, and conversations unlock once the advisor opens the agency.",
    "session.exit": "Leave agency",
    "session.exitPrompt": "Leave this agency?",
    "session.exitMessage": "You can access it again later with the agency code.",
    "transfers.title": "Make a transfer",
    "transfers.subtitle": "Move funds instantly between customers.",
    "transfers.from": "From",
    "transfers.to": "To",
    "transfers.availableBalance": "Available balance",
    "transfers.noPlayers": "No other customers are available yet.",
    "transfers.dummy": "Assisted customer",
    "transfers.player": "Customer",
    "transfers.amount": "Amount",
    "transfers.note": "Note",
    "transfers.notePlaceholder": "What is this for?",
    "transfers.sending": "Sending",
    "transfers.summary": "₦{amount} to {name}",
    "transfers.selectPlayer": "Select a customer",
    "transfers.send": "Send transfer",
    "transfers.error": "Choose a customer and a valid amount.",
    "home.balance": "Balance",
    "home.recent": "Recent operations",
    "home.noActivity": "No activity yet.",
    "blackout.title": "EMP",
    "blackout.defaultReason": "EMP in effect",
    "blackout.active": "EMP active",
    "banker.dashboard.title": "Agency activity",
    "banker.tools.title": "Advisor controls",
    "banker.tools.playersTab": "Customers",
    "banker.tools.adminTab": "Agency",
    "banker.tools.playerOverview": "Customer overview",
    "banker.tools.noPlayers": "No customers yet.",
    "banker.tools.adjust": "Adjust balance",
    "banker.tools.apply": "Apply",
    "banker.tools.forceTransfer": "Force transfer",
    "banker.tools.force": "Force",
    "banker.tools.createDummy": "Create assisted customer",
    "banker.tools.addDummy": "Add assisted customer",
    "banker.tools.blackout": "Blackout",
    "banker.tools.blackoutActive": "Blackout active",
    "banker.tools.blackoutReason": "Blackout reason",
    "banker.tools.blackoutEnable": "Enable blackout",
    "banker.tools.blackoutDisable": "Disable blackout",
    "banker.tools.trigger": "Trigger",
    "banker.tools.endSession": "Close agency",
    "banker.tools.playerId": "Customer ID",
    "banker.tools.amountAdjust": "Amount (+/-)",
    "banker.tools.reason": "Reason",
    "banker.tools.fromPlayer": "From customer ID",
    "banker.tools.toPlayer": "To customer ID",
    "banker.tools.amount": "Amount",
    "banker.tools.note": "Note",
    "banker.tools.dummyName": "Assisted customer name",
    "banker.tools.startingBalance": "Starting balance",
    "banker.takeoverApprovals": "Recovery approvals",
    "banker.wants": "requests {name}",
    "banker.approve": "Approve",
    "banker.stateTitle": "Agency state",
    "banker.stateSubtitle": "Export or restore the current agency.",
    "banker.downloadState": "Export agency state",
    "banker.loadFromFile": "Load agency state",
    "banker.importPlaceholder": "Paste agency state JSON here",
    "banker.loadFromStorage": "Load from saved snapshots",
    "banker.stateDownloaded": "Agency state exported.",
    "banker.stateDownloadError": "Unable to export agency state.",
    "banker.stateLoaded": "Agency state loaded.",
    "banker.stateLoadError": "Unable to load agency state.",
    "banker.stateLoadInvalid": "Invalid agency state JSON.",
    "banker.autosaveTitle": "AutoSave",
    "banker.autosaveSubtitle": "Save rolling snapshots on this device.",
    "banker.autosaveEnabled": "Enable AutoSave",
    "banker.autosaveInterval": "Minutes between saves",
    "banker.autosaveKeep": "Snapshots to keep",
    "banker.autosaveNow": "Save now",
    "banker.autosaveSaved": "AutoSave captured.",
    "banker.autosaveFailed": "AutoSave failed.",
    "banker.noAutosaves": "No autosaves yet.",
    "banker.savedAt": "Saved {time}",
    "chat.title": "Messages",
    "chat.noMessages": "No messages yet",
    "chat.global": "Agency channel",
    "chat.newTitle": "New conversation",
    "chat.direct": "Direct",
    "chat.group": "Group",
    "chat.groupName": "Group name",
    "chat.choosePlayers": "Choose customers",
    "chat.startChat": "Start conversation",
    "chat.notFound": "Chat not found.",
    "chat.messagePlaceholder": "Message",
    "tabs.home": "Accounts",
    "tabs.transfers": "Payments",
    "tabs.chat": "Messages",
    "tabs.dashboard": "Agency",
    "tabs.tools": "Control",
    "transaction.transfer": "Transfer",
    "transaction.banker_adjust": "Advisor adjustment",
    "transaction.banker_force_transfer": "Advisor transfer",
    "connection.connecting": "Connecting to your agency",
    "connection.reconnecting": "Reconnecting to your agency",
    "connection.reconnectingDetail": "Attempt {count}. Live updates will resume automatically.",
    "error.parseResponse": "Unable to parse server response",
    "error.createSession": "Unable to open agency",
    "error.joinSession": "Unable to access agency",
    "error.loadSessionInfo": "Unable to load agency info",
    "error.connectionNotReady": "Connection not ready",
    "error.reconnecting": "Reconnecting to the agency. Please try again in a moment.",
  },
  fr: {
    "app.name": "Crédit Mabligop",
    "common.loading": "Chargement...",
    "common.loadingChats": "Chargement des messages...",
    "common.loadingChat": "Chargement de la conversation...",
    "common.loadingLobby": "Accès à la mise en place de l'agence...",
    "common.notice": "Info :",
    "common.online": "en ligne",
    "common.offline": "hors ligne",
    "common.dummy": "Client assisté",
    "common.player": "Client",
    "common.banker": "Conseiller",
    "common.bank": "Banque",
    "common.from": "De",
    "common.to": "Vers",
    "common.guest": "Invité",
    "common.you": "Vous",
    "common.join": "Rejoindre",
    "common.continue": "Continuer",
    "common.retryNow": "Réessayer",
    "common.transactions": "Transactions",
    "common.send": "Envoyer",
    "common.reset": "Réinitialiser",
    "common.cancel": "Annuler",
    "common.done": "OK",
    "common.exit": "Quitter",
    "common.save": "Enregistrer",
    "common.load": "Charger",
    "common.noReason": "Aucune raison fournie",
    "entry.subtitle": "Ouvrez ou accédez à une agence.",
    "entry.heroBadge": "Compagnon bancaire mobile",
    "entry.landingTitle": "Accédez à votre agence.",
    "entry.landingBody":
      "Utilisez votre code agence pour vous identifier, ou ouvrez une nouvelle agence si vous êtes le conseiller responsable.",
    "entry.landingFooter":
      "Soldes, virements et validations en temps réel pour les agences Crédit Mabligop.",
    "entry.metricRealtimeValue": "Temps réel",
    "entry.metricRealtimeLabel": "Transferts et soldes restent synchronisés.",
    "entry.metricSupervisedValue": "Supervisée",
    "entry.metricSupervisedLabel": "Chaque agence reste sous contrôle conseiller.",
    "entry.primaryEyebrow": "Accès client",
    "entry.secondaryEyebrow": "Accès conseiller",
    "entry.accessAgency": "Accéder à une agence",
    "entry.accessAgencyHint":
      "Saisissez votre code agence, identifiez-vous, puis récupérez un profil existant si besoin.",
    "entry.openAgency": "Ouvrir une agence",
    "entry.openAgencyHint":
      "Lancez une agence supervisée, invitez des clients et validez les récupérations de profils assistés.",
    "entry.joinStepTitle": "Identifiez votre agence.",
    "entry.joinStepSubtitle":
      "Saisissez le code transmis par votre conseiller pour afficher les options d'accès client disponibles.",
    "entry.createStepTitle": "Ouvrez une nouvelle agence.",
    "entry.createStepSubtitle":
      "Créez un espace piloté par un conseiller pour les soldes, virements, validations et clients assistés.",
    "entry.joinTitle": "Accès agence",
    "entry.joinDescription": "Utilisez votre code agence pour retrouver les profils clients disponibles.",
    "entry.sessionCode": "Code agence",
    "entry.previewLabel": "Agence trouvée",
    "entry.agencyCodeValue": "Code agence : {code}",
    "entry.previewCustomers": "{count} profils clients actuellement enregistrés.",
    "entry.newPlayer": "Rejoindre comme nouveau client",
    "entry.newCustomerDescription":
      "Créez un nouveau profil client et entrez immédiatement dans l'agence.",
    "entry.joinAsCustomer": "Rejoindre l'agence",
    "entry.playerName": "Nom du client",
    "entry.takeoverTitle": "Récupérer un profil existant",
    "entry.recoverCustomerDescription":
      "Demandez l'accès à un profil client assisté. Un conseiller doit valider la récupération.",
    "entry.alreadyConnected": "Ce profil client est déjà connecté.",
    "entry.dummyId": "ID du dummy (plus tard)",
    "entry.selectDummy": "Sélectionnez un client assisté",
    "entry.yourNameOptional": "Votre nom (optionnel)",
    "entry.requestTakeover": "Demander l'accord du conseiller",
    "entry.noDummies": "Aucun profil client assisté n'est disponible pour le moment.",
    "entry.takeoverPending": "En attente de la validation du conseiller.",
    "entry.createTitle": "Profil conseiller",
    "entry.createDescription":
      "Le premier profil créé devient le conseiller qui supervise cette agence.",
    "entry.bankerName": "Nom du conseiller",
    "entry.advisorName": "Nom du conseiller",
    "entry.openVault": "Ouvrir l'agence",
    "entry.linkAccessExisting": "Accéder plutôt à une agence existante",
    "entry.linkOpenNew": "Ouvrir plutôt une nouvelle agence",
    "entry.alert.enterCode": "Entrez un code agence",
    "entry.alert.enterAdvisorName": "Entrez un nom de conseiller",
    "entry.alert.sessionNotFound": "Agence introuvable",
    "entry.alert.selectDummy": "Sélectionnez un client assisté",
    "entry.alert.takeoverFailed": "Impossible de demander la reprise. Réessayez.",
    "lobby.title": "Mise en place de l'agence",
    "lobby.code": "Code agence : {code}",
    "lobby.startGame": "Ouvrir l'agence",
    "lobby.addDummyTitle": "Ajouter un client assisté",
    "lobby.addDummySubtitle":
      "Créez un profil client supervisé pour quelqu'un sans l'application mobile.",
    "lobby.enterDummyName": "Entrez un nom de client assisté",
    "lobby.addDummyButton": "Créer le client assisté",
    "lobby.heroAdvisor":
      "Finalisez les accès clients, examinez les récupérations et ouvrez l'agence quand tout est prêt.",
    "lobby.heroCustomer":
      "Votre conseiller prépare l'agence. Vous y entrerez dès son ouverture.",
    "lobby.customers": "Clients",
    "lobby.assisted": "Assistés",
    "lobby.rosterTitle": "Registre de l'agence",
    "lobby.waitingTitle": "En attente de l'ouverture de l'agence",
    "lobby.waitingBody":
      "Virements, soldes et conversations seront disponibles dès que le conseiller ouvrira l'agence.",
    "session.exit": "Quitter l'agence",
    "session.exitPrompt": "Quitter cette agence ?",
    "session.exitMessage": "Vous pourrez y accéder plus tard avec le code agence.",
    "transfers.title": "Effectuer un virement",
    "transfers.subtitle": "Transférez des fonds instantanément entre clients.",
    "transfers.from": "De",
    "transfers.to": "Vers",
    "transfers.availableBalance": "Solde disponible",
    "transfers.noPlayers": "Aucun autre client disponible pour le moment.",
    "transfers.dummy": "Client assisté",
    "transfers.player": "Client",
    "transfers.amount": "Montant",
    "transfers.note": "Note",
    "transfers.notePlaceholder": "Pour quoi ?",
    "transfers.sending": "Envoi",
    "transfers.summary": "₦{amount} à {name}",
    "transfers.selectPlayer": "Choisissez un client",
    "transfers.send": "Envoyer le virement",
    "transfers.error": "Choisissez un client et un montant valide.",
    "home.balance": "Solde",
    "home.recent": "Opérations récentes",
    "home.noActivity": "Aucune activité.",
    "blackout.title": "EMP",
    "blackout.defaultReason": "EMP en cours",
    "blackout.active": "EMP actif",
    "banker.dashboard.title": "Activité de l'agence",
    "banker.tools.title": "Pilotage conseiller",
    "banker.tools.playersTab": "Clients",
    "banker.tools.adminTab": "Agence",
    "banker.tools.playerOverview": "Vue client",
    "banker.tools.noPlayers": "Pas encore de clients.",
    "banker.tools.adjust": "Ajuster le solde",
    "banker.tools.apply": "Appliquer",
    "banker.tools.forceTransfer": "Imposer un virement",
    "banker.tools.force": "Forcer",
    "banker.tools.createDummy": "Créer un client assisté",
    "banker.tools.addDummy": "Ajouter un client assisté",
    "banker.tools.blackout": "Coupure",
    "banker.tools.blackoutActive": "Coupure active",
    "banker.tools.blackoutReason": "Raison de la coupure",
    "banker.tools.blackoutEnable": "Activer la coupure",
    "banker.tools.blackoutDisable": "Désactiver la coupure",
    "banker.tools.trigger": "Déclencher",
    "banker.tools.endSession": "Fermer l'agence",
    "banker.tools.playerId": "ID client",
    "banker.tools.amountAdjust": "Montant (+/-)",
    "banker.tools.reason": "Raison",
    "banker.tools.fromPlayer": "ID client source",
    "banker.tools.toPlayer": "ID client cible",
    "banker.tools.amount": "Montant",
    "banker.tools.note": "Note",
    "banker.tools.dummyName": "Nom du client assisté",
    "banker.tools.startingBalance": "Solde de départ",
    "banker.takeoverApprovals": "Validations de récupération",
    "banker.wants": "demande {name}",
    "banker.approve": "Approuver",
    "banker.stateTitle": "État de l'agence",
    "banker.stateSubtitle": "Exportez ou restaurez l'agence actuelle.",
    "banker.downloadState": "Exporter l'état de l'agence",
    "banker.loadFromFile": "Charger l'état de l'agence",
    "banker.importPlaceholder": "Collez le JSON d'état de l'agence ici",
    "banker.loadFromStorage": "Charger depuis les sauvegardes",
    "banker.stateDownloaded": "État de l'agence exporté.",
    "banker.stateDownloadError": "Impossible d'exporter l'état de l'agence.",
    "banker.stateLoaded": "État de l'agence chargé.",
    "banker.stateLoadError": "Impossible de charger l'état de l'agence.",
    "banker.stateLoadInvalid": "JSON d'état de l'agence invalide.",
    "banker.autosaveTitle": "AutoSave",
    "banker.autosaveSubtitle": "Enregistrez des sauvegardes sur l'appareil.",
    "banker.autosaveEnabled": "Activer AutoSave",
    "banker.autosaveInterval": "Minutes entre sauvegardes",
    "banker.autosaveKeep": "Sauvegardes à conserver",
    "banker.autosaveNow": "Sauvegarder maintenant",
    "banker.autosaveSaved": "Sauvegarde effectuée.",
    "banker.autosaveFailed": "Échec de la sauvegarde.",
    "banker.noAutosaves": "Aucune sauvegarde.",
    "banker.savedAt": "Sauvé {time}",
    "chat.title": "Messages",
    "chat.noMessages": "Aucun message",
    "chat.global": "Canal agence",
    "chat.newTitle": "Nouvelle conversation",
    "chat.direct": "Direct",
    "chat.group": "Groupe",
    "chat.groupName": "Nom du groupe",
    "chat.choosePlayers": "Choisir des clients",
    "chat.startChat": "Démarrer la conversation",
    "chat.notFound": "Chat introuvable.",
    "chat.messagePlaceholder": "Message",
    "tabs.home": "Comptes",
    "tabs.transfers": "Paiements",
    "tabs.chat": "Messages",
    "tabs.dashboard": "Agence",
    "tabs.tools": "Pilotage",
    "transaction.transfer": "Transfert",
    "transaction.banker_adjust": "Ajustement conseiller",
    "transaction.banker_force_transfer": "Virement imposé",
    "connection.connecting": "Connexion à votre agence",
    "connection.reconnecting": "Reconnexion à votre agence",
    "connection.reconnectingDetail": "Tentative {count}. Les mises à jour vont reprendre automatiquement.",
    "error.parseResponse": "Impossible de lire la réponse du serveur",
    "error.createSession": "Impossible d'ouvrir l'agence",
    "error.joinSession": "Impossible d'accéder à l'agence",
    "error.loadSessionInfo": "Impossible de charger les infos de l'agence",
    "error.connectionNotReady": "Connexion non prête",
    "error.reconnecting": "Reconnexion à l'agence en cours. Réessayez dans un instant.",
  },
} as const;

type I18nKey = keyof typeof translations.en;

export function getLocale(): Locale {
  const raw = Intl.DateTimeFormat().resolvedOptions().locale?.toLowerCase() ?? "en";
  return raw.startsWith("fr") ? "fr" : "en";
}

function translate(locale: Locale, key: I18nKey, vars?: Record<string, string | number>) {
  const table = translations[locale] ?? translations.en;
  let template: string = table[key] ?? translations.en[key] ?? key;
  if (vars) {
    Object.entries(vars).forEach(([name, value]) => {
      template = template.replace(new RegExp(`\\{${name}\\}`, "g"), String(value));
    });
  }
  return template;
}

export function useI18n() {
  const locale = useMemo(getLocale, []);
  const t = useCallback(
    (key: I18nKey, vars?: Record<string, string | number>) => translate(locale, key, vars),
    [locale],
  );
  return { t, locale };
}

export function tStatic(key: I18nKey, vars?: Record<string, string | number>) {
  return translate(getLocale(), key, vars);
}

export function formatTransactionKind(
  kind: TransactionKind,
  t: (key: I18nKey) => string,
) {
  return t(`transaction.${kind}` as I18nKey);
}
