// ============================================================
// i18n — tiny custom provider (EN / FR / ES)
// ============================================================
// No library: a flat dictionary, a React Context, and a t() helper with
// {var} interpolation. English keys are the fallback when a translation is
// missing; if a key is missing entirely, t() returns the key itself so the
// gap is visible in the page.

const LANGS = ['en', 'fr', 'es'];
const LANG_LABELS = { en: 'EN', fr: 'FR', es: 'ES' };
const STORAGE_KEY = 'beymann_lang';

const STRINGS = {
  en: {
    // Nav
    'nav.preLaunch': 'Pre-launch',
    'nav.joinWaitlist': 'Join waitlist',
    'nav.join': 'Join',

    // Scarcity banner
    'banner.scarcityPrefix': 'Founding-member pricing closes when we hit 10,000 signups.',
    'banner.scarcityCta': 'Join now →',

    // Hero
    'hero.classic.line1': 'Trade.',
    'hero.classic.line2': 'without losing',
    'hero.classic.line3': 'your money.',
    'hero.underline.prefix': 'Learn to trade.',
    'hero.underline.middle': 'Without',
    'hero.underline.accent': 'losing your money',
    'hero.serif.prefix': 'Learn to trade.',
    'hero.serif.middle': 'Without',
    'hero.serif.accent': 'losing your money',
    'hero.sub': '$50,000 in virtual capital, an AI coach, and 80% of your profits paid out in real cash. No personal capital at risk. Ever.',
    'hero.ctaJoin': 'Join the waitlist',
    'hero.ctaHow': 'See how it works ↓',

    // Problem
    'problem.eyebrow': 'The Problem',
    'problem.title': 'Retail trading is rigged against you.',
    'problem.body': "Not because you're reckless. Because you're handed complex tools, no guidance, and asked to risk your own money against markets built to take it from you.",
    'problem.quote': 'Platforms like Robinhood hand you a loaded gun and walk away.',
    'problem.bullet1': 'They make money when you trade.',
    'problem.bullet2': 'They make more when you lose.',
    'problem.bullet3': "You shouldn't have to blow up your savings to learn a craft.",

    // Fix
    'fix.eyebrow': 'The Fix',
    'fix.title.prefix': 'Beymann is what',
    'fix.title.middle': 'trading',
    'fix.title.accent': 'should',
    'fix.title.suffix': 'be.',
    'fix.body': "You should be able to learn trading the way you'd learn anything else worth learning: with the right tools, a real coach, and a way to earn from your skill without risking what you can't afford to lose.",
    'fix.tag': "That's what we're building.",
    'fix.sideLabel': 'simple.',

    // Focus
    'focus.eyebrow': 'The Focus',
    'focus.title.prefix': 'One instrument.',
    'focus.title.accent': 'No noise.',
    'focus.body': "Most platforms drown you in thousands of tickers. We strip it down to one: the Nasdaq, home of the world's top tech companies. You trade it through the MNQ futures contract, which mirrors the index in real time. Master one rhythm instead of chasing a hundred.",
    'focus.tag': 'Nasdaq-100 · MNQ Futures',

    // How it works
    'how.eyebrow': 'How it works',
    'how.title.line1': 'Three steps.',
    'how.title.line2': 'One discipline.',
    'how.sub': 'No casino, no copy-trading, no manifesting. You learn the craft, then you get paid for it.',
    'how.step1.title': 'Trade with $50,000 in virtual capital.',
    'how.step1.body': 'No personal money on the line. Same live markets, same data, same instruments as the pros.',
    'how.step2.title': 'Learn from an AI coach.',
    'how.step2.body': 'Techniques, technical analysis, statistics, jargon, discipline. The things that actually separate the 3% from the 97%.',
    'how.step3.title': 'Hit your targets, get paid in real money.',
    'how.step3.body': 'Convert 80% of your virtual profits into real cash. You keep the upside. We keep the lights on.',
    'how.visual.simulated': 'SIMULATED · NO RISK',
    'how.visual.coach': 'AI Coach',
    'how.visual.coachQuote': '"The price keeps bouncing off the same level, that\'s called support. As long as it holds, buyers are in control."',
    'how.visual.realCash': 'real cash',
    'how.visual.approved': 'Approved · paid via ACH',

    // Why Beymann
    'why.eyebrow': 'Why · Beymann',
    'why.title': 'No risk. No noise. Just skills and discipline.',
    'why.sub': "The platforms you've used were built to maximize trades, not traders.",
    'why.them': 'Robinhood & Co.',
    'why.us': 'Beymann',
    'why.row1.label': 'Your capital',
    'why.row1.them': 'Your money on the line, day one',
    'why.row1.us': '$50,000 virtual, always',
    'why.row2.label': 'Guidance',
    'why.row2.them': 'None',
    'why.row2.us': 'AI coach on every trade',
    'why.row3.label': 'What they want',
    'why.row3.them': 'You to trade more',
    'why.row3.us': 'You to trade better',
    'why.row4.label': 'When you lose',
    'why.row4.them': 'They still win',
    'why.row4.us': "We don't get paid",
    'why.footnote': "We don't think they're evil. We think the model is.",

    // Final CTA
    'finalCta.eyebrow': 'The bottom line',
    'finalCta.title.line1': 'Trading is a skill.',
    'finalCta.title.accent': 'Treat it like one.',
    'finalCta.body': "The traders who make it didn't start by gambling their savings. They started by learning. Beymann is where they would've started if it had existed.",
    'finalCta.btn': 'Join the waitlist',

    // Waitlist
    'waitlist.eyebrow': 'Founding Members',
    'waitlist.title': 'Get in before everyone else does.',
    'waitlist.sub': "We're opening Beymann to a limited group of founding members first. Skip the public line.",
    'waitlist.cardTag': '· Founding member pass ·',
    'waitlist.formTitle': 'Reserve your spot.',
    'waitlist.formSub': "No payment now. We'll reach out when your spot opens, with founding-member pricing locked in.",
    'waitlist.formPlaceholder': 'you@example.com',
    'waitlist.formInvalid': 'Enter a valid email.',
    'waitlist.formSubmit': 'Join the waitlist',
    'waitlist.formAssurance': 'We email you once. No spam, no shared lists.',
    'waitlist.whatYouGet': 'What you get',
    'waitlist.perk1.k': 'Early access',
    'waitlist.perk1.v': "Before public launch. Trade the platform while it's still being polished.",
    'waitlist.perk2.k': '$500 trading bonus',
    'waitlist.perk2.v': 'Added to your $50,000 virtual balance. A head start the day you log in.',
    'waitlist.perk3.k': '$89/month',
    'waitlist.perk3.v': 'Locked in.',
    'waitlist.perk4.k': 'Founding member status',
    'waitlist.perk4.v': 'Permanent badge in the community, plus first dibs on funded levels.',
    'waitlist.perk5.k': 'Direct line to the team',
    'waitlist.perk5.v': 'A private channel during beta. Your feedback shapes the product.',

    // Joined receipt
    'joined.onList': "You're on the list",
    'joined.welcome': 'Welcome, founding member.',
    'joined.lockedRate': 'Locked-in rate',
    'joined.perMonth': '/mo',
    'joined.skipTheLine': 'Skip the line',
    'joined.referralsCounter': '{count}/{total} referrals',
    'joined.earned': "You've earned founding-founder status. Your spot just moved to the front of the line.",
    'joined.referOne': 'Refer {n} more trader to jump the queue. Each referral skips you ahead 240 spots.',
    'joined.referMany': 'Refer {n} more traders to jump the queue. Each referral skips you ahead 240 spots.',
    'joined.copyLink': 'Copy link',
    'joined.copied': 'Copied',
    'joined.joinedOn': 'Joined {date}',
    'joined.useDifferent': 'Use a different email',

    // Blog
    'blog.eyebrow': 'The Journal',
    'blog.title': 'From our desk.',
    'blog.sub': 'Notes on markets, psychology, and the craft of trading.',
    'blog.readArticle': 'Read article →',
    'blog.readAll': 'Read all our articles on Medium',
    'blog.prev': 'Previous articles',
    'blog.next': 'Next articles',

    // X / Twitter
    'x.eyebrow': 'The Feed',
    'x.title': 'Live on X.',
    'x.sub': 'Quick takes on the markets as they move.',
    'x.follow': 'Follow us on X',
    'x.fallback': 'Our latest posts live on X.',
    'x.readPost': 'View on X',

    // Footer
    'footer.tagline': 'Financial freedom through disciplined day trading. For everyone.',
    'footer.earlyAccess': 'Early access',
    'footer.copyright': '© 2026 Beymann Capital. All rights reserved.',
    'footer.disclaimer': 'Simulated trading. No personal capital required. Results not guaranteed.',
    'footer.builtIn': 'Proudly built in the United States',
    'footer.cookiePrefs': 'Cookie preferences',

    // Meta
    'meta.title': 'Beymann. Learn to trade. Without losing your money.',
    'meta.description': 'A new way to trade with AI assistance, without risking your personal capital',
    'meta.ogTitle': 'Beymann Capital • Achieve Financial Freedom',
  },

  fr: {
    // Nav
    'nav.preLaunch': 'Avant-première',
    'nav.joinWaitlist': 'Rejoindre la liste',
    'nav.join': 'Rejoindre',

    // Scarcity banner
    'banner.scarcityPrefix': 'Le tarif fondateur se clôt à 10 000 inscriptions.',
    'banner.scarcityCta': 'Rejoindre →',

    // Hero
    'hero.classic.line1': 'Tradez.',
    'hero.classic.line2': 'sans risquer',
    'hero.classic.line3': 'votre argent.',
    'hero.underline.prefix': 'Apprenez à trader.',
    'hero.underline.middle': 'Sans',
    'hero.underline.accent': 'perdre votre argent',
    'hero.serif.prefix': 'Apprenez à trader.',
    'hero.serif.middle': 'Sans',
    'hero.serif.accent': 'perdre votre argent',
    'hero.sub': '50 000 $ de capital virtuel, un coach IA et 80 % de vos profits reversés en argent réel. Sans jamais risquer votre capital personnel.',
    'hero.ctaJoin': 'Rejoindre la liste',
    'hero.ctaHow': 'Voir comment ça marche ↓',

    // Problem
    'problem.eyebrow': 'Le Problème',
    'problem.title': 'Le marché est structurellement défavorable aux petits porteurs.',
    'problem.body': "Les outils à votre disposition sont complexes, sans aucun accompagnement, et il vous est demander de risquer votre propre argent face à des marchés conçus pour vous le prendre.",
    'problem.quote': "Des plateformes comme Robinhood vous mettent une arme chargée entre les mains, et ... débrouillez vous !",
    'problem.bullet1': "Ces plateformes veulent que vous tradiez beaucoup.",
    'problem.bullet2': 'Elles gagnent dans tous les cas, que vous perdiez ou que vous gagniez.',
    'problem.bullet3': "Apprendre à trader ne devrait pas coûter vos économies.",

    // Fix
    'fix.eyebrow': 'La Solution',
    'fix.title.prefix': "Beymann: le trading",
    'fix.title.middle': 'comme il',
    'fix.title.accent': 'devrait',
    'fix.title.suffix': 'être.',
    'fix.body': "Vous devriez pouvoir apprendre le trading comme tout métier qui en vaut la peine : avec les bons outils, un vrai coach, et un moyen de gagner grâce à votre savoir-faire sans risquer vos économies.",
    'fix.tag': "C'est ce que nous construisons.",
    'fix.sideLabel': 'simple.',

    // Focus
    'focus.eyebrow': "L'Essentiel",
    'focus.title.prefix': 'Un seul instrument.',
    'focus.title.accent': 'pas de noeud au cerveau.',
    'focus.body': "La plupart des plateformes vous noient sous des milliers de tickers. Nous nous concentrons sur un seul : le Nasdaq, berceau des plus grandes entreprises tech du monde. Vous le tradez via le contrat à terme MNQ, qui réplique l'indice en temps réel. Maîtrisez un seul rythme plutôt que d'en poursuivre cent.",
    'focus.tag': 'Nasdaq-100 · Futures MNQ',

    // How it works
    'how.eyebrow': 'Comment ça marche',
    'how.title.line1': 'Trois étapes.',
    'how.title.line2': 'Une discipline.',
    'how.sub': "Ni casino, ni copy-trading, ni magie. Vous apprenez le métier, puis vous êtes payé pour ça.",
    'how.step1.title': 'Tradez avec 50 000 $ de capital virtuel.',
    'how.step1.body': "Aucun argent personnel en jeu. Les mêmes données de marchés en live, et les mêmes instruments que les pros.",
    'how.step2.title': 'Apprenez avec un coach IA.',
    'how.step2.body': "Analyse technique, statistiques, jargon, discipline. Ce qui sépare réellement les 3 % des 97 %.",
    'how.step3.title': 'Atteignez vos objectifs, soyez payé en argent réel.',
    'how.step3.body': "Convertissez 80 % de vos profits virtuels en argent réel. Vous gardez les gains. Nous payons les factures.",
    'how.visual.simulated': 'SIMULÉ · SANS RISQUE',
    'how.visual.coach': 'Coach IA',
    'how.visual.coachQuote': "« Le prix rebondit sans cesse sur le même niveau, on appelle ça un support. Tant qu'il tient, les acheteurs gardent la main. »",
    'how.visual.realCash': 'argent réel',
    'how.visual.approved': 'Approuvé · payé par virement bancaire',

    // Why Beymann
    'why.eyebrow': 'Pourquoi Beymann',
    'why.title': 'Aucun risque personnel. Juste du savoir-faire et de la discipline.',
    'why.sub': 'Les plateformes que vous avez utilisées sont conçues pour maximiser les trades, pas les traders.',
    'why.them': 'Robinhood & Co.',
    'why.us': 'Beymann',
    'why.row1.label': 'Votre capital',
    'why.row1.them': 'Votre argent en jeu dès le premier jour',
    'why.row1.us': '50 000 $ virtuels',
    'why.row2.label': 'Accompagnement',
    'why.row2.them': 'Aucun',
    'why.row2.us': 'Coach IA à chaque trade',
    'why.row3.label': "Ce qu'ils veulent",
    'why.row3.them': 'Que vous tradiez davantage',
    'why.row3.us': 'Que vous tradiez mieux',
    'why.row4.label': 'Quand vous perdez',
    'why.row4.them': 'Ils gagnent quand même',
    'why.row4.us': 'Nous ne sommes pas payés',
    'why.footnote': "Nous ne pensons pas qu'ils soient mauvais. Nous pensons que le modèle l'est.",

    // Final CTA
    'finalCta.eyebrow': 'En résumé',
    'finalCta.title.line1': 'Le trading est une compétence.',
    'finalCta.title.accent': 'Traitez-le comme tel.',
    'finalCta.body': "Les traders qui réussissent n'ont pas commencé en jouant leurs économies. Ils ont commencé en apprenant. Beymann est l'endroit où ils auraient commencé, s'il avait existé.",
    'finalCta.btn': 'Rejoindre la liste',

    // Waitlist
    'waitlist.eyebrow': 'Membres Fondateurs',
    'waitlist.title': 'Soyez parmi les premiers.',
    'waitlist.sub': "Nous ouvrons Beymann à un groupe restreint de membres fondateurs en priorité. Soyez l'un des premiers.",
    'waitlist.cardTag': '· Pass membre fondateur ·',
    'waitlist.formTitle': 'Réservez votre place.',
    'waitlist.formSub': "Aucun paiement maintenant. Nous vous contactons dès que votre place s'ouvre, avec le tarif fondateur verrouillé.",
    'waitlist.formPlaceholder': 'vous@exemple.com',
    'waitlist.formInvalid': 'Saisissez une adresse e-mail valide.',
    'waitlist.formSubmit': 'Rejoindre la liste',
    'waitlist.formAssurance': 'Nous vous écrivons une seule fois. Aucun spam, aucune liste partagée.',
    'waitlist.whatYouGet': 'Vos avantages',
    'waitlist.perk1.k': 'Accès en avant première',
    'waitlist.perk1.v': "Avant le lancement public. Testez la plateforme pendant que nous la peaufinons.",
    'waitlist.perk2.k': '500 $ de bonus de trading',
    'waitlist.perk2.v': "Crédités sur votre solde virtuel de 50 000 $. Une longueur d'avance dès votre première connexion.",
    'waitlist.perk3.k': '89 $/mois',
    'waitlist.perk3.v': 'Verrouillé.',
    'waitlist.perk4.k': 'Statut de membre fondateur',
    'waitlist.perk4.v': "Badge permanent dans la communauté, et priorité sur les nouveaux types de comptes.",
    'waitlist.perk5.k': "Ligne directe avec l'équipe",
    'waitlist.perk5.v': 'Un canal privé pendant la bêta. Vos retours façonnent le produit.',

    // Joined receipt
    'joined.onList': 'Vous êtes sur la liste',
    'joined.welcome': 'Bienvenue, membre fondateur.',
    'joined.lockedRate': 'Tarif verrouillé',
    'joined.perMonth': '/mois',
    'joined.skipTheLine': 'Doublez la file',
    'joined.referralsCounter': '{count}/{total} parrainages',
    'joined.earned': "Vous avez décroché le statut de fondateur.",
    'joined.referOne': 'Parrainez {n} trader de plus pour passer devant. Chaque parrainage vous fait gagner 240 places.',
    'joined.referMany': 'Parrainez {n} traders de plus pour passer devant. Chaque parrainage vous fait gagner 240 places.',
    'joined.copyLink': 'Copier le lien',
    'joined.copied': 'Copié',
    'joined.joinedOn': 'Inscrit le {date}',
    'joined.useDifferent': 'Utiliser une autre adresse',

    // Blog
    'blog.eyebrow': 'Le Journal',
    'blog.title': 'Depuis notre desk.',
    'blog.sub': 'Notes sur les marchés, la psychologie et le métier du trading.',
    'blog.readArticle': "Lire l'article →",
    'blog.readAll': 'Lire tous nos articles sur Medium',
    'blog.prev': 'Articles précédents',
    'blog.next': 'Articles suivants',

    // X / Twitter
    'x.eyebrow': 'Le Fil',
    'x.title': 'En direct sur X.',
    'x.sub': 'Réactions à chaud sur les marchés en mouvement.',
    'x.follow': 'Suivez-nous sur X',
    'x.fallback': 'Nos derniers posts sont sur X.',
    'x.readPost': 'Voir sur X',

    // Footer
    'footer.tagline': 'La liberté financière grâce à un day trading discipliné. Pour tous.',
    'footer.earlyAccess': 'Accès en avant première',
    'footer.copyright': '© 2026 Beymann Capital. Tous droits réservés.',
    'footer.disclaimer': 'Trading simulé. Aucun capital personnel requis. Résultats non garantis.',
    'footer.builtIn': 'Conçu avec fierté aux États-Unis',
    'footer.cookiePrefs': 'Préférences des cookies',

    // Meta
    'meta.title': "Beymann. Apprenez à trader. Sans perdre votre argent.",
    'meta.description': "Une nouvelle façon de trader, assistée par l'IA, sans risquer votre capital personnel.",
    'meta.ogTitle': 'Beymann Capital • Vers la liberté financière',
  },

  es: {
    // Nav
    'nav.preLaunch': 'Pre-lanzamiento',
    'nav.joinWaitlist': 'Unirse a la lista',
    'nav.join': 'Unirse',

    // Scarcity banner
    'banner.scarcityPrefix': 'El precio fundador se cierra al llegar a 10 000 inscripciones.',
    'banner.scarcityCta': 'Unirse →',

    // Hero
    'hero.classic.line1': 'Opera.',
    'hero.classic.line2': 'sin arriesgar',
    'hero.classic.line3': 'tu dinero.',
    'hero.underline.prefix': 'Aprende a operar.',
    'hero.underline.middle': 'Sin',
    'hero.underline.accent': 'perder tu dinero',
    'hero.serif.prefix': 'Aprende a operar.',
    'hero.serif.middle': 'Sin',
    'hero.serif.accent': 'perder tu dinero',
    'hero.sub': '50 000 $ de capital virtual, un coach con IA y el 80 % de tus ganancias pagadas en efectivo real. Sin arriesgar nunca tu capital personal.',
    'hero.ctaJoin': 'Unirse a la lista',
    'hero.ctaHow': 'Ver cómo funciona ↓',

    // Problem
    'problem.eyebrow': 'El Problema',
    'problem.title': 'El mercado está estructuralmente en contra de los pequeños inversores.',
    'problem.body': "Las herramientas a tu disposición son complejas, sin ningún acompañamiento, y se te pide arriesgar tu propio dinero frente a mercados diseñados para quitártelo.",
    'problem.quote': 'Plataformas como Robinhood te ponen un arma cargada en las manos y... ¡apáñatelas!',
    'problem.bullet1': 'Estas plataformas quieren que operes mucho.',
    'problem.bullet2': 'Ganan en todos los casos, ya pierdas o ganes.',
    'problem.bullet3': 'Aprender a operar no debería costarte tus ahorros.',

    // Fix
    'fix.eyebrow': 'La Solución',
    'fix.title.prefix': 'Beymann: el trading',
    'fix.title.middle': 'como',
    'fix.title.accent': 'debería',
    'fix.title.suffix': 'ser.',
    'fix.body': "Deberías poder aprender a operar como cualquier otro oficio que valga la pena: con las herramientas adecuadas, un coach real y una forma de ganar con tu talento sin arriesgar tus ahorros.",
    'fix.tag': 'Eso es lo que estamos construyendo.',
    'fix.sideLabel': 'simple.',

    // Focus
    'focus.eyebrow': 'Lo Esencial',
    'focus.title.prefix': 'Un solo instrumento.',
    'focus.title.accent': 'sin liarte la cabeza.',
    'focus.body': 'La mayoría de plataformas te ahogan con miles de tickers. Nosotros nos centramos en uno solo: el Nasdaq, cuna de las mayores tecnológicas del mundo. Lo operas a través del contrato de futuros MNQ, que replica el índice en tiempo real. Domina un solo ritmo en lugar de perseguir cien.',
    'focus.tag': 'Nasdaq-100 · Futuros MNQ',

    // How it works
    'how.eyebrow': 'Cómo funciona',
    'how.title.line1': 'Tres pasos.',
    'how.title.line2': 'Una disciplina.',
    'how.sub': 'Ni casino, ni copy-trading, ni magia. Aprendes el oficio, y luego te pagan por él.',
    'how.step1.title': 'Opera con 50 000 $ de capital virtual.',
    'how.step1.body': 'Sin dinero personal en juego. Los mismos datos de mercado en directo, y los mismos instrumentos que los profesionales.',
    'how.step2.title': 'Aprende con un coach de IA.',
    'how.step2.body': 'Análisis técnico, estadística, jerga, disciplina. Lo que de verdad separa al 3 % del 97 %.',
    'how.step3.title': 'Alcanza tus objetivos y cobra en dinero real.',
    'how.step3.body': 'Convierte el 80 % de tus ganancias virtuales en efectivo real. Tú te quedas con las ganancias. Nosotros pagamos las cuentas.',
    'how.visual.simulated': 'SIMULADO · SIN RIESGO',
    'how.visual.coach': 'Coach IA',
    'how.visual.coachQuote': '«El precio sigue rebotando en el mismo nivel: eso se llama soporte. Mientras aguante, los compradores llevan el control.»',
    'how.visual.realCash': 'efectivo real',
    'how.visual.approved': 'Aprobado · pagado por transferencia bancaria',

    // Why Beymann
    'why.eyebrow': 'Por qué Beymann',
    'why.title': 'Cero riesgo personal. Solo habilidad y disciplina.',
    'why.sub': 'Las plataformas que has usado se diseñaron para maximizar las operaciones, no a los traders.',
    'why.them': 'Robinhood y Cía.',
    'why.us': 'Beymann',
    'why.row1.label': 'Tu capital',
    'why.row1.them': 'Tu dinero en juego desde el primer día',
    'why.row1.us': '50 000 $ virtuales',
    'why.row2.label': 'Acompañamiento',
    'why.row2.them': 'Ninguno',
    'why.row2.us': 'Coach IA en cada operación',
    'why.row3.label': 'Lo que quieren',
    'why.row3.them': 'Que operes más',
    'why.row3.us': 'Que operes mejor',
    'why.row4.label': 'Cuando pierdes',
    'why.row4.them': 'Ellos siguen ganando',
    'why.row4.us': 'Nosotros no cobramos',
    'why.footnote': 'No creemos que sean malvados. Creemos que el modelo lo es.',

    // Final CTA
    'finalCta.eyebrow': 'En resumen',
    'finalCta.title.line1': 'El trading es una habilidad.',
    'finalCta.title.accent': 'Trátalo como tal.',
    'finalCta.body': 'Los traders que lo consiguen no empezaron jugándose sus ahorros. Empezaron aprendiendo. Beymann es donde habrían empezado, si hubiera existido.',
    'finalCta.btn': 'Unirse a la lista',

    // Waitlist
    'waitlist.eyebrow': 'Miembros Fundadores',
    'waitlist.title': 'Sé de los primeros.',
    'waitlist.sub': 'Abrimos Beymann primero a un grupo limitado de miembros fundadores. Sé uno de los primeros.',
    'waitlist.cardTag': '· Pase de miembro fundador ·',
    'waitlist.formTitle': 'Reserva tu lugar.',
    'waitlist.formSub': 'Sin pago ahora. Te contactaremos cuando se abra tu plaza, con el precio fundador bloqueado.',
    'waitlist.formPlaceholder': 'tu@ejemplo.com',
    'waitlist.formInvalid': 'Introduce un correo válido.',
    'waitlist.formSubmit': 'Unirse a la lista',
    'waitlist.formAssurance': 'Te escribimos una sola vez. Sin spam, sin listas compartidas.',
    'waitlist.whatYouGet': 'Tus ventajas',
    'waitlist.perk1.k': 'Acceso anticipado',
    'waitlist.perk1.v': 'Antes del lanzamiento público. Prueba la plataforma mientras la pulimos.',
    'waitlist.perk2.k': '500 $ de bono de trading',
    'waitlist.perk2.v': 'Acreditados en tu saldo virtual de 50 000 $. Una ventaja desde tu primera sesión.',
    'waitlist.perk3.k': '89 $/mes',
    'waitlist.perk3.v': 'Bloqueado.',
    'waitlist.perk4.k': 'Estatus de miembro fundador',
    'waitlist.perk4.v': 'Insignia permanente en la comunidad, y prioridad en los nuevos tipos de cuentas.',
    'waitlist.perk5.k': 'Línea directa con el equipo',
    'waitlist.perk5.v': 'Un canal privado durante la beta. Tu feedback moldea el producto.',

    // Joined receipt
    'joined.onList': 'Estás en la lista',
    'joined.welcome': 'Bienvenido, miembro fundador.',
    'joined.lockedRate': 'Precio bloqueado',
    'joined.perMonth': '/mes',
    'joined.skipTheLine': 'Adelántate',
    'joined.referralsCounter': '{count}/{total} referidos',
    'joined.earned': 'Te has ganado el estatus de fundador.',
    'joined.referOne': 'Refiere a {n} trader más para adelantarte. Cada referido te sube 240 puestos.',
    'joined.referMany': 'Refiere a {n} traders más para adelantarte. Cada referido te sube 240 puestos.',
    'joined.copyLink': 'Copiar enlace',
    'joined.copied': 'Copiado',
    'joined.joinedOn': 'Inscrito el {date}',
    'joined.useDifferent': 'Usar otro correo',

    // Blog
    'blog.eyebrow': 'El Diario',
    'blog.title': 'Desde nuestra mesa de trading.',
    'blog.sub': 'Notas sobre mercados, psicología y el oficio del trading.',
    'blog.readArticle': 'Leer artículo →',
    'blog.readAll': 'Lee todos nuestros artículos en Medium',
    'blog.prev': 'Artículos anteriores',
    'blog.next': 'Artículos siguientes',

    // X / Twitter
    'x.eyebrow': 'El Feed',
    'x.title': 'En directo en X.',
    'x.sub': 'Reacciones en tiempo real a los mercados en movimiento.',
    'x.follow': 'Síguenos en X',
    'x.fallback': 'Nuestras últimas publicaciones están en X.',
    'x.readPost': 'Ver en X',

    // Footer
    'footer.tagline': 'La libertad financiera gracias a un day trading disciplinado. Para todos.',
    'footer.earlyAccess': 'Acceso anticipado',
    'footer.copyright': '© 2026 Beymann Capital. Todos los derechos reservados.',
    'footer.disclaimer': 'Trading simulado. No se requiere capital personal. Resultados no garantizados.',
    'footer.builtIn': 'Hecho con orgullo en Estados Unidos',
    'footer.cookiePrefs': 'Preferencias de cookies',

    // Meta
    'meta.title': 'Beymann. Aprende a operar. Sin perder tu dinero.',
    'meta.description': 'Una nueva forma de operar, asistida por IA, sin arriesgar tu capital personal.',
    'meta.ogTitle': 'Beymann Capital • Hacia la libertad financiera',
  },
};

