// portal-screens.jsx — Home, Pay & Documents, Timecards.
// Builds pay-stub / W-2 payloads locally and opens them via the doc engine.

// ── Local doc payload builders (portal copy) ─────────────────
function portalPayStub(me, employer, pp) {
  const regPay = pp.reg * me.baseRate;
  const otPay = pp.ot * me.baseRate * 1.5;
  const gross = pp.gross;
  const taxes = [
    { label: 'Federal income tax', amount: gross * 0.12 },
    { label: 'Montana state tax', amount: gross * 0.059 },
    { label: 'RRTA Tier I (6.20%)', amount: gross * 0.062 },
    { label: 'RRTA Tier II (4.90%)', amount: gross * 0.049 },
    { label: 'Medicare (1.45%)', amount: gross * 0.0145 },
  ];
  return {
    title: `Pay stub · ${pp.period}`, subtitle: 'Earnings statement',
    el: 'paystub',
    payload: {
      company: employer.name,
      employee: { name: me.name, badge: me.badge, address: `${me.address.line1}, ${me.address.city} ${me.address.state} ${me.address.zip}`, ssnMasked: me.ssnMasked },
      period: pp.period, payDate: pp.payDate,
      lines: [
        { code: 'F10', desc: 'RWIC — Railroad Flagger (Reg)', hrs: pp.reg, rate: me.baseRate, amount: regPay },
        ...(pp.ot > 0 ? [{ code: 'F10', desc: 'Overtime (1.5×)', hrs: pp.ot, rate: me.baseRate * 1.5, amount: otPay }] : []),
      ],
      taxes, employer: [
        { label: 'RRTA Tier I (employer 6.20%)', amount: gross * 0.062 },
        { label: 'RRTA Tier II (employer 13.10%)', amount: gross * 0.131 },
        { label: 'Medicare (employer 1.45%)', amount: gross * 0.0145 },
      ],
      gross, net: pp.net,
      ytd: me.ytd,
    },
  };
}
function portalW2(me, employer) {
  const g = me.ytd.gross;
  return {
    title: 'Form W-2 (2025)', subtitle: 'Wage and Tax Statement', el: 'w2',
    payload: {
      year: 2025, control: `RFP-${me.badge}`, employer,
      employee: { name: me.name, ssn: me.ssnFull, address: `${me.address.line1}, ${me.address.city} ${me.address.state} ${me.address.zip}` },
      boxes: { 1: g, 2: g * 0.12, 3: 0, 4: 0, 5: g, 6: g * 0.0145, 7: 0, 8: 0, 10: 0 },
      box14: [
        { code: 'RRT1', amount: g * 0.062 }, { code: 'RRT2', amount: g * 0.049 }, { code: 'RRTM', amount: g * 0.0145 },
      ],
      state: { code: me.resident, id: 'MT-99-217', wages: g, tax: g * 0.059 },
    },
  };
}

