// view-developer.jsx — "API & Webhooks" workspace (the developer add-on) plus
// the Identity/Server status panels. Gated by the 'api-webhooks' entitlement.

function DeveloperView() {
  const [tab, setTab] = useState('keys');
  // Use subscription entitlement (Supabase-backed) with fallback to localStorage addon flag
  const enabled = (RFP.subscription && RFP.subscription.hasApiAddon()) || RFP.addon('api-webhooks');

  if (!enabled) {
    return (
      <>
        <PageHeader eyebrow="DEVELOPER · ADD-ON" title="API & Webhooks"
          subtitle="Outbound API and event webhooks to push data into a customer's own systems." />
        <PageBody>
          <AddonUpsell id="api-webhooks" name="Outbound API & Webhooks" price="+$240/mo"
            checkoutUrl="https://madethis.com/checkout/railflagging-pro/md7fazavewd0tpb5xp728macvd88c1xr"
            desc="REST API keys plus signed event webhooks (timecards, pay runs, invoices, compliance). For enterprise clients with their own data lake."
            bullets={['Scoped API keys with rotation', 'Subscribe to 10 event types', 'Signed payloads + delivery log with retries', 'OIDC-secured, same identity provider']} />
        </PageBody>
      </>
    );
  }

  return (
    <>
      <PageHeader eyebrow="DEVELOPER" title="API & Webhooks"
        subtitle="Programmatic access to RailFlagsPro. OAuth 2.0 / OIDC secured."
        right={<Pill tone="good"><StatusDot tone="good" size={6} pulse /> API operational</Pill>} />
      <div style={{ padding: '14px 32px 0', borderBottom: '1px solid var(--line)', background: 'var(--panel)', display: 'flex', gap: 4 }}>
        {[['keys', 'API keys'], ['webhooks', 'Webhooks'], ['events', 'Event log'], ['docs', 'API reference']].map(([id, label]) => {
          const on = tab === id;
          return <button key={id} onClick={() => setTab(id)} style={{ padding: '10px 14px', background: 'transparent', border: 'none', borderBottom: on ? '2px solid var(--accent)' : '2px solid transparent', marginBottom: -1, color: on ? 'var(--text)' : 'var(--muted)', fontWeight: on ? 600 : 500, fontSize: 13.5 }}>{label}</button>;
        })}
      </div>
      <PageBody>
        {tab === 'keys' && <ApiKeysTab />}
        {tab === 'webhooks' && <WebhooksTab />}
        {tab === 'events' && <EventLogTab />}
        {tab === 'docs' && <ApiDocsTab />}
      </PageBody>
    </>
  );
}

function AddonUpsell({ id, name, price, desc, bullets, checkoutUrl }) {
  return (
    <div style={{ maxWidth: 620, margin: '20px auto', textAlign: 'center' }}>
      <div style={{ width: 60, height: 60, borderRadius: 15, background: 'var(--accent-soft)', color: 'var(--accent-deep)', display: 'grid', placeItems: 'center', margin: '0 auto 18px' }}><IconPlug size={28} /></div>
      <div className="eyebrow" style={{ marginBottom: 6 }}>OPTIONAL ADD-ON · {price}</div>
      <div style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.5, marginBottom: 8 }}>{name} isn't enabled</div>
      <div style={{ fontSize: 14, color: 'var(--muted)', lineHeight: 1.6, marginBottom: 18 }}>{desc}</div>
      <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: 18, textAlign: 'left', marginBottom: 18 }}>
        {bullets.map(b => <div key={b} style={{ display: 'flex', gap: 10, padding: '5px 0', fontSize: 13.5 }}><IconCheck size={15} style={{ color: 'var(--good)', flexShrink: 0, marginTop: 2 }} /> {b}</div>)}
      </div>
      {checkoutUrl ? (
        <a href={checkoutUrl} target="_blank" rel="noopener noreferrer" style={{ display: 'inline-block', padding: '11px 24px', background: 'var(--accent)', color: '#fff', borderRadius: 9, fontWeight: 700, fontSize: 14, textDecoration: 'none', marginBottom: 12 }}>
          Add {name} — {price}
        </a>
      ) : (
        <div style={{ fontSize: 12.5, color: 'var(--muted)' }}>Enable in System → Company config → Add-on modules.</div>
      )}
    </div>
  );
}

