// API Keys screen

const KEY_ROWS = [
  { name: 'Production Web App', prefix: 'ar_live_a1', owner: 'Growth Eng', status: 'active', rate: '60 req/min', sources: ['web','app'], created: 'Apr 20, 2026', used: '2m ago', expires: 'Never', util: 42 },
  { name: 'CI/CD Pipeline', prefix: 'ar_live_b7', owner: 'Platform', status: 'active', rate: '300 req/min', sources: ['batch'], created: 'Mar 14, 2026', used: '14m ago', expires: 'Jul 12, 2026', util: 178 },
  { name: 'Mobile iOS', prefix: 'ar_live_c3', owner: 'Mobile', status: 'active', rate: '60 req/min', sources: ['app'], created: 'Feb 28, 2026', used: '1h ago', expires: 'Never', util: 8 },
  { name: 'Meta Ads Webhook', prefix: 'ar_live_d9', owner: 'Marketing Ops', status: 'expiring', rate: '60 req/min', sources: ['meta_ads'], created: 'Jan 30, 2026', used: '4h ago', expires: 'Apr 30, 2026 (8d)', util: 3 },
  { name: 'Analytics BI', prefix: 'ar_live_e2', owner: 'Data', status: 'active', rate: 'Unlimited', sources: null, created: 'Jan 2, 2026', used: 'Yesterday', expires: 'Never', util: 0 },
  { name: 'Legacy Import', prefix: 'ar_live_f4', owner: 'Migration', status: 'inactive', rate: '60 req/min', sources: ['batch'], created: 'Nov 8, 2025', used: '45d ago', expires: 'Never', util: 0 },
];

const KeyStatusPill = ({ status }) => {
  const m = {
    active: { cls: 'green', label: '● Active' },
    inactive: { cls: 'plain', label: '○ Inactive' },
    expired: { cls: 'rose', label: '✕ Expired' },
    expiring: { cls: 'amber', label: '⚠ Expiring' },
  };
  return <span className={`badge ${m[status].cls}`}>{m[status].label}</span>;
};

const mapKeyRow = (k, idx) => ({
  key_id: k.key_id || k.id || null,
  name: k.name || 'API Key ' + idx,
  prefix: k.key_prefix || k.prefix || 'ar_live_xx',
  owner: k.owner || k.created_by || 'Unknown',
  status: k.status || (k.is_active === false ? 'inactive' : 'active'),
  rate: k.rate_limit ? k.rate_limit + ' req/min' : '60 req/min',
  sources: Array.isArray(k.allowed_sources) && k.allowed_sources.length ? k.allowed_sources : null,
  created: k.created_at ? new Date(k.created_at).toLocaleDateString('en-US', {month:'short',day:'numeric',year:'numeric'}) : '—',
  used: k.last_used_at ? (() => { const s = Math.round((Date.now() - new Date(k.last_used_at).getTime()) / 1000); return s < 120 ? s+'s ago' : s < 3600 ? Math.round(s/60)+'m ago' : s < 86400 ? Math.round(s/3600)+'h ago' : Math.round(s/86400)+'d ago'; })() : 'Never',
  expires: k.expires_at ? new Date(k.expires_at).toLocaleDateString('en-US', {month:'short',day:'numeric',year:'numeric'}) : 'Never',
  util: k.requests_last_minute || 0,
});

