/* Integrations — Webhooks subscriptions + Global API keys (Admin-only surfaces).
   Specs: monolith-docs/webhooks/webhooks-prd.md, monolith-docs/api-module/api-module-prd.md */
const { useState: useStateIN } = React;

const WH_STATUS = {
  active:                 { label: 'Active',        cls: 'wh-active',   icon: 'check' },
  disabled_manually:      { label: 'Disabled',      cls: 'wh-disabled', icon: 'pause' },
  disabled_auto_failures: { label: 'Auto-disabled', cls: 'wh-disabled', icon: 'alert-triangle' },
  revoked:                { label: 'Revoked',       cls: 'wh-revoked',  icon: 'ban' },
};

function NoAccess({ surface }) {
  return (
    <React.Fragment>
      <div className="mn-page-h">
        <div className="mn-page-title"><h1 className="title-1">{surface}</h1></div>
      </div>
      <div className="mn-empty" style={{ paddingTop: 120 }}>
        <Icon name="lock" size="lg" />
        <div className="mn-empty-msg">You don’t have permission to manage {surface.toLowerCase()}.</div>
        <div style={{ font: 'var(--font-weight-medium) 12px/16px var(--font-sans)', color: 'var(--text-3)' }}>
          Requires the Admin role ({surface === 'Webhooks' ? 'manage_webhooks' : 'manage_api_keys'}).
        </div>
      </div>
    </React.Fragment>
  );
}

