// SCREEN: Partner API
// Manage webhook subscriptions, Python SDK quickstart, delivery log

// ---------------------------------------------------------------------------
// MOCK DATA
// ---------------------------------------------------------------------------
const PARTNER_MOCK = {
  apiKey: 'pk_live_•••••••••••••••••••••••••••••••••',
  apiKeyReal: 'pk_live_a7b3c9d1e5f2g8h4i0j6k2l3m9n5o1p7',
  stats: {
    activeWebhooks: 3,
    deliveries24h: 847,
    successRate: 99.2,
    avgLatency: 124,
  },
  webhooks: [
    {
      id: 'wh_001',
      url: 'https://hooks.zapier.com/hooks/catch/abc123/xyz',
      events: ['decision.created', 'anomaly.detected'],
      status: 'active',
      lastDelivery: { time: '2h ago', code: 200 },
      description: 'Zapier automation trigger',
    },
    {
      id: 'wh_002',
      url: 'https://api.partner.io/astrareach/events',
      events: ['decision.approved', 'decision.rejected'],
      status: 'active',
      lastDelivery: { time: '45m ago', code: 200 },
      description: 'Partner.io integration',
    },
    {
      id: 'wh_003',
      url: 'https://webhook.site/test123-abc-456-def',
      events: ['event.ingested'],
      status: 'disabled',
      lastDelivery: { time: '3d ago', code: 500 },
      description: 'Test endpoint (exhausted retries)',
    },
  ],
  deliveryLog: [
    { ts: '2026-05-04 14:32:01', event: 'decision.created',   endpoint: 'hooks.zapier.com/…',    code: 200, latency: 112, retries: 0 },
    { ts: '2026-05-04 14:18:44', event: 'anomaly.detected',   endpoint: 'hooks.zapier.com/…',    code: 200, latency: 98,  retries: 0 },
    { ts: '2026-05-04 14:02:11', event: 'decision.approved',  endpoint: 'api.partner.io/…',      code: 200, latency: 143, retries: 0 },
    { ts: '2026-05-04 13:51:33', event: 'decision.rejected',  endpoint: 'api.partner.io/…',      code: 200, latency: 131, retries: 0 },
    { ts: '2026-05-04 13:44:07', event: 'decision.created',   endpoint: 'hooks.zapier.com/…',    code: 200, latency: 104, retries: 0 },
    { ts: '2026-05-04 12:30:55', event: 'anomaly.detected',   endpoint: 'hooks.zapier.com/…',    code: 429, latency: 0,   retries: 2 },
    { ts: '2026-05-04 12:01:19', event: 'decision.approved',  endpoint: 'api.partner.io/…',      code: 200, latency: 156, retries: 0 },
    { ts: '2026-05-04 11:47:03', event: 'event.ingested',     endpoint: 'webhook.site/test123…', code: 500, latency: 0,   retries: 3 },
    { ts: '2026-05-04 11:20:44', event: 'decision.created',   endpoint: 'hooks.zapier.com/…',    code: 200, latency: 119, retries: 0 },
    { ts: '2026-05-04 10:55:28', event: 'actor.merged',       endpoint: 'api.partner.io/…',      code: 200, latency: 138, retries: 0 },
  ],
};

const ALL_WEBHOOK_EVENTS = [
  'decision.created',
  'decision.approved',
  'decision.rejected',
  'anomaly.detected',
  'journey.bottleneck',
  'event.ingested',
  'actor.merged',
];

// ---------------------------------------------------------------------------
// Sub-components
// ---------------------------------------------------------------------------

// Webhook status pill
const WebhookStatusPill = ({ status }) => {
  const map = {
    active:   { color: 'var(--emerald)', label: '● Active' },
    disabled: { color: 'var(--amber)',   label: '⏸ Disabled' },
    failed:   { color: 'var(--rose)',    label: '✕ Failed' },
  };
  const s = map[status] || map.disabled;
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      fontSize: 11, fontWeight: 500, color: s.color,
      background: s.color + '18', borderRadius: 20,
      padding: '2px 10px', border: `1px solid ${s.color}44`,
    }}>{s.label}</span>
  );
};

