/* global React, Icon, Button, Card, PageHead, Backend */
// ============================================================
// AUTOMATISATION — ce qui tourne SANS qu'on clique, et dans quel état.
//
// Une automatisation qu'on ne voit pas est une automatisation qu'on ne contrôle pas : si le
// relevé des chiffres ne part jamais parce qu'un iPhone est piloté en permanence, il faut
// pouvoir le lire quelque part. Cette page ne liste que ce que la console sait vérifier —
// pas ce qu'elle aimerait faire un jour.
// ============================================================
function AdminAutomatisation() {
  const { useState, useEffect } = React;
  const [d, setD] = useState(null);
  const [busy, setBusy] = useState("");

  const load = async () => setD(await Backend.autoTaches());
  useEffect(() => {
    load();
    const t = setInterval(load, 20000);     // l'état change tout seul : on le relit
    return () => clearInterval(t);
  }, []);

  const regler = async (f) => { setBusy("igstats"); await Backend.igStatsAuto(f); setBusy(""); load(); };

  const duree = (t) => {
    if (t.periode_min) return "toutes les " + t.periode_min + " min";
    if (t.periode_s) return t.periode_s >= 60 ? "toutes les " + Math.round(t.periode_s / 60) + " min"
                                              : "toutes les " + t.periode_s + " s";
    return "en continu";
  };
  const inp = { background: "var(--surface-3)", border: "1px solid var(--border)", borderRadius: 7,
                color: "var(--text)", fontSize: 12, padding: "4px 7px" };

  return (
    <div>
      <PageHead title="Automatisation" sub="ce qui tourne tout seul · son état réel, et ce qui l'empêche d'avancer" />
      {d === null ? <div style={{ fontSize: 12.5, color: "var(--faint)" }}>chargement…</div>
        : <div style={{ display: "grid", gap: 10 }}>
            {(d.taches || []).map(t => (
              <Card key={t.id} pad={14}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                  <span style={{ width: 8, height: 8, borderRadius: 99, flex: "none",
                    background: t.actif ? "var(--accent)" : "var(--faint)" }} />
                  <span style={{ fontSize: 13.5, fontWeight: 700 }}>{t.nom}</span>
                  <span className="mono" style={{ fontSize: 10.5, color: "var(--faint)" }}>{duree(t)}</span>
                  <span style={{ marginLeft: "auto", fontSize: 11.5, fontWeight: 600,
                    color: t.actif ? "var(--accent)" : "var(--faint)" }}>
                    {t.actif ? "en marche" : "à l'arrêt"}
                  </span>
                </div>

                <div style={{ fontSize: 12, color: "var(--muted)", lineHeight: 1.55, marginTop: 6 }}>{t.quoi}</div>
                {t.garde_fou ? <div style={{ fontSize: 11, color: "var(--faint)", lineHeight: 1.5, marginTop: 3 }}>
                  🔒 {t.garde_fou}
                </div> : null}

                {t.id === "igstats" ? (
                  <div style={{ display: "flex", alignItems: "center", gap: 9, flexWrap: "wrap", marginTop: 9,
                                paddingTop: 9, borderTop: "1px solid var(--border)" }}>
                    <label style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12.5, cursor: "pointer" }}>
                      <input type="checkbox" checked={!!t.actif} disabled={busy === "igstats"}
                        onChange={e => regler({ on: e.target.checked })} />
                      <span>relever automatiquement</span>
                    </label>
                    <select value={t.periode_min} disabled={busy === "igstats" || !t.actif}
                      onChange={e => regler({ every: +e.target.value })} style={inp}>
                      {[15, 30, 45, 60, 120, 240].map(m => <option key={m} value={m}>{m} min</option>)}
                    </select>
                    <span style={{ fontSize: 11.5, color: "var(--muted)" }}>seuil</span>
                    <select value={t.seuil} disabled={busy === "igstats"}
                      onChange={e => regler({ seuil: +e.target.value })} style={inp}>
                      {[500, 1000, 5000, 15000].map(v => <option key={v} value={v}>{v} vues</option>)}
                    </select>
                  </div>) : null}

                {t.etat ? (
                  <div style={{ marginTop: 8, fontSize: 11.5, lineHeight: 1.5,
                    color: /aucun|pas encore|non charg/i.test(t.etat) ? "var(--faint)" : "var(--text)" }}>
                    <span style={{ color: "var(--faint)" }}>dernier passage{t.etat_at ? " à " + t.etat_at : ""} : </span>
                    {t.etat}
                  </div>) : null}
              </Card>
            ))}
          </div>}
      <div className="mono" style={{ fontSize: 10.5, color: "var(--faint)", marginTop: 12, lineHeight: 1.6 }}>
        cette page lit l'état réel du backend, elle ne le suppose pas · une tâche « à l'arrêt »
        ne tournera pas tant que personne ne l'allume ici.
      </div>
    </div>
  );
}

Object.assign(window, { AdminAutomatisation });
