// QBClone — P&L card widget (the live accounting visual for hero)
const PnLWidget = () => {
  const [rev, setRev] = React.useState(284620);
  const [exp, setExp] = React.useState(178410);
  const [pulse, setPulse] = React.useState(false);
  const net = rev - exp;
  const margin = ((net / rev) * 100).toFixed(1);

  // micro-animate the numbers (subtle drift to feel "live")
  React.useEffect(() => {
    const id = setInterval(() => {
      setRev(r => r + Math.floor(Math.random() * 380 + 60));
      setExp(e => e + Math.floor(Math.random() * 220 + 30));
      setPulse(true);
      setTimeout(() => setPulse(false), 320);
    }, 3200);
    return () => clearInterval(id);
  }, []);

  const fmt = (n) => '$' + n.toLocaleString('en-US');

  // 12 months of fake series
  const revSeries = [62, 70, 78, 74, 86, 92, 105, 112, 124, 138, 156, 172];
  const expSeries = [48, 52, 56, 58, 62, 64, 70, 74, 80, 88, 96, 104];
  const w = 460, h = 110, pad = 6;
  const max = 180;
  const stepX = (w - pad * 2) / (revSeries.length - 1);
  const path = (arr) => arr.map((v, i) => {
    const x = pad + i * stepX;
    const y = h - pad - (v / max) * (h - pad * 2);
    return (i === 0 ? 'M' : 'L') + x.toFixed(1) + ',' + y.toFixed(1);
  }).join(' ');
  const area = (arr) => {
    const top = path(arr);
    const last = pad + (arr.length - 1) * stepX;
    return top + ` L${last.toFixed(1)},${h - pad} L${pad},${h - pad} Z`;
  };

  return (
    <div className="pnl-card" aria-label="Live profit and loss card">
      <div className="pnl-head">
        <div className="pnl-co">
          <span className="pnl-co-mark">M</span>
          <div>
            <div className="pnl-co-name">Maple &amp; Co. Bakery</div>
            <div className="pnl-co-sub">co_4a82 · oct 2026 · usd</div>
          </div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div className="pnl-tag pnl-live"><span className="d"></span>LIVE</div>
          <div className="pnl-co-sub" style={{ marginTop: 4 }}>auto-sync · 14s ago</div>
        </div>
      </div>

      <div className="pnl-kpis">
        <div className="pnl-kpi">
          <div className="pnl-kpi-lbl">Revenue</div>
          <div className="pnl-kpi-val" style={{ transition: 'opacity 240ms', opacity: pulse ? 0.65 : 1 }}>
            <span className="num">{fmt(rev)}</span>
          </div>
          <div className="pnl-kpi-delta up">▲ 14.2% MoM</div>
        </div>
        <div className="pnl-kpi">
          <div className="pnl-kpi-lbl">Expenses</div>
          <div className="pnl-kpi-val" style={{ transition: 'opacity 240ms', opacity: pulse ? 0.65 : 1 }}>
            <span className="num">{fmt(exp)}</span>
          </div>
          <div className="pnl-kpi-delta up" style={{ color: 'var(--ink-60)' }}>▲ 4.6% MoM</div>
        </div>
        <div className="pnl-kpi">
          <div className="pnl-kpi-lbl">Net profit</div>
          <div className="pnl-kpi-val" style={{ transition: 'opacity 240ms', opacity: pulse ? 0.65 : 1 }}>
            <span className="num">{fmt(net)}</span>
          </div>
          <div className="pnl-kpi-delta up">▲ {margin}% margin</div>
        </div>
      </div>

      <div className="pnl-chart">
        <div className="pnl-chart-head">
          <div className="pnl-chart-h">P&amp;L · last 12 months <em>· trending up</em></div>
          <div className="pnl-chart-legend">
            <span className="li"><span className="sw" style={{ background: 'var(--qb-accent)' }}></span>Revenue</span>
            <span className="li"><span className="sw" style={{ background: 'var(--ink-40)' }}></span>Expenses</span>
          </div>
        </div>
        <svg className="pnl-chart-svg" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none">
          <defs>
            <linearGradient id="revGrad" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%"  stopColor="var(--qb-accent)" stopOpacity="0.20" />
              <stop offset="100%" stopColor="var(--qb-accent)" stopOpacity="0" />
            </linearGradient>
          </defs>
          {/* horizontal grid */}
          {[0.25, 0.5, 0.75].map((g, i) => (
            <line key={i} x1={pad} x2={w - pad} y1={h * g} y2={h * g} stroke="var(--qb-line)" strokeDasharray="2 4" />
          ))}
          <path d={area(revSeries)} fill="url(#revGrad)" />
          <path d={path(revSeries)} stroke="var(--qb-accent)" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round" />
          <path d={path(expSeries)} stroke="var(--ink-40)" strokeWidth="1.4" fill="none" strokeDasharray="3 3" strokeLinecap="round" />
          {revSeries.map((v, i) => {
            const x = pad + i * stepX;
            const y = h - pad - (v / max) * (h - pad * 2);
            if (i !== revSeries.length - 1) return null;
            return <circle key={i} cx={x} cy={y} r="3.2" fill="var(--qb-accent)" stroke="#fff" strokeWidth="1.5" />;
          })}
        </svg>
      </div>

      <div className="pnl-rows">
        <div className="pnl-row">
          <span className="ic in">+</span>
          <span className="nm">Invoice #1248 paid <span className="sub">Saltgrain Café · net-15</span></span>
          <span className="amt pos">+$4,820.00</span>
          <span className="st">cleared</span>
        </div>
        <div className="pnl-row">
          <span className="ic out">−</span>
          <span className="nm">Mill flour supply <span className="sub">Bay Mills LLC · weekly · auto</span></span>
          <span className="amt neg">−$1,265.40</span>
          <span className="st">scheduled</span>
        </div>
        <div className="pnl-row">
          <span className="ic in">+</span>
          <span className="nm">Stripe payout <span className="sub">batch 4a82 · 28 transactions</span></span>
          <span className="amt pos">+$2,144.12</span>
          <span className="st">cleared</span>
        </div>
      </div>

      <div className="pnl-footer">
        <span className="qb-mono">co_4a82 · books closed Oct 31 · 3 of 12 companies</span>
        <span className="ai-chip"><span className="star">✦</span> Ask AI about this month</span>
      </div>
    </div>
  );
};

Object.assign(window, { PnLWidget });