const DATE_LOCALES = { en: 'en-US', fr: 'fr-FR', es: 'es-ES' };

// Read the locale segment from the URL path. Returns null if no /fr or /es prefix.
const langFromPath = () => {
  if (typeof window === 'undefined') return null;
  const seg = (window.location.pathname.split('/')[1] || '').toLowerCase();
  return LANGS.includes(seg) ? seg : null;
};

// Build the URL for a target language, preserving everything after the locale
// segment (path tail, query string, hash). English lives at the root (no prefix).
const buildLangUrl = (lang) => {
  if (typeof window === 'undefined') return '/';
  const stripped = window.location.pathname.replace(/^\/(en|fr|es)(?=\/|$)/, '') || '/';
  const newPath = lang === 'en'
    ? stripped
    : '/' + lang + (stripped === '/' ? '' : stripped);
  return newPath + window.location.search + window.location.hash;
};

const detectLang = () => {
  // 1. URL path wins — explicit and shareable
  const fromPath = langFromPath();
  if (fromPath) return fromPath;
  // 2. user's stored preference
  try {
    const saved = localStorage.getItem(STORAGE_KEY);
    if (saved && LANGS.includes(saved)) return saved;
  } catch {}
  // 3. browser default
  if (typeof navigator !== 'undefined' && navigator.language) {
    const guess = navigator.language.slice(0, 2).toLowerCase();
    if (LANGS.includes(guess)) return guess;
  }
  return 'en';
};

