// i18n — Spanish + English translations
window.I18N = {
  es: {
    nav: { problema: 'Problema', solucion: 'Solución', paquetes: 'Paquetes', roi: 'ROI', casos: 'Casos', cta: 'Solicitar demo', region: 'ES · EU' },
    ticker: ['Verifactu 2027 ready','Agente Digitalizador adherido','RGPD compliant','EU-hosted','AI Act ready','A3 · Sage · Holded · Anfix','Setup desde €0 con Kit Digital','14–21 días en producción'],
    hero: {
      edition: 'Edición 04 · Otoño 2026',
      issue: 'N.º 001 / Manifiesto',
      audience: '↳ Para gestorías y asesorías españolas',
      thesisLabel: '(I) Tesis',
      thesis: 'Implementamos sistemas de IA en despachos profesionales que reciben facturas por WhatsApp.',
      h1a: 'Tu despacho,',
      h1b: 'sin picado',
      h1c: 'de datos.',
      verifLabel: 'Verifactu',
      verifReady: 'Listo en 21 días',
      lede: 'Conectamos WhatsApp, email y tu software contable —',
      ledeMid: ' A3, Sage, Holded, Anfix',
      ledeEnd: '— en un sistema operativo de IA que clasifica facturas, contesta el 60–70% de las consultas y te prepara para Verifactu antes que la competencia.',
      ctaDemo: 'Ver demo · 2 min',
      ctaDiag: 'Diagnóstico gratuito',
      bullets: ['↳ Sin contratar más personal','↳ Sin cambiar tu software','↳ RGPD · AI Act ready'],
      invoice: 'Factura · F2026-0814',
      classified: '● Clasificada IA',
      vendor: 'Suministros Pereda S.L.',
      base: 'Base imponible',
      iva: 'IVA 21%',
      account: 'Cuenta sugerida',
      accountVal: '(600) Compras',
      source: 'Fuente',
      sourceVal: 'WhatsApp · 11:42',
      entry: 'Asiento',
      entryVal: '→ A3 OK',
      hoursLabel: 'Horas/sem ahorradas',
      teamLabel: 'Equipo de 3 técnicos',
      setupLabel: 'Setup desde',
      kitLabel: 'con bono Kit Digital ↳',
    },
    prob: {
      head: '§ 02 — Problema',
      title: 'Reconocible, doloroso, específico',
      kicker: 'Diagnóstico',
      h2a: 'Tu equipo gestiona facturas que llegan por ',
      h2b: 'cuatro canales',
      h2c: ' distintos — y todos te roban horas.',
      lede: 'El 60–70% del tiempo del técnico se pierde en picado de datos, recordando vencimientos, y contestando',
      ledeQ: '"¿cuándo se paga el IVA?"',
      ledeEnd: '. Y a partir de enero 2027, Verifactu va a multiplicar ese trabajo si no tienes infraestructura ya lista.',
      channels: [
        { label: 'Email', sub: 'Adjuntos sin orden, asuntos vacíos' },
        { label: 'WhatsApp', sub: '"Foto, PDF, luego te lo paso bien"' },
        { label: 'Drive compartido', sub: 'A medias, sin permisos claros' },
        { label: 'Sobres físicos', sub: 'A fin de trimestre. Siempre.' },
      ],
      channelTag: 'Canal',
      callout: 'Verifactu obliga a remitir cada factura, en tiempo real, a la AEAT. Sin infraestructura, es trabajo manual extra. Con nosotros, está hecho.',
      calloutDate: 'Enero 2027',
    },
    sol: {
      head: '§ 03 — Solución',
      title: '— Un sistema operativo, no un plug-in',
      kicker: 'End-to-end',
      h2a: 'Conecta',
      h2b: ' con tu software.',
      h2c: 'No lo reemplaza.',
      features: [
        'Recibe documentos por WhatsApp y email',
        'Clasifica facturas con IA · 90%+ precisión',
        'Genera asientos contables automáticos',
        'Recuerda plazos fiscales por cliente',
        'Contesta consultas frecuentes 24/7',
        'Genera contratos, finiquitos, partes SS',
        'Concilia bancos automáticamente',
        'Prepara tu despacho para Verifactu 2027',
      ],
      waLabel: 'WhatsApp · Cliente',
      live: '● live',
      msg1: 'Te paso la factura del proveedor',
      photoLabel: 'FOTO · IMG_4831.jpg',
      msg2: 'Recibido. Suministros Pereda · 2.226,40€ · clasificada en (600). ¿Algo más?',
      msg3: '¿Cuándo se paga el IVA del 3T?',
      msg4: 'Modelo 303: del 1 al 20 octubre. Te recuerdo el día 18.',
      flow: [
        { t: 'Ingest', s: 'WhatsApp · Email · Drive · OCR' },
        { t: 'Clasifica', s: 'IA propietaria · 90%+ precisión' },
        { t: 'Asiento', s: '→ A3 / Sage / Holded' },
        { t: 'Verifactu', s: 'Remisión AEAT en tiempo real' },
      ],
      flowCta: 'Ver flujo completo · Loom 2:14',
    },
    porque: {
      head: '§ 04 — Por qué nosotros',
      title: 'Cinco razones, en orden',
      kicker: 'Diferenciadores',
      reasons: [
        { t: 'Agente Digitalizador adherido', d: 'El bono Kit Digital cubre €2.000–€12.000 del setup. Para muchos clientes, setup = 0€.', big: '0€' },
        { t: 'Solo despachos profesionales', d: 'No hacemos webs, ni e-commerce, ni redes. Únicamente IA para gestorías y asesorías.', big: '↳' },
        { t: 'Listos para Verifactu 2027', d: 'Implementamos hoy lo que la ley te va a exigir mañana. Empieza con ventaja.', big: '27' },
        { t: 'EU-hosted · RGPD · AI Act', d: 'Tus datos no salen de Europa. Cumplimiento desde el día 1, no como parche.', big: 'EU' },
        { t: 'Producción en 14–21 días', d: 'No en 6 meses. Empiezas a recuperar horas en la semana 3.', big: '21' },
      ],
      no: 'N.º',
    },
    pkg: {
      head: '§ 05 — Paquetes',
      title: 'Cuatro escalones · todos elegibles para Kit Digital',
      kicker: '€ + IVA',
      popular: '★ Popular',
      plan: 'Plan',
      setup: 'setup',
      monthly: '/mes',
      cta: 'Empezar',
      footer: '↳ Setup financiado por Kit Digital ↲',
      footerSub: '· Para muchos clientes el coste inicial es 0€',
      list: [
        { name: 'Quick Win Starter', sub: 'Para despachos de 1–3 técnicos', bullets: ['Ingesta WhatsApp + email','Clasificador IA básico','Recordatorios fiscales','1 integración contable'] },
        { name: 'AI Front Desk Pro', sub: 'El más popular · 4–8 técnicos', bullets: ['Todo lo anterior +','Asistente cliente 24/7','Generación de documentos','Verifactu ready','Onboarding en 21 días'] },
        { name: 'AI Operations Suite', sub: 'Despachos de 8–20 técnicos', bullets: ['Todo lo anterior +','Conciliación bancaria','Multi-agente por área','Analytics avanzado','Soporte dedicado'] },
        { name: 'Multi-Location Group', sub: 'Grupos · 20+ técnicos', bullets: ['Implementación a medida','Multi-oficina','SSO + permisos avanzados','SLA enterprise','CSM dedicado'] },
      ],
    },
    roi: {
      head: '§ 06 — Calculadora',
      title: 'Lo que pierdes hoy en picado de datos',
      kicker: 'Tiempo real',
      title2: 'Cuéntanos sobre tu despacho.',
      q1: '¿Cuántos técnicos tienes?',
      q2: '¿Horas/semana en picado de datos?',
      q3: '¿Coste/hora medio?',
      result: 'Resultado · estimación anual',
      lede: 'Con tu equipo actual, así se ven los números:',
      lose: 'Pierdes / año',
      invest: 'Tu inversión año 1',
      save: 'Ahorro neto',
      payback: 'Payback',
      months: 'meses',
      cta: 'Quiero estos números',
    },
    casos: {
      head: '§ 07 — Casos reales',
      title: 'Despachos que ya recuperaron horas',
      kicker: 'Selección',
      list: [
        { q: 'Hemos pasado de 3 personas dedicadas a 2, con la misma carga de trabajo y mejor servicio.', author: 'M. Calatrava', role: 'Asesoría Calatrava · Valencia', meta: '8 técnicos · A3' },
        { q: 'El sistema responde a clientes a las 22:00 mejor que nosotros un martes a las 11.', author: 'J. Otero', role: 'Gestoría Otero & Hijos · Bilbao', meta: '5 técnicos · Sage' },
      ],
    },
    cta: {
      kicker: '§ 08 — Cierre',
      h2a: 'Diagnóstico',
      h2b: 'gratuito.',
      h2c: '30 minutos.',
      lede: 'Sin compromiso. Sin venta agresiva. Te decimos honestamente si tu despacho está listo, qué falta, y si nuestro sistema te encaja.',
      demo: 'Ver demo · 2 min',
      book: 'Agendar llamada',
    },
    footer: {
      tag: 'Sistemas de IA para despachos profesionales. Hechos en España, alojados en Europa.',
      cols: [
        { h: 'Producto', items: ['Quick Win Starter','AI Front Desk Pro','Operations Suite','Multi-Location Group'] },
        { h: 'Empresa', items: ['Sobre nosotros','Casos','Blog','Contacto'] },
        { h: 'Legal', items: ['Privacidad','Términos','RGPD','AI Act'] },
      ],
      compliance: 'Compliance',
      copy: '© 2026 Orden Claro · Madrid · Barcelona',
      cert: 'Agente Digitalizador adherido al programa Kit Digital',
      ver: 'v.04 · Otoño\'26',
    },
  },
  en: {
    nav: { problema: 'Problem', solucion: 'Solution', paquetes: 'Plans', roi: 'ROI', casos: 'Cases', cta: 'Request demo', region: 'ES · EU' },
    ticker: ['Verifactu 2027 ready','Certified Digitalisation Agent','GDPR compliant','EU-hosted','AI Act ready','A3 · Sage · Holded · Anfix','Setup from €0 with Kit Digital','14–21 days to production'],
    hero: {
      edition: 'Issue 04 · Autumn 2026',
      issue: 'No. 001 / Manifesto',
      audience: '↳ For Spanish accounting & advisory firms',
      thesisLabel: '(I) Thesis',
      thesis: 'We deploy AI systems in professional firms that receive invoices over WhatsApp.',
      h1a: 'Your firm,',
      h1b: 'without manual',
      h1c: 'data entry.',
      verifLabel: 'Verifactu',
      verifReady: 'Live in 21 days',
      lede: 'We connect WhatsApp, email and your accounting software —',
      ledeMid: ' A3, Sage, Holded, Anfix',
      ledeEnd: '— into one AI operating system that classifies invoices, answers 60–70% of client queries, and gets you Verifactu-ready before the competition.',
      ctaDemo: 'Watch demo · 2 min',
      ctaDiag: 'Free diagnostic',
      bullets: ['↳ No new hires','↳ Keep your software','↳ GDPR · AI Act ready'],
      invoice: 'Invoice · F2026-0814',
      classified: '● AI-classified',
      vendor: 'Suministros Pereda S.L.',
      base: 'Net amount',
      iva: 'VAT 21%',
      account: 'Suggested account',
      accountVal: '(600) Purchases',
      source: 'Source',
      sourceVal: 'WhatsApp · 11:42',
      entry: 'Journal',
      entryVal: '→ A3 OK',
      hoursLabel: 'Hours/week saved',
      teamLabel: 'Team of 3',
      setupLabel: 'Setup from',
      kitLabel: 'with Kit Digital grant ↳',
    },
    prob: {
      head: '§ 02 — Problem',
      title: 'Recognisable, painful, specific',
      kicker: 'Diagnostic',
      h2a: 'Your team handles invoices arriving through ',
      h2b: 'four channels',
      h2c: ' — and every one of them eats hours.',
      lede: '60–70% of your accountants\' time is lost on data entry, chasing deadlines, and answering',
      ledeQ: '"when is VAT due?"',
      ledeEnd: '. And from January 2027, Verifactu will multiply that workload unless your infrastructure is already in place.',
      channels: [
        { label: 'Email', sub: 'Unsorted attachments, blank subjects' },
        { label: 'WhatsApp', sub: '"Photo, PDF, I\'ll send it properly later"' },
        { label: 'Shared Drive', sub: 'Half-organised, unclear permissions' },
        { label: 'Paper envelopes', sub: 'End of quarter. Always.' },
      ],
      channelTag: 'Channel',
      callout: 'Verifactu requires every invoice to be sent to the tax agency in real time. Without infrastructure, that\'s extra manual work. With us, it\'s already done.',
      calloutDate: 'January 2027',
    },
    sol: {
      head: '§ 03 — Solution',
      title: '— An operating system, not a plug-in',
      kicker: 'End-to-end',
      h2a: 'Connects',
      h2b: ' to your software.',
      h2c: 'Doesn\'t replace it.',
      features: [
        'Ingests documents via WhatsApp and email',
        'Classifies invoices with AI · 90%+ accuracy',
        'Generates accounting entries automatically',
        'Tracks tax deadlines per client',
        'Answers frequent client queries 24/7',
        'Generates contracts, severances, SS forms',
        'Reconciles bank statements automatically',
        'Gets your firm Verifactu-ready for 2027',
      ],
      waLabel: 'WhatsApp · Client',
      live: '● live',
      msg1: 'Sending you the supplier invoice',
      photoLabel: 'PHOTO · IMG_4831.jpg',
      msg2: 'Got it. Suministros Pereda · €2,226.40 · classified to (600). Anything else?',
      msg3: 'When is Q3 VAT due?',
      msg4: 'Form 303: 1–20 October. I\'ll remind you on the 18th.',
      flow: [
        { t: 'Ingest', s: 'WhatsApp · Email · Drive · OCR' },
        { t: 'Classify', s: 'Proprietary AI · 90%+ accuracy' },
        { t: 'Post', s: '→ A3 / Sage / Holded' },
        { t: 'Verifactu', s: 'Real-time submission to AEAT' },
      ],
      flowCta: 'Watch full flow · Loom 2:14',
    },
    porque: {
      head: '§ 04 — Why us',
      title: 'Five reasons, in order',
      kicker: 'Differentiators',
      reasons: [
        { t: 'Certified Digitalisation Agent', d: 'The Kit Digital grant covers €2,000–€12,000 of setup. For many clients, setup = €0.', big: '0€' },
        { t: 'Only professional firms', d: 'No websites, no e-commerce, no social. Just AI for accounting and advisory firms.', big: '↳' },
        { t: 'Verifactu 2027 ready', d: 'We deploy today what the law will require tomorrow. Start with the head start.', big: '27' },
        { t: 'EU-hosted · GDPR · AI Act', d: 'Your data never leaves Europe. Compliance from day 1, not bolted on later.', big: 'EU' },
        { t: 'In production in 14–21 days', d: 'Not 6 months. You start recovering hours by week 3.', big: '21' },
      ],
      no: 'No.',
    },
    pkg: {
      head: '§ 05 — Plans',
      title: 'Four tiers · all eligible for Kit Digital',
      kicker: '€ + VAT',
      popular: '★ Popular',
      plan: 'Plan',
      setup: 'setup',
      monthly: '/mo',
      cta: 'Get started',
      footer: '↳ Setup funded by Kit Digital ↲',
      footerSub: '· For many clients the upfront cost is €0',
      list: [
        { name: 'Quick Win Starter', sub: 'For firms with 1–3 accountants', bullets: ['WhatsApp + email ingest','Basic AI classifier','Tax reminders','1 accounting integration'] },
        { name: 'AI Front Desk Pro', sub: 'Most popular · 4–8 accountants', bullets: ['Everything above +','24/7 client assistant','Document generation','Verifactu ready','Onboarding in 21 days'] },
        { name: 'AI Operations Suite', sub: 'Firms of 8–20 accountants', bullets: ['Everything above +','Bank reconciliation','Multi-agent by area','Advanced analytics','Dedicated support'] },
        { name: 'Multi-Location Group', sub: 'Groups · 20+ accountants', bullets: ['Custom implementation','Multi-office','SSO + advanced permissions','Enterprise SLA','Dedicated CSM'] },
      ],
    },
    roi: {
      head: '§ 06 — Calculator',
      title: 'What you\'re losing today on data entry',
      kicker: 'Live',
      title2: 'Tell us about your firm.',
      q1: 'How many accountants?',
      q2: 'Hours/week on data entry?',
      q3: 'Average cost/hour?',
      result: 'Result · annual estimate',
      lede: 'With your current team, here\'s what the numbers look like:',
      lose: 'You lose / year',
      invest: 'Your year-1 investment',
      save: 'Net savings',
      payback: 'Payback',
      months: 'months',
      cta: 'I want these numbers',
    },
    casos: {
      head: '§ 07 — Real cases',
      title: 'Firms already winning hours back',
      kicker: 'Selected',
      list: [
        { q: 'We went from 3 dedicated people to 2, with the same workload and better service.', author: 'M. Calatrava', role: 'Asesoría Calatrava · Valencia', meta: '8 accountants · A3' },
        { q: 'The system answers clients at 10pm better than we do on a Tuesday at 11am.', author: 'J. Otero', role: 'Gestoría Otero & Hijos · Bilbao', meta: '5 accountants · Sage' },
      ],
    },
    cta: {
      kicker: '§ 08 — Close',
      h2a: 'Free',
      h2b: 'diagnostic.',
      h2c: '30 minutes.',
      lede: 'No commitment. No hard sell. We\'ll tell you honestly whether your firm is ready, what\'s missing, and whether our system fits.',
      demo: 'Watch demo · 2 min',
      book: 'Book a call',
    },
    footer: {
      tag: 'AI systems for professional firms. Built in Spain, hosted in Europe.',
      cols: [
        { h: 'Product', items: ['Quick Win Starter','AI Front Desk Pro','Operations Suite','Multi-Location Group'] },
        { h: 'Company', items: ['About','Cases','Blog','Contact'] },
        { h: 'Legal', items: ['Privacy','Terms','GDPR','AI Act'] },
      ],
      compliance: 'Compliance',
      copy: '© 2026 Orden Claro · Madrid · Barcelona',
      cert: 'Certified Digitalisation Agent · Kit Digital programme',
      ver: 'v.04 · Autumn \'26',
    },
  },
};

