// ApiKeysPage — Gestion des cles API publiques (Pro Commercial 129$).
// Route : #/api-keys
// Gating : visible uniquement si user tier === AGENT_COMMERCIAL.
//
// Vague 5 PR 5.5 : exposition de l'API REST publique read-only.

(function () {
  const { useState, useEffect, useCallback } = React;

  const API_BASE = (window.VESTORA_CONFIG?.apiBase || '') + '/api/v1';
  const PUBLIC_DOCS_URL = (window.VESTORA_CONFIG?.apiBase || '') + '/api/public/v1/docs';

  async function _token() {
    try {
      if (window.vestora?.auth?.getToken) return await window.vestora.auth.getToken();
    } catch (e) { /* noop */ }
    return null;
  }

  async function _fetch(path, opts = {}) {
    const t = await _token();
    const headers = { 'Content-Type': 'application/json', ...(opts.headers || {}) };
    if (t) headers['Authorization'] = 'Bearer ' + t;
    const resp = await fetch(API_BASE + path, { ...opts, headers });
    if (!resp.ok && resp.status !== 204) {
      let detail = '';
      try { detail = (await resp.json()).detail || ''; } catch (e) { /* noop */ }
      throw new Error(detail || `HTTP ${resp.status}`);
    }
    if (resp.status === 204) return null;
    return resp.json();
  }

  function _formatDate(iso) {
    if (!iso) return '—';
    try { return new Date(iso).toLocaleDateString('fr-CA'); } catch { return iso; }
  }

  function CodeBlock({ children }) {
    return (
      <pre style={{
        background: '#0b1220',
        color: '#d6e2ff',
        padding: '12px 14px',
        borderRadius: 8,
        fontSize: 12.5,
        overflowX: 'auto',
        fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace',
        margin: '8px 0',
      }}>{children}</pre>
    );
  }

  function CreateKeyModal({ onClose, onCreated }) {
    const [name, setName] = useState('');
    const [loading, setLoading] = useState(false);
    const [createdKey, setCreatedKey] = useState(null);
    const [error, setError] = useState(null);
    const [copied, setCopied] = useState(false);

    async function submit() {
      if (!name.trim()) { setError('Donnez un nom a votre cle.'); return; }
      setLoading(true); setError(null);
      try {
        const res = await _fetch('/api_keys', { method: 'POST', body: JSON.stringify({ name: name.trim() }) });
        setCreatedKey(res);
        onCreated && onCreated();
      } catch (e) {
        setError(e.message || 'Erreur lors de la creation.');
      } finally {
        setLoading(false);
      }
    }

    function copy() {
      if (!createdKey?.key) return;
      navigator.clipboard?.writeText(createdKey.key).then(() => {
        setCopied(true); setTimeout(() => setCopied(false), 2000);
      });
    }

    return (
      <div style={{
        position: 'fixed', inset: 0, background: 'rgba(15,23,42,0.55)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', zIndex: 9999,
      }} onClick={onClose}>
        <div onClick={(e) => e.stopPropagation()} style={{
          background: '#fff', borderRadius: 12, padding: 24,
          width: 'min(540px, 92vw)', boxShadow: '0 12px 40px rgba(15,23,42,0.25)',
        }}>
          {!createdKey ? (
            <>
              <h3 style={{ margin: '0 0 12px', fontSize: 18 }}>Generer une nouvelle cle API</h3>
              <p style={{ fontSize: 13.5, color: '#475569', marginBottom: 12 }}>
                Donnez un nom convivial pour reperer cette cle (ex: "CRM Hubspot", "Script Excel").
              </p>
              <input
                type="text"
                value={name}
                onChange={(e) => setName(e.target.value)}
                placeholder="Nom de la cle"
                style={{
                  width: '100%', padding: '10px 12px', borderRadius: 8,
                  border: '1px solid #cbd5e1', fontSize: 14, marginBottom: 12,
                }}
              />
              {error && <div style={{ color: '#b91c1c', fontSize: 13, marginBottom: 8 }}>{error}</div>}
              <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end' }}>
                <button onClick={onClose} disabled={loading} style={{
                  padding: '8px 14px', borderRadius: 8, border: '1px solid #cbd5e1',
                  background: '#fff', cursor: 'pointer',
                }}>Annuler</button>
                <button onClick={submit} disabled={loading} style={{
                  padding: '8px 14px', borderRadius: 8, border: 'none',
                  background: '#0b3d2e', color: '#fff', cursor: 'pointer',
                }}>{loading ? '…' : 'Generer'}</button>
              </div>
            </>
          ) : (
            <>
              <h3 style={{ margin: '0 0 8px', fontSize: 18, color: '#0b3d2e' }}>Cle creee</h3>
              <div style={{
                background: '#fef3c7', border: '1px solid #fbbf24', borderRadius: 8,
                padding: '10px 12px', marginBottom: 12, fontSize: 13.5, color: '#78350f',
              }}>
                <strong>Important :</strong> copiez cette cle maintenant — elle ne sera plus
                affichee. Conservez-la dans un gestionnaire de secrets.
              </div>
              <CodeBlock>{createdKey.key}</CodeBlock>
              <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 12 }}>
                <button onClick={copy} style={{
                  padding: '8px 14px', borderRadius: 8, border: '1px solid #0b3d2e',
                  background: '#fff', color: '#0b3d2e', cursor: 'pointer',
                }}>{copied ? 'Copie ✓' : 'Copier'}</button>
                <button onClick={onClose} style={{
                  padding: '8px 14px', borderRadius: 8, border: 'none',
                  background: '#0b3d2e', color: '#fff', cursor: 'pointer',
                }}>J'ai copie</button>
              </div>
            </>
          )}
        </div>
      </div>
    );
  }

  function ApiKeysPage({ lang, onBack, currentUser }) {
    const [keys, setKeys] = useState([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const [showModal, setShowModal] = useState(false);

    const tier = currentUser?.plan || currentUser?.tier || 'free';
    const isProCommercial = tier === 'agent_commercial' || tier === 'pro_commercial';

    const load = useCallback(async () => {
      setLoading(true); setError(null);
      try {
        const data = await _fetch('/api_keys');
        setKeys(Array.isArray(data) ? data : []);
      } catch (e) {
        setError(e.message || 'Erreur de chargement.');
      } finally {
        setLoading(false);
      }
    }, []);

    useEffect(() => { if (isProCommercial) load(); else setLoading(false); }, [isProCommercial, load]);

    async function revoke(id) {
      if (!confirm('Revoquer cette cle ? Les integrations qui l\'utilisent cesseront de fonctionner immediatement.')) return;
      try {
        await _fetch(`/api_keys/${id}`, { method: 'DELETE' });
        await load();
      } catch (e) {
        alert('Erreur : ' + (e.message || 'inconnue'));
      }
    }

    // Tier gate UI
    if (!isProCommercial) {
      return (
        <div style={{ maxWidth: 720, margin: '40px auto', padding: '0 16px', fontFamily: 'Inter, sans-serif' }}>
          <button onClick={onBack} style={{
            background: 'none', border: 'none', color: '#0b3d2e', cursor: 'pointer',
            fontSize: 14, marginBottom: 16, padding: 0,
          }}>← Retour</button>
          <h1 style={{ fontSize: 28, marginBottom: 12 }}>API publique Vestora</h1>
          <div style={{
            background: '#f1f5f9', borderRadius: 12, padding: 24, border: '1px solid #e2e8f0',
          }}>
            <h2 style={{ margin: '0 0 8px', fontSize: 18 }}>Reserve aux abonnes Pro Commercial</h2>
            <p style={{ fontSize: 14.5, color: '#475569', lineHeight: 1.6 }}>
              L'API REST publique read-only (listings, market context, comparables,
              webhooks) est incluse dans le plan <strong>Pro Commercial 129$/mois</strong>.
              Connectez votre CRM ou vos feuilles Excel directement aux donnees Vestora.
            </p>
            <a href="#/tarifs" style={{
              display: 'inline-block', marginTop: 12, padding: '10px 18px',
              background: '#0b3d2e', color: '#fff', borderRadius: 8,
              textDecoration: 'none', fontSize: 14, fontWeight: 600,
            }}>Voir les plans</a>
          </div>
        </div>
      );
    }

    return (
      <div style={{ maxWidth: 880, margin: '32px auto', padding: '0 16px', fontFamily: 'Inter, sans-serif', color: '#0f172a' }}>
        <button onClick={onBack} style={{
          background: 'none', border: 'none', color: '#0b3d2e', cursor: 'pointer',
          fontSize: 14, marginBottom: 12, padding: 0,
        }}>← Retour</button>

        <header style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 12, marginBottom: 20 }}>
          <div>
            <h1 style={{ margin: 0, fontSize: 28 }}>Mes cles API</h1>
            <p style={{ margin: '6px 0 0', color: '#64748b', fontSize: 14 }}>
              Connectez votre CRM, Excel ou outils internes a l'API publique Vestora.
            </p>
          </div>
          <button onClick={() => setShowModal(true)} style={{
            padding: '10px 16px', borderRadius: 8, border: 'none',
            background: '#0b3d2e', color: '#fff', cursor: 'pointer', fontWeight: 600,
          }}>+ Generer une cle</button>
        </header>

        {/* Liste */}
        <section style={{
          background: '#fff', border: '1px solid #e2e8f0', borderRadius: 12,
          padding: 16, marginBottom: 24,
        }}>
          {loading && <div style={{ color: '#64748b' }}>Chargement…</div>}
          {error && <div style={{ color: '#b91c1c' }}>{error}</div>}
          {!loading && !error && keys.length === 0 && (
            <div style={{ color: '#64748b', textAlign: 'center', padding: '20px 0' }}>
              Aucune cle generee pour l'instant.
            </div>
          )}
          {!loading && keys.length > 0 && (
            <table style={{ width: '100%', borderCollapse: 'collapse', fontSize: 14 }}>
              <thead>
                <tr style={{ textAlign: 'left', color: '#64748b', borderBottom: '1px solid #e2e8f0' }}>
                  <th style={{ padding: '8px 4px' }}>Nom</th>
                  <th style={{ padding: '8px 4px' }}>Prefixe</th>
                  <th style={{ padding: '8px 4px' }}>Cree</th>
                  <th style={{ padding: '8px 4px' }}>Dernier usage</th>
                  <th style={{ padding: '8px 4px' }}>Statut</th>
                  <th style={{ padding: '8px 4px' }}></th>
                </tr>
              </thead>
              <tbody>
                {keys.map(k => (
                  <tr key={k.id} style={{ borderBottom: '1px solid #f1f5f9' }}>
                    <td style={{ padding: '10px 4px' }}>{k.name}</td>
                    <td style={{ padding: '10px 4px', fontFamily: 'monospace', color: '#475569' }}>
                      vst_live_{k.key_prefix}…
                    </td>
                    <td style={{ padding: '10px 4px', color: '#64748b' }}>{_formatDate(k.created_at)}</td>
                    <td style={{ padding: '10px 4px', color: '#64748b' }}>{_formatDate(k.last_used_at)}</td>
                    <td style={{ padding: '10px 4px' }}>
                      {k.revoked_at ? (
                        <span style={{ color: '#b91c1c', fontWeight: 600 }}>Revoquee</span>
                      ) : (
                        <span style={{ color: '#0b3d2e', fontWeight: 600 }}>Active</span>
                      )}
                    </td>
                    <td style={{ padding: '10px 4px', textAlign: 'right' }}>
                      {!k.revoked_at && (
                        <button onClick={() => revoke(k.id)} style={{
                          padding: '6px 10px', borderRadius: 6, border: '1px solid #fecaca',
                          background: '#fff', color: '#b91c1c', cursor: 'pointer', fontSize: 12.5,
                        }}>Revoquer</button>
                      )}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </section>

        {/* Documentation */}
        <section style={{
          background: '#fff', border: '1px solid #e2e8f0', borderRadius: 12, padding: 20,
        }}>
          <h2 style={{ margin: '0 0 12px', fontSize: 20 }}>Documentation</h2>
          <p style={{ fontSize: 14, color: '#475569', lineHeight: 1.6 }}>
            Toutes les requetes vers <code>/api/public/v1/*</code> doivent inclure
            votre cle API dans le header <code>X-API-Key</code> ou
            <code> Authorization: Bearer</code>.
          </p>
          <h3 style={{ fontSize: 15, marginTop: 16 }}>Exemple curl — lister des annonces</h3>
          <CodeBlock>{`curl -H "X-API-Key: vst_live_XXXX" \\
  "https://api.vestora.ca/api/public/v1/listings?city=Montreal&min_units=6&limit=20"`}</CodeBlock>
          <h3 style={{ fontSize: 15, marginTop: 16 }}>Exemple curl — contexte marche</h3>
          <CodeBlock>{`curl -H "X-API-Key: vst_live_XXXX" \\
  "https://api.vestora.ca/api/public/v1/market_context?city=Levis"`}</CodeBlock>
          <h3 style={{ fontSize: 15, marginTop: 16 }}>Exemple curl — souscrire un webhook</h3>
          <CodeBlock>{`curl -X POST -H "X-API-Key: vst_live_XXXX" \\
  -H "Content-Type: application/json" \\
  -d '{"event_type":"new_listing","target_url":"https://votre-crm.com/webhook"}' \\
  "https://api.vestora.ca/api/public/v1/webhooks/subscribe"`}</CodeBlock>
          <p style={{ marginTop: 16, fontSize: 14 }}>
            <a href={PUBLIC_DOCS_URL} target="_blank" rel="noopener noreferrer" style={{
              color: '#0b3d2e', fontWeight: 600,
            }}>Documentation OpenAPI complete →</a>
          </p>
        </section>

        {showModal && <CreateKeyModal onClose={() => setShowModal(false)} onCreated={load} />}
      </div>
    );
  }

  window.ApiKeysPage = ApiKeysPage;
})();
