// hero-viz.jsx — V2: Light, fresh white+blue. Invoices arrive on the left,
// AI-extracted + coded, then materialise as rows in the auto-generated
// Skeda tal-Ħlasijiet table on the right.

const HERO_INVOICES = [
  { supplier: 'Stamperija Borg & Sons',  ref: 'INV-2026/0421', desc: 'Council newsletter — April print run', amount: 1840.00, vat: 331.20, mreq: 'Inv', pm: 'DA' },
  { supplier: 'Vella Electrical Ltd',    ref: 'INV-26-0118',   desc: 'Streetlight repairs, Triq il-Kbira',     amount: 3265.50, vat: 587.79, mreq: 'Inv', pm: 'T'  },
  { supplier: 'SkyClean Services',       ref: 'REC/4429',      desc: 'Monthly office cleaning',                amount:  620.00, vat: 111.60, mreq: 'Rec', pm: 'D'  },
  { supplier: 'MaltaPost plc',           ref: 'REC-26-7811',   desc: 'Postage, March statement',               amount:  148.20, vat:  26.68, mreq: 'P',   pm: 'DA' },
  { supplier: 'Calleja Hardware',        ref: 'INV-26-0089',   desc: 'Garden maintenance materials',           amount: 2410.75, vat: 433.94, mreq: 'Inv', pm: 'D'  },
  { supplier: 'Trans Marine Repairs',    ref: 'RFP-2026-12',   desc: 'Slipway works, Tigné foreshore',         amount: 5890.00, vat:1060.20, mreq: 'RFP', pm: 'T'  },
];

const fmt = (n) => n.toLocaleString('en-MT', { minimumFractionDigits: 2, maximumFractionDigits: 2 });

