// view-rrb.jsx — Railroad Retirement (RRTA). Per-employee Tier I / Tier II /
// Medicare computation, with company toggle for which tiers apply, plus the
// quarterly BA-3/BA-4 and W-2 box-14 export stubs.

function RRBView() {
  const { employees, timecards, ytdGross, rrbEnabled, setRrbEnabled, toast, launchDoc } = useAdmin();

  // tier toggles (company-level election shown in UI)
  const [tier1, setTier1] = useState(true);
  const [tier2, setTier2] = useState(true);
  const [medicare, setMedicare] = useState(true);

  const empGross = {};
  for (const t of timecards) {
    const e = employees.find(x => x.id === t.employeeId);
    empGross[t.employeeId] = (empGross[t.employeeId] || 0) + t.total * (e?.baseRate || 0);
  }

  const rows = employees.filter(e => empGross[e.id]).map(e => {
    const gross = empGross[e.id];
    const ytd = ytdGross[e.id] || 0;
    const calc = computeRRTA(e, ytd, gross, { tier1, tier2, medicare });
    const empTotal = calc.lines.reduce((s, l) => s + l.amount, 0);
    const erTotal = calc.employer.reduce((s, l) => s + l.amount, 0);
    return { e, gross, ytd, calc, empTotal, erTotal };
  });

  const totalEmp = rows.reduce((s, r) => s + r.empTotal, 0);
  const totalEr  = rows.reduce((s, r) => s + r.erTotal, 0);
  const rrbCount = rows.filter(r => r.e.rrbContributor).length;
  const ficaCount = rows.length - rrbCount;

  return (
    <>
      {/* Company election */}
      <AdminSection title="Railroad Retirement election (2026 rates)">
        <div style={{
          background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12,
          padding: '16px 20px', display: 'flex', alignItems: 'center', gap: 24, flexWrap: 'wrap',
        }}>
          <RrbToggle label="Tier I" sub="6.20% EE · 6.20% ER" detail="Wage base $168,600" on={tier1} onClick={() => setTier1(v => !v)} />
          <RrbToggle label="Tier II" sub="4.90% EE · 13.10% ER" detail="Wage base $125,100" on={tier2} onClick={() => setTier2(v => !v)} />
          <RrbToggle label="Medicare" sub="1.45% + 0.9% addl" detail="Over $200k threshold" on={medicare} onClick={() => setMedicare(v => !v)} />
          <div style={{ flex: 1, minWidth: 200, fontSize: 12.5, color: 'var(--muted)', lineHeight: 1.55, paddingLeft: 20, borderLeft: '1px solid var(--line)' }}>
            Employees not enrolled in Railroad Retirement fall under standard <strong>FICA</strong> (Social Security + Medicare) automatically — toggled per-employee on their profile.
          </div>
        </div>
      </AdminSection>

      {/* KPIs */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
        <KPI label="In Railroad Retirement" value={rrbCount} sub={`${ficaCount} on FICA`} tone="info" icon={<IconRRB size={16} />} />
        <KPI label="Employee withholding" value={A_fmtCurrency(totalEmp)} sub="this period" tone="neutral" icon={<IconDollar size={16} />} />
        <KPI label="Employer contribution" value={A_fmtCurrency(totalEr)} sub="this period" tone="accent" icon={<IconBuilding size={16} />} />
        <KPI label="Total RRTA + FICA" value={A_fmtCurrency(totalEmp + totalEr)} sub="remitted" tone="dark" icon={<IconGavel size={16} />} />
      </div>

      {/* Reports row */}
      <AdminSection title="Compliance reports">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          <ReportCard title="Form BA-3" sub="Annual Report of Creditable Compensation" period="Due 2027-02-28" onClick={() => launchDoc(buildBA3({ employees, ytdGross }))} />
          <ReportCard title="Form BA-4" sub="Report of Creditable Compensation Adjustments" period="As needed" onClick={() => launchDoc(buildBA4({ employees }))} />
          <ReportCard title="W-2 Box 14" sub="RRTA Tier I / Tier II / Medicare codes" period="Year-end" onClick={() => launchDoc(buildW2({ company: 'RailFlagsPro LLC', employee: employees.find(e => e.rrbContributor), ytdGross: ytdGross[employees.find(e => e.rrbContributor).id] }))} />
        </div>
      </AdminSection>

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

function RrbToggle({ label, sub, detail, on, onClick }) {
  return (
    <button onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 12, background: 'transparent', border: 'none', cursor: 'pointer', textAlign: 'left',
    }}>
      <span style={{
        width: 42, height: 24, borderRadius: 12, flexShrink: 0,
        background: on ? 'var(--info)' : 'var(--line-strong)',
        position: 'relative', transition: 'background 160ms',
      }}>
        <span style={{ position: 'absolute', top: 2, left: on ? 20 : 2, width: 20, height: 20, borderRadius: 10, background: '#fff', transition: 'left 160ms' }} />
      </span>
      <div>
        <div style={{ fontSize: 13.5, fontWeight: 700 }}>{label}</div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{sub}</div>
        <div style={{ fontSize: 10.5, color: 'var(--muted-2)' }}>{detail}</div>
      </div>
    </button>
  );
}

function ReportCard({ title, sub, period, onClick }) {
  return (
    <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: '16px 18px' }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
        <div style={{ width: 38, height: 38, borderRadius: 9, background: 'var(--indigo-soft)', color: 'var(--indigo)', display: 'grid', placeItems: 'center' }}><IconRRB size={20} /></div>
        <Pill tone="neutral">{period}</Pill>
      </div>
      <div style={{ fontWeight: 700, fontSize: 15 }}>{title}</div>
      <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2, lineHeight: 1.4, minHeight: 34 }}>{sub}</div>
      <Button variant="secondary" size="sm" icon={<IconDownload size={12} />} style={{ width: '100%', marginTop: 6 }} onClick={onClick}>Generate</Button>
    </div>
  );
}

