// WiseTokens — API Keys
function Keys({ onToast }) {
  const [keys, setKeys] = React.useState(WT.KEYS);
  const [creating, setCreating] = React.useState(false);
  const [revealed, setRevealed] = React.useState(null);
  const [newKey, setNewKey] = React.useState({ name: '', scope: 'all models', rate: 120 });

  const create = () => {
    const prefix = 'wt-live-' + Math.random().toString(36).slice(2, 6);
    const secret = prefix + '-' + Math.random().toString(36).slice(2, 12) + Math.random().toString(36).slice(2, 12);
    const k = { id: 'k' + Date.now(), name: newKey.name || 'untitled', prefix, created: new Date().toISOString().slice(0,10), lastUsed: 'never', requests: 0, scope: newKey.scope, rate: newKey.rate, status: 'active', full: secret };
    setKeys([k, ...keys]);
    setRevealed(k);
    setCreating(false);
    setNewKey({ name: '', scope: 'all models', rate: 120 });
  };

  const revoke = (id) => {
    setKeys(keys.map(k => k.id === id ? { ...k, status: 'revoked' } : k));
    onToast('Key revoked');
  };

  return (
    <div className="page">
      <div className="page-h">
        <div>
          <h1>API Keys</h1>
          <div className="sub">Create keys scoped to specific models and rate limits. Keys are shown once — store them securely.</div>
        </div>
        <div className="page-actions">
          <button className="btn primary" onClick={() => setCreating(true)}><Icon name="plus" size={13}/> Create key</button>
        </div>
      </div>

      <div className="card" style={{ padding: 0, overflow: 'hidden' }}>
        <table className="table">
          <thead>
            <tr>
              <th>Name</th><th>Key</th><th>Scope</th><th className="right">Rate / min</th><th className="right">Requests</th><th>Last used</th><th>Status</th><th></th>
            </tr>
          </thead>
          <tbody>
            {keys.map(k => (
              <tr key={k.id} style={{ opacity: k.status === 'revoked' ? 0.5 : 1 }}>
                <td style={{ fontWeight: 500, padding: '12px' }}>{k.name}</td>
                <td><span className="mono" style={{ fontSize: 12 }}>{k.prefix}····················</span></td>
                <td><span className="badge">{k.scope}</span></td>
                <td className="num right tabular">{k.rate}</td>
                <td className="num right tabular">{WT.fmt.num(k.requests)}</td>
                <td className="dim">{k.lastUsed}</td>
                <td>{k.status === 'active' ? <span className="badge ok dot">active</span> : <span className="badge dot">revoked</span>}</td>
                <td style={{ textAlign: 'right' }}>
                  {k.status === 'active' && (
                    <button className="btn sm" onClick={() => revoke(k.id)}>Revoke</button>
                  )}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      <div className="card" style={{ marginTop: 18, padding: 22 }}>
        <div className="card-h"><h3>Quickstart</h3></div>
        <div className="grid grid-2" style={{ gap: 18 }}>
          <div>
            <div className="dim" style={{ marginBottom: 8, fontSize: 12 }}>Python (OpenAI SDK)</div>
            <pre className="code"><span className="kw">from</span> openai <span className="kw">import</span> OpenAI{'\n\n'}client = OpenAI({'\n'}  base_url=<span className="str">"https://api.wisetokens.ai/v1"</span>,{'\n'}  api_key=<span className="str">"wt-live-····"</span>,{'\n'}){'\n\n'}resp = client.chat.completions.create({'\n'}  model=<span className="str">"deepseek-v3.1"</span>,{'\n'}  messages=[{'{'}<span className="str">"role"</span>: <span className="str">"user"</span>, <span className="str">"content"</span>: <span className="str">"Hi"</span>{'}'}],{'\n'}){'\n\n'}<span className="com"># Cost: $0.0004</span></pre>
          </div>
          <div>
            <div className="dim" style={{ marginBottom: 8, fontSize: 12 }}>cURL</div>
            <pre className="code">curl https://api.wisetokens.ai/v1/chat/completions \{'\n'}  -H <span className="str">"Authorization: Bearer $WT_KEY"</span> \{'\n'}  -H <span className="str">"Content-Type: application/json"</span> \{'\n'}  -d <span className="str">{"'{"}</span>{'\n'}    <span className="str">"model"</span>: <span className="str">"deepseek-v3.1"</span>,{'\n'}    <span className="str">"messages"</span>: [{'{'}<span className="str">"role"</span>:<span className="str">"user"</span>,<span className="str">"content"</span>:<span className="str">"Hi"</span>{'}'}],{'\n'}    <span className="str">"stream"</span>: <span className="num">true</span>{'\n'}  <span className="str">{"}'"}</span></pre>
          </div>
        </div>
      </div>

      {creating && (
        <div className="backdrop" onClick={() => setCreating(false)}>
          <div className="modal" onClick={e => e.stopPropagation()}>
            <div className="modal-h"><h2>Create API key</h2></div>
            <div className="modal-b" style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div className="field">
                <label>Name</label>
                <input className="input" placeholder="e.g. production" value={newKey.name} onChange={e => setNewKey({...newKey, name: e.target.value})}/>
              </div>
              <div className="field">
                <label>Model scope</label>
                <div className="seg">
                  {['all models', 'chat only', 'reasoning only', 'code only'].map(s => (
                    <button key={s} className={newKey.scope === s ? 'active' : ''} onClick={() => setNewKey({...newKey, scope: s})}>{s}</button>
                  ))}
                </div>
              </div>
              <div className="field">
                <label>Rate limit (requests/min) — <span className="mono">{newKey.rate}</span></label>
                <input type="range" min="60" max="6000" step="60" value={newKey.rate} onChange={e => setNewKey({...newKey, rate: +e.target.value})}/>
              </div>
            </div>
            <div className="modal-f">
              <button className="btn" onClick={() => setCreating(false)}>Cancel</button>
              <button className="btn primary" onClick={create}>Create key</button>
            </div>
          </div>
        </div>
      )}

      {revealed && (
        <div className="backdrop" onClick={() => setRevealed(null)}>
          <div className="modal" onClick={e => e.stopPropagation()}>
            <div className="modal-h"><h2>Key created — copy it now</h2></div>
            <div className="modal-b">
              <p className="dim" style={{ margin: '0 0 12px', fontSize: 12.5 }}>You won't be able to see the full key again. Store it in a secrets manager.</p>
              <div style={{ display: 'flex', gap: 6, padding: 12, background: 'var(--bg-sunken)', border: '1px solid var(--line)', borderRadius: 6 }}>
                <code className="mono" style={{ flex: 1, fontSize: 12.5, wordBreak: 'break-all' }}>{revealed.full}</code>
                <button className="btn sm" onClick={() => { navigator.clipboard && navigator.clipboard.writeText(revealed.full); onToast('Copied'); }}>
                  <Icon name="copy" size={12}/> Copy
                </button>
              </div>
            </div>
            <div className="modal-f">
              <button className="btn primary" onClick={() => setRevealed(null)}>Done</button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
Object.assign(window, { Keys });
