/* global React, Icon, Button, Badge, Backend */
// ============================================================
// Conteneurs multi-comptes — un conteneur = un compte sur cet iPhone
// ============================================================
const CTN_STAGES = [
  { id: "nouveau",  label: "Nouveau",  tone: "gray"  },
  { id: "warmup",   label: "Warm-up",  tone: "amber" },
  { id: "actif",    label: "Actif",    tone: "green" },
  { id: "suspendu", label: "Suspendu", tone: "amber" },
  { id: "banni",    label: "Banni",    tone: "red"   },
];
const ctnStage = (id) => CTN_STAGES.find(s => s.id === id) || CTN_STAGES[0];

// À qui cette identité est confiée. Réservé au propriétaire et aux managers : c'est une
// décision d'organisation, pas un réglage que le VA prend lui-même.
function AssignRow({ container, onAssign, busy }) {
  const { useState, useEffect } = React;
  const [team, setTeam] = useState([]);
  useEffect(() => {
    setTeam((window.DATA && DATA.realTeam ? DATA.realTeam() : []).filter(o => o.role !== "Owner"));
  }, []);
  const val = container.assigned_to || "";
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 7, flexWrap: "wrap" }}>
      <span style={{ fontSize: 11, color: "var(--faint)" }}>confié à</span>
      <select value={val} disabled={busy}
        onChange={e => {
          const o = team.find(x => x.id === e.target.value);
          onAssign(container.id, e.target.value, o ? o.name : "");
        }}
        style={{ background: "var(--surface-3)", border: "1px solid var(--border)", borderRadius: 7,
                 color: "var(--text)", fontSize: 11, padding: "3px 7px" }}>
        <option value="">— personne —</option>
        {team.map(o => <option key={o.id} value={o.id}>{o.name}</option>)}
      </select>
      {!team.length ? (
        <span style={{ fontSize: 10.5, color: "var(--faint)" }}>
          aucun VA inscrit pour l'instant — ils apparaîtront ici après validation dans « Demandes »
        </span>) : null}
    </div>
  );
}


function ContainersPanel({ device, user }) {
  const { useState, useEffect } = React;
  const udid = device && (device.udid || device.id);
  const [data, setData] = useState(null);
  const [adding, setAdding] = useState(false);
  const [name, setName] = useState("");
  const [openId, setOpenId] = useState(null);
  const [busy, setBusy] = useState(false);
  const [migrating, setMigrating] = useState(false);   // reprise de l'ancienne fiche (hook AVANT tout return)

  const load = () => { if (udid) Backend.containers(udid).then(setData); };
  useEffect(() => { load(); }, [udid]);
  if (!udid) return null;

  const list = (data && data.containers) || [];
  const active = list.find(c => c.active);
  // Identités confiées : « Modèle 4 -> Josué, Modèle 5 -> Plasti » (vidéo 1, 12:40). Chez un
  // VA, les identités confiées à quelqu'un d'autre sont GRISÉES — visibles, mais pas
  // touchables : il voit qu'elles existent sans pouvoir se tromper de compte.
  const myRank = window.ROLE_RANK ? window.ROLE_RANK(user && user.role) : 3;
  const myId = (user && (user.id || user.uid)) || "";
  const notMine = (c) => myRank <= 1 && c.assigned_to && c.assigned_to !== myId;

  const add = async () => {
    const n = name.trim(); if (!n) return;
    setBusy(true); await Backend.containerCreate(udid, n); setBusy(false);
    setName(""); setAdding(false); load();
  };
  const activate = async (id) => { setBusy(true); await Backend.containerActive(udid, id); setBusy(false); load(); };
  const assign = async (id, u, n) => { setBusy(true); await Backend.containerAssign(id, u, n); setBusy(false); load(); };
  const setStage = async (id, stage) => { setBusy(true); await Backend.containerUpdate(id, { stage }); setBusy(false); load(); };
  // Reprise de l'ancienne fiche « Information compte » (stockée dans le cloud, à part).
  // Deux fiches concurrentes = on remplit l'une et le parcours lit l'autre : on rapatrie
  // tout ici, une bonne fois, sur un clic. Les valeurs passent du navigateur à ce Mac,
  // elles ne transitent par rien d'autre. On n'écrase jamais un champ déjà rempli.
  const legacy = ((device && device.accounts) || []).filter(a => (a && ((a.name || "").trim() || (a.pass || "").trim())));
  const migrated = (() => { try { return localStorage.getItem("wl_migrated_" + udid) === "1"; } catch (e) { return false; } })();
  // Un mot de passe présent dans l'ancienne fiche mais absent des conteneurs = travail NON fait.
  // Dans ce cas on continue de le rappeler, même si la reprise a déjà été tentée ou refusée :
  // un rappel qui disparaît avant que le problème soit réglé ne sert à rien.
  const lostPw = legacy.some(a => (a.pass || "").trim())
    && !((data && data.containers) || []).some(c => ((c.account || {}).password || "").trim());
  const STAGE_OF = { cree: "nouveau", echauffement: "warmup", actif: "actif", suspendu: "suspendu" };

  const migrate = async () => {
    setMigrating(true);
    let cur = (data && data.containers) || [];
    for (let i = 0; i < legacy.length; i++) {
      const a = legacy[i];
      let c = cur[i];
      if (!c) {
        await Backend.containerCreate(udid, (a.name || "").replace(/^@/, "") || String(cur.length + 1));
        const fresh = await Backend.containers(udid);
        cur = (fresh && fresh.containers) || [];
        c = cur[i];
      }
      if (!c) continue;
      const acc = c.account || {};
      const fields = {};
      if ((a.name || "").trim() && !acc.username) fields.username = (a.name || "").trim().replace(/^@/, "");
      if ((a.pass || "").trim() && !acc.password) fields.password = a.pass;
      if (Object.keys(fields).length) await Backend.containerAccount(c.id, fields);
      if (a.status && STAGE_OF[a.status] && c.stage === "nouveau") await Backend.containerUpdate(c.id, { stage: STAGE_OF[a.status] });
    }
    try { localStorage.setItem("wl_migrated_" + udid, "1"); } catch (e) {}
    setMigrating(false);
    load();
  };

  const remove = async (id, label) => {
    if (!window.confirm(`Supprimer la fiche « ${label} » ?\n\nLe conteneur reste sur l'iPhone : seule sa fiche (compte, statut) est effacée ici.`)) return;
    setBusy(true); await Backend.containerDelete(id); setBusy(false); setOpenId(null); load();
  };

  return (
    <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--r-lg)", padding: 15, marginBottom: 14 }}>
      {legacy.length > 0 && (!migrated || lostPw) && (
        <div style={{ marginBottom: 12, padding: "9px 11px", borderRadius: 9, background: "rgba(245,185,66,.1)",
          border: "1px solid rgba(245,185,66,.3)", fontSize: 11, color: "var(--text)", lineHeight: 1.5 }}>
          <b>{lostPw && migrated ? "Mot de passe pas encore repris" : "Ancienne fiche trouvée"}</b> — {legacy.length} compte{legacy.length > 1 ? "s" : ""} dans « Information compte ».
          <div style={{ color: "var(--muted)", marginTop: 3 }}>
            {lostPw && migrated
              ? "L'ancienne fiche contient un mot de passe qui n'est toujours pas dans les conteneurs. Relance la reprise, ou ouvre l'ancienne fiche pour le lire et le recopier."
              : "Je les rapatrie ici, sans écraser ce qui est déjà rempli. C'est cette fiche que le parcours lit."}
          </div>
          <div style={{ display: "flex", gap: 6, marginTop: 7 }}>
            <button onClick={migrate} disabled={migrating} style={{ background: "var(--accent)", color: "#06281c", border: "none",
              borderRadius: 7, padding: "6px 11px", fontSize: 11, fontWeight: 700, cursor: "pointer" }}>
              {migrating ? "reprise…" : "Reprendre ces infos"}
            </button>
            <button onClick={() => { try { localStorage.setItem("wl_migrated_" + udid, "1"); } catch (e) {} load(); }}
              style={{ background: "var(--surface-3)", border: "1px solid var(--border)", borderRadius: 7, padding: "6px 11px",
                fontSize: 11, color: "var(--muted)", cursor: "pointer" }}>non merci</button>
            {/* Filet : l'ancienne fiche n'est plus affichée. Si la reprise ne récupère pas tout,
                il faut pouvoir la rouvrir pour lire ce qu'elle contient encore. */}
            <button onClick={() => { try { localStorage.setItem("wl_show_legacy_" + udid, "1"); } catch (e) {} window.location.reload(); }}
              style={{ background: "none", border: "none", padding: "6px 4px", fontSize: 11,
                color: "var(--accent-2)", cursor: "pointer", textDecoration: "underline" }}>voir l'ancienne fiche</button>
          </div>
        </div>
      )}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 12 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 8, color: "var(--muted)" }}>
          {React.createElement(Icon.apps, { size: 15 })}
          <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".06em", textTransform: "uppercase" }}>Conteneurs</span>
          <span className="mono" style={{ fontSize: 10.5, color: "var(--faint)" }}>{list.length}</span>
        </div>
        <button onClick={() => setAdding(a => !a)} style={{ display: "flex", alignItems: "center", gap: 5, background: "none",
          border: "1px dashed var(--border-2)", borderRadius: 8, padding: "5px 9px", color: "var(--muted)", fontSize: 11, cursor: "pointer" }}>
          {React.createElement(Icon.plus, { size: 13 })} Ajouter
        </button>
      </div>

      {adding && (
        <div style={{ display: "flex", gap: 8, marginBottom: 11 }}>
          <input autoFocus value={name} onChange={e => setName(e.target.value)}
            onKeyDown={e => e.key === "Enter" && add()}
            placeholder="nom vu sur le téléphone, ex. PE-P5-#3"
            style={{ flex: 1, padding: "9px 11px", background: "var(--bg-2)", border: "1px solid var(--border-2)",
                     borderRadius: 9, color: "var(--text)", fontSize: 12, outline: "none" }} />
          <Button variant="primary" disabled={!name.trim() || busy} onClick={add}>Créer</Button>
        </div>
      )}

      {list.length === 0 ? (
        <div style={{ padding: "16px 4px", textAlign: "center", color: "var(--faint)", fontSize: 11.5, lineHeight: 1.6 }}>
          Aucun conteneur.<br />Crée ici la fiche de chaque conteneur présent sur ce téléphone.
        </div>
      ) : (
        <div style={{ display: "grid", gap: 7 }}>
          {list.map(c => {
            const st = ctnStage(c.stage);
            const open = openId === c.id;
            const a = c.account || {};
            const bloque = notMine(c);
            return (
              <div key={c.id} style={{ borderRadius: 11, border: "1px solid " + (c.active ? "var(--accent-line)" : "var(--border)"),
                background: c.active ? "var(--accent-soft)" : "var(--surface-2)", overflow: "hidden",
                opacity: bloque ? .42 : 1, filter: bloque ? "grayscale(.6)" : "none" }}
                title={bloque ? "confié à " + (c.assigned_name || "quelqu'un d'autre") : undefined}>
                <div onClick={bloque ? undefined : () => setOpenId(open ? null : c.id)}
                  style={{ display: "flex", alignItems: "center", gap: 9, padding: "10px 12px",
                           cursor: bloque ? "not-allowed" : "pointer" }}>
                  <span style={{ width: 7, height: 7, borderRadius: 99, flex: "none",
                    background: st.tone === "green" ? "var(--accent)" : st.tone === "red" ? "var(--danger)" : st.tone === "amber" ? "var(--busy)" : "var(--faint)" }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12, fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{c.name}</div>
                    <div className="mono" style={{ fontSize: 10.5, color: "var(--faint)" }}>
                      {a.username ? "@" + a.username : "aucun compte"} · {st.label}
                      {c.assigned_name ? " · → " + c.assigned_name : ""}
                    </div>
                  </div>
                  {bloque
                    ? <span style={{ fontSize: 10, color: "var(--faint)" }}>🔒 pas à toi</span>
                    : c.active
                    ? <Badge tone="green">actif</Badge>
                    : <button onClick={e => { e.stopPropagation(); activate(c.id); }} disabled={busy}
                        style={{ background: "var(--surface-3)", border: "1px solid var(--border)", borderRadius: 8,
                                 padding: "4px 9px", color: "var(--text)", fontSize: 11, cursor: "pointer" }}>Actif</button>}
                </div>
                {open && (
                  <div style={{ padding: "0 12px 12px", display: "grid", gap: 9 }}>
                    <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                      {CTN_STAGES.map(s => (
                        <button key={s.id} onClick={() => setStage(c.id, s.id)} disabled={busy}
                          style={{ padding: "4px 9px", borderRadius: 7, fontSize: 11, cursor: "pointer",
                            background: c.stage === s.id ? "var(--surface-3)" : "transparent",
                            border: "1px solid " + (c.stage === s.id ? "var(--border-2)" : "var(--border)"),
                            color: c.stage === s.id ? "var(--text)" : "var(--faint)" }}>{s.label}</button>
                      ))}
                    </div>
                    {myRank >= 2 ? <AssignRow container={c} onAssign={assign} busy={busy} /> : null}
                    <AccountForm container={c} onSaved={load} user={user} device={device} />
                    <button onClick={() => remove(c.id, c.name)} style={{ background: "none", border: "none",
                      color: "var(--faint)", fontSize: 11, textAlign: "left", cursor: "pointer", padding: 0 }}>
                      supprimer cette fiche
                    </button>
                  </div>
                )}
              </div>
            );
          })}
        </div>
      )}

      {active && (
        <div className="mono" style={{ marginTop: 11, fontSize: 10.5, color: "var(--faint)", lineHeight: 1.5 }}>
          actif : {active.name}{active.account && active.account.username ? " · @" + active.account.username : ""}
          <br />la bascule se fait sur le téléphone — ceci note seulement lequel est ouvert.
        </div>
      )}
    </div>
  );
}

