// view-timecard-review.jsx — Two-step approval queue.
// Ops approves first (pending-ops → pending-acct), accounting approves second
// (pending-acct → approved). Rejections bounce back to the employee.

function TimecardReview() {
  const { timecards, employees, jobs, managers, updateTimecard, toast, setTimecardDrawer } = useAdmin();
  const [stage, setStage] = useState('pending-ops'); // which queue
  const [selected, setSelected] = useState(new Set());
  const [mgrFilter, setMgrFilter] = useState('all'); // manager routing filter (step 1)

  const counts = {
    'pending-ops':  timecards.filter(t => t.status === 'pending-ops').length,
    'pending-acct': timecards.filter(t => t.status === 'pending-acct').length,
    'approved':     timecards.filter(t => t.status === 'approved').length,
    'rejected':     timecards.filter(t => t.status === 'rejected').length,
  };

  const baseRows = timecards.filter(t => t.status === stage);
  const rows = (stage === 'pending-ops' && mgrFilter !== 'all')
    ? baseRows.filter(t => managerForTimecard(t)?.id === mgrFilter)
    : baseRows;

  // Count of freshly-arrived tablet submissions in the ops queue
  const tabletArrivals = timecards.filter(t => t.fromTablet && t.status === 'pending-ops').length;

  const toggle = (id) => setSelected(s => {
    const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n;
  });
  const toggleAll = () => setSelected(s => s.size === rows.length ? new Set() : new Set(rows.map(r => r.id)));

  const advance = (ids, action) => {
    ids.forEach(id => {
      const t = timecards.find(x => x.id === id);
      if (!t) return;
      if (action === 'approve') {
        const next = t.status === 'pending-ops' ? 'pending-acct' : 'approved';
        updateTimecard(id, { status: next });
      } else {
        updateTimecard(id, { status: 'rejected' });
      }
    });
    setSelected(new Set());
    toast(
      action === 'approve'
        ? `${ids.length} timecard${ids.length === 1 ? '' : 's'} advanced`
        : `${ids.length} timecard${ids.length === 1 ? '' : 's'} returned to employee`,
      action === 'approve' ? 'success' : 'warn'
    );
  };

  const stageLabel = {
    'pending-ops':  'Step 1 · Manager review',
    'pending-acct': 'Step 2 · Accounting review',
    'approved':     'Approved — ready for payroll',
    'rejected':     'Rejected — returned to employee',
  }[stage];

  return (
    <>
      {/* Two-step workflow explainer */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 0, marginBottom: 18,
        background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: '6px',
      }}>
        {[
          { id: 'pending-ops',  n: '1', label: 'Manager', tone: 'warn' },
          { id: 'pending-acct', n: '2', label: 'Accounting', tone: 'info' },
          { id: 'approved',     n: '✓', label: 'Approved',  tone: 'good' },
          { id: 'rejected',     n: '✕', label: 'Rejected',  tone: 'bad' },
        ].map((s, i, all) => {
          const on = stage === s.id;
          return (
            <React.Fragment key={s.id}>
              <button onClick={() => { setStage(s.id); setSelected(new Set()); }} style={{
                flex: 1, padding: '10px 14px', borderRadius: 8, border: 'none',
                background: on ? 'var(--panel-3)' : 'transparent',
                display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer',
              }}>
                <span style={{
                  width: 26, height: 26, borderRadius: 13, flexShrink: 0,
                  background: on ? `var(--${s.tone})` : 'var(--panel-3)',
                  color: on ? '#fff' : 'var(--muted)',
                  display: 'grid', placeItems: 'center', fontSize: 13, fontWeight: 700,
                }}>{s.n}</span>
                <div style={{ textAlign: 'left' }}>
                  <div style={{ fontSize: 13, fontWeight: on ? 700 : 500, color: on ? 'var(--text)' : 'var(--muted)' }}>{s.label}</div>
                  <div className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{counts[s.id]} cards</div>
                </div>
              </button>
              {i < all.length - 1 && <IconChevronRight size={14} style={{ color: 'var(--muted-2)', flexShrink: 0 }} />}
            </React.Fragment>
          );
        })}
      </div>

      {/* Bulk action bar */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
        <div style={{ fontSize: 14, fontWeight: 700 }}>{stageLabel}</div>
        <div style={{ flex: 1 }} />
        {selected.size > 0 && (stage === 'pending-ops' || stage === 'pending-acct') && (
          <div className="anim-fade" style={{ display: 'flex', gap: 8 }}>
            <span style={{ fontSize: 13, color: 'var(--muted)', alignSelf: 'center' }}>{selected.size} selected</span>
            <Button variant="secondary" size="sm" icon={<IconClose size={12} />} onClick={() => advance([...selected], 'reject')}>Return</Button>
            <Button variant="primary" size="sm" icon={<IconCheck size={12} />} onClick={() => advance([...selected], 'approve')}>
              {stage === 'pending-ops' ? 'Approve → Accounting' : 'Approve for payroll'}
            </Button>
          </div>
        )}
      </div>

      {/* Manager routing filter (step 1) — based on the posted dispatch schedule */}
      {stage === 'pending-ops' && (
        <>
          {tabletArrivals > 0 && (
            <div className="anim-fade" style={{
              display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12,
              padding: '10px 14px', borderRadius: 10,
              background: 'var(--accent-soft)', border: '1px solid var(--accent)',
            }}>
              <StatusDot tone="accent" size={8} pulse />
              <span style={{ fontSize: 13, color: 'var(--accent-deep)' }}>
                <strong>{tabletArrivals} timecard{tabletArrivals === 1 ? '' : 's'}</strong> just arrived from the field tablet — routed to {' '}
                {[...new Set(timecards.filter(t => t.fromTablet && t.status==='pending-ops').map(t => managerForTimecard(t)?.name))].filter(Boolean).join(', ')} by the dispatch schedule.
              </span>
            </div>
          )}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12, flexWrap: 'wrap' }}>
            <span className="eyebrow" style={{ marginRight: 4 }}>ROUTED TO MANAGER</span>
            <FilterChip active={mgrFilter==='all'} onClick={() => { setMgrFilter('all'); setSelected(new Set()); }} count={baseRows.length}>All managers</FilterChip>
            {managers.map(m => {
              const c = baseRows.filter(t => managerForTimecard(t)?.id === m.id).length;
              return (
                <FilterChip key={m.id} active={mgrFilter===m.id} onClick={() => { setMgrFilter(m.id); setSelected(new Set()); }} count={c}>
                  {m.name} · {m.region}
                </FilterChip>
              );
            })}
          </div>
        </>
      )}

      {/* Table */}
      <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden' }}>
        <table style={{ width: '100%', fontSize: 13.5 }}>
          <thead>
            <tr style={{ background: 'var(--panel-2)', borderBottom: '1px solid var(--line)' }}>
              {(stage === 'pending-ops' || stage === 'pending-acct') && (
                <th style={{ padding: '11px 16px', width: 40 }}>
                  <input type="checkbox" checked={rows.length > 0 && selected.size === rows.length} onChange={toggleAll} style={{ width: 16, height: 16, cursor: 'pointer' }} />
                </th>
              )}
              {['Employee', 'Date', 'Job', 'Routed to', 'Activity', 'State(s)', 'Reg', 'OT', 'Gross', 'Flags', ''].map(h => (
                <th key={h} style={{ padding: '11px 12px', fontSize: 11, fontWeight: 600, letterSpacing: 0.5, textTransform: 'uppercase', color: 'var(--muted)', textAlign: ['Reg','OT','Gross'].includes(h) ? 'right' : 'left' }}>{h}</th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rows.length === 0 && (
              <tr><td colSpan={12} style={{ padding: 40, textAlign: 'center', color: 'var(--muted-2)' }}>Queue is empty.</td></tr>
            )}
            {rows.map((t, i) => {
              const e = employees.find(x => x.id === t.employeeId);
              const job = jobs.find(j => j.id === t.jobId);
              const gross = t.total * (e?.baseRate || 0);
              const states = [...new Set(t.blocks.map(b => b.state))];
              const codes = [...new Set(t.blocks.map(b => b.code))];
              const sel = selected.has(t.id);
              return (
                <tr key={t.id} style={{
                  borderTop: i === 0 ? 'none' : '1px solid var(--line)',
                  background: sel ? 'var(--accent-soft)' : 'transparent',
                }}>
                  {(stage === 'pending-ops' || stage === 'pending-acct') && (
                    <td style={{ padding: '10px 16px' }}>
                      <input type="checkbox" checked={sel} onChange={() => toggle(t.id)} style={{ width: 16, height: 16, cursor: 'pointer' }} />
                    </td>
                  )}
                  <td style={{ padding: '10px 12px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <div style={{ width: 28, height: 28, borderRadius: 14, background: 'var(--panel-3)', display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 700 }}>{e?.avatar}</div>
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 13 }}>{e?.name}</div>
                        <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)' }}>{e?.resident} resident</div>
                      </div>
                    </div>
                  </td>
                  <td style={{ padding: '10px 12px' }} className="mono">{A_fmtDateShort(t.date)}</td>
                  <td style={{ padding: '10px 12px' }}>
                    <span className="mono" style={{ fontSize: 12 }}>{job?.id}</span>
                    {t.fromTablet && <Pill tone="accent" style={{ marginLeft: 6 }}>tablet</Pill>}
                  </td>
                  <td style={{ padding: '10px 12px' }}>
                    {(() => {
                      const m = managerForTimecard(t);
                      return m ? (
                        <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                          <div style={{ width: 24, height: 24, borderRadius: 12, background: 'var(--indigo-soft)', color: 'var(--indigo)', display: 'grid', placeItems: 'center', fontSize: 9.5, fontWeight: 700 }}>{m.initials}</div>
                          <div style={{ fontSize: 12, fontWeight: 500, lineHeight: 1.2 }}>{m.name.split(' ')[0]} {m.name.split(' ').pop().charAt(0)}.</div>
                        </div>
                      ) : <span style={{ color: 'var(--muted-2)' }}>—</span>;
                    })()}
                  </td>
                  <td style={{ padding: '10px 12px' }}>
                    {codes.map(c => <Pill key={c} tone="neutral" style={{ marginRight: 4 }}>{c}</Pill>)}
                  </td>
                  <td style={{ padding: '10px 12px' }}>
                    {states.map(s => <span key={s} className="mono" style={{ fontSize: 11.5, fontWeight: 600, marginRight: 6, color: s === e?.resident ? 'var(--text)' : 'var(--accent-deep)' }}>{s}</span>)}
                  </td>
                  <td style={{ padding: '10px 12px', textAlign: 'right' }} className="mono">{t.regular.toFixed(1)}</td>
                  <td style={{ padding: '10px 12px', textAlign: 'right' }} className="mono">
                    {t.overtime > 0 ? <span style={{ color: 'var(--warn)', fontWeight: 600 }}>{t.overtime.toFixed(1)}</span> : <span style={{ color: 'var(--muted-2)' }}>—</span>}
                  </td>
                  <td style={{ padding: '10px 12px', textAlign: 'right', fontWeight: 600 }} className="mono">{A_fmtCurrency(gross)}</td>
                  <td style={{ padding: '10px 12px' }}>
                    {t.flags.includes('extreme-ot') && <Pill tone="warn">High OT</Pill>}
                    {t.flags.includes('missing-photo') && <Pill tone="bad">Photo</Pill>}
                    {t.flags.length === 0 && <Pill tone="good"><IconCheck size={10} /> Clean</Pill>}
                  </td>
                  <td style={{ padding: '10px 12px' }}>
                    <button onClick={() => setTimecardDrawer(t)} style={{
                      background: 'transparent', border: '1px solid var(--line)', borderRadius: 7,
                      padding: '5px 10px', fontSize: 12, color: 'var(--text-2)', fontWeight: 500,
                    }}>Review</button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {/* Totals footer */}
      {rows.length > 0 && (
        <div style={{
          marginTop: 12, display: 'flex', justifyContent: 'flex-end', gap: 28,
          padding: '12px 16px', background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12,
        }}>
          {(() => {
            const hrs = rows.reduce((s, t) => s + t.total, 0);
            const ot = rows.reduce((s, t) => s + t.overtime, 0);
            const gross = rows.reduce((s, t) => { const e = employees.find(x => x.id === t.employeeId); return s + t.total * (e?.baseRate || 0); }, 0);
            return (
              <>
                <Total label="Cards" value={rows.length} />
                <Total label="Hours" value={A_fmtNum(hrs, 1)} />
                <Total label="OT hours" value={A_fmtNum(ot, 1)} tone="warn" />
                <Total label="Gross" value={A_fmtCurrency(gross)} tone="accent" />
              </>
            );
          })()}
        </div>
      )}
    </>
  );
}

function Total({ label, value, tone }) {
  return (
    <div style={{ textAlign: 'right' }}>
      <div className="eyebrow" style={{ fontSize: 10 }}>{label}</div>
      <div className="mono" style={{ fontSize: 18, fontWeight: 700, color: tone === 'accent' ? 'var(--accent)' : tone === 'warn' ? 'var(--warn)' : 'var(--text)' }}>{value}</div>
    </div>
  );
}

Object.assign(window, { TimecardReview });