// HTTP status code color helper
const httpCodeColor = (code) => {
  if (code >= 200 && code < 300) return 'var(--emerald)';
  if (code >= 400 && code < 500) return 'var(--amber)';
  return 'var(--rose)';
};

// Event type badge
const EventBadge = ({ event }) => (
  <span style={{
    display: 'inline-flex', alignItems: 'center',
    fontSize: 10, fontFamily: 'var(--mono)',
    background: 'rgba(139,92,246,0.12)', color: '#c4b5fd',
    border: '1px solid rgba(139,92,246,0.3)',
    borderRadius: 4, padding: '2px 6px',
  }}>{event}</span>
);

// Inline test-response banner shown beneath the webhook card
const TestResultBanner = ({ result }) => {
  if (!result) return null;
  const ok = result.ok;
  return (
    <div style={{
      marginTop: 8, padding: '6px 10px',
      background: ok ? 'rgba(16,185,129,0.1)' : 'rgba(244,63,94,0.1)',
      border: `1px solid ${ok ? 'rgba(16,185,129,0.35)' : 'rgba(244,63,94,0.35)'}`,
      borderRadius: 6, fontSize: 11,
      color: ok ? 'var(--emerald)' : 'var(--rose)',
    }}>
      {ok
        ? '✓ Test event delivered successfully'
        : `✕ Delivery failed: ${result.error || 'Unknown error'}`}
    </div>
  );
};

// Shared input style (matches keys.jsx pattern)
const pInputStyle = {
  width: '100%',
  background: 'var(--bg-1)',
  border: '1px solid var(--border)',
  borderRadius: 8,
  padding: '8px 12px',
  fontSize: 13,
  color: 'var(--text-1)',
  fontFamily: 'inherit',
  outline: 'none',
  marginTop: 4,
};

// Simple per-line Python syntax highlighter using colored spans (no external lib)
const PythonCodeBlock = ({ code }) => {
  const lines = code.split('\n');
  return (
    <div style={{
      background: 'var(--bg-0)', border: '1px solid var(--border)', borderRadius: 8,
      padding: '14px 18px', fontFamily: 'var(--mono)', fontSize: 12,
      lineHeight: 1.7, overflowX: 'auto',
    }}>
      {lines.map((line, i) => {
        const trimmed = line.trimStart();
        let lineColor = 'var(--text-1)';
        if (trimmed.startsWith('#'))  lineColor = 'var(--text-3)';
        else if (trimmed.startsWith('@')) lineColor = '#fb923c';
        else if (/^(from|import|def|if|return|class)\b/.test(trimmed)) lineColor = '#c084fc';
        return (
          <div key={i} style={{ color: lineColor, minHeight: '1.4em', whiteSpace: 'pre' }}>
            {line || ''}
          </div>
        );
      })}
    </div>
  );
};