// ---- numéro jetable : demande, attente du code, frappe sur le téléphone ----
// Une location coûte de l'argent : elle n'a lieu que sur clic explicite, jamais toute seule.
// Pseudos Instagram : on propose des noms du bon style ET on ne garde que ceux qui sont
// LIBRES — la vérification se fait sur la page publique du profil, côté Mac (jamais depuis
// le téléphone : rien ne relie ces recherches au compte en cours de création).
// Une date de naissance plausible : 19 à 29 ans, jamais le 1er du mois (trop régulier),
// au format JJ/MM/AAAA — c'est ce que la console sait ensuite régler sur le téléphone.
function genBirthdate() {
  const age = 19 + Math.floor(Math.random() * 11);
  const y = new Date().getFullYear() - age;
  const m = 1 + Math.floor(Math.random() * 12);
  const last = new Date(y, m, 0).getDate();
  const d = 2 + Math.floor(Math.random() * (Math.min(28, last) - 1));
  const p = (n) => String(n).padStart(2, "0");
  return p(d) + "/" + p(m) + "/" + y;
}

// ============================================================
// Bios — dans le ton des exemples d'Arthur : un compte refait après suppression,
// tout en minuscules, phrase courte, puis ce qu'on cherche.
// Trois morceaux tirés au hasard = des milliers de combinaisons : deux comptes de la
// même ferme n'auront pas la même bio, ce qui est tout l'intérêt.
// ============================================================
const BIO_LOST = [
  "my old acc got nuked", "old account banned again", "my ig got deleted",
  "lost my old page", "got wiped again", "my last account is gone",
  "banned out of nowhere", "old acc disappeared", "they took my old one",
  "second account, first got deleted", "my page got removed",
];
const BIO_LINK = [
  "so... here we are again", "so hi i guess", "starting fresh",
  "back again", "round two", "so... take two", "here we go again",
  "new page, same me", "trying again",
];
const BIO_WANT = [
  "looking for someone nice", "just looking for real convos",
  "here to talk to real people", "just want normal conversations",
  "looking for someone to talk to", "dm me if you're chill",
  "not here for games", "just being myself this time",
  "say hi, i don't bite", "looking for something real",
];
const BIO_TAIL = ["", "", "", " lol", " 🙃", " 🤍", " ✨", " ..."];

function genBio() {
  const pick = (a) => a[Math.floor(Math.random() * a.length)];
  for (let i = 0; i < 30; i++) {
    const r = Math.random();
    let t;
    if (r < 0.45) t = pick(BIO_LOST) + " " + pick(BIO_LINK) + ", " + pick(BIO_WANT);
    else if (r < 0.8) t = pick(BIO_LOST) + "... " + pick(BIO_LINK) + " " + pick(BIO_WANT);
    else t = pick(BIO_LOST) + " " + pick(BIO_LINK);
    // une seule marque de suspension par bio : deux dans la même phrase se lisent mal
    let first = true;
    t = t.replace(/\.\.\./g, () => { if (first) { first = false; return "..."; } return ""; });
    let tail = pick(BIO_TAIL);
    if (tail.includes("...") && t.includes("...")) tail = "";
    t = (t + tail).replace(/\s+/g, " ").replace(/\s+,/g, ",").trim();
    if (t.length <= 150) return t;        // Instagram coupe au-delà de 150 caractères
  }
  return pick(BIO_LOST) + " " + pick(BIO_LINK);
}

function PseudoPicker({ base, onPick }) {
  const { useState, useEffect } = React;
  const [rows, setRows] = useState(null);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState("");

  const load = async (withBase) => {
    setBusy(true); setErr("");
    const r = await Backend.usernames({ base: withBase ? (base || "") : "", count: 5 });
    setBusy(false);
    if (!r) { setErr("vérification impossible (pas de réseau ?)"); return; }
    setRows(r.suggestions || []);
    if (r.error) setErr(r.error);
  };
  useEffect(() => { load(!!(base || "").trim()); }, []);

  const dot = { free: "var(--accent)", taken: "#ff6b6b", unknown: "var(--faint)" };
  const word = { free: "libre", taken: "déjà pris", unknown: "pas vérifiable" };
  const wrap = { background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 10, padding: 10 };
  const line = { display: "flex", alignItems: "center", gap: 8, padding: "5px 0" };
  const use = { background: "var(--accent-soft)", border: "1px solid var(--accent-line)", borderRadius: 7,
                padding: "3px 9px", color: "var(--accent)", cursor: "pointer", fontSize: 11, fontWeight: 600 };

  return (
    <div style={wrap}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 6 }}>
        <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: ".05em", textTransform: "uppercase", color: "var(--muted)" }}>Pseudos disponibles</span>
        <span style={{ marginLeft: "auto", display: "flex", gap: 5 }}>
          {(base || "").trim() ? <button onClick={() => load(true)} disabled={busy} style={{ ...use, background: "var(--surface-3)", color: "var(--muted)", borderColor: "var(--border)" }}>variantes de « {base} »</button> : null}
          <button onClick={() => load(false)} disabled={busy} style={{ ...use, background: "var(--surface-3)", color: "var(--muted)", borderColor: "var(--border)" }}>{busy ? "…" : "↻ autres"}</button>
        </span>
      </div>
      {busy && !rows ? <div style={{ fontSize: 11, color: "var(--faint)" }}>vérification sur Instagram… (~10 s)</div> : null}
      {rows && rows.length === 0 ? <div style={{ fontSize: 11, color: "var(--faint)" }}>aucune proposition — réessaie.</div> : null}
      {(rows || []).map(r => (
        <div key={r.username} style={line}>
          <span style={{ width: 7, height: 7, borderRadius: 99, background: dot[r.status], flex: "none" }} />
          <span className="mono" style={{ fontSize: 12, color: r.status === "taken" ? "var(--faint)" : "var(--text)", textDecoration: r.status === "taken" ? "line-through" : "none" }}>{r.username}</span>
          <span style={{ fontSize: 10.5, color: "var(--faint)" }}>{word[r.status]}</span>
          {r.status !== "taken" && <button onClick={() => onPick(r.username)} style={{ ...use, marginLeft: "auto" }}>utiliser</button>}
        </div>
      ))}
      {err ? <div style={{ fontSize: 10.5, color: "var(--busy, #f5b942)", marginTop: 5 }}>⚠️ {err}</div> : null}
      <div className="mono" style={{ fontSize: 10, color: "var(--faint)", marginTop: 6, lineHeight: 1.4 }}>
        « libre » = le profil n'existe pas aujourd'hui. Instagram garde le dernier mot au moment de l'inscription.
      </div>
    </div>
  );
}