/* ===== Webhooks ============================================================ */
function Webhooks({ role, onToast }) {
  const D = window.MonolitData;
  const [openSub, setOpenSub] = useStateIN('whsub_9f2a');
  const [form, setForm] = useStateIN(false);
  const [secret, setSecret] = useStateIN(null);
  if (!window.MonolitRBAC.can(role, 'webhooks.manage')) return <NoAccess surface="Webhooks" />;
  const deliveries = D.webhookDeliveries.filter(d => d.sub === openSub);
  const sub = D.webhooks.find(w => w.id === openSub);

  return (
    <React.Fragment>
      <div className="mn-page-h">
        <div className="mn-page-title">
          <h1 className="title-1">Webhooks</h1>
          <span className="mn-page-count">{D.webhooks.filter(w => w.status === 'active').length} active</span>
        </div>
        <div className="mn-page-actions">
          <Button variant="ghost" size="md" icon="book-open">Event taxonomy</Button>
          <Button variant="primary" size="md" icon="plus" onClick={() => setForm(true)}>New subscription</Button>
        </div>
      </div>
      {form ? <WebhookForm onClose={() => setForm(false)} onCreated={() => { setForm(false); setSecret('whsec_' + Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 10)); }} /> : null}
      {secret ? <SecretOnceModal kind="webhook" value={secret} onClose={() => { setSecret(null); onToast && onToast('Webhook subscription created'); }} /> : null}

      <div className="mn-stack-lg" style={{ paddingTop: 4 }}>
        <Card title="Subscriptions" eyebrow="Push events to your receivers · HMAC-SHA256 signed" padding="md">
          <table className="mn-table" style={{ marginTop: -4 }}>
            <thead>
              <tr>
                <th>Name</th><th>Events</th><th style={{ width: 130 }}>Status</th>
                <th style={{ width: 130 }}>Last delivery</th><th style={{ width: 170 }}>7d ok / fail</th><th style={{ width: 36 }}></th>
              </tr>
            </thead>
            <tbody>
              {D.webhooks.map((w) => {
                const st = WH_STATUS[w.status];
                return (
                  <tr key={w.id} className={'mn-row--clickable' + (openSub === w.id ? ' mn-row--selected' : '')}
                      onClick={(e) => { if (e.target.closest('button')) return; setOpenSub(w.id); }}>
                    <td>
                      <div className="mn-cell-name-text">
                        <strong>{w.name}</strong>
                        <span className="mn-mono" style={{ fontSize: 11 }}>{w.id} · {w.url}</span>
                      </div>
                    </td>
                    <td>
                      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                        {w.events.map(ev => <span key={ev} className="mn-chip mn-chip--tag" style={{ fontFamily: 'var(--font-mono)' }}>{ev}</span>)}
                      </div>
                    </td>
                    <td><span className={`mn-chip mn-chip--${st.cls}`}><Icon name={st.icon} size="xs" stroke="2" />{st.label}</span></td>
                    <td><span className="mn-mono" style={{ fontSize: 12, color: 'var(--text-3)' }}>{w.lastDelivery}</span></td>
                    <td>
                      <span className="mn-mono" style={{ fontSize: 12 }}>
                        <span style={{ color: 'var(--success-main)' }}>{w.counts.d7.ok.toLocaleString('en-GB')}</span>
                        <span style={{ color: 'var(--text-3)' }}> / </span>
                        <span style={{ color: w.counts.d7.fail > 0 ? 'var(--error-main)' : 'var(--text-3)' }}>{w.counts.d7.fail}</span>
                      </span>
                    </td>
                    <td onClick={(e) => e.stopPropagation()}><IconButton icon="more-horizontal" size="sm" title="Edit · Disable · Revoke" /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
          {D.webhooks.some(w => w.status === 'disabled_auto_failures') ? (
            <div className="mn-robanner" style={{ marginTop: 12, marginBottom: 0 }}>
              <Icon name="alert-triangle" size="sm" />
              “Legacy ERP bridge” was auto-disabled after 100 consecutive failed deliveries. Fix the receiver and re-enable it.
            </div>
          ) : null}
        </Card>

        <Card title={`Delivery log — ${sub ? sub.name : ''}`} eyebrow="90-day retention · at-least-once · retries at 1 / 5 / 30 min" padding="md">
          {deliveries.length > 0 ? (
            <table className="mn-table" style={{ marginTop: -4 }}>
              <thead>
                <tr><th style={{ width: 110 }}>Delivery</th><th>Event</th><th style={{ width: 120 }}>Status</th><th style={{ width: 90 }}>HTTP</th><th style={{ width: 100 }}>Latency</th><th style={{ width: 90 }}>Attempt</th><th style={{ width: 110 }}>When</th></tr>
              </thead>
              <tbody>
                {deliveries.map((d) => (
                  <tr key={d.id}>
                    <td><span className="mn-mono" style={{ fontSize: 12, color: 'var(--text-3)' }}>{d.id}</span></td>
                    <td><span className="mn-mono" style={{ fontSize: 12, color: 'var(--text-2)' }}>{d.event}</span></td>
                    <td><span className={`mn-chip mn-chip--dlv-${d.status}`}>{d.status}</span></td>
                    <td><span className="mn-mono" style={{ fontSize: 12, color: d.code >= 400 ? 'var(--error-main)' : 'var(--text-2)' }}>{d.code || '—'}</span></td>
                    <td><span className="mn-mono" style={{ fontSize: 12, color: 'var(--text-3)' }}>{d.ms != null ? `${d.ms} ms` : '—'}</span></td>
                    <td><span className="mn-mono" style={{ fontSize: 12, color: 'var(--text-3)' }}>{d.attempt} of 4</span></td>
                    <td><span className="mn-mono" style={{ fontSize: 12, color: 'var(--text-3)' }}>{d.at}</span></td>
                  </tr>
                ))}
              </tbody>
            </table>
          ) : (
            <div className="mn-empty" style={{ padding: 24 }}>
              <Icon name="inbox" size="lg" />
              <div className="mn-empty-msg">No deliveries for this subscription yet.</div>
            </div>
          )}
        </Card>
      </div>
    </React.Fragment>
  );
}

/* ===== API keys ============================================================ */
function ApiKeys({ role, onToast }) {
  const D = window.MonolitData;
  const [form, setForm] = useStateIN(false);
  const [secret, setSecret] = useStateIN(null);
  if (!window.MonolitRBAC.can(role, 'api_keys.manage')) return <NoAccess surface="API keys" />;

  return (
    <React.Fragment>
      <div className="mn-page-h">
        <div className="mn-page-title">
          <h1 className="title-1">API keys</h1>
          <span className="mn-page-count">{D.apiKeys.filter(k => k.status === 'active').length} of 25 (Growth plan)</span>
        </div>
        <div className="mn-page-actions">
          <Button variant="ghost" size="md" icon="book-open">API reference</Button>
          <Button variant="primary" size="md" icon="plus" onClick={() => setForm(true)}>Create key</Button>
        </div>
      </div>
      {form ? <ApiKeyForm onClose={() => setForm(false)} onCreated={() => { setForm(false); setSecret('key_' + Math.random().toString(36).slice(2, 8) + '…' + Math.random().toString(36).slice(2, 6)); }} /> : null}
      {secret ? <SecretOnceModal kind="apikey" value={secret} onClose={() => { setSecret(null); onToast && onToast('API key created'); }} /> : null}

      <div className="mn-stack-lg" style={{ paddingTop: 4 }}>
        <Card title="Keys" eyebrow="Read-only v1 · role-scoped · IP allowlist mandatory · secret shown once" padding="md">
          <table className="mn-table" style={{ marginTop: -4 }}>
            <thead>
              <tr>
                <th>Name</th><th style={{ width: 120 }}>Key ID</th><th style={{ width: 120 }}>Inherits role</th>
                <th>IP allowlist</th><th style={{ width: 120 }}>Requests 24h</th>
                <th style={{ width: 110 }}>Last used</th><th style={{ width: 110 }}>Status</th><th style={{ width: 36 }}></th>
              </tr>
            </thead>
            <tbody>
              {D.apiKeys.map((k) => (
                <tr key={k.id}>
                  <td>
                    <div className="mn-cell-name-text">
                      <strong>{k.name}</strong>
                      <span style={{ fontSize: 11 }}>{k.rateTier} · by {k.createdBy}</span>
                    </div>
                  </td>
                  <td><span className="mn-mono" style={{ fontSize: 12, color: 'var(--text-2)' }}>{k.id}</span></td>
                  <td><span className="mn-chip mn-chip--neutral">{k.role}</span></td>
                  <td>
                    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                      {k.ips.map(ip => <span key={ip} className="mn-chip mn-chip--tag" style={{ fontFamily: 'var(--font-mono)' }}>{ip}</span>)}
                    </div>
                  </td>
                  <td><span className="mn-mono" style={{ fontSize: 12 }}>{k.counts.d1.toLocaleString('en-GB')}</span></td>
                  <td><span className="mn-mono" style={{ fontSize: 12, color: 'var(--text-3)' }}>{k.lastUsed}</span></td>
                  <td>
                    <span className={`mn-chip mn-chip--${k.status === 'active' ? 'wh-active' : 'wh-revoked'}`}>
                      <Icon name={k.status === 'active' ? 'check' : 'ban'} size="xs" stroke="2" />{k.status}
                    </span>
                  </td>
                  <td><IconButton icon="more-horizontal" size="sm" title="Edit · Revoke" /></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>

        <Card title="Authentication" eyebrow="Two headers on every HTTPS request" padding="md">
          <pre className="mn-mono" style={{ margin: 0, padding: 12, background: 'var(--bg-2)', borderRadius: 'var(--radi-sm)', fontSize: 12, lineHeight: '20px', color: 'var(--text-2)', overflow: 'auto' }}>
{`GET /api/v1/clients?view=my&business_status=prospect
X-API-Key:    key_2f8c…a8f2
X-API-Secret: ••••••••••••••••••••••••  (shown once at creation)`}
          </pre>
        </Card>
      </div>
    </React.Fragment>
  );
}

function WebhookForm({ onClose, onCreated }) {
  const D = window.MonolitData;
  const [name, setName] = useStateIN('');
  const [url, setUrl] = useStateIN('https://');
  const [events, setEvents] = useStateIN(['lead.created']);
  const [touched, setTouched] = useStateIN(false);
  const urlOk = /^https:\/\/.+/.test(url);
  const valid = name.trim().length >= 2 && urlOk && events.length > 0;
  function toggleEvent(e) { setEvents(s => s.includes(e) ? s.filter(x => x !== e) : [...s, e]); }
  const footer = <React.Fragment>
    <Button variant="ghost" size="md" onClick={onClose}>Cancel</Button>
    <Button variant="primary" size="md" icon="check" disabled={touched && !valid} onClick={() => { setTouched(true); if (valid) onCreated(); }}>Create subscription</Button>
  </React.Fragment>;
  return (
    <Modal open onClose={onClose} size="md" icon="webhook" iconTone="primary" eyebrow="Webhooks" title="New subscription" subtitle="HTTPS-only · HMAC-SHA256 signed · at-least-once delivery" footer={footer}>
      <div className="mn-form-grid">
        <div className="mn-col-2"><Field label="Name" required error={touched && name.trim().length < 2 ? 'Min. 2 characters' : undefined}><Input fullWidth value={name} onChange={setName} placeholder="Data warehouse sync" autoFocus /></Field></div>
        <div className="mn-col-2"><Field label="Endpoint URL" required error={touched && !urlOk ? 'Must be a valid https:// URL' : undefined}><Input fullWidth icon="link" value={url} onChange={setUrl} placeholder="https://hooks.example.com/…" /></Field></div>
        <div className="mn-col-2"><Field label="Events" required error={touched && !events.length ? 'Pick at least one event' : undefined}>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {D.webhookEvents.map(ev => (
              <button key={ev} type="button" onClick={() => toggleEvent(ev)} className={'mn-chip mn-chip--tag mn-chip--btn' + (events.includes(ev) ? ' mn-chip--wh-active' : '')} style={{ fontFamily: 'var(--font-mono)' }}>
                {events.includes(ev) ? <Icon name="check" size="xs" stroke="2" /> : null}{ev}
              </button>
            ))}
          </div>
        </Field></div>
      </div>
      <div className="mn-robanner" style={{ marginTop: 14, marginBottom: 0, background: 'var(--bg-2)', color: 'var(--text-3)', borderColor: 'var(--border-1)' }}>
        <Icon name="shield" size="sm" />Auto-disables after 100 consecutive failures · retries at 1 / 5 / 30 min · 90-day delivery log.
      </div>
    </Modal>
  );
}

function ApiKeyForm({ onClose, onCreated }) {
  const [name, setName] = useStateIN('');
  const [keyRole, setKeyRole] = useStateIN('Viewer');
  const [ips, setIps] = useStateIN([]);
  const [touched, setTouched] = useStateIN(false);
  const valid = name.trim().length >= 2 && ips.length > 0;
  const footer = <React.Fragment>
    <Button variant="ghost" size="md" onClick={onClose}>Cancel</Button>
    <Button variant="primary" size="md" icon="check" disabled={touched && !valid} onClick={() => { setTouched(true); if (valid) onCreated(); }}>Create key</Button>
  </React.Fragment>;
  return (
    <Modal open onClose={onClose} size="md" icon="key-round" iconTone="primary" eyebrow="API keys" title="Create API key" subtitle="Read-only v1 · inherits a role · IP allowlist mandatory" footer={footer}>
      <div className="mn-form-grid">
        <div className="mn-col-2"><Field label="Name" required error={touched && name.trim().length < 2 ? 'Min. 2 characters' : undefined}><Input fullWidth value={name} onChange={setName} placeholder="BI warehouse reader" autoFocus /></Field></div>
        <Field label="Inherits role" hint="Scopes what the key can read"><Select fullWidth value={keyRole} onChange={setKeyRole} options={window.MonolitRBAC.ROLES} /></Field>
        <Field label="Rate tier"><Input fullWidth value="Growth · 300 rpm" disabled /></Field>
        <div className="mn-col-2"><Field label="IP allowlist" required error={touched && !ips.length ? 'At least one IP / CIDR is required' : undefined}>
          <TagInput tags={ips} onChange={setIps} suggestions={['52.18.92.0/24', '203.0.113.40', '198.51.100.0/28']} placeholder="Add IP or CIDR…" />
        </Field></div>
      </div>
    </Modal>
  );
}

function SecretOnceModal({ kind, value, onClose }) {
  // Generate the secret once so it stays stable across re-renders and Copy grabs the shown value.
  const [secret] = useStateIN(() => 'sk_live_' + Math.random().toString(36).slice(2, 18));
  const [copied, setCopied] = useStateIN('');
  const copy = (which, txt) => { try { if (navigator.clipboard) navigator.clipboard.writeText(txt); } catch (e) {} setCopied(which); };
  const footer = <Button variant="primary" size="md" icon="check" onClick={onClose}>I’ve copied it — done</Button>;
  return (
    <Modal open onClose={onClose} dismissable={false} size="md" icon="key-round" iconTone="warning" eyebrow="Shown once" title={kind === 'apikey' ? 'API key created' : 'Signing secret created'} subtitle="Copy it now — it will never be shown again." footer={footer}>
      <div className="mn-form-sec" style={{ marginBottom: 0 }}>
        <Field label={kind === 'apikey' ? 'Key ID' : 'Webhook secret'}>
          <div className="mn-row" style={{ gap: 8 }}>
            <Input fullWidth value={value} />
            <Button variant="ghost" size="md" icon={copied === 'id' ? 'check' : 'copy'} onClick={() => copy('id', value)}>{copied === 'id' ? 'Copied' : 'Copy'}</Button>
          </div>
        </Field>
        {kind === 'apikey' ? (
          <div style={{ marginTop: 12 }}>
            <Field label="Secret (X-API-Secret)">
              <div className="mn-row" style={{ gap: 8 }}>
                <Input fullWidth value={secret} />
                <Button variant="ghost" size="md" icon={copied === 'secret' ? 'check' : 'copy'} onClick={() => copy('secret', secret)}>{copied === 'secret' ? 'Copied' : 'Copy'}</Button>
              </div>
            </Field>
          </div>
        ) : null}
        <div className="mn-robanner" style={{ marginTop: 14, marginBottom: 0 }}>
          <Icon name="alert-triangle" size="sm" />Store this securely. For your protection we can’t display it again — you’d need to rotate the {kind === 'apikey' ? 'key' : 'secret'}.
        </div>
      </div>
    </Modal>
  );
}

Object.assign(window, { Webhooks, ApiKeys });