// view-payroll-run.jsx — Guided payroll run wizard.
// Step 1 Earnings (approved hours) → Step 2 Taxes & RRB preview →
// Step 3 Choose target + confirm → Success. Overlays the whole console.

function PayrollRunWizard() {
  const { payrollWizard, setPayrollWizard, timecards, employees, taxPolicy, ytdGross, toast, launchDoc } = useAdmin();
  const [step, setStep] = useState(1);
  const [target, setTarget] = useState('ADP RUN');
  const [done, setDone] = useState(false);

  useEffect(() => { if (payrollWizard) { setStep(1); setDone(false); } }, [payrollWizard]);
  if (!payrollWizard) return null;

  // Only approved cards are payable
  const payable = timecards.filter(t => t.status === 'approved');
  const byEmp = {};
  for (const t of payable) {
    byEmp[t.employeeId] = byEmp[t.employeeId] || { reg: 0, ot: 0, hrs: 0 };
    byEmp[t.employeeId].reg += t.regular;
    byEmp[t.employeeId].ot += t.overtime;
    byEmp[t.employeeId].hrs += t.total;
  }
  const empRows = Object.entries(byEmp).map(([id, v]) => {
    const e = employees.find(x => x.id === id);
    const gross = v.reg * e.baseRate + v.ot * e.baseRate * 1.5;
    return { e, ...v, gross };
  });
  const totalGross = empRows.reduce((s, r) => s + r.gross, 0);
  const totalHrs = empRows.reduce((s, r) => s + r.hrs, 0);
  const totalOT = empRows.reduce((s, r) => s + r.ot, 0);

  // Tax + RRB rollups (reuse engines)
  let stateTax = 0, eeRRTA = 0, erRRTA = 0;
  for (const r of empRows) {
    const blocks = payable.filter(t => t.employeeId === r.e.id).flatMap(t => t.blocks);
    allocateWages(r.e, blocks, taxPolicy).forEach(b => stateTax += b.taxAmt);
    const calc = computeRRTA(r.e, ytdGross[r.e.id] || 0, r.gross, {});
    eeRRTA += calc.lines.reduce((s, l) => s + l.amount, 0);
    erRRTA += calc.employer.reduce((s, l) => s + l.amount, 0);
  }
  const netEstimate = totalGross - stateTax - eeRRTA;
  const employerBurden = totalGross + erRRTA;

  const TARGETS = ['ADP RUN', 'ADP Workforce Now', 'Paychex Flex', 'Gusto', 'QuickBooks', 'Paylocity', 'CSV / IIF'];

  const steps = [
    { n: 1, label: 'Earnings' },
    { n: 2, label: 'Taxes & RRB' },
    { n: 3, label: 'Confirm & push' },
  ];

  const runPush = () => {
    setDone(true);
    toast(`Payroll pushed to ${target} · ${empRows.length} employees`, 'success', 4000);
  };

  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 500, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div onClick={() => setPayrollWizard(false)} style={{ position: 'absolute', inset: 0, background: 'rgba(15,23,42,0.55)' }} />
      <div style={{
        position: 'relative',
        width: 880, maxHeight: '88%', background: 'var(--paper)', borderRadius: 16,
        boxShadow: 'var(--shadow-lg)', display: 'flex', flexDirection: 'column', overflow: 'hidden',
      }}>
        {/* Header + stepper */}
        <div style={{ padding: '18px 24px', borderBottom: '1px solid var(--line)', background: 'var(--panel)' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
            <div>
              <div className="eyebrow">PAYROLL RUN · PERIOD 05-18 → 05-31</div>
              <div style={{ fontSize: 19, fontWeight: 700, letterSpacing: -0.3 }}>Run payroll</div>
            </div>
            <button onClick={() => setPayrollWizard(false)} style={{ width: 32, height: 32, borderRadius: 16, border: 'none', background: 'var(--panel-3)', display: 'grid', placeItems: 'center' }}><IconClose size={16} /></button>
          </div>
          {!done && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 0 }}>
              {steps.map((s, i) => (
                <React.Fragment key={s.n}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{
                      width: 26, height: 26, borderRadius: 13,
                      background: step >= s.n ? 'var(--accent)' : 'var(--panel-3)',
                      color: step >= s.n ? '#fff' : 'var(--muted)',
                      display: 'grid', placeItems: 'center', fontSize: 13, fontWeight: 700,
                    }}>{step > s.n ? '✓' : s.n}</span>
                    <span style={{ fontSize: 13, fontWeight: step === s.n ? 700 : 500, color: step >= s.n ? 'var(--text)' : 'var(--muted)' }}>{s.label}</span>
                  </div>
                  {i < steps.length - 1 && <div style={{ flex: 1, height: 2, background: step > s.n ? 'var(--accent)' : 'var(--line)', margin: '0 12px' }} />}
                </React.Fragment>
              ))}
            </div>
          )}
        </div>

        {/* Body */}
        <div style={{ flex: 1, overflowY: 'auto', padding: '20px 24px' }}>
          {done ? (
            <div style={{ textAlign: 'center', padding: '30px 20px' }}>
              <div style={{ width: 64, height: 64, borderRadius: 32, background: 'var(--good-soft)', color: 'var(--good)', display: 'grid', placeItems: 'center', margin: '0 auto 16px' }}>
                <IconCheckCircle size={36} />
              </div>
              <div style={{ fontSize: 22, fontWeight: 700 }}>Payroll pushed to {target}</div>
              <div style={{ fontSize: 14, color: 'var(--muted)', marginTop: 6, maxWidth: 460, margin: '6px auto 0', lineHeight: 1.5 }}>
                {empRows.length} employees · {A_fmtCurrency(totalGross)} gross · pay date 2026-05-22.
                Multi-state withholding and RRTA/FICA splits transmitted. A confirmation will post to the audit log.
              </div>
              <div style={{ display: 'flex', gap: 10, justifyContent: 'center', marginTop: 22 }}>
                <Button variant="secondary" icon={<IconDownload size={14} />} onClick={() => {
                  const rows = empRows.map(r => ({ name: r.e.name, badge: r.e.badge, resident: r.e.resident, reg: r.reg, ot: r.ot, gross: r.gross, payDate: '2026-06-05', job: '' }));
                  const c = buildPayrollCSV(rows, '2026-05-18 — 2026-05-31');
                  if (typeof downloadBlob === 'function') downloadBlob('pay-register.csv', c, 'text/csv');
                  toast('Pay register CSV downloaded', 'success');
                }}>Pay register</Button>
                <Button variant="primary" onClick={() => setPayrollWizard(false)}>Done</Button>
              </div>
            </div>
          ) : step === 1 ? (
            <>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12, marginBottom: 18 }}>
                <KPI label="Approved employees" value={empRows.length} icon={<IconUsersBig size={16} />} />
                <KPI label="Total hours" value={A_fmtNum(totalHrs, 1)} sub={`${A_fmtNum(totalOT,1)} OT`} icon={<IconClock size={16} />} />
                <KPI label="Gross" value={A_fmtCurrency(totalGross)} tone="accent" icon={<IconDollar size={16} />} />
              </div>
              {empRows.length === 0 ? (
                <div style={{ padding: 30, textAlign: 'center', color: 'var(--muted-2)', background: 'var(--panel)', border: '1px dashed var(--line-strong)', borderRadius: 12 }}>
                  No approved timecards yet. Approve cards through the two-step workflow first.
                </div>
              ) : (
                <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden' }}>
                  <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr', gap: 10, padding: '10px 16px', background: 'var(--panel-2)', borderBottom: '1px solid var(--line)', fontSize: 10.5, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase', color: 'var(--muted)' }}>
                    <span>Employee</span><span style={{ textAlign: 'right' }}>Reg</span><span style={{ textAlign: 'right' }}>OT</span><span style={{ textAlign: 'right' }}>Rate</span><span style={{ textAlign: 'right' }}>Gross</span>
                  </div>
                  {empRows.map((r, i) => (
                    <div key={r.e.id} style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr', gap: 10, padding: '11px 16px', borderTop: i === 0 ? 'none' : '1px solid var(--line)', alignItems: 'center' }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <div style={{ width: 26, height: 26, borderRadius: 13, background: 'var(--panel-3)', display: 'grid', placeItems: 'center', fontSize: 10.5, fontWeight: 700 }}>{r.e.avatar}</div>
                        <span style={{ fontSize: 13, fontWeight: 600 }}>{r.e.name}</span>
                      </div>
                      <span className="mono" style={{ textAlign: 'right', fontSize: 12.5 }}>{r.reg.toFixed(1)}</span>
                      <span className="mono" style={{ textAlign: 'right', fontSize: 12.5, color: r.ot > 0 ? 'var(--warn)' : 'var(--muted-2)' }}>{r.ot > 0 ? r.ot.toFixed(1) : '—'}</span>
                      <span className="mono" style={{ textAlign: 'right', fontSize: 12.5, color: 'var(--muted)' }}>{A_fmtCurrency(r.e.baseRate)}</span>
                      <span className="mono" style={{ textAlign: 'right', fontSize: 13, fontWeight: 600 }}>{A_fmtCurrency(r.gross)}</span>
                    </div>
                  ))}
                </div>
              )}
            </>
          ) : step === 2 ? (
            <>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: '16px 18px' }}>
                  <div className="eyebrow" style={{ marginBottom: 10 }}>WITHHELD FROM EMPLOYEES</div>
                  {[
                    ['Gross wages', totalGross],
                    [`State income tax (${taxPolicy})`, -stateTax],
                    ['RRTA / FICA (employee)', -eeRRTA],
                  ].map(([k, v], i) => (
                    <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '7px 0', borderTop: i === 0 ? 'none' : '1px solid var(--line)', fontSize: 13 }}>
                      <span style={{ color: 'var(--muted)' }}>{k}</span>
                      <span className="mono" style={{ fontWeight: 600, color: v < 0 ? 'var(--bad)' : 'var(--text)' }}>{A_fmtCurrency(v)}</span>
                    </div>
                  ))}
                  <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0 0', marginTop: 6, borderTop: '2px solid var(--text)', fontSize: 15, fontWeight: 700 }}>
                    <span>Est. net pay</span><span className="mono">{A_fmtCurrency(netEstimate)}</span>
                  </div>
                </div>
                <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: '16px 18px' }}>
                  <div className="eyebrow" style={{ marginBottom: 10 }}>EMPLOYER REMITS</div>
                  {[
                    ['Gross wages', totalGross],
                    ['RRTA / FICA (employer)', erRRTA],
                  ].map(([k, v], i) => (
                    <div key={k} style={{ display: 'flex', justifyContent: 'space-between', padding: '7px 0', borderTop: i === 0 ? 'none' : '1px solid var(--line)', fontSize: 13 }}>
                      <span style={{ color: 'var(--muted)' }}>{k}</span>
                      <span className="mono" style={{ fontWeight: 600 }}>{A_fmtCurrency(v)}</span>
                    </div>
                  ))}
                  <div style={{ display: 'flex', justifyContent: 'space-between', padding: '10px 0 0', marginTop: 6, borderTop: '2px solid var(--text)', fontSize: 15, fontWeight: 700 }}>
                    <span>Total employer burden</span><span className="mono">{A_fmtCurrency(employerBurden)}</span>
                  </div>
                </div>
              </div>
              <div style={{ marginTop: 16, padding: '12px 16px', background: 'var(--info-soft)', borderRadius: 10, fontSize: 12.5, color: 'var(--info)', lineHeight: 1.5 }}>
                State withholding follows the company <strong>{taxPolicy}</strong> policy with reciprocal credits applied. Non-RRB employees are remitted under FICA automatically.
              </div>
            </>
          ) : (
            <>
              <div className="eyebrow" style={{ marginBottom: 10 }}>PUSH TO</div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginBottom: 20 }}>
                {TARGETS.map(t => {
                  const on = target === t;
                  return (
                    <button key={t} onClick={() => setTarget(t)} style={{
                      padding: '14px 16px', textAlign: 'left', borderRadius: 10, cursor: 'pointer',
                      background: on ? 'var(--accent-soft)' : 'var(--panel)',
                      border: `1.5px solid ${on ? 'var(--accent)' : 'var(--line)'}`,
                      display: 'flex', alignItems: 'center', gap: 10,
                    }}>
                      <div style={{ width: 32, height: 32, borderRadius: 8, background: on ? 'var(--accent)' : 'var(--panel-3)', color: on ? '#fff' : 'var(--text-2)', display: 'grid', placeItems: 'center' }}><IconPlug size={16} /></div>
                      <span style={{ fontWeight: 600, fontSize: 13.5, color: on ? 'var(--accent-deep)' : 'var(--text)' }}>{t}</span>
                    </button>
                  );
                })}
              </div>
              <div style={{ background: '#0F172A', color: '#fff', borderRadius: 12, padding: '18px 20px' }}>
                <div className="eyebrow" style={{ color: 'rgba(255,255,255,0.6)' }}>READY TO TRANSMIT</div>
                <div style={{ display: 'flex', gap: 28, marginTop: 10, flexWrap: 'wrap' }}>
                  <div><div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)' }}>Employees</div><div className="mono" style={{ fontSize: 20, fontWeight: 700 }}>{empRows.length}</div></div>
                  <div><div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)' }}>Gross</div><div className="mono" style={{ fontSize: 20, fontWeight: 700 }}>{A_fmtCurrency(totalGross)}</div></div>
                  <div><div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)' }}>Employer burden</div><div className="mono" style={{ fontSize: 20, fontWeight: 700 }}>{A_fmtCurrency(employerBurden)}</div></div>
                  <div><div style={{ fontSize: 11, color: 'rgba(255,255,255,0.55)' }}>Pay date</div><div className="mono" style={{ fontSize: 20, fontWeight: 700 }}>05-22</div></div>
                </div>
              </div>
            </>
          )}
        </div>

        {/* Footer */}
        {!done && (
          <div style={{ padding: '14px 24px', borderTop: '1px solid var(--line)', background: 'var(--panel)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <Button variant="ghost" onClick={() => step === 1 ? setPayrollWizard(false) : setStep(step - 1)}>
              {step === 1 ? 'Cancel' : 'Back'}
            </Button>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <span style={{ fontSize: 13, color: 'var(--muted)' }}>Step {step} of 3</span>
              {step < 3
                ? <Button variant="primary" iconRight={<IconArrowRight size={14} />} disabled={empRows.length === 0} onClick={() => setStep(step + 1)}>Continue</Button>
                : <Button variant="primary" icon={<IconUpload size={14} />} onClick={runPush}>Push to {target}</Button>}
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { PayrollRunWizard });