// ── API keys ─────────────────────────────────────────────────
function ApiKeysTab() {
  const { toast } = useAdmin();
  const [keys, setKeys] = useState(() => RFP.webhooks.listKeys());
  const [reveal, setReveal] = useState(null);
  const create = () => { const k = RFP.webhooks.createKey('Production key', ['read', 'write']); setKeys(RFP.webhooks.listKeys()); setReveal(k.id); toast('API key created — copy the secret now', 'success'); };
  const revoke = (id) => { RFP.webhooks.revokeKey(id); setKeys(RFP.webhooks.listKeys()); toast('Key revoked', 'info'); };
  return (
    <>
      <AdminSection title="API keys" action={<Button variant="primary" size="sm" icon={<IconPlus size={12} />} onClick={create}>Create key</Button>}>
        {keys.length === 0 && <div style={{ background: 'var(--panel)', border: '1px dashed var(--line-strong)', borderRadius: 12, padding: 28, textAlign: 'center', color: 'var(--muted)' }}>No API keys yet. Create one to start making requests.</div>}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {keys.map(k => (
            <div key={k.id} style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 14, opacity: k.status === 'revoked' ? 0.55 : 1 }}>
              <div style={{ width: 38, height: 38, borderRadius: 9, background: 'var(--panel-3)', display: 'grid', placeItems: 'center', color: 'var(--muted)' }}><IconSettings size={18} /></div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600, fontSize: 14 }}>{k.label}</div>
                <div className="mono" style={{ fontSize: 12, color: 'var(--muted)' }}>{reveal === k.id ? k.secret : k.prefix + '••••••••••••••••'}</div>
              </div>
              <div style={{ display: 'flex', gap: 4 }}>{k.scopes.map(s => <Pill key={s} tone="neutral">{s}</Pill>)}</div>
              {k.status === 'active' ? <Pill tone="good">active</Pill> : <Pill tone="bad">revoked</Pill>}
              {k.status === 'active' && <Button variant="secondary" size="sm" onClick={() => revoke(k.id)}>Revoke</Button>}
            </div>
          ))}
        </div>
      </AdminSection>
      <div style={{ background: 'var(--info-soft)', border: '1px solid rgba(29,111,184,0.25)', borderRadius: 10, padding: '12px 16px', fontSize: 12.5, color: 'var(--info)' }}>
        <b>Authentication:</b> send <span className="mono">Authorization: Bearer &lt;access_token&gt;</span> from the OAuth token endpoint, or <span className="mono">X-API-Key: &lt;secret&gt;</span> for server-to-server. All requests are logged.
      </div>
    </>
  );
}

