// DemoFatura.jsx — auto-looping demo: criar e certificar uma fatura (AT e-fatura).
// Timeline ~10s: cliente escrito → NIF validado → linhas → total → cursor
// clica "Certificar e emitir" → comunicação à AT → carimbo ATCUD + QR + toast.

(function () {
  const STR = {
    pt: {
      windowTitle: 'Vendas · Nova fatura',
      badgeCertified: 'Emitida · ATCUD',
      badgeSending: 'A comunicar…',
      badgeDraft: 'Rascunho',
      clientLabel: 'Cliente',
      colSku: 'SKU',
      colDesc: 'Designação',
      colQty: 'Qtd',
      colTotal: 'Total',
      totalVat: 'Total c/ IVA (22%)',
      series: 'Série 2026 · contínua',
      btnSending: 'A comunicar à AT…',
      btnDone: 'Emitida',
      btnIdle: 'Emitir e comunicar à AT',
      toast: 'Fatura FT 2026/0042 emitida · ATCUD e QR incluídos',
      rows: [
        { sku: 'CEM-25', name: 'Cimento CEM II 32,5N · 25 kg', qty: '120 un', total: '€ 514,80' },
        { sku: 'TIJ-30', name: 'Tijolo cerâmico 30×20×15', qty: '500 un', total: '€ 412,50' },
      ],
    },
    en: {
      windowTitle: 'Sales · New invoice',
      badgeCertified: 'Issued · ATCUD',
      badgeSending: 'Submitting…',
      badgeDraft: 'Draft',
      clientLabel: 'Customer',
      colSku: 'SKU',
      colDesc: 'Description',
      colQty: 'Qty',
      colTotal: 'Total',
      totalVat: 'Total w/ VAT (22%)',
      series: 'Series 2026 · continuous',
      btnSending: 'Submitting to AT…',
      btnDone: 'Issued',
      btnIdle: 'Issue and submit to AT',
      toast: 'Invoice FT 2026/0042 issued · ATCUD and QR included',
      rows: [
        { sku: 'CEM-25', name: 'Cement CEM II 32.5N · 25 kg', qty: '120 pcs', total: '€ 514,80' },
        { sku: 'TIJ-30', name: 'Ceramic brick 30×20×15', qty: '500 pcs', total: '€ 412,50' },
      ],
    },
    es: {
      windowTitle: 'Ventas · Nueva factura',
      badgeCertified: 'Emitida · ATCUD',
      badgeSending: 'Comunicando…',
      badgeDraft: 'Borrador',
      clientLabel: 'Cliente',
      colSku: 'SKU',
      colDesc: 'Descripción',
      colQty: 'Cant.',
      colTotal: 'Total',
      totalVat: 'Total c/ IVA (22%)',
      series: 'Serie 2026 · continua',
      btnSending: 'Comunicando a la AT…',
      btnDone: 'Emitida',
      btnIdle: 'Emitir y comunicar a la AT',
      toast: 'Factura FT 2026/0042 emitida · ATCUD y QR incluidos',
      rows: [
        { sku: 'CEM-25', name: 'Cemento CEM II 32,5N · 25 kg', qty: '120 ud', total: '€ 514,80' },
        { sku: 'TIJ-30', name: 'Ladrillo cerámico 30×20×15', qty: '500 ud', total: '€ 412,50' },
      ],
    },
  };

  function DemoFatura() {
    const lang = (window.__DEMO_LANG === 'en' || window.__DEMO_LANG === 'es') ? window.__DEMO_LANG : 'pt';
    const s = STR[lang];
    const D = 10000;
    const t = window.useDemoLoop(D, 8200);
    const { dkProg, dkEase, dkTyped, dkCursor, dkEUR } = window;
    const { DemoCaret, DemoCursor, DemoToast, MiniWindow, DemoStage, FakeQR } = window;

    const client = dkTyped('Construções Santa Cruz, Lda.', t, 500, 1700);
    const typing = t >= 500 && t < 1700;
    const nif = t >= 2000;
    const rowOn = [t >= 2400, t >= 2850];
    // € 927,30 net × 1.22 — Madeira normal rate (2026: 4/12/22)
    const total = 1131.31 * dkEase(dkProg(t, 3100, 4100));
    const sending = t >= 5050 && t < 6600;
    const done = t >= 6600;
    const toast = t >= 6950 && t < 9400;

    const cur = dkCursor(t, [
      { at: 0, x: 538, y: 392, hidden: true },
      { at: 3900, x: 538, y: 392 },
      { at: 4150, x: 447, y: 322 },
      { at: 7800, x: 538, y: 392, hidden: true },
    ], [4900]);

    const badge = done ? (
      <span className="inline-flex items-center gap-1 h-5 px-2 rounded-full bg-emerald-50 border border-emerald-200 text-emerald-700 text-[10.5px] font-medium demo-rise">
        <L name="check" className="w-3 h-3" />{s.badgeCertified}
      </span>
    ) : sending ? (
      <span className="inline-flex items-center gap-1 h-5 px-2 rounded-full bg-amber-50 border border-amber-200 text-amber-700 text-[10.5px] font-medium demo-rise">
        {s.badgeSending}
      </span>
    ) : (
      <span className="inline-flex items-center h-5 px-2 rounded-full bg-zinc-100 border border-zinc-200 text-zinc-500 text-[10.5px] font-medium">
        {s.badgeDraft}
      </span>
    );

    return (
      <DemoStage t={t} dur={D}>
        <MiniWindow title={s.windowTitle} icon="file-text" width={480} right={badge}>
          <div className="p-4">
            <div className="text-[10.5px] uppercase tracking-widest text-zinc-400 font-medium mb-1.5">{s.clientLabel}</div>
            <div className="flex items-center gap-2 mb-3">
              <div className="flex-1 h-9 px-3 rounded-md border border-zinc-200 bg-white shadow-sm flex items-center text-[13px] text-zinc-900">
                {client}
                <DemoCaret show={typing} />
              </div>
              <div
                className="inline-flex items-center gap-1.5 h-9 px-2.5 rounded-md border border-emerald-200 bg-emerald-50 text-[11.5px] font-mono text-emerald-700 whitespace-nowrap"
                style={{ opacity: nif ? 1 : 0, transform: nif ? 'none' : 'translateY(6px)', transition: 'all .45s cubic-bezier(.2,.8,.2,1)' }}
              >
                <L name="badge-check" className="w-3.5 h-3.5" />
                NIF 501 234 567
              </div>
            </div>

            <div className="rounded-md border border-zinc-200 overflow-hidden">
              <div className="grid grid-cols-[64px_1fr_60px_84px] px-3 h-7 items-center bg-zinc-50 border-b border-zinc-100 text-[10.5px] uppercase tracking-wider text-zinc-400 font-medium">
                <span>{s.colSku}</span><span>{s.colDesc}</span><span className="text-right">{s.colQty}</span><span className="text-right">{s.colTotal}</span>
              </div>
              {s.rows.map((r, i) => (
                <div key={r.sku}
                  className="grid grid-cols-[64px_1fr_60px_84px] px-3 h-9 items-center border-b border-zinc-100 text-[12px]"
                  style={{ opacity: rowOn[i] ? 1 : 0, transform: rowOn[i] ? 'none' : 'translateY(6px)', transition: 'all .45s cubic-bezier(.2,.8,.2,1)' }}
                >
                  <span className="font-mono text-[11px] text-zinc-400">{r.sku}</span>
                  <span className="text-zinc-900 truncate pr-2">{r.name}</span>
                  <span className="text-right text-zinc-500">{r.qty}</span>
                  <span className="text-right font-mono text-zinc-900">{r.total}</span>
                </div>
              ))}
              <div className="flex justify-between px-3 h-9 items-center bg-zinc-50 text-[12px]">
                <span className="text-zinc-500">{s.totalVat}</span>
                <span className="font-mono font-semibold text-zinc-900 tabular-nums">{dkEUR(total)}</span>
              </div>
            </div>

            <div className="mt-3.5 flex items-center justify-between">
              <span className="text-[11px] text-zinc-400 font-mono">{s.series}</span>
              <button
                className="inline-flex items-center gap-2 h-9 px-4 rounded-md text-white text-[12.5px] font-medium whitespace-nowrap"
                style={{ background: done ? '#059669' : '#18181B', transition: 'background .4s' }}
              >
                {sending ? (
                  <span className="inline-flex items-center gap-2"><L name="loader-2" className="w-3.5 h-3.5 animate-spin" />{s.btnSending}</span>
                ) : done ? (
                  <span className="inline-flex items-center gap-2"><L name="check" className="w-3.5 h-3.5" />{s.btnDone}</span>
                ) : (
                  <span className="inline-flex items-center gap-2"><L name="shield-check" className="w-3.5 h-3.5" />{s.btnIdle}</span>
                )}
              </button>
            </div>
          </div>

          {done && (
            <div className="demo-stamp absolute z-20 bg-white border-2 border-emerald-500 rounded-lg p-2.5 flex items-center gap-2.5"
              style={{ right: 22, top: 96, boxShadow: '0 10px 26px -10px rgba(5,150,105,.4)' }}>
              <FakeQR size={48} />
              <div>
                <div className="text-[9.5px] uppercase tracking-widest text-emerald-600 font-semibold">AT · e-fatura</div>
                <div className="font-mono text-[11px] text-zinc-900 mt-0.5">ATCUD JFF4-0042</div>
                <div className="font-mono text-[10px] text-zinc-400">FT 2026/0042</div>
              </div>
            </div>
          )}
        </MiniWindow>

        <DemoCursor s={cur} />
        <DemoToast show={toast} text={s.toast} />
      </DemoStage>
    );
  }

  window.DemoFatura = DemoFatura;
})();