function SmsBlock({ container, user, onPhone }) {
  const { useState, useEffect, useRef } = React;
  const isBoss = !!user && ["Owner", "Admin"].indexOf(user.role) >= 0;
  const a = container.account || {};
  const [cfg, setCfg] = useState(null);
  const [key, setKey] = useState("");
  const [rental, setRental] = useState(a.sms_rental_id || null);
  const [number, setNumber] = useState(a.sms_number || a.phone || "");
  const [code, setCode] = useState(null);
  const [state, setState] = useState(a.sms_status || null);   // active / completed / cancelled
  const [busy, setBusy] = useState("");
  const [err, setErr] = useState(null);
  const timer = useRef(null);

  useEffect(() => { Backend.smsStatus().then(setCfg); }, []);

  // tant qu'une location est active et sans code, on interroge toutes les 4 s
  useEffect(() => {
    clearInterval(timer.current);
    if (!rental || code || state !== "active") return;
    timer.current = setInterval(async () => {
      const r = await Backend.smsPoll(container.id, rental);
      if (!r.ok) {
        // 429 = on interroge trop vite, on patiente. 404 = la location n'existe plus :
        // inutile de continuer à attendre un SMS qui n'arrivera jamais.
        if (r.gone) { setState("expired"); clearInterval(timer.current); }
        return;
      }
      if (r.code) { setCode(r.code); setState(r.status || "completed"); clearInterval(timer.current); }
      else if (r.status && r.status !== "active") { setState(r.status); clearInterval(timer.current); }
    }, 6000);
    return () => clearInterval(timer.current);
  }, [rental, code, state, container.id]);

  const rent = async () => {
    setErr(null); setBusy("rent"); setCode(null);
    const r = await Backend.smsRent(container.id);
    setBusy("");
    if (!r.ok) return setErr(r.error);
    setRental(String(r.id)); setNumber(r.number); setState("active");
    onPhone && onPhone(r.number);
  };
  const type = async (txt) => { setBusy("type"); await Backend.smsType(container.id, txt); setBusy(""); };
  const stop = async (kind) => {
    setBusy(kind);
    const r = kind === "cancel" ? await Backend.smsCancel(container.id, rental)
                                : await Backend.smsDone(container.id, rental);
    setBusy("");
    if (!r.ok) return setErr(r.error);
    setState(kind === "cancel" ? "cancelled" : "completed");
    clearInterval(timer.current);
  };

  const lab = { fontSize: 10.5, fontWeight: 600, color: "var(--faint)", textTransform: "uppercase", letterSpacing: ".05em" };
  const chip = { background: "var(--surface-3)", border: "1px solid var(--border)", borderRadius: 7,
                 padding: "5px 9px", color: "var(--muted)", fontSize: 11, cursor: "pointer" };

  if (!cfg) return null;
  if (!cfg.configured) {
    return (
      <div style={{ padding: "10px 11px", borderRadius: 9, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
        <div style={lab}>Numéro de téléphone</div>
        <div style={{ fontSize: 11, color: "var(--faint)", marginTop: 5, lineHeight: 1.5 }}>
          {isBoss
            ? "Enregistre ta clé Getatext dans « API » (menu de gauche) pour activer les numéros."
            : "Service de numéros non configuré — demande-le à ton responsable."}
        </div>
      </div>
    );
  }

  return (
    <div style={{ padding: "10px 11px", borderRadius: 9, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <span style={lab}>Numéro de téléphone</span>
        <div style={{ flex: 1 }} />
        {cfg.balance && cfg.balance.ok
          ? <span className="mono" style={{ fontSize: 10.5, color: "var(--faint)" }}>solde {cfg.balance.balance} $</span>
          : null}
      </div>

      {!number || state === "cancelled" ? (
        <div style={{ marginTop: 7 }}>
          <button onClick={rent} disabled={busy === "rent"} style={{ ...chip, background: "var(--accent)",
            color: "#06281c", border: "none", fontWeight: 600, padding: "8px 12px" }}>
            {busy === "rent" ? "demande…" : "Demander un numéro"}
          </button>
          <span style={{ fontSize: 10.5, color: "var(--faint)", marginLeft: 8 }}>débite ton compte Getatext</span>
        </div>
      ) : (
        <div style={{ marginTop: 7, display: "grid", gap: 7 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
            <span className="mono" style={{ fontSize: 13.5, fontWeight: 700, color: "var(--text)" }}>{number}</span>
            <button style={chip} onClick={() => { try { navigator.clipboard.writeText(number); } catch (e) {} }}>copier</button>
            <button style={chip} onClick={() => type(number)}>taper sur le tél.</button>
          </div>

          {code ? (
            <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
              <span className="mono" style={{ fontSize: 16, fontWeight: 700, letterSpacing: ".1em", color: "var(--accent)" }}>{code}</span>
              <button style={chip} onClick={() => { try { navigator.clipboard.writeText(code); } catch (e) {} }}>copier</button>
              <button style={chip} onClick={() => type(code)}>taper sur le tél.</button>
            </div>
          ) : state === "active" ? (
            <div style={{ fontSize: 11, color: "var(--busy)" }}>⏳ en attente du SMS…</div>
          ) : (
            <div style={{ fontSize: 11, color: "var(--faint)" }}>
              Ce numéro est terminé : Instagram n'enverra plus de code dessus.
            </div>
          )}

          {state === "active" ? (
            <div style={{ display: "flex", gap: 6 }}>
              <button style={chip} disabled={busy === "cancel"} onClick={() => stop("cancel")}>annuler (remboursé)</button>
              {code && <button style={chip} disabled={busy === "done"} onClick={() => stop("done")}>terminé</button>}
            </div>
          ) : (
            /* location finie (code déjà utilisé, expirée…) : sans ce bouton on reste coincé,
               le « I didn't get the code » d'Instagram enverrait sur un numéro qui n'écoute plus. */
            <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
              <button onClick={rent} disabled={busy === "rent"} style={{ ...chip, background: "var(--accent)",
                color: "#06281c", border: "none", fontWeight: 600, padding: "7px 11px" }}>
                {busy === "rent" ? "demande…" : "Demander un autre numéro"}
              </button>
              <span style={{ fontSize: 10.5, color: "var(--faint)" }}>débite ton compte Getatext · pense à le retaper dans l'app</span>
            </div>
          )}
        </div>
      )}
      {err && <div style={{ marginTop: 7, fontSize: 11, color: "var(--danger)" }}>{err}</div>}
    </div>
  );
}

// ---- code 2FA vivant : calculé sur ce Mac, jamais envoyé à un service tiers ----
// ============================================================
// Médias DU COMPTE : chaque conteneur a son dossier de contenu (photo de profil, vidéos…).
// Le contenu se range par COMPTE et pas par téléphone : un iPhone en porte plusieurs, et
// envoyer la photo de profil du mauvais compte est l'erreur qui le fait griller.
// ============================================================
// ============================================================
// Chiffres du compte, relevés en lisant son profil à l'écran (v1 05:35 : « ça détecte »).
// Le verdict suit la règle de la vidéo : si les dernières vidéos ne décollent pas, le compte
// est à jeter. On ne tranche pas avant d'avoir assez de vidéos — un compte d'un jour n'est
// pas un compte mort.
// ============================================================
function AccountStats({ container, device }) {
  const { useState, useEffect } = React;
  const [d, setD] = useState(null);
  const [busy, setBusy] = useState("");
  const [msg, setMsg] = useState("");
  const udid = device && (device.udid || device.id);

  const load = async () => setD(await Backend.igStats(container.id));
  useEffect(() => { load(); }, [container.id]);

  const read = async (withSwitch) => {
    setBusy("read"); setMsg("");
    const r = await Backend.igStatsRead(container.id, udid, withSwitch);
    setBusy("");
    setMsg(!r ? "pas de réponse" : r.ok ? "" : (r.error || "échec"));
    if (r && r.ok) load();
  };

  const last = d && d.last;
  const done = new Set(((d && d.reposted) || []).map(x => x.at));
  const COL = { garder: "var(--accent)", supprimer: "#ff6b6b",
                surveiller: "var(--busy, #f5b942)", attendre: "var(--busy, #f5b942)" };
  const MOT = { garder: "à garder", supprimer: "compte + conteneur à supprimer",
                surveiller: "à surveiller", attendre: "trop tôt pour juger" };
  const chip = { background: "var(--surface-3)", border: "1px solid var(--border)", borderRadius: 7,
                 padding: "4px 9px", color: "var(--muted)", fontSize: 11, cursor: "pointer" };

  return (
    <div style={{ padding: "10px 11px", borderRadius: 9, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
        <span style={{ fontSize: 10.5, fontWeight: 600, color: "var(--faint)", textTransform: "uppercase", letterSpacing: ".05em" }}>
          Chiffres du compte
        </span>
        {last ? <span className="mono" style={{ fontSize: 10, color: "var(--faint)" }}>
          relevé {(last.at || "").slice(5, 16)}{last.source ? " · " + (last.source === "application" ? "lu dans l'app" : "lu à l'écran") : ""}
        </span> : null}
        <span style={{ marginLeft: "auto", display: "flex", gap: 5 }}>
          <button style={chip} disabled={busy === "read"} onClick={() => read(false)}>
            {busy === "read" ? "lecture…" : "↻ Relever"}
          </button>
          <button style={chip} disabled={busy === "read"} title="bascule d'abord le téléphone sur ce compte"
            onClick={() => read(true)}>⇄ + relever</button>
        </span>
      </div>

      {last ? (
        <div style={{ marginTop: 8, display: "grid", gap: 6 }}>
          <div className="mono" style={{ fontSize: 11, display: "flex", gap: 14, flexWrap: "wrap" }}>
            <span>{last.profile.posts != null ? last.profile.posts : "—"} publications</span>
            <span>{last.profile.followers != null ? last.profile.followers : "—"} abonnés</span>
            <span>{last.profile.following != null ? last.profile.following : "—"} abonnements</span>
          </div>
          {last.views && last.views.length ? (
            <div className="mono" style={{ fontSize: 10.5, color: "var(--faint)" }}>
              vues des dernières vidéos : {last.views.slice(0, 10).join(" · ")}
            </div>
          ) : null}
          <div style={{ fontSize: 11.5, fontWeight: 600, color: COL[last.verdict.etat] }}>
            {last.verdict.etat === "supprimer" ? "❌ " : last.verdict.etat === "garder" ? "✅ "
              : last.verdict.etat === "surveiller" ? "👀 " : "⏳ "}
            {MOT[last.verdict.etat]}
            {last.verdict.niveau === "golden"
              ? <span style={{ marginLeft: 6, background: "rgba(245,185,66,.16)", border: "1px solid rgba(245,185,66,.45)",
                               borderRadius: 6, padding: "1px 6px", fontSize: 10, color: "#f5b942" }}>GOLDEN</span>
              : last.verdict.niveau === "correct"
              ? <span style={{ marginLeft: 6, fontSize: 10, color: "var(--faint)", fontWeight: 400 }}>bon départ</span>
              : null}
            <span style={{ fontWeight: 400, color: "var(--faint)", fontSize: 11 }}> — {last.verdict.raison}</span>
          </div>
          {last.faibles > 0 ? (
            <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
              <span style={{ background: "rgba(255,107,107,.14)", border: "1px solid rgba(255,107,107,.4)",
                color: "#ff6b6b", borderRadius: 99, padding: "3px 10px", fontSize: 11, fontWeight: 700 }}>
                réels à reposter : {last.faibles}
              </span>
              {done.has(last.at)
                ? <span style={{ fontSize: 11, color: "var(--accent)" }}>✓ traité</span>
                : <button style={{ ...chip, color: "var(--accent)" }} disabled={busy === "rep"}
                    onClick={async () => {
                      setBusy("rep");
                      await Backend.igStatsReposted(container.id, last.at);
                      setBusy(""); load();
                    }}>marquer reposté</button>}
            </div>
          ) : null}
        </div>
      ) : (
        <div style={{ marginTop: 7, fontSize: 11, color: "var(--faint)", lineHeight: 1.5 }}>
          Aucun relevé. « Relever » ouvre le profil sur le téléphone et lit les chiffres à l'écran —
          aucune donnée n'est saisie à la main.
        </div>
      )}
      {msg ? <div style={{ marginTop: 6, fontSize: 11, color: "var(--busy, #f5b942)", lineHeight: 1.45 }}>⚠️ {msg}</div> : null}
    </div>
  );
}

function ContainerMedia({ container }) {
  const { useState, useEffect, useRef } = React;
  const [d, setD] = useState(null);
  const [busy, setBusy] = useState("");
  const [msg, setMsg] = useState(null);
  const [open, setOpen] = useState(false);
  const input = useRef(null);

  const [sent, setSent] = useState([]);
  const load = async () => {
    setD(await Backend.containerMedia(container.id));
    setSent(await Backend.sends(container.id));
  };
  useEffect(() => { if (open) load(); }, [open, container.id]);
  const sentNames = new Set((sent || []).map(x => x.name));

  const flash = (ok, text) => { setMsg({ ok, text }); setTimeout(() => setMsg(null), 7000); };
  const add = async (files) => {
    if (!files || !files.length || !d) return;
    setBusy("up");
    for (const f of files) await Backend.libUpload(d.path, f);
    setBusy(""); load();
  };
  const push = async (name) => {
    setBusy(name);
    const r = await Backend.libPush(d.path, name, d.udid, container.id);
    setBusy("");
    const ok = r && r.pushed && !r.error && (!r.result || r.result.ok !== false);
    flash(ok, ok ? name + " envoyé dans la pellicule du téléphone"
                 : ((r && (r.error || (r.result && r.result.error))) || "envoi impossible"));
  };
  const del = async (name) => {
    if (!window.confirm("Supprimer « " + name + " » du dossier de ce compte ?")) return;
    await Backend.libDelFile(d.path + "/" + name); load();
  };

  const lab = { fontSize: 10.5, fontWeight: 600, color: "var(--faint)", textTransform: "uppercase", letterSpacing: ".05em" };
  const chip = { background: "var(--surface-3)", border: "1px solid var(--border)", borderRadius: 7,
                 padding: "4px 8px", color: "var(--muted)", fontSize: 11, cursor: "pointer" };
  const n = d ? d.files.length : null;

  return (
    <div style={{ padding: "10px 11px", borderRadius: 9, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
      <button onClick={() => setOpen(o => !o)} style={{ display: "flex", alignItems: "center", gap: 8, width: "100%",
        background: "none", border: "none", cursor: "pointer", color: "var(--text)", padding: 0, textAlign: "left" }}>
        <span style={lab}>Médias de ce compte</span>
        {n != null ? <span className="mono" style={{ fontSize: 10.5, color: "var(--faint)" }}>{n} fichier{n > 1 ? "s" : ""}</span> : null}
        <span style={{ marginLeft: "auto", color: "var(--faint)", fontSize: 11, transform: open ? "rotate(90deg)" : "none" }}>▸</span>
      </button>

      {open && (!d ? <div style={{ fontSize: 11, color: "var(--faint)", marginTop: 7 }}>chargement…</div> : (
        <div style={{ marginTop: 8, display: "grid", gap: 7 }}>
          <div className="mono" style={{ fontSize: 10, color: "var(--faint)" }}>dossier : {d.path}</div>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            <button style={{ ...chip, background: "var(--accent)", color: "#06281c", border: "none", fontWeight: 600 }}
              disabled={busy === "up"} onClick={() => input.current && input.current.click()}>
              {busy === "up" ? "envoi…" : "+ Ajouter des fichiers"}
            </button>
            <input ref={input} type="file" multiple accept="image/*,video/*" style={{ display: "none" }}
              onChange={e => { add([...e.target.files]); e.target.value = ""; }} />
          </div>
          {d.files.length === 0
            ? <div style={{ fontSize: 11, color: "var(--faint)", lineHeight: 1.5 }}>
                Aucun fichier. Dépose ici la photo de profil et les vidéos de <b>{d.label}</b> — elles ne partiront que sur ce compte.
              </div>
            : d.files.map(f => (
              <div key={f.name} style={{ display: "flex", alignItems: "center", gap: 7 }}>
                <span style={{ fontSize: 11.5 }}>{f.kind === "video" ? "🎬" : f.kind === "image" ? "🖼️" : "📄"}</span>
                <span className="mono" style={{ fontSize: 11, flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap",
                  color: sentNames.has(f.name) ? "var(--faint)" : "var(--text)" }}
                  title={sentNames.has(f.name) ? "déjà envoyé sur ce compte" : ""}>
                  {sentNames.has(f.name) ? "✓ " : ""}{f.name}</span>
                <button style={{ ...chip, color: "var(--accent)" }} disabled={busy === f.name}
                  onClick={() => push(f.name)}
                  title="copie le fichier dans /DCIM — iOS ne l'indexe pas dans Photos">{busy === f.name ? "envoi…" : "→ /DCIM"}</button>
                <button style={{ ...chip, color: "var(--accent-2)" }} disabled={busy === "lien" + f.name}
                  title="dépose le fichier en ligne et l'ouvre dans Safari sur le téléphone : appui long → Ajouter aux photos"
                  onClick={async () => {
                    setBusy("lien" + f.name);
                    const r = await Backend.mediaViaLink(d.path, f.name, d.udid, container.id);
                    setBusy("");
                    flash(!!(r && r.ok), !r ? "pas de réponse"
                      : r.ok ? "ouvert dans Safari sur le téléphone — appui long sur l'image, puis « Ajouter aux photos »"
                             : (r.error || "échec"));
                  }}>{busy === "lien" + f.name ? "…" : "→ Photos"}</button>
                <button style={chip} onClick={() => del(f.name)} title="supprimer">✕</button>
              </div>
            ))}
          {msg && <div style={{ fontSize: 11, lineHeight: 1.45, color: msg.ok ? "var(--accent)" : "var(--busy, #f5b942)" }}>
            {msg.ok ? "✓ " : "⚠️ "}{msg.text}</div>}
          {sent && sent.length ? <details style={{ marginTop: 4 }}>
            <summary style={{ fontSize: 10.5, color: "var(--muted)", cursor: "pointer" }}>
              {sent.length} envoi{sent.length > 1 ? "s" : ""} sur ce compte
            </summary>
            <div style={{ display: "grid", gap: 3, marginTop: 5 }}>
              {sent.slice(0, 12).map((x, i) => (
                <div key={i} className="mono" style={{ fontSize: 10, color: "var(--faint)", display: "flex", gap: 6 }}>
                  <span>{(x.at || "").slice(5, 16)}</span>
                  <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{x.name}</span>
                  <span>{x.via === "photos" ? "→ Photos" : "→ /DCIM"}</span>
                  {x.by ? <span>{x.by}</span> : null}
                </div>
              ))}
            </div>
          </details> : null}
          <div className="mono" style={{ fontSize: 10, color: "var(--faint)", lineHeight: 1.4 }}>
            « → téléphone » copie le fichier dans /DCIM, et chaque envoi produit une copie unique.
        ⚠️ Mesuré le 29/09 sur iOS 16.7 : Photos n'indexe PAS ce dossier, le fichier n'apparaît donc
        pas dans la pellicule. Il faut encore passer par un autre chemin pour le rendre publiable.
          </div>
        </div>
      ))}
    </div>
  );
}

function TotpLive({ container, secret }) {
  const { useState, useEffect } = React;
  const [r, setR] = useState(null);
  const [typed, setTyped] = useState(false);
  const has = !!(secret || "").trim();
  // Le code est calculé à partir de la clé ENREGISTRÉE. Tant que ce qui est tapé dans le champ
  // n'a pas été sauvegardé, on le dit clairement au lieu d'afficher « aucune clé sur cette fiche »
  // (message exact côté base, mais incompréhensible quand on vient juste de coller la clé).
  const savedKey = ((container.account || {}).twofa || "").trim();
  const unsaved = has && (secret || "").trim() !== savedKey;
  // Contrôle immédiat, avant d'enregistrer : se tromper de presse-papier (e-mail, mot de passe,
  // code à 6 chiffres) est l'erreur la plus fréquente — autant la voir tout de suite.
  const badKey = (() => {
    const v = (secret || "").trim();
    if (!v || v.toLowerCase().startsWith("otpauth://")) return "";
    if (v.includes("@")) return "on dirait une adresse e-mail";
    if (/^\d+$/.test(v)) return "on dirait le code à 6 chiffres — c'est la CLÉ qu'il faut coller ici";
    const up = v.replace(/[\s-]/g, "").toUpperCase();
    const bad = [...new Set([...up].filter(c => !/[A-Z2-7=]/.test(c)))];
    if (bad.length) return "caractère" + (bad.length > 1 ? "s" : "") + " interdit" + (bad.length > 1 ? "s" : "") + " : " + bad.join(" ");
    if (up.replace(/=/g, "").length < 16) return "clé trop courte, il en manque un bout";
    return "";
  })();

  const fetchCode = async () => {
    if (!has) return setR(null);
    const x = await Backend.containerTotp(container.id, false);
    setR(x);
  };
  // rafraîchit à chaque seconde : le code change toutes les 30 s
  useEffect(() => {
    if (!has) { setR(null); return; }
    fetchCode();
    const t = setInterval(() => {
      setR(p => {
        if (!p || !p.ok) return p;
        if (p.remaining <= 1) { fetchCode(); return p; }
        return { ...p, remaining: p.remaining - 1 };
      });
    }, 1000);
    return () => clearInterval(t);
  }, [container.id, has, savedKey]);

  if (!has) return null;
  if (badKey) return (
    <div style={{ marginTop: 6, fontSize: 11, color: "var(--danger)", lineHeight: 1.45 }}>
      Ce n'est pas une clé 2FA : {badKey}.<br />
      <span style={{ color: "var(--faint)" }}>Elle ressemble à ça : <span className="mono">XYBH WWKL 5UZV T5TN …</span> — c'est ce qu'Instagram affiche sous « Scan this barcode/QR code or copy the key ».</span>
    </div>
  );
  if (unsaved) return (
    <div style={{ marginTop: 6, fontSize: 11, color: "var(--busy, #f5b942)", lineHeight: 1.45 }}>
      Clé saisie mais pas encore enregistrée — clique sur <b>Enregistrer</b> en bas de la fiche, le code apparaîtra ici.
    </div>
  );
  if (r && !r.ok) return (
    <div style={{ marginTop: 6, fontSize: 11, color: "var(--danger)" }}>{r.error}</div>
  );
  if (!r) return <div style={{ marginTop: 6, fontSize: 11, color: "var(--faint)" }}>calcul…</div>;

  const pct = Math.max(0, Math.min(1, r.remaining / (r.period || 30)));
  const urgent = r.remaining <= 5;
  return (
    <div style={{ marginTop: 7, display: "flex", alignItems: "center", gap: 9, padding: "9px 11px",
      borderRadius: 9, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
      <span className="mono" style={{ fontSize: 16, fontWeight: 700, letterSpacing: ".12em",
        color: urgent ? "var(--busy)" : "var(--accent)" }}>
        {r.code.slice(0, 3)} {r.code.slice(3)}
      </span>
      <span title={r.remaining + " s"} style={{ width: 22, height: 22, flex: "none", borderRadius: 99,
        background: "conic-gradient(" + (urgent ? "var(--busy)" : "var(--accent)") + " " + (pct * 360) + "deg, var(--border) 0)" }} />
      <div style={{ flex: 1 }} />
      <button onClick={() => { try { navigator.clipboard.writeText(r.code); } catch (e) {} }}
        style={{ background: "var(--surface-3)", border: "1px solid var(--border)", borderRadius: 7,
                 padding: "5px 9px", color: "var(--muted)", fontSize: 11, cursor: "pointer" }}>copier</button>
      <button onClick={async () => {
          const x = await Backend.containerTotp(container.id, true);
          setTyped(!!x.typed); setTimeout(() => setTyped(false), 2500);
        }}
        style={{ background: typed ? "var(--accent-soft)" : "var(--surface-3)",
                 border: "1px solid " + (typed ? "var(--accent-line)" : "var(--border)"), borderRadius: 7,
                 padding: "5px 9px", color: typed ? "var(--accent)" : "var(--text)", fontSize: 11, cursor: "pointer" }}>
        {typed ? "tapé ✓" : "taper sur le tél."}
      </button>
    </div>
  );
}

// ---- fiche du compte hébergé par un conteneur ----
function AccountForm({ container, onSaved, user, device }) {
  const { useState } = React;
  const a = container.account || {};
  const [f, setF] = useState({
    username: a.username || "", password: a.password || "", email: a.email || "",
    email_pass: a.email_pass || "", birthdate: a.birthdate || "", full_name: a.full_name || "",
    bio: a.bio || "", twofa: a.twofa || "", link: a.link || "",
  });
  const [saved, setSaved] = useState(false);
  const [show, setShow] = useState(false);
  const [, setTyped] = useState(0);

  // mot de passe lisible mais solide : Instagram refuse les suites trop simples
  const genPassword = () => {
    const A = "abcdefghijkmnpqrstuvwxyz", B = "ABCDEFGHJKLMNPQRSTUVWXYZ", N = "23456789", S = "!?.";
    const pick = (s, n) => Array.from({ length: n }, () => s[Math.floor(Math.random() * s.length)]).join("");
    const raw = (pick(B, 1) + pick(A, 6) + pick(N, 3) + pick(S, 1)).split("");
    for (let i = raw.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [raw[i], raw[j]] = [raw[j], raw[i]]; }
    return raw.join("");
  };
  const set = (k, v) => { setF(x => ({ ...x, [k]: v })); setSaved(false); };
  const [pseudoOpen, setPseudo] = useState(false);
  const [reading, setReading] = useState("");     // lecture de la clé 2FA sur l'écran
  const [expanded, setExpanded] = useState({});   // champs remplis rouverts à la main
  const [busyBd, setBusyBd] = useState("");       // réglage de la date de naissance
  const [busySw, setBusySw] = useState(false);    // bascule de conteneur
  const [swMsg, setSwMsg] = useState("");
  const [bdMsg, setBdMsg] = useState("");

  const save = async () => {
    await Backend.containerAccount(container.id, f);
    setSaved(true); setTimeout(() => setSaved(false), 2500);
    onSaved && onSaved();
  };
  const copy = (v) => { try { navigator.clipboard.writeText(v || ""); } catch (e) {} };

  const box = { width: "100%", padding: "8px 10px", background: "var(--bg-2)", border: "1px solid var(--border-2)",
                borderRadius: 8, color: "var(--text)", fontSize: 11.5, outline: "none" };
  const lab = { fontSize: 10.5, fontWeight: 600, color: "var(--faint)", textTransform: "uppercase", letterSpacing: ".05em" };

  const chip = { background: "var(--surface-3)", border: "1px solid var(--border)", borderRadius: 7,
                 padding: "0 8px", color: "var(--muted)", cursor: "pointer", fontSize: 11 };

  // tape la valeur dans le champ actuellement actif du téléphone
  const typeOnPhone = async (v) => {
    if (!v) return;
    setTyped(k => k);            // no-op : garde la signature simple
    await Backend.smsType(container.id, v);
  };

  // Un champ REMPLI se replie en une ligne : sa valeur + copier + taper sur le téléphone.
  // L'écran ne montre alors que ce qu'il reste à faire — on clique dessus pour le rouvrir.
  const Field = ({ k, label, type, wide, gen, suggest }) => {
    const v = f[k] || "";
    const done = !!v.trim();
    const shown = expanded[k];
    if (done && !shown) {
      const masked = type === "password" && !show ? "•".repeat(Math.min(14, v.length)) : v;
      return (
        <div style={{ gridColumn: wide ? "1 / -1" : "auto" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 5, padding: "6px 8px", borderRadius: 8,
            background: "var(--surface-2)", border: "1px solid var(--border)" }}>
            <span style={{ color: "var(--accent)", fontSize: 11, flex: "none" }}>✓</span>
            <button onClick={() => setExpanded(e => ({ ...e, [k]: true }))} title="modifier"
              style={{ background: "none", border: "none", padding: 0, cursor: "pointer", textAlign: "left", flex: 1, overflow: "hidden" }}>
              <div style={{ ...lab, fontSize: 9.5 }}>{label}</div>
              <div className="mono" style={{ fontSize: 11, color: "var(--text)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{masked}</div>
            </button>
            <button onClick={() => copy(v)} title="copier" style={chip}>⧉</button>
            <button onClick={() => typeOnPhone(v)} title="taper sur le téléphone" style={{ ...chip, color: "var(--accent)" }}>⌨</button>
          </div>
        </div>
      );
    }
    return (
      <div style={{ gridColumn: wide ? "1 / -1" : "auto" }}>
        <label style={lab}>{label}</label>
        <div style={{ display: "flex", gap: 5, marginTop: 3 }}>
          <input type={type || "text"} value={v} onChange={e => set(k, e.target.value)} style={box} />
          {suggest ? <button onClick={() => setPseudo(o => !o)} title="proposer des pseudos disponibles"
            style={{ ...chip, color: pseudoOpen ? "var(--accent)" : "var(--muted)" }}>⚄</button> : null}
          {gen ? <button onClick={() => set(k, gen())} title="générer" style={chip}>⚄</button> : null}
          {done ? <button onClick={() => copy(v)} title="copier" style={chip}>⧉</button> : null}
          {done ? <button onClick={() => typeOnPhone(v)} title="taper sur le téléphone"
            style={{ ...chip, color: "var(--accent)" }}>⌨</button> : null}
          {done ? <button onClick={() => setExpanded(e => ({ ...e, [k]: false }))} title="replier" style={chip}>▴</button> : null}
        </div>
      </div>
    );
  };

  return (
    <div style={{ display: "grid", gap: 8 }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
        <Field k="username" label="Identifiant" suggest />
        {pseudoOpen && <div style={{ gridColumn: "1 / -1" }}>
          <PseudoPicker base={f.username} onPick={u => { set("username", u); setPseudo(false); }} />
        </div>}
        <Field k="password" label="Mot de passe" type={show ? "text" : "password"} gen={genPassword} />
        <Field k="email" label="E-mail" />
        <Field k="email_pass" label="Mdp e-mail" type={show ? "text" : "password"} />
        <Field k="full_name" label="Prénom / nom" />
        <Field k="birthdate" label="Date de naissance" gen={genBirthdate} />
        <div style={{ gridColumn: "1 / -1", display: "flex", gap: 6, alignItems: "center", flexWrap: "wrap" }}>
          <button style={chip} disabled={busyBd === "dry"} onClick={async () => {
              setBusyBd("dry"); const r = await Backend.setBirthdate(container.id, true); setBusyBd("");
              setBdMsg(!r ? "pas de réponse"
                : r.ok ? "Lu à l'écran : " + r.read.day + "/" + r.read.month + "/" + r.read.year
                         + " → " + r.steps.map(x => x.col + " " + (x.delta > 0 ? "+" : "") + x.delta).join(", ")
                : r.error);
            }}>👁 Essai à blanc</button>
          <button style={{ ...chip, color: "var(--accent)" }} disabled={busyBd === "run"} onClick={async () => {
              setBusyBd("run"); const r = await Backend.setBirthdate(container.id, false); setBusyBd("");
              setBdMsg(!r ? "pas de réponse" : r.ok ? "✓ date réglée sur le téléphone" : (r.error || "échec"));
            }}>{busyBd === "run" ? "réglage…" : "📅 Régler sur le téléphone"}</button>
          {bdMsg ? <span style={{ fontSize: 10.5, color: "var(--muted)", flexBasis: "100%", lineHeight: 1.4 }}>{bdMsg}</span> : null}
        </div>
        <div style={{ gridColumn: "1 / -1" }}>
          <SmsBlock container={container} user={user} onPhone={n => set("phone", n)} />
        </div>
        <div style={{ gridColumn: "1 / -1" }}>
          <label style={lab}>Clé 2FA</label>
          <div style={{ display: "flex", gap: 5, marginTop: 3 }}>
            <input type={show ? "text" : "password"} value={f.twofa} onChange={e => set("twofa", e.target.value)}
              placeholder="clé du QR code, ou l'adresse otpauth://…" style={box} />
          </div>
          <div style={{ display: "flex", gap: 6, marginTop: 5, alignItems: "center", flexWrap: "wrap" }}>
            <button onClick={async () => {
                setReading("...");
                const r = await Backend.read2fa(container.id);
                setReading(r && r.ok ? "" : ((r && r.error) || "lecture impossible"));
                if (r && r.ok && r.key) { set("twofa", r.key); onSaved && onSaved(); }
              }}
              title="Lit la clé affichée sur l'écran du téléphone, sans la retaper"
              style={{ ...chip, padding: "5px 9px", color: "var(--accent)" }}>
              {reading === "..." ? "lecture…" : "📷 Lire la clé sur l'écran"}
            </button>
            {reading && reading !== "..." ? <span style={{ fontSize: 10.5, color: "var(--busy, #f5b942)" }}>{reading}</span> : null}
          </div>
          <TotpLive container={container} secret={f.twofa} />
        </div>
        <Field k="link" label="Lien (story / highlight)" wide />
        <div style={{ gridColumn: "1 / -1", display: "flex", gap: 7, alignItems: "center", flexWrap: "wrap" }}>
          <button style={{ ...chip, color: "var(--accent)" }} disabled={busySw}
            title="Change le conteneur actif du téléphone (Crane) pour ce compte, sans y toucher"
            onClick={async () => {
              setBusySw(true);
              const r = await Backend.craneSwitch(device && (device.udid || device.id), container.name);
              setBusySw(false);
              setSwMsg(!r ? "pas de réponse" : r.ok ? "le téléphone est passé sur le conteneur « " + r.container + " »" : (r.error || "échec"));
              setTimeout(() => setSwMsg(""), 9000);
            }}>{busySw ? "bascule…" : "⇄ Basculer le téléphone sur ce compte"}</button>
          {swMsg ? <span style={{ fontSize: 10.5, color: "var(--muted)", flexBasis: "100%", lineHeight: 1.4 }}>{swMsg}</span> : null}
        </div>
        <div style={{ gridColumn: "1 / -1" }}>
          <AccountStats container={container} device={device} />
        </div>
        <div style={{ gridColumn: "1 / -1" }}>
          <ContainerMedia container={container} />
        </div>
        <div style={{ gridColumn: "1 / -1" }}>
          <div style={{ display: "flex", alignItems: "center", gap: 7 }}>
            <label style={lab}>Bio</label>
            <button onClick={() => set("bio", genBio())} title="proposer une bio"
              style={{ ...chip, padding: "1px 8px" }}>⚄ générer</button>
            {f.bio ? <button onClick={() => typeOnPhone(f.bio)} title="taper sur le téléphone"
              style={{ ...chip, padding: "1px 8px", color: "var(--accent)" }}>⌨</button> : null}
            <span className="mono" style={{ marginLeft: "auto", fontSize: 10,
              color: (f.bio || "").length > 150 ? "var(--danger)" : "var(--faint)" }}>
              {(f.bio || "").length}/150
            </span>
          </div>
          <textarea value={f.bio} onChange={e => set("bio", e.target.value)} rows={2}
            style={{ ...box, marginTop: 3, resize: "vertical", fontFamily: "inherit" }} />
        </div>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
        <Button variant={saved ? "outline" : "primary"} onClick={save}>{saved ? "Enregistré ✓" : "Enregistrer"}</Button>
        <button onClick={() => setShow(s => !s)} style={{ background: "none", border: "none", color: "var(--faint)",
          fontSize: 11, cursor: "pointer" }}>{show ? "masquer" : "afficher"} les mots de passe</button>
      </div>
      <div className="mono" style={{ fontSize: 10, color: "var(--faint)", lineHeight: 1.5 }}>
        ces identifiants restent sur ce Mac (base locale) — ils ne partent pas dans le cloud.
      </div>
    </div>
  );
}


// ============================================================
// Page « Comptes » — tout ce qui a été créé sur la ferme, d'un coup d'œil (31:01 de la vidéo).
// Aucun secret ici : on montre seulement SI le mot de passe et la 2FA sont enregistrés.
// ============================================================
// ============================================================
// « Rythme de création » — à quelle heure les comptes sortent, et par qui.
// Dans la vidéo (03:35-05:00), c'est ce graphe qui sert à décider d'embaucher : il voit la
// colonne du matin vide et celle du soir saturée, et il dit « il me faut plus de VA ici ».
// ============================================================
function CreationRhythm({ jours = 30, data = null }) {
  const { useState, useEffect } = React;
  const [d, setD] = useState(data);
  const [n, setN] = useState(jours);
  // `data` sert quand l'appelant a déjà les chiffres (et à vérifier l'affichage hors navigateur).
  useEffect(() => { if (data) return; (async () => setD(await Backend.creationStats(n)))(); }, [n, data]);

  if (!d) return null;
  // Réponse sans chiffres (Mac injoignable, tunnel coupé, route absente) : on le DIT au lieu de planter.
  if (!Array.isArray(d.heures)) return (
    <Card pad={18}><div style={{ fontSize: 13, fontWeight: 700 }}>Rythme de création</div>
      <div style={{ fontSize: 11.5, color: "var(--faint)", marginTop: 6 }}>Chiffres indisponibles : le Mac de la ferme ne répond pas{d.error ? ` (${d.error})` : ""}.</div></Card>);
  const pic = Math.max(1, ...d.heures.map(h => h.n));
  const sature = new Set(d.sature || []);
  const creux = new Set(d.creux || []);
  const PER = { nuit: "0h-6h", matin: "6h-12h", midi: "12h-18h", soir: "18h-24h" };

  return (
    <Card pad={18}>
      <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", marginBottom: 14 }}>
        <div>
          <div style={{ fontSize: 13, fontWeight: 700 }}>Rythme de création</div>
          <div className="mono" style={{ fontSize: 10.5, color: "var(--faint)", marginTop: 2 }}>
            {d.total} compte(s) sur {d.jours} jours · réel
          </div>
        </div>
        <select value={n} onChange={e => setN(+e.target.value)}
          style={{ marginLeft: "auto", background: "var(--surface-3)", border: "1px solid var(--border)",
                   borderRadius: 7, color: "var(--text)", fontSize: 11, padding: "3px 6px" }}>
          {[7, 30, 90, 365].map(v => <option key={v} value={v}>{v} jours</option>)}
        </select>
      </div>

      {/* histogramme 24 h — une barre par heure, la hauteur en proportion du pic */}
      <div style={{ display: "flex", alignItems: "flex-end", gap: 2, height: 96 }}>
        {d.heures.map(h => (
          <div key={h.h} title={`${h.h}h — ${h.n} compte(s)`}
            style={{ flex: 1, display: "flex", flexDirection: "column", justifyContent: "flex-end", height: "100%" }}>
            <div style={{ height: Math.max(h.n ? 3 : 1, Math.round((h.n / pic) * 88)) + "px",
                          borderRadius: "3px 3px 0 0",
                          background: sature.has(h.h) ? "var(--busy, #f5b942)"
                                    : creux.has(h.h) ? "rgba(255,107,107,.30)"
                                    : h.n ? "var(--accent)" : "var(--surface-3)" }} />
          </div>
        ))}
      </div>
      <div style={{ display: "flex", gap: 2, marginTop: 4 }}>
        {d.heures.map(h => (
          <div key={h.h} className="mono" style={{ flex: 1, textAlign: "center", fontSize: 8.5,
                 color: sature.has(h.h) ? "var(--busy, #f5b942)" : "var(--faint)" }}>
            {h.h % 3 === 0 ? h.h : ""}
          </div>
        ))}
      </div>

      <div style={{ display: "flex", gap: 14, flexWrap: "wrap", marginTop: 12, fontSize: 11 }}>
        {d.periodes.map(p => (
          <span key={p.nom} style={{ color: "var(--muted)" }}>
            {p.nom} <span className="mono" style={{ color: "var(--text)", fontWeight: 600 }}>{p.n}</span>
            <span style={{ color: "var(--faint)", fontSize: 10 }}> {PER[p.nom]}</span>
          </span>
        ))}
        {(d.gens || []).filter(g => g.nom !== "—").length ? (
          <span style={{ marginLeft: "auto", color: "var(--faint)" }}>
            {d.gens.filter(g => g.nom !== "—").map(g => `${g.nom} ${g.n}`).join(" · ")}
          </span>) : null}
      </div>

      <div style={{ marginTop: 10, fontSize: 11.5, lineHeight: 1.55,
                    color: d.total >= 20 ? "var(--text)" : "var(--faint)" }}>
        {d.lecture}
        {d.creux && d.creux.length ? (
          <span style={{ color: "var(--faint)" }}> — c'est là qu'il manque quelqu'un.</span>) : null}
      </div>
    </Card>
  );
}


// Quel compte est ouvert sur ce téléphone — en gros, au-dessus de l'écran (vidéo 1, 07:20 :
// un « 1 » plein écran et le pseudo). Sur une ferme, l'erreur qui coûte cher est de travailler
// sur le mauvais compte : le numéro de conteneur doit se lire sans effort, de loin.
function ContainerActif({ device, compact }) {
  const { useState, useEffect } = React;
  const [ct, setCt] = useState(null);
  const udid = device && (device.udid || device.id);
  useEffect(() => {
    let vivant = true;
    const charger = async () => {
      if (!udid) return;
      const d = await Backend.containers(udid);
      if (vivant) setCt(((d && d.containers) || []).find(c => c.active) || null);
    };
    charger();
    const t = setInterval(charger, 6000);      // le conteneur peut changer depuis le téléphone
    return () => { vivant = false; clearInterval(t); };
  }, [udid]);
  if (!udid) return null;
  const a = (ct && ct.account) || {};
  const st = ct ? ctnStage(ct.stage) : null;
  const TON = { green: "var(--accent)", amber: "var(--busy, #f5b942)", red: "#ff6b6b", gray: "var(--faint)" };
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, padding: compact ? "5px 9px" : "7px 12px",
      borderRadius: 10, background: "var(--surface-2)", border: "1px solid var(--border)", maxWidth: 300 }}
      title={ct ? "conteneur ouvert sur ce téléphone" : "aucun conteneur marqué actif"}>
      <span className="num" style={{ fontSize: compact ? 22 : 30, fontWeight: 800, lineHeight: 1,
        letterSpacing: "-.03em", color: ct ? "var(--accent)" : "var(--faint)" }}>
        {ct ? ct.name : "—"}
      </span>
      <span style={{ minWidth: 0 }}>
        <span className="mono" style={{ display: "block", fontSize: compact ? 11.5 : 12.5, fontWeight: 700,
          overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
          {a.username ? "@" + a.username : (ct ? "aucun compte sur ce conteneur" : "aucun conteneur actif")}
        </span>
        {st ? <span style={{ fontSize: 10, color: TON[st.tone] || "var(--faint)" }}>{st.label}</span> : null}
      </span>
    </div>
  );
}


// Le code à 6 chiffres, à la demande, directement dans la liste : c'est le geste le plus
// fréquent quand on ouvre un compte. La CLÉ, elle, ne sort jamais d'ici — on affiche un code
// valable 30 secondes, pas le secret qui les fabrique tous.
function CodeTotp({ id }) {
  const { useState } = React;
  const [c, setC] = useState(null);
  const [busy, setBusy] = useState(false);
  const demander = async () => {
    setBusy(true);
    const r = await Backend.containerTotp(id, false);
    setBusy(false);
    if (r && r.ok && r.code) {
      setC(r.code);
      try { await navigator.clipboard.writeText(r.code); } catch (e) {}
      setTimeout(() => setC(null), (r.remaining || 30) * 1000);
    } else {
      setC("—");
      setTimeout(() => setC(null), 4000);
    }
  };
  if (c) return <span className="mono" title="copié" style={{ fontSize: 12, fontWeight: 700, color: "var(--accent)" }}>{c}</span>;
  return (
    <button onClick={demander} disabled={busy} title="affiche et copie le code à 6 chiffres"
      style={{ background: "var(--surface-3)", border: "1px solid var(--border)", borderRadius: 6,
               padding: "1px 7px", fontSize: 10.5, color: "var(--muted)", cursor: "pointer" }}>
      {busy ? "…" : "code"}
    </button>
  );
}


// Le verdict du dernier relevé, en une case : c'est ce qui permet de balayer la liste et de
// voir tout de suite les comptes à jeter, sans ouvrir les fiches une par une.
function VerdictCell({ stat }) {
  if (!stat || !stat.verdict || !stat.verdict.etat) {
    return <span style={{ fontSize: 11, color: "var(--faint)" }}>jamais relevé</span>;
  }
  const v = stat.verdict;
  const COL = { garder: "var(--accent)", supprimer: "#ff6b6b",
                surveiller: "var(--busy, #f5b942)", attendre: "var(--busy, #f5b942)" };
  const MOT = { garder: "à garder", supprimer: "à supprimer", surveiller: "à surveiller", attendre: "trop tôt" };
  const SIG = { garder: "✅", supprimer: "❌", surveiller: "👀", attendre: "⏳" };
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 6, flexWrap: "wrap" }}
      title={(v.raison || "") + " · relevé " + (stat.at || "")}>
      <span style={{ fontSize: 11.5, fontWeight: 600, color: COL[v.etat] || "var(--muted)" }}>
        {SIG[v.etat] || ""} {MOT[v.etat] || v.etat}
      </span>
      {v.niveau === "golden" ? (
        <span style={{ background: "rgba(245,185,66,.16)", border: "1px solid rgba(245,185,66,.45)",
                       borderRadius: 6, padding: "1px 5px", fontSize: 9.5, color: "#f5b942", fontWeight: 700 }}>GOLDEN</span>) : null}
      {v.max ? <span className="mono" style={{ fontSize: 10.5, color: "var(--faint)" }}>{v.max} vues max</span> : null}
      {stat.faibles > 0 && !stat.traite ? (
        <span style={{ background: "rgba(255,107,107,.14)", border: "1px solid rgba(255,107,107,.4)",
                       borderRadius: 6, padding: "1px 6px", fontSize: 10, color: "#ff8f8f" }}>
          {stat.faibles} à reposter
        </span>) : null}
      {stat.traite ? <span style={{ fontSize: 10, color: "var(--faint)" }}>✓ traité</span> : null}
    </span>
  );
}


// Le relevé qui tourne tout seul. Il ne lit QUE le compte déjà ouvert sur chaque iPhone, et
// seulement quand personne ne pilote le téléphone — sinon il volerait l'écran au VA.
function AutoReadSwitch({ auto, onDone }) {
  const { useState } = React;
  const [busy, setBusy] = useState(false);
  const save = async (f) => {
    setBusy(true);
    await Backend.igStatsAuto(f);
    setBusy(false);
    if (onDone) onDone();
  };
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap", marginBottom: 12,
                  padding: "9px 12px", borderRadius: 9, background: "var(--surface-2)",
                  border: "1px solid var(--border)" }}>
      <label style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12, cursor: "pointer" }}>
        <input type="checkbox" checked={!!auto.on} disabled={busy}
          onChange={e => save({ on: e.target.checked })} />
        <span>Relever les chiffres automatiquement</span>
      </label>
      <span style={{ fontSize: 11.5, color: "var(--muted)" }}>toutes les</span>
      <select value={auto.every} disabled={busy || !auto.on} onChange={e => save({ every: +e.target.value })}
        style={{ background: "var(--surface-3)", border: "1px solid var(--border)", borderRadius: 7,
                 color: "var(--text)", fontSize: 11.5, padding: "4px 7px" }}>
        {[15, 30, 45, 60, 120, 240].map(m => <option key={m} value={m}>{m} min</option>)}
      </select>
      <span style={{ fontSize: 11, color: "var(--faint)", flex: "1 1 260px", lineHeight: 1.5 }}>
        seuil {auto.seuil} vues · lit le compte déjà ouvert sur chaque iPhone en ligne, et attend
        que personne ne pilote le téléphone. Pour relever un autre compte, ouvre sa fiche.
      </span>
    </div>
  );
}


function AdminAccounts({ parc }) {
  const { useState, useEffect } = React;
  const [data, setData] = useState(null);
  const [q, setQ] = useState("");
  const [pilule, setPilule] = useState("tous");
  const farm = useLiveDevices ? useLiveDevices() : { list: null };
  const load = async () => {
    const r = await Backend.containersAll();
    setData(r || { containers: [] });
  };
  useEffect(() => { load(); }, []);

  const devName = (udid) => {
    const d = (farm.list || []).find(x => (x.udid || x.id) === udid);
    return d ? (d.tag || d.name) : (udid || "").slice(0, 8) + "…";
  };
  // Filtres en pilules, comme dans la vidéo (TOUS (31) · scotti (29) · SANS OPÉRATEUR (2)).
  // Le compte est écrit sur la pilule : c'est lui qui rend le filtre utile — « sans compte 2 »
  // repère les conteneurs orphelins sans avoir à parcourir la liste.
  // Cadrage par parc : quand la barre est groupée par ferme, « Comptes » ne doit montrer que
  // les comptes de CETTE ferme — sinon le groupement ment sur ce qu'il affiche.
  const dansParc = (c) => {
    if (!parc || parc === "tous") return true;
    const d = (farm.list || []).find(x => (x.udid || x.id) === c.udid);
    return !!d && d.pool === parc;
  };
  const tous = ((data && data.containers) || []).filter(dansParc);
  const stats = (data && data.stats) || {};
  const PILULES = [
    { id: "tous", label: "tous", test: () => true },
    ...[...new Set(tous.map(c => c.udid))].map(u => ({ id: "tel:" + u, label: devName(u), test: c => c.udid === u })),
    { id: "orphelins", label: "sans compte", test: c => !((c.account || {}).username || "").trim() },
    { id: "asupprimer", label: "à supprimer", test: c => ((stats[c.id] || {}).verdict || {}).etat === "supprimer" },
  ];
  const pil = PILULES.find(x => x.id === pilule) || PILULES[0];
  const rows = tous.filter(pil.test).filter(c => {
    const t = (q || "").toLowerCase();
    if (!t) return true;
    const a = c.account || {};
    return [a.username, c.name, c.stage, a.sms_number, a.link].some(v => (v || "").toLowerCase().includes(t));
  });
  const STAGE = { nouveau: ["Nouveau", "var(--muted)"], warmup: ["Warm-up", "var(--busy, #f5b942)"],
                  actif: ["Actif", "var(--accent)"], suspendu: ["Suspendu", "#ff6b6b"], banni: ["Banni", "#ff6b6b"] };
  const dot = (on) => <span style={{ color: on ? "var(--accent)" : "var(--faint)" }}>{on ? "✓" : "—"}</span>;

  return (
    <div>
      <PageHead title={parc && parc !== "tous" ? "Comptes · " + parc : "Comptes"}
        sub={(parc && parc !== "tous" ? "les comptes de ce parc" : "tous les comptes créés sur la ferme")
             + " · pseudo, téléphone, stade, ce qui est enregistré"}>
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="chercher un pseudo, un numéro…"
          style={{ padding: "8px 11px", background: "var(--surface-2)", border: "1px solid var(--border)",
                   borderRadius: 9, color: "var(--text)", fontSize: 12, outline: "none", minWidth: 220 }} />
        <Button variant="outline" icon="refresh" onClick={load}>Rafraîchir</Button>
      </PageHead>

      {data && data.auto ? <AutoReadSwitch auto={data.auto} onDone={load} /> : null}

      {data ? <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 11 }}>
        {PILULES.map(x => {
          const n = tous.filter(x.test).length;
          const on = pil.id === x.id;
          if (!n && x.id !== "tous" && !on) return null;      // une pilule vide n'apprend rien
          return (
            <button key={x.id} onClick={() => setPilule(x.id)}
              style={{ padding: "3px 10px", borderRadius: 99, fontSize: 11.5, cursor: "pointer",
                background: on ? "var(--accent-soft)" : "var(--surface-2)",
                border: "1px solid " + (on ? "var(--accent-line)" : "var(--border)"),
                color: on ? "var(--accent)" : "var(--muted)", fontWeight: on ? 700 : 600 }}>
              {x.label} <span className="num" style={{ opacity: .75 }}>{n}</span>
            </button>
          );
        })}
      </div> : null}

      {data === null ? <div style={{ fontSize: 12, color: "var(--faint)" }}>chargement…</div>
        : rows.length === 0
          ? <Card pad={22}><div style={{ fontSize: 12, color: "var(--faint)", lineHeight: 1.6 }}>
              {q ? "Aucun compte ne correspond à cette recherche."
                 : "Aucun compte pour l'instant. Ils apparaîtront ici au fur et à mesure que tu en crées, depuis « Pilotage iPhone »."}
            </div></Card>
          : <div>
              <Table head={<>
                <Th>Compte</Th><Th>iPhone</Th><Th>Stade</Th><Th>Verdict</Th><Th>Numéro</Th>
                <Th>Lien</Th><Th>Mot de passe</Th><Th>2FA</Th><Th>Créé le</Th>
              </>}>
                {rows.map(c => {
                  const a = c.account || {};
                  const st = STAGE[c.stage] || [c.stage || "—", "var(--muted)"];
                  return (
                    <tr key={c.id}>
                      <Td><span className="mono" style={{ fontWeight: 600 }}>{a.username || <span style={{ color: "var(--faint)", fontWeight: 400 }}>sans pseudo</span>}</span></Td>
                      <Td style={{ whiteSpace: "nowrap" }}><span className="mono" style={{ fontSize: 11 }}>{devName(c.udid)}</span>{c.active ? <span style={{ marginLeft: 6, fontSize: 10, color: "var(--accent)" }}>actif</span> : null}</Td>
                      <Td style={{ whiteSpace: "nowrap" }}><span style={{ color: st[1], fontSize: 11.5, fontWeight: 600 }}>{st[0]}</span></Td>
                      <Td><VerdictCell stat={(data.stats || {})[c.id]} /></Td>
                      <Td style={{ whiteSpace: "nowrap" }}><span className="mono" style={{ fontSize: 11 }}>{a.sms_number || "—"}</span></Td>
                      <Td style={{ maxWidth: 200 }}>
                        {a.link
                          ? <a href={a.link} target="_blank" rel="noopener noreferrer"
                              style={{ fontSize: 11, color: "var(--accent-2)", overflow: "hidden",
                                       textOverflow: "ellipsis", whiteSpace: "nowrap", display: "block" }}
                              title={a.link}>{a.link.replace(/^https?:\/\//, "")}</a>
                          : <span style={{ color: "var(--faint)" }}>—</span>}
                      </Td>
                      <Td>{dot(a.has_password)}</Td>
                      <Td>{a.has_twofa ? <CodeTotp id={c.id} /> : dot(false)}</Td>
                      <Td style={{ whiteSpace: "nowrap" }}><span className="mono" style={{ fontSize: 10.5, color: "var(--faint)" }}>{(c.created || "").slice(0, 16)}</span></Td>
                    </tr>
                  );
                })}
              </Table>
            </div>}
      <div className="mono" style={{ fontSize: 10.5, color: "var(--faint)", marginTop: 10, lineHeight: 1.5 }}>
        {data ? `${rows.length} compte(s)${q || pilule !== "tous" ? " sur " + tous.length : ""}` : ""} · ni mot de passe
        ni clé 2FA n'apparaît ici. « Code » demande un code à 6 chiffres, valable 30 secondes,
        et le copie : c'est le code qui sort, jamais la clé qui le fabrique.
      </div>
    </div>
  );
}
Object.assign(window, { AdminAccounts, VerdictCell, AutoReadSwitch, CreationRhythm, AssignRow, CodeTotp, ContainerActif });