// ── HOME ─────────────────────────────────────────────────────
function PortalHome({ go }) {
  const { me, payPeriods, ptoBalances, inbox, certs, setActiveDoc } = usePortal();
  const lastPaid = payPeriods.find(p => p.status === 'paid');
  const nextPay = payPeriods.find(p => p.status === 'pending');
  const ptoAvail = ptoBalances.reduce((s, b) => s + (b.accrued - b.used - b.pending), 0);
  const actionDocs = inbox.filter(d => d.status === 'action-required').length;
  const certIssues = certs.filter(c => c.status !== 'current').length;

  return (
    <div className="anim-fade">
      <div style={{ marginBottom: 22 }}>
        <div className="eyebrow">{P_date(new Date().toISOString())}</div>
        <h1 style={{ margin: '4px 0 0', fontSize: 28, fontWeight: 700, letterSpacing: -0.6 }}>Welcome back, {me.first}.</h1>
        <div style={{ fontSize: 14, color: 'var(--muted)', marginTop: 4 }}>{me.role} · <span className="mono">{me.badge}</span> · {me.payrollFreq} payroll</div>
      </div>

      {/* Alerts */}
      {(actionDocs > 0 || certIssues > 0) && (
        <div style={{ display: 'flex', gap: 12, marginBottom: 20, flexWrap: 'wrap' }}>
          {actionDocs > 0 && (
            <button onClick={() => go('inbox')} style={{ flex: 1, minWidth: 260, textAlign: 'left', background: 'var(--bad-soft)', border: '1px solid var(--bad)', borderRadius: 12, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer' }}>
              <IconBell size={20} style={{ color: 'var(--bad)' }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 13.5, color: 'var(--bad)' }}>{actionDocs} document{actionDocs > 1 ? 's' : ''} need your signature</div>
                <div style={{ fontSize: 12, color: 'var(--text-2)' }}>Open your documents inbox →</div>
              </div>
            </button>
          )}
          {certIssues > 0 && (
            <button onClick={() => go('certs')} style={{ flex: 1, minWidth: 260, textAlign: 'left', background: 'var(--warn-soft)', border: '1px solid var(--warn)', borderRadius: 12, padding: '12px 16px', display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer' }}>
              <IconShield size={20} style={{ color: 'var(--warn)' }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontWeight: 700, fontSize: 13.5, color: 'var(--warn)' }}>{certIssues} certification{certIssues > 1 ? 's' : ''} need attention</div>
                <div style={{ fontSize: 12, color: 'var(--text-2)' }}>Review & upload renewals →</div>
              </div>
            </button>
          )}
        </div>
      )}

      {/* Stat row */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
        <PStat label="Last net pay" value={lastPaid ? P_money(lastPaid.net) : '—'} sub={lastPaid ? `Paid ${P_date(lastPaid.payDate)}` : ''} tone="accent" icon={<IconDollar size={16} />} />
        <PStat label="YTD gross" value={P_money(me.ytd.gross)} sub="2026" icon={<IconDollar size={16} />} />
        <PStat label="PTO available" value={`${ptoAvail}h`} sub={`${(ptoAvail/8).toFixed(1)} days`} tone="good" icon={<IconClock size={16} />} />
        <PStat label="Next pay date" value={nextPay ? P_date(nextPay.payDate).replace(', 2026','') : '—'} sub={nextPay ? P_money(nextPay.net) + ' est.' : ''} icon={<IconClock size={16} />} />
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 22 }}>
        <div>
          <PSectionTitle action={<button onClick={() => go('pay')} style={ghostLink}>All pay stubs →</button>}>Recent pay</PSectionTitle>
          <PCard pad={0}>
            {payPeriods.slice(0, 4).map((pp, i) => (
              <div key={pp.id} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '13px 16px', borderTop: i === 0 ? 'none' : '1px solid var(--line)' }}>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 13.5 }}>{pp.period}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>Pay date {P_date(pp.payDate)} · {P_num(pp.reg + pp.ot, 1)}h</div>
                </div>
                <div className="mono" style={{ fontWeight: 700, fontSize: 14 }}>{P_money(pp.net)}</div>
                <PStatusPill status={pp.status} />
                <button onClick={() => setActiveDoc(portalPayStub(me, EMPLOYER, pp))} style={miniBtn}>View stub</button>
              </div>
            ))}
          </PCard>
        </div>
        <div>
          <PSectionTitle action={<button onClick={() => go('pay')} style={ghostLink}>Tax docs →</button>}>Quick actions</PSectionTitle>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            <QuickAction icon={<IconRRB size={18} />} title="2025 W-2" sub="Wage & tax statement" onClick={() => setActiveDoc(portalW2(me, EMPLOYER))} />
            <QuickAction icon={<IconClock size={18} />} title="Request time off" sub={`${ptoAvail}h available`} onClick={() => go('pto')} />
            <QuickAction icon={<IconDollar size={18} />} title="Submit reimbursement" sub="Per-diem or mileage" onClick={() => go('reimb')} />
            <QuickAction icon={<IconUser size={18} />} title="Update direct deposit" sub="Banking & profile" onClick={() => go('profile')} />
          </div>
        </div>
      </div>
    </div>
  );
}

function QuickAction({ icon, title, sub, onClick }) {
  return (
    <button onClick={onClick} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '13px 16px', background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, cursor: 'pointer', textAlign: 'left', width: '100%' }}>
      <div style={{ width: 38, height: 38, borderRadius: 10, background: 'var(--accent-soft)', color: 'var(--accent-deep)', display: 'grid', placeItems: 'center' }}>{icon}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontWeight: 600, fontSize: 13.5 }}>{title}</div>
        <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{sub}</div>
      </div>
      <IconChevronRight size={16} style={{ color: 'var(--muted-2)' }} />
    </button>
  );
}

// ── PAY & DOCUMENTS ──────────────────────────────────────────
function PortalPay() {
  const { me, payPeriods, setActiveDoc } = usePortal();
  return (
    <div className="anim-fade">
      <h1 style={{ margin: '0 0 4px', fontSize: 26, fontWeight: 700, letterSpacing: -0.5 }}>Pay & documents</h1>
      <div style={{ fontSize: 14, color: 'var(--muted)', marginBottom: 22 }}>Pay stubs and year-end tax forms. View in-app or download a PDF.</div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginBottom: 22 }}>
        <PStat label="YTD gross" value={P_money(me.ytd.gross)} icon={<IconDollar size={16} />} />
        <PStat label="YTD taxes" value={P_money(me.ytd.tax)} tone="warn" icon={<IconTax size={16} />} />
        <PStat label="YTD net" value={P_money(me.ytd.net)} tone="good" icon={<IconDollar size={16} />} />
      </div>

      <PSectionTitle>Year-end tax forms</PSectionTitle>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12, marginBottom: 22 }}>
        <TaxDocCard title="Form W-2 (2025)" sub="Wage and Tax Statement · RRTA box 14" onClick={() => setActiveDoc(portalW2(me, EMPLOYER))} />
        <TaxDocCard title="Form W-2 (2024)" sub="Wage and Tax Statement" onClick={() => setActiveDoc(portalW2(me, EMPLOYER))} />
      </div>

      <PSectionTitle>Pay stubs</PSectionTitle>
      <PCard pad={0}>
        <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 0.8fr 0.8fr 0.8fr 110px', gap: 10, padding: '11px 16px', background: 'var(--panel-2)', borderBottom: '1px solid var(--line)', fontSize: 10.5, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase', color: 'var(--muted)' }}>
          <span>Period</span><span>Pay date</span><span style={{ textAlign: 'right' }}>Hours</span><span style={{ textAlign: 'right' }}>Gross</span><span style={{ textAlign: 'right' }}>Net</span><span></span>
        </div>
        {payPeriods.map((pp, i) => (
          <div key={pp.id} style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr 0.8fr 0.8fr 0.8fr 110px', gap: 10, padding: '12px 16px', borderTop: i === 0 ? 'none' : '1px solid var(--line)', alignItems: 'center' }}>
            <div style={{ fontWeight: 600, fontSize: 13 }}>{pp.period}</div>
            <div className="mono" style={{ fontSize: 12.5 }}>{P_date(pp.payDate)}</div>
            <div className="mono" style={{ textAlign: 'right', fontSize: 12.5 }}>{P_num(pp.reg + pp.ot, 1)}</div>
            <div className="mono" style={{ textAlign: 'right', fontSize: 12.5 }}>{P_money(pp.gross)}</div>
            <div className="mono" style={{ textAlign: 'right', fontSize: 13, fontWeight: 700 }}>{P_money(pp.net)}</div>
            <div style={{ textAlign: 'right' }}>
              <button onClick={() => setActiveDoc(portalPayStub(me, EMPLOYER, pp))} style={miniBtn}>View stub</button>
            </div>
          </div>
        ))}
      </PCard>
    </div>
  );
}