// ── Webhooks ─────────────────────────────────────────────────
function WebhooksTab() {
  const { toast } = useAdmin();
  const [hooks, setHooks] = useState(() => RFP.webhooks.listWebhooks());
  const [url, setUrl] = useState('https://hooks.bnsf.com/railflagspro');
  const [sel, setSel] = useState(['timecard.approved', 'payrun.accepted', 'invoice.posted']);
  const add = () => { if (!url) return; RFP.webhooks.addWebhook(url, sel); setHooks(RFP.webhooks.listWebhooks()); toast('Webhook endpoint added', 'success'); };
  const toggle = (id) => { RFP.webhooks.toggleWebhook(id); setHooks(RFP.webhooks.listWebhooks()); };
  const del = (id) => { RFP.webhooks.deleteWebhook(id); setHooks(RFP.webhooks.listWebhooks()); toast('Webhook removed', 'info'); };
  const test = (h) => { const r = RFP.webhooks.emit(h.events[0] || 'invoice.posted', { test: true }); toast(`Test event sent · ${r.delivered} delivered`, 'success'); };
  return (
    <>
      <AdminSection title="Add endpoint">
        <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: 16 }}>
          <div style={{ display: 'flex', gap: 10, marginBottom: 12 }}>
            <input value={url} onChange={e => setUrl(e.target.value)} placeholder="https://your-system.com/webhook" style={{ flex: 1, padding: '9px 12px', border: '1px solid var(--line-strong)', borderRadius: 9, fontSize: 13.5, fontFamily: 'var(--font-mono)' }} />
            <Button variant="primary" icon={<IconPlus size={14} />} onClick={add}>Add</Button>
          </div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {RFP.webhooks.EVENT_TYPES.map(ev => {
              const on = sel.includes(ev);
              return <button key={ev} onClick={() => setSel(s => on ? s.filter(x => x !== ev) : [...s, ev])} style={{ padding: '5px 11px', borderRadius: 100, border: `1px solid ${on ? 'var(--accent)' : 'var(--line)'}`, background: on ? 'var(--accent-soft)' : 'var(--panel)', color: on ? 'var(--accent-deep)' : 'var(--muted)', fontSize: 11.5, fontWeight: 600, fontFamily: 'var(--font-mono)', cursor: 'pointer' }}>{ev}</button>;
            })}
          </div>
        </div>
      </AdminSection>
      <AdminSection title="Endpoints">
        {hooks.length === 0 && <div style={{ color: 'var(--muted)', fontSize: 13 }}>No endpoints configured.</div>}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {hooks.map(h => (
            <div key={h.id} style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: '14px 16px' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 8 }}>
                <StatusDot tone={h.status === 'active' ? 'good' : 'muted'} size={8} pulse={h.status === 'active'} />
                <span className="mono" style={{ flex: 1, fontSize: 13, fontWeight: 600 }}>{h.url}</span>
                <Button variant="ghost" size="sm" onClick={() => test(h)}>Send test</Button>
                <Button variant="ghost" size="sm" onClick={() => toggle(h.id)}>{h.status === 'active' ? 'Pause' : 'Resume'}</Button>
                <Button variant="ghost" size="sm" onClick={() => del(h.id)}>Delete</Button>
              </div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 5 }}>{h.events.map(e => <Pill key={e} tone="neutral">{e}</Pill>)}</div>
              <div className="mono" style={{ fontSize: 11, color: 'var(--muted-2)', marginTop: 8 }}>Signing secret: {h.secret.slice(0, 16)}••••</div>
            </div>
          ))}
        </div>
      </AdminSection>
    </>
  );
}

