// i18n.jsx — minimal translation system

const I18N = {
  fr: {
    // Sidebar
    "sidebar.atelier": "Atelier",
    "sidebar.scripts": "Scripts",
    "sidebar.history": "Historique",
    "sidebar.community": "Communauté",
    "sidebar.explore": "Explorer",
    "sidebar.favorites": "Favoris",
    "sidebar.suite": "Suite FMAtique",
    "sidebar.account": "Compte",
    "sidebar.profile": "Profil",
    "sidebar.settings": "Paramètres",
    "sidebar.extension": "Extension",
    "sidebar.extension.sub": "Travaillez sans le site",
    "sidebar.plugin": "Plugin",
    "sidebar.plugin.sub": "Détection d'erreurs",
    "sidebar.logout": "Déconnexion",

    // Companion bar
    "companion.connected": "Companion connecté",
    "companion.ready": "— prêt à créer des scripts",
    "companion.disconnected": "Companion non connecté",
    "companion.instructions": "— ouvrez Terminal et collez la commande :",
    "companion.copy": "Copier",
    "companion.copied": "Copié",

    // Scripts page
    "scripts.breadcrumb": "Scripts",
    "scripts.name": "Nom du script",
    "scripts.placeholder": "Nouveau_Script",
    "scripts.fmVersion": "Version FM",
    "scripts.speed": "Vitesse d'exécution",
    "scripts.speedNames": ["Lent", "Normal", "Rapide", "Turbo"],
    "scripts.create": "Créer dans FileMaker",
    "scripts.creating": "Génération…",
    "scripts.resume": "Reprendre à la ligne",
    "scripts.resuming": "Reprise…",
    "scripts.error.noCompanion": "Companion non connecté — installez-le d'abord depuis le bandeau ci-dessus.",
    "scripts.error.noCode": "Écrivez ou collez du code de script d'abord.",
    "scripts.error.generation": "Erreur lors de la génération.",
    "scripts.error.connection": "Erreur de connexion.",
    "scripts.error.resume": "Erreur lors de la reprise.",
    "scripts.error.detected": "Erreur FileMaker détectée",
    "scripts.error.atLine": "Erreur FileMaker à la ligne {line}",
    "scripts.error.resumeInstructions": "Corrigez l'erreur dans FileMaker, puis indiquez à quelle ligne reprendre :",
    "scripts.success": "Script \"{name}\" créé dans FileMaker — {steps} steps.",
    "scripts.resumeSuccess": "Reprise effectuée. Script terminé.",
    "scripts.codeLabel": "Code du script",
    "scripts.clear": "Effacer",
    "scripts.copy": "Copier",
    "scripts.resumeAt": "Reprendre à la ligne",

    // History page
    "history.breadcrumb": "Historique",
    "history.search": "Rechercher…",
    "history.scriptsMonth": "Scripts ce mois",
    "history.included": "/ 30 inclus",
    "history.stepsGenerated": "Steps générés",
    "history.total": "total",
    "history.timeSaved": "Temps économisé",
    "history.clicks": "clics",
    "history.loading": "Chargement…",
    "history.noResults": "Aucun script trouvé",
    "history.empty": "Aucun script dans l'historique",
    "history.loadEditor": "Charger dans l'éditeur",
    "history.copyCode": "Copier le code",
    "history.delete": "Supprimer",
    "history.timeAgo.now": "à l'instant",
    "history.timeAgo.min": "il y a {n} min",
    "history.timeAgo.hour": "il y a {n} h",
    "history.timeAgo.yesterday": "hier",

    // Profile page
    "profile.breadcrumb": "Profil",
    "profile.info": "Informations",
    "profile.username": "Pseudo",
    "profile.usernamePlaceholder": "votre_pseudo",
    "profile.firstName": "Prénom",
    "profile.lastName": "Nom",
    "profile.email": "Email",
    "profile.save": "Enregistrer",
    "profile.saving": "Enregistrement…",
    "profile.saved": "Enregistré",
    "profile.subscription": "Abonnement",
    "profile.invoices": "Voir les factures",
    "profile.currentPlan": "Plan actuel",
    "profile.free": "Gratuit",
    "profile.freePlan": "Plan Gratuit",
    "profile.scriptsMonth": "30 scripts/mois",
    "profile.freeDesc": "30 scripts/mois · Historique 30 jours",
    "profile.deleteAccount": "Supprimer le compte",
    "profile.deleteWarning": "Action irréversible. Tous vos scripts et historique seront effacés.",
    "profile.memberSince": "Membre depuis {date}",

    // Settings page
    "settings.breadcrumb": "Paramètres",
    "settings.saved": "Enregistré",
    "settings.fmVersions": "Versions de FileMaker installées",
    "settings.fmVersionsDesc": "Sélectionnez la version active. FMAutoScript utilisera ce nom d'application pour piloter FileMaker.",
    "settings.helpTitle": "Comment trouver le nom de l'application ?",
    "settings.helpText1": "Ouvrez le <strong>Finder</strong>, allez dans <strong>/Applications</strong> et repérez le nom exact de votre FileMaker. Par défaut c'est <code>FileMaker Pro</code>.",
    "settings.helpText2": "Si vous avez plusieurs versions installées côte à côte, elles ont souvent des noms différents :",
    "settings.helpExample1": "FileMaker Pro</code> — version la plus récente",
    "settings.helpExample2": "FileMaker Pro 19</code> — version 19 renommée",
    "settings.helpText3": "Le <strong>Nom d'application</strong> doit correspondre <strong>exactement</strong> au nom affiché dans le Finder (sans <code>.app</code>).",
    "settings.addVersion": "Ajouter une version",
    "settings.newVersion": "Nouvelle version",
    "settings.labelField": "Label (ex: FileMaker 2024)",
    "settings.appNameField": "Nom d'application macOS (ex: FileMaker Pro)",
    "settings.appNameHint": "Le nom exact tel qu'affiché dans le Finder, sans .app",
    "settings.cancel": "Annuler",
    "settings.add": "Ajouter",
    "settings.execPrefs": "Préférences d'exécution",
    "settings.fullKbd": "Activer Full Keyboard Access au lancement",
    "settings.fullKbdDesc": "Nécessaire pour piloter les dialogues FileMaker au clavier.",
    "settings.fiveTabs": "Mode \"5 tabs\" pour Set Field",
    "settings.fiveTabsDesc": "À activer si votre base nécessite 2 tabs entre le champ et le champ Répétition.",
    "settings.keystrokeDelay": "Délai entre keystrokes",
    "settings.keystrokeHint": "Augmentez si vos scripts échouent fréquemment dans les dialogues.",
    "settings.language": "Langue",

    // Community page
    "community.breadcrumb": "Communauté",
    "community.explore": "Explorer",
    "community.myModules": "Mes modules",
    "community.newModule": "Nouveau module",
    "community.all": "Tous",
    "community.loading": "Chargement…",
    "community.noModules": "Aucun module trouvé",
    "community.noOwn": "Vous n'avez pas encore créé de module",
    "community.published": "Publié",
    "community.draft": "Brouillon",
    "community.edit": "Modifier",
    "community.by": "par {author}",
    "community.favorite": "Favori",
    "community.addFav": "Ajouter",
    "community.load": "Charger",

    // Favorites page
    "favorites.breadcrumb": "Favoris",
    "favorites.empty": "Aucun favori pour l'instant",
    "favorites.emptyHint": "Explorez la communauté et ajoutez des modules à vos favoris",

    // Module form
    "form.editModule": "Modifier le module",
    "form.newModule": "Nouveau module",
    "form.title": "Titre",
    "form.titlePlaceholder": "Mon pack de scripts",
    "form.description": "Description",
    "form.descPlaceholder": "Décrivez ce que fait ce module…",
    "form.tags": "Tags",
    "form.scripts": "Scripts",
    "form.fromHistory": "Depuis l'historique",
    "form.emptyScript": "Script vide",
    "form.scriptName": "Nom du script",
    "form.publish": "Publier dans la communauté",
    "form.cancel": "Annuler",
    "form.save": "Créer le module",
    "form.update": "Mettre à jour",
    "form.saving": "Enregistrement…",
    "form.titleRequired": "Titre requis",
    "form.scriptRequired": "Au moins un script requis",
    "form.pickHistory": "Choisir depuis l'historique",
    "form.historyEmpty": "Aucun script dans l'historique",
  },

  en: {
    // Sidebar
    "sidebar.atelier": "Workshop",
    "sidebar.scripts": "Scripts",
    "sidebar.history": "History",
    "sidebar.community": "Community",
    "sidebar.explore": "Explore",
    "sidebar.favorites": "Favorites",
    "sidebar.suite": "FMAtique Suite",
    "sidebar.account": "Account",
    "sidebar.profile": "Profile",
    "sidebar.settings": "Settings",
    "sidebar.extension": "Extension",
    "sidebar.extension.sub": "Work without the site",
    "sidebar.plugin": "Plugin",
    "sidebar.plugin.sub": "Error detection",
    "sidebar.logout": "Log out",

    // Companion bar
    "companion.connected": "Companion connected",
    "companion.ready": "— ready to create scripts",
    "companion.disconnected": "Companion not connected",
    "companion.instructions": "— open Terminal and paste the command:",
    "companion.copy": "Copy",
    "companion.copied": "Copied",

    // Scripts page
    "scripts.breadcrumb": "Scripts",
    "scripts.name": "Script name",
    "scripts.placeholder": "New_Script",
    "scripts.fmVersion": "FM Version",
    "scripts.speed": "Execution speed",
    "scripts.speedNames": ["Slow", "Normal", "Fast", "Turbo"],
    "scripts.create": "Create in FileMaker",
    "scripts.creating": "Generating…",
    "scripts.resume": "Resume at line",
    "scripts.resuming": "Resuming…",
    "scripts.error.noCompanion": "Companion not connected — install it first from the bar above.",
    "scripts.error.noCode": "Write or paste script code first.",
    "scripts.error.generation": "Error during generation.",
    "scripts.error.connection": "Connection error.",
    "scripts.error.resume": "Error during resume.",
    "scripts.error.detected": "FileMaker error detected",
    "scripts.error.atLine": "FileMaker error at line {line}",
    "scripts.error.resumeInstructions": "Fix the error in FileMaker, then choose which line to resume from:",
    "scripts.success": "Script \"{name}\" created in FileMaker — {steps} steps.",
    "scripts.resumeSuccess": "Resume complete. Script finished.",
    "scripts.codeLabel": "Script code",
    "scripts.clear": "Clear",
    "scripts.copy": "Copy",
    "scripts.resumeAt": "Resume at line",

    // History page
    "history.breadcrumb": "History",
    "history.search": "Search…",
    "history.scriptsMonth": "Scripts this month",
    "history.included": "/ 30 included",
    "history.stepsGenerated": "Steps generated",
    "history.total": "total",
    "history.timeSaved": "Time saved",
    "history.clicks": "clicks",
    "history.loading": "Loading…",
    "history.noResults": "No script found",
    "history.empty": "No scripts in history",
    "history.loadEditor": "Load in editor",
    "history.copyCode": "Copy code",
    "history.delete": "Delete",
    "history.timeAgo.now": "just now",
    "history.timeAgo.min": "{n} min ago",
    "history.timeAgo.hour": "{n} h ago",
    "history.timeAgo.yesterday": "yesterday",

    // Profile page
    "profile.breadcrumb": "Profile",
    "profile.info": "Information",
    "profile.username": "Username",
    "profile.usernamePlaceholder": "your_username",
    "profile.firstName": "First name",
    "profile.lastName": "Last name",
    "profile.email": "Email",
    "profile.save": "Save",
    "profile.saving": "Saving…",
    "profile.saved": "Saved",
    "profile.subscription": "Subscription",
    "profile.invoices": "View invoices",
    "profile.currentPlan": "Current plan",
    "profile.free": "Free",
    "profile.freePlan": "Free Plan",
    "profile.scriptsMonth": "30 scripts/month",
    "profile.freeDesc": "30 scripts/month · 30-day history",
    "profile.deleteAccount": "Delete account",
    "profile.deleteWarning": "This action is irreversible. All your scripts and history will be deleted.",
    "profile.memberSince": "Member since {date}",

    // Settings page
    "settings.breadcrumb": "Settings",
    "settings.saved": "Saved",
    "settings.fmVersions": "Installed FileMaker versions",
    "settings.fmVersionsDesc": "Select the active version. FMAutoScript will use this application name to drive FileMaker.",
    "settings.helpTitle": "How to find the application name?",
    "settings.helpText1": "Open <strong>Finder</strong>, go to <strong>/Applications</strong> and look for the exact name of your FileMaker. The default is <code>FileMaker Pro</code>.",
    "settings.helpText2": "If you have multiple versions installed side by side, they often have different names:",
    "settings.helpExample1": "FileMaker Pro</code> — latest version",
    "settings.helpExample2": "FileMaker Pro 19</code> — renamed version 19",
    "settings.helpText3": "The <strong>Application name</strong> must match <strong>exactly</strong> the name shown in Finder (without <code>.app</code>).",
    "settings.addVersion": "Add a version",
    "settings.newVersion": "New version",
    "settings.labelField": "Label (e.g. FileMaker 2024)",
    "settings.appNameField": "macOS app name (e.g. FileMaker Pro)",
    "settings.appNameHint": "The exact name as shown in Finder, without .app",
    "settings.cancel": "Cancel",
    "settings.add": "Add",
    "settings.execPrefs": "Execution preferences",
    "settings.fullKbd": "Enable Full Keyboard Access on launch",
    "settings.fullKbdDesc": "Required to drive FileMaker dialogs via keyboard.",
    "settings.fiveTabs": "\"5 tabs\" mode for Set Field",
    "settings.fiveTabsDesc": "Enable if your database requires 2 tabs between field and repetition field.",
    "settings.keystrokeDelay": "Keystroke delay",
    "settings.keystrokeHint": "Increase if your scripts frequently fail in dialogs.",
    "settings.language": "Language",

    // Community page
    "community.breadcrumb": "Community",
    "community.explore": "Explore",
    "community.myModules": "My modules",
    "community.newModule": "New module",
    "community.all": "All",
    "community.loading": "Loading…",
    "community.noModules": "No modules found",
    "community.noOwn": "You haven't created any modules yet",
    "community.published": "Published",
    "community.draft": "Draft",
    "community.edit": "Edit",
    "community.by": "by {author}",
    "community.favorite": "Favorite",
    "community.addFav": "Add",
    "community.load": "Load",

    // Favorites page
    "favorites.breadcrumb": "Favorites",
    "favorites.empty": "No favorites yet",
    "favorites.emptyHint": "Explore the community and add modules to your favorites",

    // Module form
    "form.editModule": "Edit module",
    "form.newModule": "New module",
    "form.title": "Title",
    "form.titlePlaceholder": "My script pack",
    "form.description": "Description",
    "form.descPlaceholder": "Describe what this module does…",
    "form.tags": "Tags",
    "form.scripts": "Scripts",
    "form.fromHistory": "From history",
    "form.emptyScript": "Empty script",
    "form.scriptName": "Script name",
    "form.publish": "Publish to community",
    "form.cancel": "Cancel",
    "form.save": "Create module",
    "form.update": "Update",
    "form.saving": "Saving…",
    "form.titleRequired": "Title required",
    "form.scriptRequired": "At least one script required",
    "form.pickHistory": "Pick from history",
    "form.historyEmpty": "No scripts in history",
  }
};

function useI18n() {
  const [lang, setLang] = React.useState(() => localStorage.getItem('pref_lang') || 'fr');

  React.useEffect(() => {
    const handler = () => setLang(localStorage.getItem('pref_lang') || 'fr');
    window.addEventListener('lang-change', handler);
    return () => window.removeEventListener('lang-change', handler);
  }, []);

  const dict = I18N[lang] || I18N.fr;

  const t = (key, params) => {
    let val = dict[key] || I18N.fr[key] || key;
    if (params && typeof val === 'string') {
      Object.entries(params).forEach(([k, v]) => {
        val = val.replace(`{${k}}`, v);
      });
    }
    return val;
  };

  return { t, lang };
}

function setAppLang(newLang) {
  localStorage.setItem('pref_lang', newLang);
  window.dispatchEvent(new Event('lang-change'));
}

window.useI18n = useI18n;
window.setAppLang = setAppLang;
window.I18N = I18N;