function TaxDocCard({ title, sub, onClick }) {
  return (
    <PCard>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <div style={{ width: 44, height: 44, borderRadius: 10, background: 'var(--indigo-soft)', color: 'var(--indigo)', display: 'grid', placeItems: 'center' }}><IconRRB size={22} /></div>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 700, fontSize: 14.5 }}>{title}</div>
          <div style={{ fontSize: 12, color: 'var(--muted)' }}>{sub}</div>
        </div>
        <Button variant="secondary" size="sm" icon={<IconDownload size={13} />} onClick={onClick}>Open</Button>
      </div>
    </PCard>
  );
}

// ── TIMECARDS ────────────────────────────────────────────────
function PortalTimecards() {
  const { timecards } = usePortal();
  const total = timecards.reduce((s, t) => s + t.hrs, 0);
  return (
    <div className="anim-fade">
      <h1 style={{ margin: '0 0 4px', fontSize: 26, fontWeight: 700, letterSpacing: -0.5 }}>My timecards</h1>
      <div style={{ fontSize: 14, color: 'var(--muted)', marginBottom: 22 }}>Submitted from your field tablet. Track approval status here.</div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, marginBottom: 22 }}>
        <PStat label="Logged (shown)" value={`${P_num(total, 1)}h`} icon={<IconClock size={16} />} />
        <PStat label="Awaiting approval" value={timecards.filter(t => t.status.startsWith('pending')).length} tone="warn" icon={<IconClipboard size={16} />} />
        <PStat label="Approved / paid" value={timecards.filter(t => t.status === 'approved' || t.status === 'paid').length} tone="good" icon={<IconCheck size={16} />} />
      </div>

      <PCard pad={0}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1.4fr 0.8fr 140px', gap: 10, padding: '11px 16px', background: 'var(--panel-2)', borderBottom: '1px solid var(--line)', fontSize: 10.5, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase', color: 'var(--muted)' }}>
          <span>Date</span><span>Job</span><span>Activity</span><span style={{ textAlign: 'right' }}>Hours</span><span style={{ textAlign: 'right' }}>Status</span>
        </div>
        {timecards.map((t, i) => (
          <div key={t.date} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1.4fr 0.8fr 140px', gap: 10, padding: '12px 16px', borderTop: i === 0 ? 'none' : '1px solid var(--line)', alignItems: 'center' }}>
            <div className="mono" style={{ fontSize: 12.5 }}>{P_date(t.date)}</div>
            <div className="mono" style={{ fontSize: 12.5 }}>{t.job}</div>
            <div style={{ display: 'flex', gap: 4 }}>{t.codes.map(c => <PPill key={c} tone="neutral">{c}</PPill>)}</div>
            <div className="mono" style={{ textAlign: 'right', fontSize: 13, fontWeight: 600 }}>{P_num(t.hrs, 1)}</div>
            <div style={{ textAlign: 'right' }}><PStatusPill status={t.status} /></div>
          </div>
        ))}
      </PCard>
    </div>
  );
}

const ghostLink = { background: 'transparent', border: 'none', color: 'var(--accent-deep)', fontWeight: 600, fontSize: 13, cursor: 'pointer' };
const miniBtn = { background: 'var(--panel)', border: '1px solid var(--line-strong)', borderRadius: 8, padding: '6px 12px', fontSize: 12, fontWeight: 600, color: 'var(--text-2)', cursor: 'pointer' };

Object.assign(window, { PortalHome, PortalPay, PortalTimecards, portalPayStub, portalW2, QuickAction, TaxDocCard, ghostLink, miniBtn });
