// view-tax.jsx — Multi-state tax allocation. Lets accounting choose the
// company tax policy (home / work / hybrid) and shows per-employee allocation
// using the engine in admin-state-4.jsx.

function TaxView() {
  const { employees, timecards, taxPolicy, setTaxPolicy, icExempt, setICExempt, toast, launchDoc } = useAdmin();

  // Aggregate each employee's blocks across the period
  const empBlocks = {};
  for (const t of timecards) {
    empBlocks[t.employeeId] = empBlocks[t.employeeId] || [];
    empBlocks[t.employeeId].push(...t.blocks);
  }

  const rows = employees
    .filter(e => empBlocks[e.id])
    .map(e => {
      const breakdown = allocateWages(e, empBlocks[e.id], taxPolicy);
      const gross = breakdown.reduce((s, b) => s + b.wage, 0);
      const tax = breakdown.reduce((s, b) => s + b.taxAmt, 0);
      const credit = breakdown.reduce((s, b) => s + b.credit, 0);
      return { e, breakdown, gross, tax, credit, states: breakdown.length };
    });

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

  const POLICIES = [
    { id: 'home',   label: 'Resident state only', desc: 'All wages withheld to home state. Simplest, but often not compliant when work crosses state lines.' },
    { id: 'work',   label: 'State where earned',  desc: 'Each state taxes the wages earned in it. Most defensible for short multi-state stints.' },
    { id: 'hybrid', label: 'Hybrid + reciprocal', desc: 'Applies reciprocal-state agreements and computes a resident-state credit for tax paid elsewhere. Most accurate.' },
  ];

  return (
    <>
      {/* Policy selector */}
      <AdminSection title="Company tax policy"
        action={<Button variant="ghost" size="sm" icon={<IconDownload size={12} />} onClick={() => {
          const content = buildWithholdingCSV(rows, taxPolicy, '2026-05-18 — 2026-05-31');
          launchDoc({ kind: 'csvpreview', title: 'Multi-State Withholding Worksheet', subtitle: `Policy: ${taxPolicy}`, payload: { content, note: 'One row per employee × work-state. Reciprocal credits included.' }, file: { filename: 'withholding-worksheet.csv', content, mime: 'text/csv' } });
        }}>Withholding worksheet</Button>}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          {POLICIES.map(p => {
            const on = taxPolicy === p.id;
            return (
              <button key={p.id} onClick={() => setTaxPolicy(p.id)} style={{
                textAlign: 'left', padding: '16px 18px',
                background: on ? 'var(--accent-soft)' : 'var(--panel)',
                border: `1.5px solid ${on ? 'var(--accent)' : 'var(--line)'}`,
                borderRadius: 12, cursor: 'pointer',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 6 }}>
                  <span style={{ fontWeight: 700, fontSize: 14, color: on ? 'var(--accent-deep)' : 'var(--text)' }}>{p.label}</span>
                  <span style={{
                    width: 18, height: 18, borderRadius: 9, flexShrink: 0,
                    border: `2px solid ${on ? 'var(--accent)' : 'var(--line-strong)'}`,
                    background: on ? 'var(--accent)' : 'transparent',
                    display: 'grid', placeItems: 'center',
                  }}>{on && <IconCheck size={11} stroke={3} style={{ color: '#fff' }} />}</span>
                </div>
                <div style={{ fontSize: 12, color: 'var(--muted)', lineHeight: 1.5 }}>{p.desc}</div>
              </button>
            );
          })}
        </div>

        {/* IC exemption toggle */}
        <div style={{
          marginTop: 12, padding: '12px 16px', borderRadius: 10,
          background: icExempt ? 'var(--warn-soft)' : 'var(--panel-2)',
          border: `1px solid ${icExempt ? 'var(--warn)' : 'var(--line)'}`,
          display: 'flex', alignItems: 'center', gap: 12,
        }}>
          <button onClick={() => setICExempt(!icExempt)} style={{
            width: 42, height: 24, borderRadius: 12, border: 'none', flexShrink: 0,
            background: icExempt ? 'var(--warn)' : 'var(--line-strong)',
            position: 'relative', cursor: 'pointer', transition: 'background 160ms',
          }}>
            <span style={{
              position: 'absolute', top: 2, left: icExempt ? 20 : 2,
              width: 20, height: 20, borderRadius: 10, background: '#fff',
              transition: 'left 160ms',
            }} />
          </button>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13.5, fontWeight: 600 }}>Interstate commerce exemption (49 U.S.C. § 11502 / Amtrak Act)</div>
            <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 1 }}>
              When a qualifying rail carrier, nonresident-state withholding is pre-empted. <strong>Most contractors do not qualify</strong> — leave off unless counsel confirms.
            </div>
          </div>
          <Pill tone={icExempt ? 'warn' : 'neutral'}>{icExempt ? 'Claimed' : 'Not claimed'}</Pill>
        </div>
      </AdminSection>

      {/* Summary KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
        <KPI label="Period gross" value={A_fmtCurrency(totalGross)} tone="neutral" icon={<IconDollar size={16} />} />
        <KPI label="State tax withheld" value={A_fmtCurrency(totalTax)} tone="accent" icon={<IconTax size={16} />} />
        <KPI label="Resident-state credits" value={A_fmtCurrency(totalCredit)} sub="hybrid policy" tone="good" icon={<IconGavel size={16} />} />
        <KPI label="States touched" value={[...new Set(rows.flatMap(r => r.breakdown.map(b => b.state)))].length} sub="this period" icon={<IconMap size={16} />} />
      </div>

      {/* Allocation table */}
      <AdminSection title="Per-employee allocation"
        action={<Button variant="ghost" size="sm" icon={<IconDownload size={12} />} onClick={() => toast('Multi-state allocation CSV exported', 'success')}>Export allocation</Button>}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {rows.map(r => <TaxRow key={r.e.id} row={r} />)}
        </div>
      </AdminSection>
    </>
  );
}

