// view-payroll-push.jsx — Live payroll-push modal. Drives RFPpayroll.push and
// renders the real lifecycle (auth → submit → poll → receipt) as a timeline.

function PayrollPushModal({ open, providerId, onClose }) {
  const { timecards, employees, jobs, taxPolicy, ytdGross, toast } = useAdmin();
  const [events, setEvents] = useState([]);
  const [running, setRunning] = useState(false);
  const [receipt, setReceipt] = useState(null);
  const prov = providerId && RFPpayroll.PROVIDERS[providerId];

  // Build the employee push rows from approved/ready cards
  const rows = useMemo(() => {
    const byEmp = {};
    timecards.filter(t => t.status === 'approved' || t.status === 'pending-acct').forEach(t => {
      const e = employees.find(x => x.id === t.employeeId); if (!e) return;
      if (!byEmp[e.id]) {
        const blocks = timecards.filter(x => x.employeeId === e.id).flatMap(x => x.blocks);
        const alloc = (typeof allocateWages === 'function') ? allocateWages(e, blocks, taxPolicy) : [];
        const rr = (typeof computeRRTA === 'function') ? computeRRTA(e, ytdGross[e.id] || 0, 0, {}) : null;
        byEmp[e.id] = {
          name: e.name, badge: e.badge, resident: e.resident, rate: e.baseRate,
          reg: 0, ot: 0, gross: 0,
          alloc: alloc.map(a => ({ state: a.state, wages: +a.wage.toFixed(2), tax: +a.taxAmt.toFixed(2) })),
          rrb: e.rrbContributor ? { enrolled: true, tier1: true, tier2: true } : { enrolled: false },
        };
      }
      byEmp[e.id].reg += t.regular;
      byEmp[e.id].ot += t.overtime;
      byEmp[e.id].gross += t.regular * e.baseRate + t.overtime * e.baseRate * 1.5;
    });
    return Object.values(byEmp);
  }, [timecards, employees, taxPolicy, ytdGross]);

  useEffect(() => { if (open) { setEvents([]); setReceipt(null); setRunning(false); } }, [open, providerId]);
  if (!open || !prov) return null;

  const totalGross = rows.reduce((s, r) => s + r.gross, 0);

  const run = async () => {
    setRunning(true); setEvents([]); setReceipt(null);
    await RFPpayroll.push(
      { providerId, period: '2026-05-18 — 2026-05-31', payDate: '2026-06-05', employees: rows },
      (ev) => {
        setEvents(prev => {
          // collapse repeated phase 'active' into the latest line per phase tail
          return [...prev, { ...ev, t: Date.now(), id: prev.length }];
        });
        if (ev.phase === 'done' && ev.data && ev.data.receipt) setReceipt(ev.data.receipt);
      }
    );
    setRunning(false);
    toast(`Pay run pushed to ${prov.name}`, 'success');
  };

  const phaseMeta = {
    connect: 'Connect', auth: 'Authenticate', submit: 'Submit batch', poll: 'Provider processing', done: 'Confirmed', error: 'Error',
  };

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 500, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, background: 'rgba(15,23,42,0.55)' }}>
      <div className="anim-up" style={{ width: 720, maxHeight: '90%', background: 'var(--paper)', borderRadius: 16, boxShadow: 'var(--shadow-lg)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        {/* Header */}
        <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 14, background: '#0F172A', color: '#fff' }}>
          <div style={{ width: 44, height: 44, borderRadius: 10, background: 'rgba(255,255,255,0.1)', display: 'grid', placeItems: 'center' }}><IconPlug size={22} /></div>
          <div style={{ flex: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 17 }}>Push pay run → {prov.name}</div>
            <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.6)' }}>
              {prov.sandbox ? 'Sandbox environment' : 'Production'} · {prov.auth === 'oauth2' ? 'OAuth 2.0' : 'API key'} · {prov.base}
            </div>
          </div>
          <button onClick={onClose} style={{ width: 32, height: 32, borderRadius: 16, border: 'none', background: 'rgba(255,255,255,0.1)', color: '#fff', cursor: 'pointer' }}>✕</button>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: 24 }}>
          {/* Batch summary */}
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 20 }}>
            <SummaryStat label="Employees" value={rows.length} />
            <SummaryStat label="Gross" value={A_fmtCurrency(totalGross)} />
            <SummaryStat label="Pay date" value="Jun 5, 2026" />
          </div>

          {/* Lifecycle timeline */}
          {events.length === 0 && !running && (
            <div style={{ background: 'var(--panel)', border: '1px dashed var(--line-strong)', borderRadius: 12, padding: 24, textAlign: 'center', color: 'var(--muted)' }}>
              <div style={{ fontSize: 13.5, lineHeight: 1.6 }}>
                This runs the full provider handshake: <b>OAuth token exchange → batch submit → status polling → confirmation receipt</b>.<br />
                Sandbox mode — no real wages move.
              </div>
            </div>
          )}

          {events.length > 0 && (
            <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden' }}>
              {events.map((ev, i) => (
                <div key={ev.id} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, padding: '11px 16px', borderTop: i === 0 ? 'none' : '1px solid var(--line)' }}>
                  <div style={{ marginTop: 2 }}>
                    {ev.status === 'done' ? <span style={{ color: 'var(--good)' }}><IconCheckCircle size={16} /></span>
                      : ev.status === 'error' ? <span style={{ color: 'var(--bad)' }}><IconAlert size={16} /></span>
                      : <span style={{ display: 'inline-block', width: 14, height: 14, borderRadius: 7, border: '2px solid var(--accent)', borderTopColor: 'transparent', animation: 'spin 0.7s linear infinite' }} />}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600 }}>{phaseMeta[ev.phase] || ev.phase}</div>
                    <div className="mono" style={{ fontSize: 11.5, color: 'var(--muted)', wordBreak: 'break-all' }}>{ev.detail}</div>
                  </div>
                  <span className="mono" style={{ fontSize: 10.5, color: 'var(--muted-2)' }}>{new Date(ev.t).toLocaleTimeString('en-US', { hour12: false })}</span>
                </div>
              ))}
            </div>
          )}

          {/* Receipt */}
          {receipt && (
            <div style={{ marginTop: 16, background: 'var(--good-soft)', border: '1px solid var(--good)', borderRadius: 12, padding: '16px 18px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                <IconCheckCircle size={18} style={{ color: 'var(--good)' }} />
                <div style={{ fontWeight: 700, fontSize: 14.5, color: 'var(--good)' }}>Accepted by {receipt.provider}</div>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                <ReceiptRow label="Confirmation" value={receipt.confirmation} />
                <ReceiptRow label="Batch ID" value={receipt.batchId} />
                <ReceiptRow label="Employees" value={receipt.employees} />
                <ReceiptRow label="Gross" value={A_fmtCurrency(receipt.gross)} />
              </div>
            </div>
          )}
        </div>

        {/* Footer */}
        <div style={{ padding: '14px 24px', borderTop: '1px solid var(--line)', background: 'var(--panel)', display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
          <Button variant="secondary" onClick={onClose}>{receipt ? 'Close' : 'Cancel'}</Button>
          {!receipt && <Button variant="primary" icon={<IconUpload size={14} />} disabled={running || rows.length === 0} onClick={run}>{running ? 'Pushing…' : `Push ${rows.length} employees`}</Button>}
          {receipt && <Button variant="primary" icon={<IconDownload size={14} />} onClick={() => { downloadBlob(`payrun-receipt-${receipt.confirmation}.txt`, `RailFlagsPro Payroll Push Receipt\nProvider: ${receipt.provider}\nConfirmation: ${receipt.confirmation}\nBatch: ${receipt.batchId}\nEmployees: ${receipt.employees}\nGross: ${A_fmtCurrency(receipt.gross)}\nAccepted: ${receipt.acceptedAt}\n`, 'text/plain'); }}>Download receipt</Button>}
        </div>
      </div>
    </div>
  );
}

function SummaryStat({ label, value }) {
  return (
    <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 10, padding: '12px 14px' }}>
      <div className="eyebrow" style={{ fontSize: 10 }}>{label}</div>
      <div className="mono" style={{ fontSize: 18, fontWeight: 700, marginTop: 3 }}>{value}</div>
    </div>
  );
}
function ReceiptRow({ label, value }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', gap: 8 }}>
      <span style={{ fontSize: 12, color: 'var(--text-2)' }}>{label}</span>
      <span className="mono" style={{ fontSize: 12, fontWeight: 700 }}>{value}</span>
    </div>
  );
}

Object.assign(window, { PayrollPushModal });