function RrbRow({ row }) {
  const [open, setOpen] = useState(false);
  const { e, gross, ytd, calc, empTotal, erTotal } = row;
  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 }}>
              {calc.enrolled ? <Pill tone="info">Railroad Retirement</Pill> : <Pill tone="neutral">FICA</Pill>}
            </div>
          </div>
        </div>
        <div className="mono" style={{ textAlign: 'right', fontSize: 12.5 }}>
          {A_fmtCurrency(gross)}
          <div style={{ fontSize: 10.5, color: 'var(--muted-2)' }}>YTD {A_fmtCurrency(ytd)}</div>
        </div>
        <div className="mono" style={{ textAlign: 'right', fontWeight: 600 }}>{A_fmtCurrency(empTotal)}</div>
        <div className="mono" style={{ textAlign: 'right', color: 'var(--accent-deep)', fontWeight: 600 }}>{A_fmtCurrency(erTotal)}</div>
        <div className="mono" style={{ textAlign: 'right', fontWeight: 700 }}>{A_fmtCurrency(empTotal + erTotal)}</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: '12px 16px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 20 }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 8 }}>EMPLOYEE WITHHELD</div>
            {calc.lines.map((l, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '5px 0', fontSize: 12.5, borderTop: i === 0 ? 'none' : '1px solid var(--line)' }}>
                <span style={{ color: 'var(--text-2)' }}>{l.label}</span>
                <span className="mono" style={{ fontWeight: 600 }}>{A_fmtCurrency(l.amount)}</span>
              </div>
            ))}
          </div>
          <div>
            <div className="eyebrow" style={{ marginBottom: 8 }}>EMPLOYER CONTRIBUTION</div>
            {calc.employer.map((l, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '5px 0', fontSize: 12.5, borderTop: i === 0 ? 'none' : '1px solid var(--line)' }}>
                <span style={{ color: 'var(--text-2)' }}>{l.label}</span>
                <span className="mono" style={{ fontWeight: 600 }}>{A_fmtCurrency(l.amount)}</span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { RRBView });
