// view-integrations.jsx — Payroll & accounting platform connections + export
// formats. Connect/disconnect, set primary, and one-click export the current
// run in the right format for any target.

function IntegrationsView() {
  const { integrations, payrollRuns, toast, timecards, employees, jobs, taxPolicy, ytdGross, launchDoc } = useAdmin();
  const [active, setActive] = useState(null);
  const [pushProvider, setPushProvider] = useState(null);

  // Build payroll rows from billable cards for real exports
  const runRows = (() => {
    const byEmp = {};
    timecards.filter(t => t.status === 'approved' || t.status === 'pending-acct').forEach(t => {
      const e = employees.find(x => x.id === t.employeeId); if (!e) return;
      byEmp[e.id] = byEmp[e.id] || { name: e.name, badge: e.badge, resident: e.resident, reg: 0, ot: 0, gross: 0, job: (jobs.find(j => j.id === t.jobId) || {}).id, payDate: '2026-06-05' };
      byEmp[e.id].reg += t.regular; byEmp[e.id].ot += t.overtime;
      byEmp[e.id].gross += t.regular * e.baseRate + t.overtime * e.baseRate * 1.5;
    });
    return Object.values(byEmp);
  })();
  const period = '2026-05-18 — 2026-05-31';
  const doExport = (fmt) => {
    if (fmt === 'ADP API') { setPushProvider('adp-run'); return; }
    if (fmt === 'CSV') { const c = buildPayrollCSV(runRows, period); launchDoc({ kind: 'csvpreview', title: 'Payroll Register (CSV)', subtitle: period, payload: { content: c, note: 'One row per employee · import to any system.' }, file: { filename: 'payroll-register.csv', content: c, mime: 'text/csv' } }); }
    else if (fmt === 'IIF file') { const c = buildPayrollIIF(runRows, period); launchDoc({ kind: 'csvpreview', title: 'QuickBooks IIF Export', subtitle: period, payload: { content: c, note: 'Tab-delimited IIF · File → Utilities → Import in QuickBooks Desktop.' }, file: { filename: 'payroll.iif', content: c, mime: 'text/plain' } }); }
    else toast(`Exported pay period as ${fmt}`, 'success');
  };

  const payroll = integrations.filter(i => i.kind === 'payroll');
  const gl = integrations.filter(i => i.kind === 'gl');
  const exports = integrations.filter(i => i.kind === 'export');

  const connectedCount = integrations.filter(i => i.status === 'connected').length;

  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
        <KPI label="Connected" value={connectedCount} sub={`of ${integrations.length}`} tone="good" icon={<IconPlug size={16} />} />
        <KPI label="Primary payroll" value="ADP RUN" tone="dark" icon={<IconDollar size={16} />} footer="Bi-weekly · API" />
        <KPI label="Last sync" value="06:00" sub="today" icon={<IconRefresh size={16} />} footer="All systems current" />
        <KPI label="Export formats" value="API · CSV · IIF" tone="neutral" icon={<IconDownload size={16} />} />
      </div>

      {/* Quick export of current run */}
      <AdminSection title="Export current pay period">
        <div style={{
          background: '#0F172A', borderRadius: 14, padding: '18px 20px', color: '#fff',
          display: 'flex', alignItems: 'center', gap: 20, flexWrap: 'wrap',
        }}>
          <div style={{ flex: 1, minWidth: 200 }}>
            <div className="eyebrow" style={{ color: 'rgba(255,255,255,0.6)' }}>READY TO EXPORT</div>
            <div style={{ fontSize: 18, fontWeight: 700, marginTop: 4 }}>Period 05-18 → 05-31 · approved cards</div>
            <div style={{ fontSize: 12.5, color: 'rgba(255,255,255,0.6)', marginTop: 2 }}>
              Includes multi-state allocation, RRTA/FICA splits, OT, and GL account mapping.
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            {['ADP API', 'QuickBooks', 'IIF file', 'CSV', 'JSON / Webhook'].map(fmt => (
              <button key={fmt} onClick={() => doExport(fmt)} style={{
                background: 'rgba(255,255,255,0.10)', border: '1px solid rgba(255,255,255,0.18)',
                color: '#fff', padding: '8px 14px', borderRadius: 9, fontSize: 13, fontWeight: 600,
                display: 'inline-flex', alignItems: 'center', gap: 6,
              }}>
                <IconDownload size={13} /> {fmt}
              </button>
            ))}
          </div>
        </div>
      </AdminSection>

      <AdminSection title="Payroll systems">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          {payroll.map(i => <IntegrationCard key={i.id} integ={i} onClick={() => setActive(i)} />)}
        </div>
      </AdminSection>

      <AdminSection title="General ledger / accounting">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          {gl.map(i => <IntegrationCard key={i.id} integ={i} onClick={() => setActive(i)} />)}
        </div>
      </AdminSection>

      <AdminSection title="Generic export">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
          {exports.map(i => <IntegrationCard key={i.id} integ={i} onClick={() => setActive(i)} />)}
        </div>
      </AdminSection>

      {/* Connection drawer */}
      <Drawer open={!!active} onClose={() => setActive(null)}
        eyebrow={active?.kind === 'payroll' ? 'PAYROLL SYSTEM' : active?.kind === 'gl' ? 'GENERAL LEDGER' : 'EXPORT'}
        title={active?.name || ''}
        footer={active && (
          <>
            <Button variant="secondary" onClick={() => setActive(null)}>Close</Button>
            {active.status === 'connected'
              ? (RFPpayroll.PROVIDERS[active.id]
                  ? <Button variant="primary" icon={<IconUpload size={14} />} onClick={() => { setPushProvider(active.id); setActive(null); }}>Push pay run</Button>
                  : <Button variant="primary" icon={<IconDownload size={14} />} onClick={() => { toast(`${active.name} export queued`, 'success'); setActive(null); }}>Export now</Button>)
              : <Button variant="primary" icon={<IconPlug size={14} />} onClick={() => { toast(`${active.name} connected`, 'success'); setActive(null); }}>Connect {active.name}</Button>}
          </>
        )}>
        {active && (
          <>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 20 }}>
              <div style={{ width: 52, height: 52, borderRadius: 12, background: 'var(--panel-3)', display: 'grid', placeItems: 'center', color: 'var(--text-2)' }}><IconPlug size={26} /></div>
              <div>
                <div style={{ fontWeight: 700, fontSize: 18 }}>{active.name}</div>
                <div style={{ fontSize: 13, color: 'var(--muted)' }}>{active.desc}</div>
              </div>
              <div style={{ marginLeft: 'auto' }}>
                {active.status === 'connected' ? <Pill tone="good"><IconCheck size={10} /> Connected</Pill> : <Pill tone="neutral">Available</Pill>}
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginBottom: 18 }}>
              <FieldStat label="Transport" value={active.format} />
              <FieldStat label="Last sync" value={active.lastSync ? (active.lastSync.length > 12 ? active.lastSync.slice(0, 16).replace('T', ' ') : active.lastSync) : 'Never'} />
            </div>

            <div className="eyebrow" style={{ marginBottom: 8 }}>WHAT GETS SENT</div>
            <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden' }}>
              {[
                ['Employee earnings', 'Regular, OT, per activity code (RFL F/T/M/A/L/V)'],
                ['Multi-state allocation', 'Per-state taxable wages + withholding'],
                ['RRTA / FICA', 'Tier I, Tier II, Medicare splits (EE + ER)'],
                ['GL mapping', 'Job-costed to project + client'],
                ['GPS / audit refs', 'Attached as memo lines'],
              ].map(([k, v], i) => (
                <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, padding: '10px 14px', borderTop: i === 0 ? 'none' : '1px solid var(--line)' }}>
                  <span style={{ fontSize: 13, fontWeight: 600 }}>{k}</span>
                  <span style={{ fontSize: 12, color: 'var(--muted)', textAlign: 'right', flex: 1 }}>{v}</span>
                </div>
              ))}
            </div>
          </>
        )}
      </Drawer>

      <PayrollPushModal open={!!pushProvider} providerId={pushProvider} onClose={() => setPushProvider(null)} />
    </>
  );
}