const KeysScreen = () => {
  const [rows, setRows] = React.useState(KEY_ROWS);
  const [showModal, setShowModal] = React.useState(false);
  const [step, setStep] = React.useState(1);
  const [newKey, setNewKey] = React.useState(null);
  const [generating, setGenerating] = React.useState(false);
  const [expandUsage, setExpandUsage] = React.useState(false);
  const [usageRange, setUsageRange] = React.useState('7d');
  const [codeTab, setCodeTab] = React.useState('cURL');
  const [inactiveOn, setInactiveOn] = React.useState(false);
  const [keyName, setKeyName] = React.useState('New Key');
  const [keyRateLimit, setKeyRateLimit] = React.useState(60);
  const [keyExpiry, setKeyExpiry] = React.useState(90); // days; null = never
  const [allowedSources, setAllowedSources] = React.useState(['web', 'app']);
  const [generateError, setGenerateError] = React.useState(null);
  const visibleRows = rows.filter(r => inactiveOn || r.status !== 'inactive');

  const reloadKeys = () => arFetch('/v1/auth/keys')
    .then(d => { const arr = Array.isArray(d) ? d : (d?.keys || []); if (arr.length) setRows(arr.map(mapKeyRow)); })
    .catch(() => {});

  React.useEffect(() => { reloadKeys(); }, []);

  const handleGenerate = () => {
    setGenerating(true);
    setGenerateError(null);
    arFetch('/v1/auth/keys', { method: 'POST', body: JSON.stringify({ name: keyName, rate_limit: keyRateLimit, ...(keyExpiry ? { expires_days: keyExpiry } : {}), ...(allowedSources.length ? { allowed_sources: allowedSources } : {}) }) })
      .then(d => {
        if (d?.api_key) setNewKey(d.api_key);
        else setNewKey('ar_live_' + Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 10));
        setStep(2);
        reloadKeys();
      })
      .catch(() => {
        // API not yet live — generate client-side demo key
        const fakeKey = 'ar_live_' + Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 10);
        const fakePrefix = 'ar_live_' + Math.random().toString(36).slice(2, 8);
        setNewKey(fakeKey);
        setStep(2);
        // Add to local rows
        setRows(prev => [{
          name: keyName,
          prefix: fakePrefix,
          owner: 'You',
          status: 'active',
          rate: keyRateLimit === 999999 ? 'Unlimited' : keyRateLimit + ' req/min',
          sources: allowedSources.length ? [...allowedSources] : null,
          created: new Date().toLocaleDateString('en-US', {month:'short', day:'numeric', year:'numeric'}),
          used: 'Never',
          expires: keyExpiry ? (() => { const d = new Date(); d.setDate(d.getDate() + keyExpiry); return d.toLocaleDateString('en-US', {month:'short', day:'numeric', year:'numeric'}); })() : 'Never',
          util: 0,
          key_id: null,
        }, ...prev]);
      })
      .finally(() => setGenerating(false));
  };

  const handleDelete = (row) => {
    if (!window.confirm('Delete key ' + row.prefix + '?')) return;
    if (row.key_id) {
      arFetch('/v1/auth/keys/' + row.key_id, { method: 'DELETE' })
        .then(() => setRows(rs => rs.filter(r => r.prefix !== row.prefix)))
        .catch(() => setRows(rs => rs.filter(r => r.prefix !== row.prefix))); // still delete locally on error
    } else {
      setRows(rs => rs.filter(r => r.prefix !== row.prefix));
    }
  };

  const handleToggle = (prefix) => {
    const row = rows.find(r => r.prefix === prefix);
    if (!row) return;
    // FIX: compute target status once and close over it, avoiding stale action string
    const newStatus = row.status === 'active' ? 'inactive' : 'active';
    const action = newStatus === 'active' ? 'activate' : 'deactivate';
    const apply = () => setRows(rs => rs.map(r => r.prefix === prefix ? {...r, status: newStatus} : r));
    if (row.key_id) {
      arFetch('/v1/auth/keys/' + row.key_id + '/' + action, { method: 'PUT', body: JSON.stringify({}) })
        .then(apply).catch(apply);
    } else {
      apply();
    }
  };

  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 18}}>
      <div style={{display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between'}}>
        <div>
          <div style={{fontSize: 11, color: 'var(--text-4)', fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 6}}>Platform / API Keys</div>
          <div style={{fontSize: 24, fontWeight: 700, letterSpacing: '-0.02em'}}>API Keys</div>
          <div style={{fontSize: 13, color: 'var(--text-3)', marginTop: 2}}>Authenticate event ingestion and API access. Keys are hashed — the raw value is shown only once.</div>
        </div>
        <div style={{display: 'flex', gap: 10, alignItems: 'center'}}>
          <span style={{fontSize: 11, color: 'var(--text-3)'}}>Include inactive</span>
          <div className={`toggle ${inactiveOn?'on':''}`} onClick={() => setInactiveOn(v => !v)}/>
          <span className="badge green">{rows.filter(r => r.status === 'active').length} active keys</span>
          <button className="btn primary" onClick={() => { setShowModal(true); setStep(1); setKeyName('New Key'); setKeyRateLimit(60); setKeyExpiry(90); setAllowedSources(['web', 'app']); setGenerateError(null); }}><Icon name="plus" size={12}/>Generate New Key</button>
        </div>
      </div>

      {/* Stats */}
      <div style={{display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12}}>
        <div className="card" style={{padding: 14}}>
          <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 10}}>Total Active Keys</div>
          <div style={{fontSize: 32, fontWeight: 700, color: 'var(--emerald)', letterSpacing: '-0.02em'}}>{rows.filter(r => r.status === 'active').length}</div>
          <div style={{fontSize: 11, color: 'var(--text-3)'}}>API keys</div>
        </div>
        <div className="card" style={{padding: 14}}>
          <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 10}}>Used Today</div>
          <div style={{fontSize: 32, fontWeight: 700, letterSpacing: '-0.02em'}}>3<span style={{fontSize: 16, color: 'var(--text-3)'}}> / 5</span></div>
          <div className="progress" style={{marginTop: 8}}><div style={{width: '60%'}}/></div>
        </div>
        <div className="card" style={{padding: 14}}>
          <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 10, display: 'flex', justifyContent: 'space-between'}}>
            <span>Requests / min</span>
            <span style={{display: 'flex', gap: 4, alignItems: 'center'}}><span className="dot pulse" style={{width: 6, height: 6}}/><span style={{color: 'var(--emerald)'}}>Live</span></span>
          </div>
          <div style={{fontSize: 32, fontWeight: 700, letterSpacing: '-0.02em'}}>127</div>
          <div style={{fontSize: 11, color: 'var(--text-3)'}}>across all keys</div>
        </div>
        <div className="card" style={{padding: 14}}>
          <div style={{fontSize: 10, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.08em', marginBottom: 10}}>Expiring Soon</div>
          <div style={{fontSize: 32, fontWeight: 700, color: 'var(--amber)', letterSpacing: '-0.02em'}}>1</div>
          <a style={{fontSize: 11, color: 'var(--amber)', cursor: 'pointer'}} onClick={() => document.querySelector('[data-expiring="true"]')?.scrollIntoView({ behavior: 'smooth', block: 'center' })}>in 8 days · View →</a>
        </div>
      </div>

      {/* Table */}
      <div className="card" style={{padding: 0, overflow: 'hidden'}}>
        <div style={{overflow: 'auto'}}>
          <table className="data-table">
            <thead><tr>
              <th>Name</th><th>Prefix</th><th>Owner</th><th>Status</th>
              <th>Rate Limit</th><th>Sources</th><th>Created</th><th>Last Used</th><th>Expires</th><th style={{textAlign:'right'}}>Actions</th>
            </tr></thead>
            <tbody>
              {visibleRows.map((r, i) => (
                <tr key={i} data-expiring={r.status === 'expiring' ? 'true' : undefined} style={{
                  opacity: r.status === 'inactive' ? 0.5 : 1,
                  borderLeft: r.status === 'expiring' ? '2px solid var(--amber)' : r.status === 'expired' ? '2px solid var(--rose)' : 'none'
                }}>
                  <td style={{color: 'var(--text-1)', fontWeight: 500}}>{r.name}</td>
                  <td><span className="mono" style={{color: '#c4b5fd'}}>{r.prefix}</span></td>
                  <td>{r.owner}</td>
                  <td><KeyStatusPill status={r.status}/></td>
                  <td className="mono">{r.rate}</td>
                  <td>
                    {r.sources ? (
                      <div style={{display: 'flex', gap: 4}}>
                        {r.sources.map(s => <SourceBadge key={s} src={s}/>)}
                      </div>
                    ) : <span style={{color: 'var(--text-3)', fontSize: 11}}>All sources</span>}
                  </td>
                  <td style={{color: 'var(--text-3)', fontSize: 11}}>{r.created}</td>
                  <td style={{color: 'var(--text-3)', fontSize: 11}}>{r.used}</td>
                  <td style={{fontSize: 11, color: r.status === 'expiring' ? 'var(--amber)' : 'var(--text-3)'}}>{r.expires}</td>
                  <td style={{textAlign: 'right'}}>
                    <div style={{display: 'flex', gap: 4, justifyContent: 'flex-end', color: 'var(--text-3)'}}>
                      <span style={{cursor: 'pointer', padding: '2px 4px'}} title="Copy prefix" onClick={() => navigator.clipboard?.writeText(r.prefix)}>📋</span>
                      <span style={{cursor: 'pointer', padding: '2px 4px'}} title={r.status === 'active' ? 'Disable' : 'Enable'} onClick={() => handleToggle(r.prefix)}>{r.status === 'active' ? '⏸' : '▶'}</span>
                      <span style={{cursor: 'pointer', padding: '2px 4px', color: 'var(--rose)'}} title="Delete" onClick={() => handleDelete(r)}>🗑</span>
                      <span style={{cursor: 'pointer', padding: '2px 4px', color: 'var(--cyan)'}} title="View usage" onClick={() => setExpandUsage(true)}>📊</span>
                    </div>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      {/* Rate limit utilization */}
      <div className="card">
        <div className="card-header">
          <div>
            <div className="card-title">Live Rate Limit Utilization</div>
            <div className="card-sub">Last 60 seconds</div>
          </div>
          <span style={{display: 'flex', gap: 6, alignItems: 'center', fontSize: 11, color: 'var(--emerald)'}}><span className="dot pulse" style={{width: 6, height: 6}}/>Live</span>
        </div>
        <div style={{display: 'flex', flexDirection: 'column', gap: 12}}>
          {rows.filter(r => r.status !== 'inactive').map(r => {
            const limit = parseInt(r.rate) || 1000;
            const pct = Math.min(100, (r.util / limit) * 100);
            const color = pct >= 80 ? 'var(--rose)' : pct >= 60 ? 'var(--amber)' : 'var(--emerald)';
            return (
              <div key={r.prefix} style={{display: 'grid', gridTemplateColumns: '200px 1fr 120px', alignItems: 'center', gap: 14}}>
                <div>
                  <div style={{fontSize: 13, fontWeight: 500}}>{r.name}</div>
                  <div className="mono" style={{fontSize: 10, color: 'var(--text-4)'}}>{r.prefix}</div>
                </div>
                <div style={{height: 10, background: 'var(--bg-3)', borderRadius: 5, overflow: 'hidden'}}>
                  <div style={{height: '100%', width: pct + '%', background: color, transition: 'width .3s'}}/>
                </div>
                <div className="mono" style={{fontSize: 12, color: 'var(--text-2)', textAlign: 'right'}}>{r.util} / {r.rate.split(' ')[0]}</div>
              </div>
            );
          })}
        </div>
      </div>

      {/* Usage analytics */}
      <div className="card" style={{padding: 0}}>
        <div style={{padding: 16, display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: 'pointer'}} onClick={() => setExpandUsage(v => !v)}>
          <div>
            <div className="card-title">API Key Usage</div>
            <div className="card-sub">Last 7 days</div>
          </div>
          <div style={{display: 'flex', alignItems: 'center', gap: 10}}>
            <div className="seg">
              <button className={usageRange==='7d'?'active':''} onClick={()=>setUsageRange('7d')}>7d</button>
              <button className={usageRange==='30d'?'active':''} onClick={()=>setUsageRange('30d')}>30d</button>
            </div>
            <Icon name="chevron" size={14} style={{transform: expandUsage ? 'rotate(90deg)' : 'none', transition: 'transform .15s', color: 'var(--text-3)'}}/>
          </div>
        </div>
        {expandUsage && (
          <div style={{padding: 16, borderTop: '1px solid var(--border)', display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14}}>
            {rows.filter(r => r.status === 'active').slice(0, 4).map(r => {
              const bars = MOCK.spark(r.prefix.charCodeAt(8));
              const max = Math.max(...bars);
              return (
                <div key={r.prefix} style={{padding: 12, background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 8}}>
                  <div style={{display: 'flex', justifyContent: 'space-between', marginBottom: 10}}>
                    <span style={{fontSize: 12, fontWeight: 500}}>{r.name}</span>
                    <span className="mono" style={{fontSize: 10, color: '#c4b5fd'}}>{r.prefix}</span>
                  </div>
                  <div style={{display: 'flex', alignItems: 'flex-end', gap: 3, height: 42}}>
                    {bars.slice(0, 7).map((v, i) => <div key={i} style={{flex: 1, height: ((v/max)*100) + '%', background: 'var(--accent)', opacity: 0.8, borderRadius: 2}}/>)}
                  </div>
                  <div style={{fontSize: 11, color: 'var(--text-3)', marginTop: 8}}>{(r.util * 120 + 400).toLocaleString()} requests</div>
                </div>
              );
            })}
          </div>
        )}
      </div>

      {/* Modal */}
      {showModal && (
        <div style={{position: 'fixed', inset: 0, background: 'rgba(7,9,15,0.75)', zIndex: 200, display: 'flex', alignItems: 'center', justifyContent: 'center'}}>
          <div style={{width: 560, maxHeight: '90vh', overflow: 'auto', background: 'var(--bg-2)', border: '1px solid var(--border-strong)', borderRadius: 12, padding: 24, boxShadow: '0 40px 80px rgba(0,0,0,0.6)'}}>
            <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16}}>
              <div style={{fontSize: 18, fontWeight: 700}}>{step === 1 ? 'Generate New API Key' : '✅ API Key Generated — Save It Now'}</div>
              <button className="btn ghost" style={{padding: 4}} onClick={() => setShowModal(false)}><Icon name="x" size={14}/></button>
            </div>

            <div style={{padding: 10, background: 'rgba(245,158,11,0.1)', border: '1px solid rgba(245,158,11,0.3)', borderRadius: 8, fontSize: 12, color: '#fbbf24', marginBottom: 16}}>
              ⚠️ {step === 1 ? 'The full API key is shown only once — immediately after creation. Store it in your secrets manager before closing this dialog.' : 'This is the ONLY time this key will be displayed. We store only the SHA-256 hash — the raw key is unrecoverable.'}
            </div>

            {step === 1 && (
              <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
                {generateError && (
                  <div style={{padding: '10px 14px', background: 'rgba(244,63,94,0.1)', border: '1px solid rgba(244,63,94,0.3)', borderRadius: 8, fontSize: 12, color: 'var(--rose)'}} role="alert">
                    ⚠ {generateError}
                  </div>
                )}
                <div>
                  <label style={{fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em'}}>Name</label>
                  <input value={keyName} onChange={e => setKeyName(e.target.value)} style={inputStyle}/>
                </div>
                <div>
                  <label style={{fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em'}}>Description</label>
                  <textarea rows={2} placeholder="What is this key used for?" style={{...inputStyle, resize: 'none'}}/>
                </div>
                <div>
                  <label style={{fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em', display: 'block', marginBottom: 6}}>Allowed Sources</label>
                  <div style={{display: 'flex', gap: 6, flexWrap: 'wrap'}}>
                    {['web','app','offline','meta_ads','google_ads','batch'].map(s => (
                      <button key={s} className={`filter-chip ${allowedSources.includes(s)?'active':''}`}
                        onClick={() => setAllowedSources(prev => prev.includes(s) ? prev.filter(x => x !== s) : [...prev, s])}>
                        {s}
                      </button>
                    ))}
                  </div>
                </div>
                <div>
                  <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6}}>
                    <label style={{fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em'}}>Rate Limit</label>
                  </div>
                  <div style={{display: 'flex', gap: 6}}>
                    {[10,60,300,1000,'Unlimited'].map(p => <button key={p} onClick={() => setKeyRateLimit(p === 'Unlimited' ? 999999 : p)} className={`filter-chip ${(p === 'Unlimited' ? 999999 : p) === keyRateLimit ? 'active' : ''}`}>{p}</button>)}
                    <span style={{fontSize: 11, color: 'var(--text-3)', marginLeft: 'auto', alignSelf: 'center'}}>{keyRateLimit === 999999 ? 'Unlimited' : keyRateLimit + ' req/min'}</span>
                  </div>
                </div>
                <div>
                  <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6}}>
                    <label style={{fontSize: 11, color: 'var(--text-3)', textTransform: 'uppercase', letterSpacing: '0.05em'}}>Expiration</label>
                  </div>
                  <div style={{display: 'flex', gap: 6}}>
                    {[[30,'30d'],[90,'90d'],[365,'1y'],[0,'Never']].map(([v,label]) => (
                      <button key={v} onClick={() => setKeyExpiry(v)} className={`filter-chip ${keyExpiry===v?'active':''}`}>{label}</button>
                    ))}
                  </div>
                </div>
                <div style={{display: 'flex', justifyContent: 'flex-end', gap: 8, marginTop: 10}}>
                  <button className="btn ghost" onClick={() => setShowModal(false)}>Cancel</button>
                  <button className="btn primary" onClick={handleGenerate} disabled={generating}>{generating ? 'Generating…' : 'Generate Key →'}</button>
                </div>
              </div>
            )}

            {step === 2 && (
              <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
                <div style={{padding: 16, background: 'var(--bg-0)', border: '1px solid var(--border-strong)', borderRadius: 8, display: 'flex', alignItems: 'center', gap: 10}}>
                  <div className="mono" style={{flex: 1, color: '#c4b5fd', fontSize: 14, wordBreak: 'break-all'}}>{newKey || 'ar_live_a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0'}</div>
                  <button className="btn" style={{fontSize: 11, flexShrink: 0}} onClick={() => navigator.clipboard?.writeText(newKey || '')}>📋 Copy</button>
                </div>
                <div>
                  <div style={{display: 'flex', gap: 4, marginBottom: 8}}>
                    {['cURL','Python','Node.js'].map(lang => (
                      <button key={lang} className={`filter-chip ${codeTab===lang?'active':''}`} onClick={()=>setCodeTab(lang)}>{lang}</button>
                    ))}
                  </div>
                  <div className="json-view" style={{fontSize: 11}}>
                    {codeTab === 'cURL' && `curl -X POST https://api.astrareach.ai/v1/events \\
  -H "X-API-Key: ${newKey||'ar_live_a1b2c3d4...'}" \\
  -H "Content-Type: application/json" \\
  -d '{"events": [{"type":"page_view","actor_id":"act_xxx","source":"web"}]}'`}
                    {codeTab === 'Python' && `import requests\n\nres = requests.post(\n  "https://api.astrareach.ai/v1/events",\n  headers={"X-API-Key": "${newKey||'ar_live_a1b2c3d4...'}"},\n  json={"events": [{"type": "page_view", "actor_id": "act_xxx", "source": "web"}]}\n)\nprint(res.json())`}
                    {codeTab === 'Node.js' && `const res = await fetch("https://api.astrareach.ai/v1/events", {\n  method: "POST",\n  headers: {\n    "X-API-Key": "${newKey||'ar_live_a1b2c3d4...'}",\n    "Content-Type": "application/json",\n  },\n  body: JSON.stringify({ events: [{ type: "page_view", actor_id: "act_xxx", source: "web" }] }),\n});\nconsole.log(await res.json());`}
                  </div>
                </div>
                <div style={{padding: 12, background: 'var(--bg-1)', borderRadius: 8, fontSize: 12, color: 'var(--text-2)', lineHeight: 1.8}}>
                  • Name: <b>{keyName || '—'}</b><br/>
                  • Rate Limit: {keyRateLimit === 999999 ? 'Unlimited' : `${Number(keyRateLimit).toLocaleString()} req/min`}<br/>
                  • Sources: {allowedSources.length ? allowedSources.join(', ') : 'All'}<br/>
                  • Expires: {keyExpiry === 0 ? 'Never' : new Date(Date.now() + keyExpiry * 86400000).toLocaleDateString('en-US', {year: 'numeric', month: 'short', day: 'numeric'})}
                </div>
                <button className="btn" style={{background: 'var(--emerald)', color: '#001', borderColor: 'var(--emerald)', fontSize: 13, padding: 10}} onClick={() => setShowModal(false)}>I've saved the key — Close</button>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
};

const inputStyle = { width: '100%', background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 8, padding: '8px 12px', fontSize: 13, color: 'var(--text-1)', fontFamily: 'var(--sans)', outline: 'none', marginTop: 6 };

window.KeysScreen = KeysScreen;
