import { useCallback, useMemo } from "react";

type Locale = "en" | "fr";

const translations = {
  en: {
    "app.name": "Negopoly Companion",
    "common.loading": "Loading...",
    "common.loadingChats": "Loading chats...",
    "common.loadingChat": "Loading chat...",
    "common.loadingLobby": "Joining lobby...",
    "common.notice": "Notice:",
    "common.online": "online",
    "common.offline": "offline",
    "common.dummy": "Dummy",
    "common.player": "Player",
    "common.banker": "Banker",
    "common.bank": "Bank",
    "common.from": "From",
    "common.to": "To",
    "common.guest": "Guest",
    "common.you": "You",
    "common.join": "Join",
    "common.continue": "Continue",
    "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": "Create or join a session.",
    "entry.joinTitle": "Join a session",
    "entry.sessionCode": "Session code",
    "entry.newPlayer": "New player",
    "entry.playerName": "Player name",
    "entry.takeoverTitle": "Take over dummy",
    "entry.alreadyConnected": "You are already connected.",
    "entry.dummyId": "Dummy ID (select later)",
    "entry.selectDummy": "Select a dummy",
    "entry.yourNameOptional": "Your name (optional)",
    "entry.requestTakeover": "Request takeover",
    "entry.noDummies": "No dummies available yet.",
    "entry.takeoverPending": "Waiting for the banker to approve your takeover.",
    "entry.createTitle": "Create a session",
    "entry.bankerName": "Banker name",
    "entry.openVault": "Open the vault",
    "entry.alert.enterCode": "Enter a session code",
    "entry.alert.sessionNotFound": "Session not found",
    "entry.alert.selectDummy": "Select a dummy player",
    "entry.alert.takeoverFailed": "Unable to request takeover. Please try again.",
    "lobby.title": "Lobby",
    "lobby.code": "Code: {code}",
    "lobby.startGame": "Start game",
    "lobby.addDummyTitle": "Add dummy player",
    "lobby.addDummySubtitle": "Create a player for someone without the app.",
    "lobby.enterDummyName": "Enter a dummy name",
    "lobby.addDummyButton": "Add dummy",
    "session.exit": "Exit game",
    "session.exitPrompt": "Leave this game?",
    "session.exitMessage": "You can rejoin later with the session code.",
    "transfers.title": "Make a transfer",
    "transfers.subtitle": "Move funds instantly between players.",
    "transfers.from": "From",
    "transfers.to": "To",
    "transfers.availableBalance": "Available balance",
    "transfers.noPlayers": "No other players available yet.",
    "transfers.dummy": "Dummy player",
    "transfers.player": "Player",
    "transfers.amount": "Amount",
    "transfers.note": "Note",
    "transfers.notePlaceholder": "What is this for?",
    "transfers.sending": "Sending",
    "transfers.summary": "₦{amount} to {name}",
    "transfers.selectPlayer": "Select a player",
    "transfers.send": "Send transfer",
    "transfers.error": "Choose a player and a valid amount.",
    "home.balance": "Balance",
    "home.recent": "Recent activity",
    "home.noActivity": "No activity yet.",
    "blackout.title": "EMP",
    "blackout.defaultReason": "EMP in effect",
    "blackout.active": "EMP active",
    "banker.dashboard.title": "Session activity",
    "banker.tools.title": "Banker tools",
    "banker.tools.playersTab": "Players",
    "banker.tools.adminTab": "Admin",
    "banker.tools.playerOverview": "Player overview",
    "banker.tools.noPlayers": "No players yet.",
    "banker.tools.adjust": "Adjust balance",
    "banker.tools.apply": "Apply",
    "banker.tools.forceTransfer": "Force transfer",
    "banker.tools.force": "Force",
    "banker.tools.createDummy": "Create dummy",
    "banker.tools.addDummy": "Add dummy",
    "banker.tools.blackout": "EMP",
    "banker.tools.blackoutActive": "EMP active",
    "banker.tools.blackoutReason": "EMP reason",
    "banker.tools.blackoutEnable": "Enable EMP",
    "banker.tools.blackoutDisable": "Disable EMP",
    "banker.tools.trigger": "Trigger",
    "banker.tools.endSession": "End session",
    "banker.tools.playerId": "Player ID",
    "banker.tools.amountAdjust": "Amount (+/-)",
    "banker.tools.reason": "Reason",
    "banker.tools.fromPlayer": "From player ID",
    "banker.tools.toPlayer": "To player ID",
    "banker.tools.amount": "Amount",
    "banker.tools.note": "Note",
    "banker.tools.dummyName": "Dummy name",
    "banker.tools.startingBalance": "Starting balance",
    "banker.takeoverApprovals": "Takeover approvals",
    "banker.wants": "wants {name}",
    "banker.approve": "Approve",
    "banker.stateTitle": "GameState",
    "banker.stateSubtitle": "Export or restore the current session.",
    "banker.downloadState": "Export GameState",
    "banker.loadFromFile": "Load GameState",
    "banker.importPlaceholder": "Paste GameState JSON here",
    "banker.loadFromStorage": "Load from saved snapshots",
    "banker.stateDownloaded": "GameState exported.",
    "banker.stateDownloadError": "Unable to export GameState.",
    "banker.stateLoaded": "GameState loaded.",
    "banker.stateLoadError": "Unable to load GameState.",
    "banker.stateLoadInvalid": "Invalid GameState 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": "Chats",
    "chat.noMessages": "No messages yet",
    "chat.global": "Global chat",
    "chat.newTitle": "New chat",
    "chat.direct": "Direct",
    "chat.group": "Group",
    "chat.groupName": "Group name",
    "chat.choosePlayers": "Choose players",
    "chat.startChat": "Start chat",
    "chat.notFound": "Chat not found.",
    "chat.messagePlaceholder": "Message",
    "tabs.home": "Home",
    "tabs.transfers": "Transfers",
    "tabs.chat": "Chat",
    "tabs.dashboard": "Dashboard",
    "tabs.tools": "Tools",
    "transaction.transfer": "Transfer",
    "transaction.banker_adjust": "Banker adjustment",
    "transaction.banker_force_transfer": "Forced transfer",
    "error.parseResponse": "Unable to parse server response",
    "error.createSession": "Unable to create session",
    "error.joinSession": "Unable to join session",
    "error.loadSessionInfo": "Unable to load session info",
    "error.connectionNotReady": "Connection not ready",
  },
  fr: {
    "app.name": "Negopoly Companion",
    "common.loading": "Chargement...",
    "common.loadingChats": "Chargement des chats...",
    "common.loadingChat": "Chargement du chat...",
    "common.loadingLobby": "Connexion au lobby...",
    "common.notice": "Info :",
    "common.online": "en ligne",
    "common.offline": "hors ligne",
    "common.dummy": "Dummy",
    "common.player": "Joueur",
    "common.banker": "Banquier",
    "common.bank": "Banque",
    "common.from": "De",
    "common.to": "Vers",
    "common.guest": "Invité",
    "common.you": "Vous",
    "common.join": "Rejoindre",
    "common.continue": "Continuer",
    "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": "Créez ou rejoignez une session.",
    "entry.joinTitle": "Rejoindre une session",
    "entry.sessionCode": "Code de session",
    "entry.newPlayer": "Nouveau joueur",
    "entry.playerName": "Nom du joueur",
    "entry.takeoverTitle": "Reprendre un dummy",
    "entry.alreadyConnected": "Vous êtes déjà connecté.",
    "entry.dummyId": "ID du dummy (plus tard)",
    "entry.selectDummy": "Sélectionnez un dummy",
    "entry.yourNameOptional": "Votre nom (optionnel)",
    "entry.requestTakeover": "Demander la reprise",
    "entry.noDummies": "Aucun dummy disponible pour le moment.",
    "entry.takeoverPending": "En attente de l'approbation du banquier.",
    "entry.createTitle": "Créer une session",
    "entry.bankerName": "Nom du banquier",
    "entry.openVault": "Ouvrir le coffre",
    "entry.alert.enterCode": "Entrez un code de session",
    "entry.alert.sessionNotFound": "Session introuvable",
    "entry.alert.selectDummy": "Sélectionnez un dummy",
    "entry.alert.takeoverFailed": "Impossible de demander la reprise. Réessayez.",
    "lobby.title": "Lobby",
    "lobby.code": "Code : {code}",
    "lobby.startGame": "Démarrer la partie",
    "lobby.addDummyTitle": "Ajouter un dummy",
    "lobby.addDummySubtitle": "Créez un joueur pour quelqu'un sans l'application.",
    "lobby.enterDummyName": "Entrez un nom de dummy",
    "lobby.addDummyButton": "Ajouter un dummy",
    "session.exit": "Quitter la partie",
    "session.exitPrompt": "Quitter cette session ?",
    "session.exitMessage": "Vous pourrez rejoindre plus tard avec le code.",
    "transfers.title": "Faire un transfert",
    "transfers.subtitle": "Transférez des fonds instantanément entre joueurs.",
    "transfers.from": "De",
    "transfers.to": "Vers",
    "transfers.availableBalance": "Solde disponible",
    "transfers.noPlayers": "Aucun autre joueur disponible.",
    "transfers.dummy": "Dummy",
    "transfers.player": "Joueur",
    "transfers.amount": "Montant",
    "transfers.note": "Note",
    "transfers.notePlaceholder": "Pour quoi ?",
    "transfers.sending": "Envoi",
    "transfers.summary": "₦{amount} à {name}",
    "transfers.selectPlayer": "Choisissez un joueur",
    "transfers.send": "Envoyer le transfert",
    "transfers.error": "Choisissez un joueur et un montant valide.",
    "home.balance": "Solde",
    "home.recent": "Activité récente",
    "home.noActivity": "Aucune activité.",
    "blackout.title": "EMP",
    "blackout.defaultReason": "EMP en cours",
    "blackout.active": "EMP actif",
    "banker.dashboard.title": "Activité de la session",
    "banker.tools.title": "Outils banquier",
    "banker.tools.playersTab": "Joueurs",
    "banker.tools.adminTab": "Admin",
    "banker.tools.playerOverview": "Vue joueur",
    "banker.tools.noPlayers": "Pas encore de joueurs.",
    "banker.tools.adjust": "Ajuster le solde",
    "banker.tools.apply": "Appliquer",
    "banker.tools.forceTransfer": "Forcer un transfert",
    "banker.tools.force": "Forcer",
    "banker.tools.createDummy": "Créer un dummy",
    "banker.tools.addDummy": "Ajouter un dummy",
    "banker.tools.blackout": "EMP",
    "banker.tools.blackoutActive": "EMP actif",
    "banker.tools.blackoutReason": "Raison de l'EMP",
    "banker.tools.blackoutEnable": "Activer l'EMP",
    "banker.tools.blackoutDisable": "Désactiver l'EMP",
    "banker.tools.trigger": "Déclencher",
    "banker.tools.endSession": "Terminer la session",
    "banker.tools.playerId": "ID joueur",
    "banker.tools.amountAdjust": "Montant (+/-)",
    "banker.tools.reason": "Raison",
    "banker.tools.fromPlayer": "ID joueur source",
    "banker.tools.toPlayer": "ID joueur cible",
    "banker.tools.amount": "Montant",
    "banker.tools.note": "Note",
    "banker.tools.dummyName": "Nom du dummy",
    "banker.tools.startingBalance": "Solde de départ",
    "banker.takeoverApprovals": "Approbations de reprise",
    "banker.wants": "veut {name}",
    "banker.approve": "Approuver",
    "banker.stateTitle": "État de partie",
    "banker.stateSubtitle": "Exportez ou restaurez la session.",
    "banker.downloadState": "Exporter l'état",
    "banker.loadFromFile": "Charger l'état",
    "banker.importPlaceholder": "Collez le JSON d'état ici",
    "banker.loadFromStorage": "Charger depuis les sauvegardes",
    "banker.stateDownloaded": "État exporté.",
    "banker.stateDownloadError": "Impossible d'exporter l'état.",
    "banker.stateLoaded": "État chargé.",
    "banker.stateLoadError": "Impossible de charger l'état.",
    "banker.stateLoadInvalid": "JSON d'état 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": "Chats",
    "chat.noMessages": "Aucun message",
    "chat.global": "Chat global",
    "chat.newTitle": "Nouveau chat",
    "chat.direct": "Direct",
    "chat.group": "Groupe",
    "chat.groupName": "Nom du groupe",
    "chat.choosePlayers": "Choisir des joueurs",
    "chat.startChat": "Démarrer le chat",
    "chat.notFound": "Chat introuvable.",
    "chat.messagePlaceholder": "Message",
    "tabs.home": "Accueil",
    "tabs.transfers": "Transferts",
    "tabs.chat": "Chat",
    "tabs.dashboard": "Tableau",
    "tabs.tools": "Outils",
    "transaction.transfer": "Transfert",
    "transaction.banker_adjust": "Ajustement banquier",
    "transaction.banker_force_transfer": "Transfert forcé",
    "error.parseResponse": "Impossible de lire la réponse du serveur",
    "error.createSession": "Impossible de créer la session",
    "error.joinSession": "Impossible de rejoindre la session",
    "error.loadSessionInfo": "Impossible de charger les infos de session",
    "error.connectionNotReady": "Connexion non prête",
  },
} 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 = 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: "transfer" | "banker_adjust" | "banker_force_transfer",
  t: (key: I18nKey) => string,
) {
  return t(`transaction.${kind}` as I18nKey);
}