function TaxRow({ row }) {
  const [open, setOpen] = useState(false);
  const { e, breakdown, gross, tax, credit } = row;
  const multi = breakdown.length > 1;
  return (
    <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden' }}>
      <div onClick={() => setOpen(o => !o)} style={{
        display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr 1fr 40px', alignItems: 'center', gap: 12,
        padding: '12px 16px', cursor: 'pointer',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
          <div style={{ width: 32, height: 32, borderRadius: 16, background: 'var(--panel-3)', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 700 }}>{e.avatar}</div>
          <div>
            <div style={{ fontWeight: 600, fontSize: 13.5 }}>{e.name}</div>
            <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>
              Resident <span className="mono" style={{ fontWeight: 600 }}>{e.resident}</span>
              {multi && <span> · works {breakdown.length} states</span>}
            </div>
          </div>
        </div>
        <div>
          <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
            {breakdown.map(b => (
              <span key={b.state} className="mono" style={{
                fontSize: 11, fontWeight: 700, padding: '2px 6px', borderRadius: 4,
                background: b.state === e.resident ? 'var(--panel-3)' : 'var(--accent-soft)',
                color: b.state === e.resident ? 'var(--text-2)' : 'var(--accent-deep)',
              }}>{b.state}</span>
            ))}
          </div>
        </div>
        <div className="mono" style={{ textAlign: 'right', fontWeight: 600 }}>{A_fmtCurrency(gross)}</div>
        <div className="mono" style={{ textAlign: 'right', color: 'var(--accent-deep)', fontWeight: 600 }}>{A_fmtCurrency(tax)}</div>
        <div className="mono" style={{ textAlign: 'right', color: credit > 0 ? 'var(--good)' : 'var(--muted-2)' }}>{credit > 0 ? A_fmtCurrency(credit) : '—'}</div>
        <div style={{ textAlign: 'center' }}><IconChevronDown size={16} style={{ color: 'var(--muted)', transform: open ? 'rotate(180deg)' : 'none', transition: 'transform 160ms' }} /></div>
      </div>
      {open && (
        <div className="anim-fade" style={{ borderTop: '1px solid var(--line)', background: 'var(--panel-2)', padding: '4px 16px 8px' }}>
          {breakdown.map((b, i) => (
            <div key={b.state} style={{
              display: 'grid', gridTemplateColumns: '60px 1fr 90px 70px 90px', gap: 12, alignItems: 'center',
              padding: '10px 0', borderTop: i === 0 ? 'none' : '1px solid var(--line)',
            }}>
              <span className="mono" style={{ fontSize: 13, fontWeight: 700 }}>{b.state}</span>
              <span style={{ fontSize: 12, color: 'var(--muted)' }}>{b.note}</span>
              <span className="mono" style={{ textAlign: 'right', fontSize: 12.5 }}>{A_fmtCurrency(b.wage)}</span>
              <span className="mono" style={{ textAlign: 'right', fontSize: 12.5, color: 'var(--muted)' }}>{(b.taxRate * 100).toFixed(2)}%</span>
              <span className="mono" style={{ textAlign: 'right', fontSize: 12.5, fontWeight: 600 }}>
                taxed to {b.taxedBy}
              </span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { TaxView });