const interpolate = (str, vars) => {
  if (!vars) return str;
  return str.replace(/\{(\w+)\}/g, (_, k) => (k in vars ? String(vars[k]) : `{${k}}`));
};

const I18nContext = React.createContext({
  lang: 'en',
  setLang: () => {},
  t: (k) => k,
  dateLocale: 'en-US',
});

const I18nProvider = ({ children }) => {
  const [lang, setLangState] = React.useState(() => detectLang());

  React.useEffect(() => {
    try { document.documentElement.setAttribute('lang', lang); } catch {}
  }, [lang]);

  // Browser back/forward should swap language if the URL crosses a locale boundary.
  React.useEffect(() => {
    const onPop = () => {
      const fromPath = langFromPath();
      if (fromPath && fromPath !== lang) setLangState(fromPath);
      else if (!fromPath && lang !== 'en') setLangState('en');
    };
    window.addEventListener('popstate', onPop);
    return () => window.removeEventListener('popstate', onPop);
  }, [lang]);

  const setLang = React.useCallback((next) => {
    if (!LANGS.includes(next)) return;
    try { localStorage.setItem(STORAGE_KEY, next); } catch {}
    try {
      const url = buildLangUrl(next);
      if (url !== window.location.pathname + window.location.search + window.location.hash) {
        window.history.pushState({ lang: next }, '', url);
      }
    } catch {}
    setLangState(next);
  }, []);

  const t = React.useCallback((key, vars) => {
    const dict = STRINGS[lang] || STRINGS.en;
    const fallback = STRINGS.en;
    const raw = (key in dict ? dict[key] : (key in fallback ? fallback[key] : key));
    return interpolate(raw, vars);
  }, [lang]);

  const value = React.useMemo(
    () => ({ lang, setLang, t, dateLocale: DATE_LOCALES[lang] || 'en-US' }),
    [lang, setLang, t]
  );

  return <I18nContext.Provider value={value}>{children}</I18nContext.Provider>;
};

const useI18n = () => React.useContext(I18nContext);

Object.assign(window, { I18nContext, I18nProvider, useI18n, LANGS, LANG_LABELS, STRINGS });