// ---------------------------------------------------------------------------
// PartnerScreen
// ---------------------------------------------------------------------------
const PartnerScreen = () => {
  // API key state
  const [keyRevealed, setKeyRevealed] = React.useState(false);
  const [keyCopied,   setKeyCopied]   = React.useState(false);

  // Webhooks list state
  const [webhooks, setWebhooks] = React.useState(PARTNER_MOCK.webhooks);

  // Per-webhook test state: { [id]: { ok: bool, error?: string } }
  const [testResults, setTestResults] = React.useState({});
  const [testingIds,   setTestingIds]   = React.useState(new Set());

  // Delete: first click sets pending, second click confirms
  const [pendingDeleteId, setPendingDeleteId] = React.useState(null);

  // Add-webhook form
  const [showAddForm,    setShowAddForm]    = React.useState(false);
  const [formUrl,        setFormUrl]        = React.useState('');
  const [formDesc,       setFormDesc]       = React.useState('');
  const [formEvents,     setFormEvents]     = React.useState([]);
  const [formSubmitting, setFormSubmitting] = React.useState(false);
  const [formError,      setFormError]      = React.useState(null);
  const [newSecret,      setNewSecret]      = React.useState(null);
  const [secretCopied,   setSecretCopied]   = React.useState(false);

  // SDK snippet copy
  const [sdkCopied, setSdkCopied] = React.useState(false);

  // Delivery log collapsible
  const [logOpen, setLogOpen] = React.useState(false);

  // Stats (loaded from API, falls back to MOCK)
  const [stats, setStats] = React.useState(PARTNER_MOCK.stats);

  // ---------------------------------------------------------------------------
  // On mount: fetch webhook list; silently keep MOCK on error
  // ---------------------------------------------------------------------------
  React.useEffect(() => {
    arFetch('/v1/partner/webhooks')
      .then(data => { if (Array.isArray(data) && data.length) setWebhooks(data); })
      .catch(() => {});
  }, []);

  // ---------------------------------------------------------------------------
  // Handlers
  // ---------------------------------------------------------------------------

  const handleCopyKey = () => {
    if (!navigator.clipboard) return;
    navigator.clipboard.writeText(PARTNER_MOCK.apiKeyReal)
      .then(function() { setKeyCopied(true); setTimeout(function() { setKeyCopied(false); }, 1800); })
      .catch(function() {});
  };

  const handleTest = (id) => {
    setTestingIds(prev => new Set(prev).add(id));
    arFetch(`/v1/partner/webhooks/${id}/test`, { method: 'POST', body: JSON.stringify({}) })
      .then(data => setTestResults(prev => ({ ...prev, [id]: { ok: true, ...data } })))
      .catch(() => setTestResults(prev => ({ ...prev, [id]: { ok: false, error: 'Endpoint returned an error' } })))
      .finally(() => setTestingIds(prev => { const s = new Set(prev); s.delete(id); return s; }));
  };

  const handleDelete = (id) => {
    // First click: ask for confirmation
    if (pendingDeleteId !== id) { setPendingDeleteId(id); return; }
    // Second click: delete
    arFetch(`/v1/partner/webhooks/${id}`, { method: 'DELETE' })
      .then(() => setWebhooks(ws => ws.filter(w => w.id !== id)))
      .catch(() => {})
      .finally(() => setPendingDeleteId(null));
  };

  const toggleFormEvent = (ev) =>
    setFormEvents(prev => prev.includes(ev) ? prev.filter(e => e !== ev) : [...prev, ev]);

  const handleAddSubmit = () => {
    if (!formUrl.startsWith('https://')) {
      setFormError('URL must start with https://');
      return;
    }
    if (!formEvents.length) {
      setFormError('Select at least one event type.');
      return;
    }
    setFormSubmitting(true);
    setFormError(null);

    const body = JSON.stringify({ url: formUrl, events: formEvents, description: formDesc });
    arFetch('/v1/partner/webhooks', { method: 'POST', body })
      .then(data => {
        const created = {
          id: data.id || ('wh_' + Date.now()),
          url: formUrl, events: formEvents, status: 'active',
          lastDelivery: { time: 'Never', code: null },
          description: formDesc,
        };
        setWebhooks(ws => [...ws, created]);
        setNewSecret(data.signing_secret || 'wss_•••••••••••••••••••••••••••••••');
        setFormUrl(''); setFormDesc(''); setFormEvents([]);
        setShowAddForm(false);
      })
      .catch(() => {
        // MOCK fallback on error: still add locally and show a fake secret
        const mockCreated = {
          id: 'wh_' + Date.now(),
          url: formUrl, events: formEvents, status: 'active',
          lastDelivery: { time: 'Never', code: null },
          description: formDesc,
        };
        setWebhooks(ws => [...ws, mockCreated]);
        setNewSecret('wss_•••••••••••••••••••••••••••••••');
        setFormUrl(''); setFormDesc(''); setFormEvents([]);
      })
      .finally(() => setFormSubmitting(false));
  };

  const handleCopySecret = () => {
    if (!navigator.clipboard) return;
    navigator.clipboard.writeText(newSecret || '')
      .then(function() { setSecretCopied(true); setTimeout(function() { setSecretCopied(false); }, 1800); })
      .catch(function() {});
  };

  const sdkCodeText = `from astrareach_sdk import AstraReachClient

client = AstraReachClient(api_key="sk_live_...")

# Subscribe to decision events
client.webhooks.create(
    url="https://your-app.com/webhook",
    events=["decision.created", "anomaly.detected"]
)

# Receive events (Flask example)
@app.route("/webhook", methods=["POST"])
def handle_event():
    event = client.webhooks.verify(request)
    if event.type == "decision.created":
        print(f"New decision: {event.data['decision_id']}")
    return {"ok": True}`;

  const handleCopySDK = () => {
    if (!navigator.clipboard) return;
    navigator.clipboard.writeText(sdkCodeText)
      .then(function() { setSdkCopied(true); setTimeout(function() { setSdkCopied(false); }, 1800); })
      .catch(function() {});
  };

  // Delivery log summary counts
  const logOk     = PARTNER_MOCK.deliveryLog.filter(d => d.code >= 200 && d.code < 300).length;
  const logFailed = PARTNER_MOCK.deliveryLog.filter(d => d.code >= 400).length;

  // ---------------------------------------------------------------------------
  // Render
  // ---------------------------------------------------------------------------
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>

      {/* ── Page header ── */}
      <div>
        <div style={{
          fontSize: 11, color: 'var(--text-3)', fontFamily: 'var(--mono)',
          textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 6,
        }}>Platform / Partner API</div>
        <div style={{ fontSize: 24, fontWeight: 700, letterSpacing: '-0.02em' }}>Partner API</div>
        <div style={{ fontSize: 13, color: 'var(--text-3)', marginTop: 2 }}>
          Manage webhook subscriptions, configure integrations, and access the Python SDK.
        </div>
      </div>

      {/* ── Section 1: Credentials + Stats row ── */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>

        {/* API Key card */}
        <div className="card" style={{ padding: 16 }}>
          <div style={{
            fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase',
            letterSpacing: '0.08em', marginBottom: 10,
          }}>Partner API Key</div>

          {/* Masked key + copy/reveal buttons */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
            <div style={{
              flex: 1, padding: '8px 12px',
              background: 'var(--bg-0)', border: '1px solid var(--border)',
              borderRadius: 7, fontFamily: 'var(--mono)', fontSize: 12, color: '#c4b5fd',
              overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
            }}>
              {keyRevealed ? PARTNER_MOCK.apiKeyReal : PARTNER_MOCK.apiKey}
            </div>
            <button className="btn ghost" style={{ padding: '5px 9px', fontSize: 11, flexShrink: 0 }}
              onClick={() => setKeyRevealed(v => !v)}>
              {keyRevealed ? '🙈 Hide' : '👁 Reveal'}
            </button>
            <button className="btn" style={{ padding: '5px 9px', fontSize: 11, flexShrink: 0 }}
              onClick={handleCopyKey}>
              {keyCopied ? '✓ Copied' : '📋 Copy'}
            </button>
          </div>

          {/* SDK install snippet */}
          <div style={{
            background: 'var(--bg-0)', border: '1px solid var(--border)',
            borderRadius: 7, padding: '10px 14px',
            fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--text-2)', lineHeight: 1.8,
          }}>
            <span style={{ color: '#c084fc' }}>pip</span>
            <span style={{ color: 'var(--text-1)' }}> install astrareach-sdk</span>
            <br />
            <span style={{ color: 'var(--text-3)' }}># then: </span>
            <span style={{ color: 'var(--cyan)' }}>from</span>
            <span style={{ color: 'var(--text-2)' }}> astrareach_sdk </span>
            <span style={{ color: 'var(--cyan)' }}>import</span>
            <span style={{ color: 'var(--text-1)' }}> AstraReachClient</span>
          </div>
        </div>

        {/* 4 stat cards */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12 }}>
          {[
            { label: 'Active Webhooks', value: stats.activeWebhooks,               color: 'var(--accent)' },
            { label: 'Deliveries 24h',  value: stats.deliveries24h.toLocaleString(), color: 'var(--cyan)' },
            { label: 'Success Rate',    value: stats.successRate + '%',             color: 'var(--emerald)' },
            { label: 'Avg Latency',     value: stats.avgLatency + 'ms',             color: 'var(--amber)' },
          ].map(({ label, value, color }) => (
            <div key={label} className="card" style={{ padding: 14 }}>
              <div style={{ fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 8 }}>
                {label}
              </div>
              <div style={{ fontSize: 26, fontWeight: 700, color, letterSpacing: '-0.02em' }}>
                {value}
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* ── Section 2: Webhook Subscriptions ── */}
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>

        {/* Card header */}
        <div style={{
          padding: '14px 16px', display: 'flex',
          justifyContent: 'space-between', alignItems: 'center',
          borderBottom: showAddForm ? '1px solid var(--border)' : 'none',
        }}>
          <div>
            <div className="card-title">Webhook Subscriptions</div>
            <div className="card-sub">
              {webhooks.filter(w => w.status === 'active').length} active · {webhooks.length} total
            </div>
          </div>
          <button className="btn primary" onClick={() => { setShowAddForm(v => !v); setFormError(null); setFormSubmitting(false); setFormUrl(''); setFormDesc(''); setFormEvents([]); }}>
            <Icon name="plus" size={12} />
            {showAddForm ? 'Cancel' : 'Add Endpoint'}
          </button>
        </div>

        {/* ── Add-endpoint form (inline, toggled) ── */}
        {showAddForm && (
          <div style={{
            padding: 16, borderBottom: '1px solid var(--border)',
            background: 'rgba(139,92,246,0.03)',
          }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text-1)', marginBottom: 12 }}>
              New Webhook Endpoint
            </div>

            {/* Validation error */}
            {formError && (
              <div style={{
                padding: '8px 12px', marginBottom: 10,
                background: 'rgba(244,63,94,0.1)', border: '1px solid rgba(244,63,94,0.3)',
                borderRadius: 7, fontSize: 12, color: 'var(--rose)',
              }}>⚠ {formError}</div>
            )}

            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>

              {/* URL field */}
              <div>
                <label style={{ fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                  Endpoint URL
                </label>
                <input
                  type="url"
                  placeholder="https://your-app.com/webhook"
                  value={formUrl}
                  onChange={e => setFormUrl(e.target.value)}
                  style={pInputStyle}
                />
                {formUrl && !formUrl.startsWith('https://') && (
                  <div style={{ fontSize: 11, color: 'var(--amber)', marginTop: 3 }}>
                    ⚠ URL must start with https://
                  </div>
                )}
              </div>

              {/* Event type checkboxes */}
              <div>
                <label style={{
                  display: 'block', fontSize: 11, color: 'var(--text-3)',
                  textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 8,
                }}>Event Types</label>
                <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                  {ALL_WEBHOOK_EVENTS.map(ev => (
                    <button
                      key={ev}
                      className={`filter-chip ${formEvents.includes(ev) ? 'active' : ''}`}
                      style={{ fontFamily: 'var(--mono)', fontSize: 11 }}
                      onClick={() => toggleFormEvent(ev)}>
                      {ev}
                    </button>
                  ))}
                </div>
              </div>

              {/* Optional description */}
              <div>
                <label style={{ fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em' }}>
                  Description (optional)
                </label>
                <input
                  type="text"
                  placeholder="What is this endpoint for?"
                  value={formDesc}
                  onChange={e => setFormDesc(e.target.value)}
                  style={pInputStyle}
                />
              </div>

              <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
                <button className="btn ghost" onClick={() => { setShowAddForm(false); setFormError(null); setNewSecret(null); setFormUrl(''); setFormDesc(''); setFormEvents([]); setFormSubmitting(false); }}>
                  Cancel
                </button>
                <button className="btn primary" onClick={handleAddSubmit} disabled={formSubmitting}>
                  {formSubmitting ? 'Creating…' : 'Create Webhook →'}
                </button>
              </div>

            </div>
          </div>
        )}

        {/* Signing secret reveal after successful creation — outside showAddForm gate so it survives form close */}
        {newSecret && (
          <div style={{
            margin: '0 16px 16px',
            padding: 14,
            background: 'rgba(16,185,129,0.08)', border: '1px solid rgba(16,185,129,0.3)',
            borderRadius: 8,
          }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: 'var(--emerald)', marginBottom: 8 }}>
              ✓ Webhook created — save your signing secret now
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <div style={{
                flex: 1, fontFamily: 'var(--mono)', fontSize: 12,
                color: '#6ee7b7', background: 'var(--bg-0)',
                borderRadius: 6, padding: '6px 10px', border: '1px solid var(--border)',
                overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
              }}>{newSecret}</div>
              <button className="btn" style={{ fontSize: 11, flexShrink: 0 }} onClick={handleCopySecret}>
                {secretCopied ? '✓ Copied' : '📋 Copy'}
              </button>
            </div>
            <div style={{ fontSize: 11, color: 'var(--text-3)', marginTop: 6 }}>
              This secret is shown only once. Use it to verify incoming webhook signatures on your server.
            </div>
          </div>
        )}

        {/* ── Webhook cards list ── */}
        <div style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
          {webhooks.map(wh => (
            <div key={wh.id} style={{
              padding: 14,
              background: 'var(--bg-1)', border: '1px solid var(--border)',
              borderRadius: 10,
              borderLeft: `3px solid ${
                wh.status === 'active'   ? 'var(--emerald)' :
                wh.status === 'failed'   ? 'var(--rose)'    : 'var(--amber)'
              }`,
            }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, flexWrap: 'wrap' }}>

                {/* Left: URL, description, event badges, last delivery */}
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 5, flexWrap: 'wrap' }}>
                    <span
                      title={wh.url}
                      style={{
                        fontFamily: 'var(--mono)', fontSize: 12, color: 'var(--text-1)',
                        overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                        maxWidth: 340,
                      }}>
                      {wh.url}
                    </span>
                    <WebhookStatusPill status={wh.status} />
                  </div>

                  {wh.description && (
                    <div style={{ fontSize: 11, color: 'var(--text-3)', marginBottom: 7 }}>
                      {wh.description}
                    </div>
                  )}

                  {/* Event type badges */}
                  <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap', marginBottom: 8 }}>
                    {wh.events.map(ev => <EventBadge key={ev} event={ev} />)}
                  </div>

                  {/* Last delivery row */}
                  <div style={{ display: 'flex', gap: 8, alignItems: 'center', fontSize: 11, color: 'var(--text-3)' }}>
                    <span>Last delivery: {wh.lastDelivery.time}</span>
                    {wh.lastDelivery.code && (
                      <span style={{
                        fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 600,
                        color: httpCodeColor(wh.lastDelivery.code),
                        background: httpCodeColor(wh.lastDelivery.code) + '18',
                        borderRadius: 4, padding: '1px 6px',
                      }}>{wh.lastDelivery.code}</span>
                    )}
                  </div>

                  {/* Inline test result */}
                  <TestResultBanner result={testResults[wh.id]} />
                </div>

                {/* Right: action buttons */}
                <div style={{ display: 'flex', gap: 6, flexShrink: 0, alignItems: 'flex-start', paddingTop: 2 }}>
                  <button
                    className="btn"
                    style={{
                      fontSize: 11, padding: '5px 10px',
                      color: 'var(--cyan)', borderColor: 'rgba(34,211,238,0.35)',
                    }}
                    disabled={testingIds.has(wh.id) || wh.status === 'disabled'}
                    onClick={() => handleTest(wh.id)}>
                    {testingIds.has(wh.id) ? '⏳ Sending…' : '▶ Test'}
                  </button>

                  <button
                    className="btn"
                    style={{
                      fontSize: 11, padding: '5px 10px',
                      color: pendingDeleteId === wh.id ? 'var(--rose)' : 'var(--text-3)',
                      borderColor: pendingDeleteId === wh.id ? 'rgba(244,63,94,0.4)' : 'var(--border)',
                    }}
                    onClick={() => {
                      if (pendingDeleteId && pendingDeleteId !== wh.id) setPendingDeleteId(null);
                      handleDelete(wh.id);
                    }}>
                    {pendingDeleteId === wh.id ? '⚠ Confirm?' : '🗑 Delete'}
                  </button>

                  {/* Cancel pending delete */}
                  {pendingDeleteId === wh.id && (
                    <button className="btn ghost" style={{ fontSize: 11, padding: '5px 8px' }}
                      onClick={() => setPendingDeleteId(null)}>
                      Cancel
                    </button>
                  )}
                </div>
              </div>
            </div>
          ))}

          {webhooks.length === 0 && (
            <div style={{ textAlign: 'center', padding: 40, color: 'var(--text-3)', fontSize: 13 }}>
              No webhook subscriptions yet. Click "Add Endpoint" to get started.
            </div>
          )}
        </div>
      </div>

      {/* ── Section 3: Python SDK Quickstart ── */}
      <div className="card">
        <div className="card-header">
          <div>
            <div className="card-title">Python SDK Quickstart</div>
            <div className="card-sub">astrareach-sdk · v1.4.0 · MIT</div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className="btn" style={{ fontSize: 11 }} onClick={handleCopySDK}>
              {sdkCopied ? '✓ Copied' : '📋 Copy'}
            </button>
            <a
              href="https://pypi.org/project/astrareach-sdk/"
              target="_blank"
              rel="noopener noreferrer"
              className="btn"
              style={{ fontSize: 11, textDecoration: 'none' }}>
              View on PyPI ↗
            </a>
          </div>
        </div>

        <PythonCodeBlock code={sdkCodeText} />
      </div>

      {/* ── Section 4: Delivery Log (collapsible) ── */}
      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>

        {/* Toggle header */}
        <div
          style={{
            padding: '14px 16px', cursor: 'pointer',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          }}
          onClick={() => setLogOpen(v => !v)}>
          <div>
            <div className="card-title">Delivery Log</div>
            <div className="card-sub">
              Last {PARTNER_MOCK.deliveryLog.length} deliveries ·{' '}
              <span style={{ color: 'var(--emerald)' }}>{logOk} ok</span> ·{' '}
              <span style={{ color: 'var(--rose)' }}>{logFailed} failed</span>
            </div>
          </div>
          <Icon name="chevron" size={13} style={{
            transform: logOpen ? 'rotate(90deg)' : 'none',
            transition: 'transform .15s',
            color: 'var(--text-3)',
          }} />
        </div>

        {logOpen && (
          <div style={{ borderTop: '1px solid var(--border)', overflowX: 'auto' }}>
            <table className="data-table">
              <thead>
                <tr>
                  <th>Timestamp</th>
                  <th>Event Type</th>
                  <th>Endpoint</th>
                  <th>Status</th>
                  <th style={{ textAlign: 'right' }}>Latency</th>
                  <th style={{ textAlign: 'right' }}>Retries</th>
                </tr>
              </thead>
              <tbody>
                {PARTNER_MOCK.deliveryLog.map((row, i) => (
                  <tr key={i}>
                    <td className="mono" style={{ fontSize: 11, color: 'var(--text-3)' }}>
                      {row.ts}
                    </td>
                    <td>
                      <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: '#c4b5fd' }}>
                        {row.event}
                      </span>
                    </td>
                    <td className="mono" style={{
                      fontSize: 11, color: 'var(--text-2)',
                      maxWidth: 200, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                    }}>
                      {row.endpoint}
                    </td>
                    <td>
                      <span style={{
                        fontFamily: 'var(--mono)', fontSize: 11, fontWeight: 600,
                        color: httpCodeColor(row.code),
                      }}>{row.code}</span>
                    </td>
                    <td className="mono" style={{ textAlign: 'right', fontSize: 11, color: 'var(--text-2)' }}>
                      {row.latency > 0 ? row.latency + 'ms' : '—'}
                    </td>
                    <td style={{
                      textAlign: 'right', fontSize: 11,
                      color: row.retries > 0 ? 'var(--amber)' : 'var(--text-3)',
                    }}>
                      {row.retries > 0 ? `${row.retries}×` : '—'}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}
      </div>

    </div>
  );
};

window.PartnerScreen = PartnerScreen;
