/* global React, window */
// ============================================================
// 🤖 Grokbot — MCP par onglet (demande du 2026-11-03)
// ============================================================
// Panneau owner : un interrupteur lecture/écriture PAR ONGLET, plus l'émission/révocation du
// jeton du bot. Rien n'est accordé par défaut — chaque case part décochée. Révoquer un onglet
// ici coupe l'accès À L'INSTANT (le serveur revérifie à chaque appel, pas seulement à l'émission
// du jeton). Voir le bloc « GROKBOT » dans _worker.js pour ce que chaque onglet couvre, et
// pourquoi les données du parc (comptes IG, iPhones, proxys) n'y sont PAS : elles vivent dans le
// backend Python local, pas dans ce Worker.
function GrokBot() {
  const { useState, useEffect } = React;
  const [onglets, setOnglets] = useState(null);     // null = pas encore chargé
  const [erreur, setErreur] = useState("");
  const [saving, setSaving] = useState(false);
  const [jeton, setJeton] = useState(null);
  const [msg, setMsg] = useState("");

  const charger = () => {
    setErreur("");
    window.Backend.authed("/api/grok/scopes").then(r => r.json()).then(d => {
      if (d && Array.isArray(d.onglets)) setOnglets(d.onglets); else setErreur(d && d.error || "réponse inattendue");
    }).catch(e => setErreur(String((e && e.message) || e)));
  };
  useEffect(charger, []);

  const toggle = (id, champ) => {
    setOnglets(list => list.map(o => {
      if (o.id !== id) return o;
      const next = { ...o, [champ]: !o[champ] };
      if (champ === "write" && next.write) next.read = true;   // l'écriture implique la lecture
      if (champ === "read" && !next.read) next.write = false;  // retirer la lecture retire l'écriture
      return next;
    }));
  };

  const enregistrer = async () => {
    setSaving(true);
    const corps = {}; onglets.forEach(o => { corps[o.id] = { read: o.read, write: o.write }; });
    const r = await window.Backend.authed("/api/grok/scopes", { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(corps) }).then(r => r.json()).catch(() => null);
    setSaving(false);
    setMsg(r && r.ok ? "✓ Enregistré" : "Échec de l'enregistrement");
    setTimeout(() => setMsg(""), 2500);
  };

  const emettreJeton = async () => {
    const r = await window.Backend.authed("/api/grok/bot-token", { method: "POST" }).then(r => r.json()).catch(() => null);
    if (r && r.token) setJeton(r.token); else setMsg("Impossible d'émettre le jeton");
  };
  const revoquerJeton = async () => {
    await window.Backend.authed("/api/grok/bot-token", { method: "DELETE" }).catch(() => null);
    setJeton(null); setMsg("Jeton révoqué — l'accès du bot est coupé");
    setTimeout(() => setMsg(""), 2500);
  };

  const btn = { padding: "9px 16px", borderRadius: 9, fontSize: 13, fontWeight: 700, cursor: "pointer", border: "1px solid var(--border)", background: "var(--surface-2)", color: "var(--text)" };
  const btnAccent = { ...btn, background: "var(--accent)", color: "#06281c", border: "none" };
  const urlMcp = (typeof location !== "undefined" ? location.origin : "") + "/api/mcp";

  return (
    <div style={{ maxWidth: 720, margin: "0 auto", padding: "28px 20px" }}>
      {window.PageHead
        ? <window.PageHead title="Grokbot" icon="bolt" subtitle="Accès MCP pour ton bot de veille — rien n'est accordé tant que tu ne coches rien." />
        : <div style={{ fontSize: 20, fontWeight: 800, marginBottom: 18 }}>🤖 Grokbot</div>}

      <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 13, padding: "16px 18px", marginBottom: 16 }}>
        <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 6 }}>Jeton du bot</div>
        <div style={{ fontSize: 12, color: "var(--muted)", marginBottom: 10 }}>
          À coller dans la config MCP du Grokbot (en-tête <code className="mono">Authorization: Bearer …</code>).
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
          <code style={{ fontSize: 12, padding: "6px 9px", borderRadius: 7, background: "var(--surface-2)", border: "1px solid var(--border)", wordBreak: "break-all", flex: 1 }}>{urlMcp}</code>
          <button style={btn} onClick={() => { try { navigator.clipboard.writeText(urlMcp); setMsg("URL copiée"); setTimeout(() => setMsg(""), 2000); } catch (e) {} }}>Copier</button>
        </div>
        {jeton ? (
          <div style={{ display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" }}>
            <code style={{ fontSize: 12, padding: "6px 9px", borderRadius: 7, background: "var(--surface-2)", border: "1px solid var(--border)", wordBreak: "break-all" }}>{jeton}</code>
            <button style={btn} onClick={() => { try { navigator.clipboard.writeText(jeton); setMsg("Jeton copié"); setTimeout(() => setMsg(""), 2000); } catch (e) {} }}>Copier</button>
            <button style={btn} onClick={() => setJeton(null)}>Masquer</button>
          </div>
        ) : (
          <div style={{ display: "flex", gap: 8 }}>
            <button style={btnAccent} onClick={emettreJeton} title="Émet un nouveau jeton — l'ancien cesse de marcher">Émettre un jeton</button>
            <button style={btn} onClick={revoquerJeton} title="Coupe l'accès immédiatement">Révoquer l'accès</button>
          </div>
        )}
      </div>

      <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 13, padding: "16px 18px" }}>
        <div style={{ fontWeight: 700, fontSize: 14, marginBottom: 10 }}>Accès par onglet</div>
        {erreur && <div style={{ fontSize: 12, color: "var(--danger)", marginBottom: 8 }}>{erreur} <button style={{ ...btn, padding: "3px 8px", fontSize: 11 }} onClick={charger}>Réessayer</button></div>}
        {onglets === null && !erreur && <div style={{ fontSize: 12, color: "var(--muted)" }}>Chargement…</div>}
        {onglets && onglets.map(o => (
          <div key={o.id} style={{ display: "flex", alignItems: "center", justifyContent: "space-between", padding: "9px 0", borderTop: "1px solid var(--border)" }}>
            <span style={{ fontSize: 13 }}>{o.label}</span>
            <span style={{ display: "flex", gap: 14 }}>
              <label style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 12, color: "var(--muted)", cursor: "pointer" }}>
                <input type="checkbox" checked={o.read} onChange={() => toggle(o.id, "read")} /> Lecture
              </label>
              <label style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 12, color: "var(--muted)", cursor: "pointer" }}>
                <input type="checkbox" checked={o.write} onChange={() => toggle(o.id, "write")} /> Écriture
              </label>
            </span>
          </div>
        ))}
        {onglets && (
          <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 16, gap: 10, alignItems: "center" }}>
            {msg && <span style={{ fontSize: 12.5, color: "var(--accent)", fontWeight: 600 }}>{msg}</span>}
            <button style={btnAccent} onClick={enregistrer} disabled={saving}>{saving ? "Enregistrement…" : "Enregistrer"}</button>
          </div>
        )}
      </div>
    </div>
  );
}

window.GrokBot = GrokBot;
