/* global React, Icon, Button, Badge, Card, PageHead, Backend, useLiveDevices */
// ============================================================
// STOCKAGE COMPTES — la réserve, avant qu'un compte soit posé sur un téléphone.
// Chez lui (36:27 de la vidéo du 25/09) : « Stockage comptes · 1 748 ». C'est une autre
// façon de travailler — on pioche dans un stock au lieu de créer à la demande.
//
// Les identifiants ne descendent PAS dans la liste : elle dit seulement s'ils existent.
// Un bouton les demande ligne par ligne, et les copie. C'est la même règle que partout
// ailleurs dans la console : un secret ne s'affiche que quand quelqu'un le demande.
// ============================================================
const ETATS_STOCK = [
  { id: "", label: "tous" },
  { id: "libre", label: "libres" },
  { id: "utilisé", label: "utilisés" },
  { id: "grillé", label: "grillés" },
];

function AdminStock({ user }) {
  const { useState, useEffect } = React;
  const [d, setD] = useState(null);
  const [etat, setEtat] = useState("");
  const [q, setQ] = useState("");
  const [busy, setBusy] = useState("");
  const [msg, setMsg] = useState(null);
  const [coller, setColler] = useState(false);
  const [texte, setTexte] = useState("");
  const [source, setSource] = useState("");
  const [rapport, setRapport] = useState(null);
  const [ouvert, setOuvert] = useState(null);     // id dont on a demandé les identifiants
  const [vus, setVus] = useState({});             // id -> identifiants rendus
  const [cibles, setCibles] = useState([]);       // conteneurs libres où poser

  const load = async () => setD(await Backend.stock(etat, q));
  useEffect(() => { load(); }, [etat, q]);
  useEffect(() => { (async () => {
    const r = await Backend.containersAll();
    setCibles(((r && r.containers) || []).filter(c => !((c.account || {}).username || "").trim()));
  })(); }, []);

  const flash = (ok, t) => { setMsg({ ok, text: t }); setTimeout(() => setMsg(null), 9000); };

  const importer = async () => {
    if (!texte.trim()) return;
    setBusy("lot");
    const r = await Backend.stockLot(texte, source);
    setBusy("");
    if (!r || r.ok === false) return flash(false, (r && r.error) || "import impossible");
    setRapport(r); setTexte(""); load();
  };
  const voir = async (id) => {
    if (ouvert === id) return setOuvert(null);
    setOuvert(id);
    if (!vus[id]) {
      const r = await Backend.stockSecrets(id);
      if (r && r.ok) setVus(v => ({ ...v, [id]: r }));
      else flash(false, (r && r.error) || "identifiants illisibles");
    }
  };
  const poser = async (id, cid) => {
    if (!cid) return;
    setBusy(id);
    const r = await Backend.stockTake(id, cid);
    setBusy("");
    if (r && r.ok) { flash(true, "@" + r.username + " posé sur le conteneur"); load(); }
    else flash(false, (r && r.error) || "pose impossible");
  };
  const marquer = async (id, e) => { await Backend.stockEtat(id, e); load(); };
  const retirer = async (id, u) => {
    if (!window.confirm("Retirer @" + u + " du stock ? Les identifiants sont effacés.")) return;
    await Backend.stockDelete(id); load();
  };

  const chip = { background: "var(--surface-3)", border: "1px solid var(--border)", borderRadius: 6,
                 padding: "1px 7px", color: "var(--muted)", fontSize: 10.5, cursor: "pointer" };
  const inp = { background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 8,
                color: "var(--text)", fontSize: 12.5, padding: "7px 10px", outline: "none" };
  const par = (d && d.par_etat) || {};
  const TON = { libre: "var(--accent)", "utilisé": "var(--faint)", "grillé": "#ff6b6b" };

  return (
    <div>
      <PageHead title="Stockage comptes" sub="la réserve · des comptes prêts, avant d'être posés sur un téléphone">
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="pseudo, e-mail, lot…" style={{ ...inp, minWidth: 190 }} />
        <Button variant="primary" icon="plus" onClick={() => setColler(c => !c)}>Coller un lot</Button>
      </PageHead>

      {msg ? <div style={{ marginBottom: 12, fontSize: 12.5, lineHeight: 1.5, borderRadius: 9, padding: "9px 11px",
        color: msg.ok ? "var(--accent)" : "var(--busy, #f5b942)",
        background: msg.ok ? "var(--accent-soft)" : "rgba(245,185,66,.1)",
        border: "1px solid " + (msg.ok ? "var(--accent-line)" : "rgba(245,185,66,.3)") }}>{msg.text}</div> : null}

      {coller ? (
        <Card pad={14} style={{ marginBottom: 12 }}>
          <div style={{ fontSize: 12.5, fontWeight: 700, marginBottom: 6 }}>Coller un lot</div>
          <div style={{ fontSize: 11.5, color: "var(--muted)", lineHeight: 1.55, marginBottom: 8 }}>
            Une ligne par compte, dans l'ordre <span className="mono">pseudo : mot de passe : e-mail :
            mot de passe e-mail : clé 2FA</span>. Les séparateurs <span className="mono">: ; | tab</span>
            sont acceptés, et tout ce qui vient après le mot de passe est facultatif.
            Une ligne sans mot de passe n'est pas un compte : elle te sera rendue telle quelle.
          </div>
          <textarea value={texte} onChange={e => setTexte(e.target.value)} rows={7}
            placeholder={"lunabeautyx:Mdp2026:luna@mail.com:EmailPwd:JBSWY3DPEHPK3PXP\nhoneylunaluv:Secret99:honey@mail.com"}
            style={{ ...inp, width: "100%", fontFamily: "ui-monospace, monospace", fontSize: 11.5, resize: "vertical" }} />
          <div style={{ display: "flex", gap: 8, alignItems: "center", marginTop: 8, flexWrap: "wrap" }}>
            <input value={source} onChange={e => setSource(e.target.value)} placeholder="d'où vient ce lot (vendeur, date…)" style={{ ...inp, flex: "1 1 220px" }} />
            <Button variant="primary" onClick={importer}>{busy === "lot" ? "…" : "Importer"}</Button>
            <Button variant="ghost" onClick={() => { setColler(false); setRapport(null); }}>Fermer</Button>
          </div>
          {rapport ? (
            <div style={{ marginTop: 10, fontSize: 12, lineHeight: 1.6 }}>
              <span style={{ color: "var(--accent)" }}>{rapport.ajoutes} ajouté(s)</span>
              {rapport.doublons.length ? <span style={{ color: "var(--muted)" }}> · {rapport.doublons.length} déjà en stock ({rapport.doublons.slice(0, 4).join(", ")}{rapport.doublons.length > 4 ? "…" : ""})</span> : null}
              {rapport.ignorees.length ? <div style={{ color: "var(--busy, #f5b942)", marginTop: 4 }}>
                {rapport.ignorees.length} ligne(s) sans mot de passe, laissées de côté :
                <span className="mono" style={{ fontSize: 11 }}> {rapport.ignorees.slice(0, 3).join(" · ")}</span>
              </div> : null}
            </div>) : null}
        </Card>
      ) : null}

      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 11 }}>
        {ETATS_STOCK.map(x => {
          const n = x.id ? (par[x.id] || 0) : (d ? d.total : 0);
          const on = etat === x.id;
          return (
            <button key={x.id || "tous"} onClick={() => setEtat(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>

      {d === null ? <div style={{ fontSize: 12.5, color: "var(--faint)" }}>chargement…</div>
        : !d.comptes.length ? <Card pad={20}><div style={{ fontSize: 12.5, color: "var(--faint)", lineHeight: 1.6 }}>
            {q || etat ? "Rien ne correspond." : "Le stock est vide. « Coller un lot » pour y mettre des comptes — ils attendront là jusqu'à ce que tu les poses sur un conteneur."}
          </div></Card>
        : <Table head={<><Th>Compte</Th><Th>E-mail</Th><Th>Mot de passe</Th><Th>2FA</Th><Th>État</Th><Th>Lot</Th><Th>Ajouté</Th><Th style={{ textAlign: "right" }}>Actions</Th></>}>
            {d.comptes.map(c => {
              const vu = vus[c.id];
              const montre = ouvert === c.id && vu;
              return (
                <tr key={c.id}>
                  <Td style={{ whiteSpace: "nowrap" }}><span className="mono" style={{ fontWeight: 600 }}>@{c.username}</span></Td>
                  <Td><span className="mono" style={{ fontSize: 11 }}>{montre ? vu.email : (c.email || "—")}</span></Td>
                  <Td><span className="mono" style={{ fontSize: 11 }}>{montre ? (vu.password || "—") : (c.has_password ? c.password : "—")}</span></Td>
                  <Td><span className="mono" style={{ fontSize: 11 }}>{montre ? (vu.twofa || "—") : (c.has_twofa ? c.twofa : "—")}</span></Td>
                  <Td style={{ whiteSpace: "nowrap" }}><span style={{ fontSize: 11.5, fontWeight: 600, color: TON[c.etat] || "var(--muted)" }}>{c.etat}</span>
                    {c.used_by ? <span className="mono" style={{ fontSize: 10, color: "var(--faint)" }}> → {c.used_by.slice(0, 10)}</span> : null}</Td>
                  <Td><span style={{ fontSize: 11, color: "var(--faint)" }}>{c.source || "—"}</span></Td>
                  <Td style={{ whiteSpace: "nowrap" }}><span className="mono" style={{ fontSize: 10.5, color: "var(--faint)" }}>{(c.created || "").slice(0, 16)}</span></Td>
                  <Td>
                    <div style={{ display: "flex", gap: 5, justifyContent: "flex-end", flexWrap: "wrap" }}>
                      <button style={chip} onClick={() => voir(c.id)}>{montre ? "masquer" : "identifiants"}</button>
                      {c.etat === "libre" ? (
                        <select defaultValue="" disabled={busy === c.id} onChange={e => poser(c.id, e.target.value)}
                          style={{ ...chip, padding: "1px 5px" }}>
                          <option value="">poser sur…</option>
                          {cibles.map(t => <option key={t.id} value={t.id}>{t.name} · {t.udid.slice(0, 6)}</option>)}
                        </select>) : null}
                      {c.etat !== "grillé" ? <button style={chip} onClick={() => marquer(c.id, "grillé")}>grillé</button> : null}
                      {c.etat === "grillé" ? <button style={chip} onClick={() => marquer(c.id, "libre")}>remettre libre</button> : null}
                      <button style={{ ...chip, color: "var(--faint)" }} onClick={() => retirer(c.id, c.username)}>retirer</button>
                    </div>
                  </Td>
                </tr>
              );
            })}
          </Table>}

      <div className="mono" style={{ fontSize: 10.5, color: "var(--faint)", marginTop: 12, lineHeight: 1.6 }}>
        {d ? `${d.comptes.length} ligne(s)${d.tronque ? " (liste tronquée)" : ""} · ${par["libre"] || 0} libre(s)` : ""}
        · les identifiants restent sur ce Mac et ne descendent pas dans la liste : il faut les
        demander ligne par ligne. Poser un compte le retire du stock et remplit la fiche du conteneur.
      </div>
    </div>
  );
}

Object.assign(window, { AdminStock });