// ── Event/delivery log ───────────────────────────────────────
function EventLogTab() {
  const { toast } = useAdmin();
  const [, force] = useState(0);
  const deliveries = RFP.webhooks.listDeliveries();
  const events = RFP.webhooks.listEvents();
  const redeliver = (id) => { RFP.webhooks.redeliver(id); toast('Redelivered', 'success'); force(x => x + 1); };
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
      <div>
        <AdminSection title={`Recent events (${events.length})`}>
          <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden', maxHeight: 480, overflowY: 'auto' }}>
            {events.length === 0 && <div style={{ padding: 24, textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>No events emitted yet.</div>}
            {events.map((e, i) => (
              <div key={e.id} style={{ padding: '10px 14px', borderTop: i === 0 ? 'none' : '1px solid var(--line)' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: 'var(--accent-deep)' }}>{e.type}</span>
                  <span className="mono" style={{ fontSize: 11, color: 'var(--muted-2)' }}>{new Date(e.at).toLocaleTimeString('en-US', { hour12: false })}</span>
                </div>
                <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)', marginTop: 2 }}>{e.id}</div>
              </div>
            ))}
          </div>
        </AdminSection>
      </div>
      <div>
        <AdminSection title={`Deliveries (${deliveries.length})`}>
          <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden', maxHeight: 480, overflowY: 'auto' }}>
            {deliveries.length === 0 && <div style={{ padding: 24, textAlign: 'center', color: 'var(--muted)', fontSize: 13 }}>No deliveries yet. Add a webhook and emit an event.</div>}
            {deliveries.map((d, i) => (
              <div key={d.id} style={{ padding: '10px 14px', borderTop: i === 0 ? 'none' : '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 10 }}>
                {d.status === 'delivered' ? <IconCheckCircle size={15} style={{ color: 'var(--good)' }} /> : <IconAlert size={15} style={{ color: 'var(--bad)' }} />}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div className="mono" style={{ fontSize: 11.5, fontWeight: 600 }}>{d.type}</div>
                  <div className="mono" style={{ fontSize: 10.5, color: 'var(--muted)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{d.url}</div>
                </div>
                <span className="mono" style={{ fontSize: 11, fontWeight: 700, color: d.responseCode === 200 ? 'var(--good)' : 'var(--bad)' }}>{d.responseCode}</span>
                <span className="mono" style={{ fontSize: 10.5, color: 'var(--muted-2)' }}>{d.ms}ms</span>
                {d.status === 'failed' && <button onClick={() => redeliver(d.id)} style={{ background: 'none', border: 'none', color: 'var(--accent-deep)', fontWeight: 600, fontSize: 11.5, cursor: 'pointer' }}>Retry</button>}
              </div>
            ))}
          </div>
        </AdminSection>
      </div>
    </div>
  );
}

// ── API reference ────────────────────────────────────────────
function ApiDocsTab() {
  const cfg = RFP.idp.config();
  const endpoints = [
    ['GET', '/v1/health', 'Service health check'],
    ['POST', '/oauth/token', 'Exchange credentials for an access token'],
    ['GET', '/userinfo', 'OIDC userinfo for the bearer token'],
    ['GET', '/v1/accounts', 'List identity-directory accounts'],
    ['POST', '/v1/accounts', 'Create an account'],
    ['PATCH', '/v1/accounts/:id', 'Update an account'],
    ['GET', '/v1/payruns', 'List payroll runs'],
  ];
  const mtone = { GET: 'info', POST: 'good', PATCH: 'warn', DELETE: 'bad' };
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 18 }}>
      <AdminSection title="Endpoints">
        <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden' }}>
          {endpoints.map(([m, p, d], i) => (
            <div key={p + m} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 16px', borderTop: i === 0 ? 'none' : '1px solid var(--line)' }}>
              <span style={{ minWidth: 56 }}><Pill tone={mtone[m]}>{m}</Pill></span>
              <span className="mono" style={{ flex: 1, fontSize: 12.5, fontWeight: 600 }}>{p}</span>
              <span style={{ fontSize: 12, color: 'var(--muted)' }}>{d}</span>
            </div>
          ))}
        </div>
        <div style={{ marginTop: 14 }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>EXAMPLE REQUEST</div>
          <pre className="mono" style={{ background: '#0F172A', color: '#e2e8f0', padding: 16, borderRadius: 10, fontSize: 11.5, overflow: 'auto', lineHeight: 1.6, margin: 0 }}>{`curl -X POST https://api.railflagspro.com/oauth/token \\
  -d grant_type=password \\
  -d username=svc@bnsf.com \\
  -d password=•••• \\
  -d scope="openid compliance"

# → { "access_token": "eyJ…", "token_type": "Bearer",
#     "expires_in": 86400, "id_token": "eyJ…" }`}</pre>
        </div>
      </AdminSection>
      <AdminSection title="OIDC discovery">
        <div style={{ background: 'var(--panel)', border: '1px solid var(--line)', borderRadius: 12, padding: 16 }}>
          <div className="eyebrow" style={{ marginBottom: 8 }}>/.well-known/openid-configuration</div>
          {[['issuer', cfg.issuer], ['token', cfg.token_endpoint], ['userinfo', cfg.userinfo_endpoint], ['jwks', cfg.jwks_uri]].map(([k, v]) => (
            <div key={k} style={{ marginBottom: 8 }}>
              <div style={{ fontSize: 11, color: 'var(--muted)', fontWeight: 600 }}>{k}</div>
              <div className="mono" style={{ fontSize: 11.5, wordBreak: 'break-all' }}>{v}</div>
            </div>
          ))}
          <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--line)', display: 'flex', flexWrap: 'wrap', gap: 5 }}>
            {cfg.grant_types_supported.map(g => <Pill key={g} tone="neutral">{g}</Pill>)}
          </div>
        </div>
      </AdminSection>
    </div>
  );
}

Object.assign(window, { DeveloperView, AddonUpsell });