function HeroViz() {
  const N = HERO_INVOICES.length;
  const TOTAL_STEPS = 2 + N * 2 + 4;
  // Print mode: start at the "all done + export pulse" beat and disable the interval.
  const isPrint = typeof window !== 'undefined' && window.__IS_PRINT;
  const [step, setStep] = React.useState(isPrint ? (2 + N * 2 + 1) : 0);
  const [paused, setPaused] = React.useState(false);

  React.useEffect(() => {
    if (paused || isPrint) return;
    const t = setInterval(() => setStep(s => (s + 1) % TOTAL_STEPS), 900);
    return () => clearInterval(t);
  }, [paused, TOTAL_STEPS, isPrint]);

  const a = (s) => { let c = 0; for (let i = 0; i < N; i++) if (s >= 2 + i*2) c++; return c; };
  const p = (s) => { let c = 0; for (let i = 0; i < N; i++) if (s >= 3 + i*2) c++; return c; };
  const arrivedN   = a(step);
  const processedN = p(step);

  const allDone = processedN === N;
  const exportPulse = allDone && step >= 2 + N*2;

  const total = HERO_INVOICES.slice(0, processedN).reduce((s, i) => s + i.amount + i.vat, 0);

  return (
    <div className="heroviz" onMouseEnter={() => setPaused(true)} onMouseLeave={() => setPaused(false)}>
      <div className="chrome">
        <div className="dot" /><div className="dot" /><div className="dot" />
        <div style={{display:'flex', alignItems:'center', gap:8, marginLeft:14, fontSize:12, color:'var(--ink-3)'}}>
          <IconLogo size={14} color="var(--ink-3)" />
          <span>auto-council.mt</span>
          <span style={{color:'var(--ink-4)'}}>/finance/april-2026</span>
        </div>
        <div style={{marginLeft:'auto', display:'flex', alignItems:'center', gap:10, fontSize:11.5, color:'var(--ink-3)'}}>
          <span style={{display:'inline-flex', alignItems:'center', gap:6}}>
            <span style={{width:6, height:6, borderRadius:'50%', background:'var(--green)', boxShadow:'0 0 0 3px var(--green-tint)'}} />
            Live
          </span>
        </div>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'minmax(280px, 340px) 1fr', minHeight: 460}}>
        {/* Left: upload tray */}
        <div style={{padding:'18px 18px 18px 20px', borderRight:'1px solid var(--hairline)', background:'var(--bg-tint)'}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14}}>
            <div style={{fontSize:11, fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--ink-3)'}}>Uploads</div>
            <div style={{fontSize:11, color:'var(--accent-2)', fontWeight:500, display:'inline-flex', alignItems:'center', gap:5}}>
              <IconSparkle size={11}/> AI extraction
            </div>
          </div>

          <div style={{display:'flex', flexDirection:'column', gap:10}}>
            {HERO_INVOICES.map((inv, i) => {
              const isArrived = i < arrivedN;
              const isProcessed = i < processedN;
              return (
                <div key={i} className="inv-card" style={{
                  opacity: isArrived ? 1 : 0,
                  transform: isArrived ? 'translateY(0)' : 'translateY(-8px)',
                  transition: 'opacity 400ms ease, transform 400ms ease',
                  borderColor: isProcessed ? 'var(--hairline)' : 'var(--accent)',
                  boxShadow: !isProcessed && isArrived ? '0 0 0 3px var(--accent-tint)' : '0 1px 2px rgba(14,26,51,0.04)'
                }}>
                  <div style={{display:'flex', justifyContent:'space-between', alignItems:'baseline', gap:8}}>
                    <div style={{fontWeight:600, fontSize:12.5, color:'var(--ink)'}}>{inv.supplier}</div>
                    <div style={{fontSize:12, color:'var(--ink-2)', fontVariantNumeric:'tabular-nums'}}>€{fmt(inv.amount)}</div>
                  </div>
                  <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:5, fontSize:11, color:'var(--ink-3)'}}>
                    <span className="mono" style={{fontSize:10.5}}>{inv.ref}</span>
                    {isProcessed ? (
                      <span style={{display:'inline-flex', alignItems:'center', gap:4, color:'var(--green)', fontSize:10.5}}>
                        <IconCheck size={11} stroke={2} /> coded
                      </span>
                    ) : (
                      <span style={{display:'inline-flex', alignItems:'center', gap:4, color:'var(--accent-2)', fontSize:10.5}}>
                        <span style={{
                          width:6, height:6, borderRadius:'50%', background:'var(--accent)',
                          animation:'pulse 1.2s ease-in-out infinite'
                        }} />
                        extracting…
                      </span>
                    )}
                  </div>
                </div>
              );
            })}
          </div>

          {/* AI label */}
          <div style={{
            marginTop: 16, padding:'10px 12px',
            background:'#fff', border:'1px solid var(--hairline)', borderRadius: 10,
            fontSize: 11.5, color:'var(--ink-3)', display:'flex', alignItems:'center', gap:8
          }}>
            <IconSparkle size={14} color="var(--accent)" />
            <span>AI extracts amount, VAT, supplier, due date</span>
          </div>
        </div>

        {/* Right: Skeda */}
        <div style={{padding:'18px 22px 18px 22px', background:'#fff'}}>
          <div style={{display:'flex', justifyContent:'space-between', alignItems:'flex-start', marginBottom:14}}>
            <div>
              <div style={{fontSize:11, fontWeight:600, letterSpacing:'0.06em', textTransform:'uppercase', color:'var(--ink-3)'}}>Schedule of Payments</div>
              <div className="display" style={{fontSize:18, fontWeight:500, marginTop:2}}>Skeda tal-Ħlasijiet · April 2026</div>
              <div style={{fontSize:11.5, color:'var(--ink-4)', marginTop:2}}>DLG format · auto-generated</div>
            </div>
            <button className="btn btn-primary" style={{
              fontSize: 12.5, padding: '8px 12px',
              transform: exportPulse ? 'scale(1.02)' : 'scale(1)',
              boxShadow: exportPulse
                ? '0 0 0 4px var(--accent-tint), 0 1px 0 rgba(255,255,255,0.18) inset, 0 6px 20px -8px rgba(59,110,255,0.55)'
                : '0 1px 0 rgba(255,255,255,0.18) inset, 0 6px 20px -8px rgba(59,110,255,0.55)',
              transition: 'transform 240ms ease, box-shadow 240ms ease'
            }}>
              <IconArrowUpRight size={14} /> Export Skeda
            </button>
          </div>

          <div style={{border:'1px solid var(--hairline)', borderRadius: 10, overflow:'hidden'}}>
            <table className="skeda">
              <thead>
                <tr>
                  <th style={{width: 36}}>#</th>
                  <th>Supplier</th>
                  <th style={{width:74}}>M·Req</th>
                  <th style={{width:64}}>P·M</th>
                  <th className="right" style={{width:90}}>Net</th>
                  <th className="right" style={{width:78}}>VAT</th>
                  <th className="right" style={{width:96}}>Total</th>
                </tr>
              </thead>
              <tbody>
                {Array.from({length: Math.max(processedN, 0)}).map((_, i) => {
                  const inv = HERO_INVOICES[i];
                  const isNewest = i === processedN - 1;
                  return (
                    <tr key={i} className={isNewest ? 'row-appear' : ''}>
                      <td className="mono" style={{color:'var(--ink-4)'}}>{String(i+1).padStart(2,'0')}</td>
                      <td>
                        <div style={{fontWeight:500}}>{inv.supplier}</div>
                        <div style={{fontSize:10.5, color:'var(--ink-4)', marginTop:1}}>{inv.desc}</div>
                      </td>
                      <td><span className="tag">{inv.mreq}</span></td>
                      <td><span className="tag soft">{inv.pm}</span></td>
                      <td className="right">{fmt(inv.amount)}</td>
                      <td className="right text-ink3">{fmt(inv.vat)}</td>
                      <td className="right" style={{fontWeight:600}}>{fmt(inv.amount + inv.vat)}</td>
                    </tr>
                  );
                })}
                {Array.from({length: Math.max(0, N - processedN)}).map((_, i) => (
                  <tr key={`empty-${i}`}>
                    <td className="mono" style={{color:'var(--ink-5)'}}>{String(processedN + i + 1).padStart(2,'0')}</td>
                    <td colSpan={6}><div style={{height: 14, background:'var(--surface-2)', borderRadius: 3, opacity: 0.5}} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>

          <div style={{display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:14}}>
            <div style={{display:'flex', gap:18, fontSize:11.5, color:'var(--ink-3)', flexWrap:'wrap'}}>
              <span><span className="mono" style={{color:'var(--ink-4)'}}>P</span> · Payable</span>
              <span><span className="mono" style={{color:'var(--ink-4)'}}>Inv</span> · Invoice</span>
              <span><span className="mono" style={{color:'var(--ink-4)'}}>Rec</span> · Recurring</span>
              <span><span className="mono" style={{color:'var(--ink-4)'}}>DA</span> · Direct Award</span>
              <span><span className="mono" style={{color:'var(--ink-4)'}}>T</span> · Tender</span>
            </div>
            <div style={{display:'flex', alignItems:'baseline', gap:8}}>
              <span style={{fontSize:11.5, color:'var(--ink-3)'}}>Total</span>
              <span className="tnum" style={{fontFamily:'var(--serif)', fontSize:22, fontWeight:500, color:'var(--ink)'}}>€{fmt(total)}</span>
            </div>
          </div>
        </div>
      </div>

      <style>{`
        @keyframes pulse {
          0%, 100% { opacity: 1; transform: scale(1); }
          50%      { opacity: 0.4; transform: scale(0.85); }
        }
      `}</style>
    </div>
  );
}

Object.assign(window, { HeroViz, HERO_INVOICES, fmtMoney: fmt });