function IntegrationCard({ integ, onClick }) {
  const connected = integ.status === 'connected';
  return (
    <button onClick={onClick} style={{
      background: 'var(--panel)', border: `1px solid ${connected ? 'var(--good)' : 'var(--line)'}`,
      borderRadius: 12, padding: '16px 18px', textAlign: 'left', cursor: 'pointer',
      display: 'flex', flexDirection: 'column', gap: 10,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{
          width: 40, height: 40, borderRadius: 9,
          background: connected ? 'var(--good-soft)' : 'var(--panel-3)',
          color: connected ? 'var(--good)' : 'var(--text-2)',
          display: 'grid', placeItems: 'center',
        }}><IconPlug size={20} /></div>
        {integ.primary && <Pill tone="accent">Primary</Pill>}
        {connected && !integ.primary && <Pill tone="good"><IconCheck size={10} /> Connected</Pill>}
        {!connected && <Pill tone="neutral">Connect</Pill>}
      </div>
      <div>
        <div style={{ fontWeight: 700, fontSize: 14.5 }}>{integ.name}</div>
        <div style={{ fontSize: 12, color: 'var(--muted)', marginTop: 2, lineHeight: 1.4 }}>{integ.desc}</div>
      </div>
      <div className="mono" style={{ fontSize: 11, color: 'var(--muted-2)' }}>{integ.format}{integ.lastSync ? ` · synced ${typeof integ.lastSync === 'string' && integ.lastSync.includes('T') ? integ.lastSync.slice(5, 10) : integ.lastSync}` : ''}</div>
    </button>
  );
}

function FieldStat({ label, value }) {
  return (
    <div style={{ background: 'var(--panel-2)', border: '1px solid var(--line)', borderRadius: 10, padding: '10px 14px' }}>
      <div className="eyebrow" style={{ fontSize: 10 }}>{label}</div>
      <div className="mono" style={{ fontSize: 13.5, fontWeight: 600, marginTop: 3 }}>{value}</div>
    </div>
  );
}

Object.assign(window, { IntegrationsView });