// Language context + provider
window.LangContext = React.createContext({ lang: 'es', setLang: () => {}, t: window.I18N.es });

window.LangProvider = ({ children }) => {
  const [lang, setLang] = React.useState(() => {
    try { return localStorage.getItem('caudal-lang') || 'es'; } catch (e) { return 'es'; }
  });
  React.useEffect(() => {
    try { localStorage.setItem('caudal-lang', lang); } catch (e) {}
    document.documentElement.lang = lang;
  }, [lang]);
  const value = React.useMemo(() => ({ lang, setLang, t: window.I18N[lang] }), [lang]);
  return React.createElement(window.LangContext.Provider, { value }, children);
};

window.useT = () => React.useContext(window.LangContext);

// Toggle component
window.LangToggle = () => {
  const { lang, setLang } = window.useT();
  return (
    <div style={{
      display: 'inline-flex',
      border: '1px solid var(--ink)',
      borderRadius: 999,
      padding: 3,
      background: 'var(--paper)',
      fontFamily: 'JetBrains Mono, monospace',
      fontSize: 11,
      letterSpacing: '0.08em',
    }}>
      {['es','en'].map(l => (
        <button
          key={l}
          onClick={() => setLang(l)}
          style={{
            padding: '6px 12px',
            borderRadius: 999,
            background: lang === l ? 'var(--ink)' : 'transparent',
            color: lang === l ? 'var(--paper)' : 'var(--ink)',
            textTransform: 'uppercase',
            transition: 'all 0.2s',
            cursor: 'pointer',
          }}
        >{l}</button>
      ))}
    </div>
  );
};
