// Scripts d'automatisation (bouton 🤖 à côté d'« Allumer l'écran », 2026-11-08).
// Deux blocs réductibles : « Lancer les scripts » et « Enregistrer un script ».
// Une bibliothèque par famille (pirate / classique / cloud) : un script ne s'affiche et ne se lance
// que sur sa famille. L'enregistreur écoute Backend.action, le point de passage unique des commandes.

const SA_ACTIONS = ["click", "tap", "hold", "gesture", "swipe", "home", "back", "recents", "wake", "lock", "unlock", "inputText", "launchApp"];
const SA_FAMILLES = { pirate: "🏴‍☠️ iPhones pirates", classique: "📱 iPhones classiques", cloud: "☁️ Cloud phones" };
const SA_PAUSE_MAX = 20000;   // une longue hésitation à l'enregistrement ne devient pas une longue attente
const SA_POINTS_MAX = 40;
let saClicInterne = false;    // le clic d'une étape « texte » : déjà noté comme tel, pas à enregistrer en plus

const saFamille = (d) => (d && d._cloud) ? "cloud" : (d && d.pirate) ? "pirate" : "classique";
const saSleep = (ms) => new Promise(r => setTimeout(r, ms));
const saLire = (cle, defaut) => { try { const v = JSON.parse(localStorage.getItem(cle)); return v === null ? defaut : v; } catch (e) { return defaut; } };
const saEcrire = (cle, v) => { try { localStorage.setItem(cle, JSON.stringify(v)); } catch (e) {} };

// Pause réelle : les intervalles restent tels quels, une durée fixe varie de ±15 %.
function saDuree(a) {
  if (a && typeof a === "object") return a.min + Math.random() * (a.max - a.min);
  const n = Number(a) || 0;
  return n ? n * (0.85 + Math.random() * 0.3) : 0;
}
function saAlleger(points) {
  if (!Array.isArray(points) || points.length <= SA_POINTS_MAX) return points;
  const pas = (points.length - 1) / (SA_POINTS_MAX - 1);
  return Array.from({ length: SA_POINTS_MAX }, (_, i) => points[Math.round(i * pas)]);
}
function saDirection(pts) {
  if (!pts || pts.length < 2) return "";
  const a = pts[0], b = pts[pts.length - 1], dx = b.x - a.x, dy = b.y - a.y;
  return Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? "←" : "→") : (dy > 0 ? "↑" : "↓");   // où va l'écran, pas le doigt
}
function saLibelle(e) {
  if (e.k === "texte") return `Cliquer sur « ${e.texte} »`;
  const x = e.extra || {}, pc = v => Math.round(v * 100) + " %";
  switch (e.action) {
    case "click": case "tap": return `Clic (${pc(x.x)}, ${pc(x.y)})`;
    case "hold": return `Appui long (${pc(x.x)}, ${pc(x.y)})`;
    case "gesture": case "swipe": return "Glissement " + saDirection(x.points);
    case "inputText": return `Taper « ${String(x.content || "").slice(0, 30)} »`;
    case "launchApp": return "Ouvrir une app";
    case "home": return "Home"; case "back": return "Retour"; case "recents": return "Apps récentes";
    case "wake": return "Allumer l'écran"; case "lock": return "Verrouiller"; case "unlock": return "Déverrouiller";
    default: return e.action;
  }
}
// Glissement réglable. Doux = le doigt ralentit avant de se lever : presque pas d'inertie, la liste
// s'arrête où on l'attend. Fort = vitesse constante : la liste continue sur sa lancée. 7 points : le
// moteur en garde 8 au plus, dont celui ajouté par le backend pour respecter la durée.
const SA_FORCES = [
  { l: "Très doux", distance: .25, duree: 700, appui: 0 }, { l: "Doux", distance: .4, duree: 600, appui: 0 }, { l: "Moyen", distance: .55, duree: 500, appui: 0 },
  { l: "Fort", distance: .75, duree: 300, appui: 0 }, { l: "Très fort", distance: .8, duree: 50, appui: 0 }];
// Mesuré sur liste de 250 lignes (08/11, iPhone X) : 80 % en 50 ms = 111 à 154 lignes, 5 essais sur 5.
// Un appui avant le glissement réduit la portée. 30 ms va plus loin (206-235) mais 16 ms est lu comme
// un CLIC et choisit la ligne touchée : on garde 50 ms, qui laisse de la marge.
const SA_LANCER = { sens: "haut", distance: .8, duree: 50, appui: 0 };
// `appui` : le doigt reste posé (ms) avant de partir. Un rapide part en DEUX segments seulement : le
// glissement d'origine (3 points) lançait la liste bien plus loin qu'un chemin découpé en 6 morceaux.
function saGesteChemin({ sens, distance, duree, appui }) {
  const m = distance / 2, freine = duree >= 400, attente = appui || 0, n = freine ? (attente ? 5 : 6) : 2;
  const [x1, y1, x2, y2] = { droite: [.5 - m, .5, .5 + m, .5], gauche: [.5 + m, .5, .5 - m, .5], haut: [.5, .5 + m, .5, .5 - m], bas: [.5, .5 - m, .5, .5 + m] }[sens];
  const pts = attente ? [{ x: +x1.toFixed(3), y: +y1.toFixed(3), t: 0 }] : [];
  for (let i = 0; i <= n; i++) {
    const r = i / n, k = freine ? 1 - Math.pow(1 - r, 3) : r;
    pts.push({ x: +(x1 + (x2 - x1) * k).toFixed(3), y: +(y1 + (y2 - y1) * k).toFixed(3), t: Math.round(attente + duree * r) });
  }
  return pts;
}
function saGesteReglage(points) {
  const p = points || [], a = p[0] || { x: .5, y: .5, t: 0 }, b = p[p.length - 1] || a;
  const dx = b.x - a.x, dy = b.y - a.y, h = Math.abs(dx) > Math.abs(dy);
  const appui = p.length > 2 && p[1].x === a.x && p[1].y === a.y ? Math.max(0, (p[1].t || 0) - (a.t || 0)) : 0;
  return { sens: h ? (dx > 0 ? "droite" : "gauche") : (dy > 0 ? "bas" : "haut"), distance: +(h ? Math.abs(dx) : Math.abs(dy)).toFixed(2), duree: Math.max(50, (b.t || 0) - (a.t || 0) - appui), appui };
}
const saSwipe = (sens, fort) => saGesteChemin(fort ? { sens, distance: .8, duree: 130 } : { sens, distance: .35, duree: 420 });
const SA_ABSENT = "texte introuvable à l'écran";
function saCliquerA(udid, r) {
  saClicInterne = true;
  const envoi = window.Backend.action(udid, "click", { x: r.x, y: r.y, duration: 0.1 });   // l'écoute est synchrone
  saClicInterne = false;
  return envoi;
}
// Cherche le texte et clique dessus. Avec `defiler` : fait défiler jusqu'à le lire. Lève une erreur sinon.
async function saCliquerTexte(device, e, vivant) {
  const udid = device.udid, texte = String(e.texte || "").trim(), d = e.defiler;
  if (!texte) throw new Error("le texte à chercher est vide");
  // Grands glissements d'abord (pour les textes tout en bas), puis défilement fin.
  const lancers = d ? (d.lancers || 0) : 0;
  const essais = d ? lancers + d.max + 1 : 4;
  let r = null;
  for (let i = 0; i < essais; i++) {
    if (!vivant()) return;
    r = await window.Backend.scriptTrouver(udid, texte, !!d && i > 0);     // après un glissement : lit l'écran une fois la liste arrêtée
    if (!vivant()) return;
    if (r && r.ok) { await saCliquerA(udid, r); return; }
    if (r && r.error && r.error !== SA_ABSENT) throw new Error(r.error);
    if (i === essais - 1) break;
    if (d) {
      const grand = i < lancers, g = grand ? { ...SA_LANCER, ...(d.lancer || {}) } : d;
      await window.Backend.action(udid, "gesture", { points: saGesteChemin(g), reel: true });
      await saSleep((g.appui || 0) + g.duree + (grand ? 2800 : 1100));     // après un grand lancer, la liste roule encore
    } else await saSleep(1500);
  }
  throw new Error(`« ${texte} » introuvable à l'écran` + (d ? ` après ${lancers + d.max} défilements` : ""));
}
// Une étape, seule : utilisée par la lecture du script et par le bouton Exécuter.
async function saExecuter(device, e, vivant) {
  if (e.k === "texte") return saCliquerTexte(device, e, vivant);
  return window.Backend.action(device.udid, e.action, e.extra);
}

// ── Petits éléments ─────────────────────────────────────────────────────────────────────
const saBtn = { background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 9, padding: "8px 11px", color: "var(--text)", fontSize: 12.5, fontWeight: 600, cursor: "pointer" };
const saPrim = { ...saBtn, background: "var(--accent)", color: "#06281c", border: "1px solid transparent", fontWeight: 800 };
const saChamp = { width: "100%", boxSizing: "border-box", background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 9, padding: "9px 11px", color: "var(--text)", fontSize: 13 };

function SaBloc({ id, titre, droite, children }) {
  const { useState } = React;
  const [ouvert, setOuvert] = useState(() => saLire("pl.scripts.bloc." + id, id === "lancer"));
  const basculer = () => setOuvert(o => { saEcrire("pl.scripts.bloc." + id, !o); return !o; });
  return (
    <div style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--r-lg)", padding: 14, marginBottom: 12 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <button type="button" onClick={basculer} style={{ flex: 1, minWidth: 0, display: "flex", alignItems: "center", gap: 8, background: "none", border: "none", padding: 0, cursor: "pointer", color: "var(--text)", fontSize: 14, fontWeight: 800, textAlign: "left" }}>
          <span style={{ color: "var(--faint)", fontSize: 11 }}>{ouvert ? "▼" : "▶"}</span> {titre}
        </button>
        {droite}
      </div>
      {ouvert && <div style={{ marginTop: 12 }}>{children}</div>}
    </div>
  );
}

function SaCapture({ udid, id, style, onClick }) {
  const { useState, useEffect } = React;
  const [url, setUrl] = useState(null);
  useEffect(() => {
    let vivant = true, u = null; setUrl(null);
    if (id) window.Backend.scriptCaptureUrl(udid, id).then(x => { u = x; if (vivant) setUrl(x); });
    return () => { vivant = false; if (u) URL.revokeObjectURL(u); };
  }, [udid, id]);
  if (!id) return null;
  return url ? <img src={url} alt="écran de départ" onClick={onClick} style={{ display: "block", objectFit: "contain", background: "#000", borderRadius: 10, cursor: onClick ? "zoom-in" : "default", ...style }} />
    : <div style={{ display: "grid", placeItems: "center", background: "#000", borderRadius: 10, color: "var(--faint)", fontSize: 11, ...style }}>…</div>;
}

// Fenêtre « Êtes-vous sûr d'être à cet endroit-là ? »
function SaConfirmer({ device, script, onAnnuler, onConfirmer }) {
  return (
    <div onClick={onAnnuler} style={{ position: "fixed", inset: 0, zIndex: 3000, background: "rgba(0,0,0,.72)", display: "grid", placeItems: "center", padding: 16 }}>
      <div onClick={e => e.stopPropagation()} style={{ width: "min(420px, 100%)", maxHeight: "92vh", overflow: "auto", background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 16, padding: 18, display: "grid", gap: 12 }}>
        <div style={{ fontSize: 16, fontWeight: 800 }}>Êtes-vous sûr d'être à cet endroit-là ?</div>
        <div style={{ fontSize: 12.5, color: "var(--muted)" }}>Avant de lancer <b style={{ color: "var(--text)" }}>{script.nom}</b></div>
        {script.capture && <SaCapture udid={device.udid} id={script.capture} style={{ width: "100%", maxHeight: "56vh" }} />}
        {script.depart && <div style={{ fontSize: 12.5, lineHeight: 1.45, color: "var(--text)" }}>{script.depart}</div>}
        <div style={{ display: "flex", gap: 8 }}>
          <button type="button" onClick={onAnnuler} style={{ ...saBtn, flex: 1 }}>Annuler</button>
          <button type="button" onClick={() => onConfirmer(false)} style={{ ...saPrim, flex: 2 }}>Confirmer</button>
        </div>
        <button type="button" onClick={() => onConfirmer(true)} style={{ background: "none", border: "none", color: "var(--faint)", fontSize: 11.5, cursor: "pointer", textDecoration: "underline" }}>Confirmer et ne plus me le rappeler</button>
      </div>
    </div>
  );
}

// Nom, capture, note de départ et liste des étapes : après un enregistrement, ou pour modifier un script.
// Réglage d'un glissement : sens, force toute prête, ou réglage fin.
function SaReglage({ r, onChange }) {
  const pill = (actif) => ({ ...saBtn, padding: "1px 6px", fontSize: 10.5, borderRadius: 7, background: actif ? "var(--accent-soft)" : "var(--surface)", color: actif ? "var(--accent)" : "var(--text)", borderColor: actif ? "var(--accent-line)" : "var(--border)" });
  // La flèche dit où va l'ÉCRAN (▼ = descendre dans la liste). `sens` reste celui du doigt, stocké tel quel.
  const sens = [["bas", "▲", "Remonter dans la liste"], ["haut", "▼", "Descendre dans la liste"], ["droite", "◀", "Aller vers la gauche"], ["gauche", "▶", "Aller vers la droite"]];
  const curseur = (v, min, max, pas, surChange) => <input type="range" min={min} max={max} step={pas} value={v} onChange={ev => surChange(Number(ev.target.value))} style={{ flex: 1, minWidth: 0, height: 12, margin: 0, accentColor: "var(--accent)" }} />;
  return (
    <div style={{ display: "grid", gap: 2, fontSize: 10.5 }}>
      <div style={{ display: "flex", gap: 3, flexWrap: "wrap", marginBottom: 2 }}>
        {sens.map(([id, t, titre]) => <button type="button" key={id} title={titre} onClick={() => onChange({ sens: id })} style={pill(r.sens === id)}>{t}</button>)}
        <span style={{ width: 3 }} />
        {SA_FORCES.map(f => <button type="button" key={f.l} onClick={() => onChange({ distance: f.distance, duree: f.duree, appui: f.appui })} style={pill(Math.abs(r.distance - f.distance) < .01 && r.duree === f.duree && (r.appui || 0) === f.appui)}>{f.l}</button>)}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 7 }}><span style={{ width: 48, flex: "none" }}>Distance</span>{curseur(r.distance, .05, .9, .01, v => onChange({ distance: v }))}<span className="mono" style={{ width: 48, flex: "none", textAlign: "right" }}>{Math.round(r.distance * 100)} %</span></div>
      <div style={{ display: "flex", alignItems: "center", gap: 7 }}><span style={{ width: 48, flex: "none" }}>Durée</span>{curseur(r.duree, 50, 2000, 10, v => onChange({ duree: v }))}<span className="mono" style={{ width: 48, flex: "none", textAlign: "right" }}>{r.duree} ms</span></div>
      <div title="Temps pendant lequel le doigt reste posé avant de glisser" style={{ display: "flex", alignItems: "center", gap: 7 }}><span style={{ width: 48, flex: "none" }}>Appui</span>{curseur(r.appui || 0, 0, 1000, 10, v => onChange({ appui: v }))}<span className="mono" style={{ width: 48, flex: "none", textAlign: "right" }}>{r.appui || 0} ms</span></div>
    </div>
  );
}

function SaEditeur({ device, initial, dead, onAnnuler, onSauve }) {
  const { useRef, useEffect } = React;
  const { useState } = React;
  // _k : identité stable d'une étape dans l'éditeur (déplacer sans mélanger les champs). Le serveur l'ignore.
  const nouvelleCle = () => Math.random().toString(36).slice(2);
  const [s, setS] = useState(() => ({ ...initial, etapes: initial.etapes.map(e => ({ ...e, _k: nouvelleCle() })) }));
  const [occupe, setOccupe] = useState(false);
  const [err, setErr] = useState("");
  const maj = (p) => setS(x => ({ ...x, ...p }));
  const etape = (i, p) => setS(x => ({ ...x, etapes: x.etapes.map((e, j) => j === i ? { ...e, ...p } : e) }));
  const extra = (i, p) => setS(x => ({ ...x, etapes: x.etapes.map((e, j) => j === i ? { ...e, extra: { ...e.extra, ...p } } : e) }));
  const deplacer = (i, d) => setS(x => { const l = [...x.etapes], j = i + d; if (j < 0 || j >= l.length) return x; [l[i], l[j]] = [l[j], l[i]]; return { ...x, etapes: l }; });
  const [ajoutApres, setAjoutApres] = useState(null);
  const ajouter = (e, pos) => { const k = nouvelleCle(); setAjoutApres(null); setS(x => { const l = [...x.etapes]; l.splice(pos == null ? l.length : pos + 1, 0, { attente: 1500, ...e, _k: k }); return { ...x, etapes: l }; }); return k; };
  // 🎯 Le prochain clic sur l'écran du téléphone donne la position, sans être envoyé au téléphone.
  const [visee, setVisee] = useState(null);
  const annulerVisee = () => { setVisee(null); if (window.TapCapture) window.TapCapture.annuler(); };
  const viser = (k, n) => {
    if (!window.TapCapture) return;
    setVisee(k);
    window.TapCapture.demander("Étape " + n + " : choisis l'endroit", (x, y) => {
      setVisee(null);
      setS(c => ({ ...c, etapes: c.etapes.map(e => e._k === k ? { ...e, extra: { ...e.extra, x, y } } : e) }));
    });
  };
  useEffect(() => {
    if (!window.TapCapture) return;
    return window.TapCapture.sub(() => { if (!window.TapCapture.actif()) setVisee(null); });
  }, []);
  useEffect(() => () => { if (window.TapCapture) window.TapCapture.annuler(); }, []);
  const dupliquer = (i) => setS(x => { const l = [...x.etapes]; l.splice(i + 1, 0, { ...JSON.parse(JSON.stringify(l[i])), _k: nouvelleCle() }); return { ...x, etapes: l }; });

  // Exécuter une étape seule, ou d'ici à la fin, avec les valeurs affichées (même non enregistrées).
  const [test, setTest] = useState(null);       // { k, en, ok, t }
  const testeur = useRef(0);
  const deadRef = useRef(dead); deadRef.current = dead;
  useEffect(() => () => { testeur.current++; }, []);
  const executer = async (i, jusquaFin) => {
    const moi = ++testeur.current, vivant = () => testeur.current === moi, l = s.etapes;
    const fin = jusquaFin ? l.length : i + 1;
    let j = i;
    try {
      for (; j < fin; j++) {
        if (deadRef.current) throw new Error("téléphone déconnecté");
        setTest({ k: l[j]._k, en: true, n: j + 1 });
        { const t = Date.now() + saDuree(l[j].attente); while (Date.now() < t) { if (!vivant()) return; await saSleep(100); } }
        if (!vivant()) return;
        await saExecuter(device, l[j], vivant);
      }
      if (vivant()) setTest({ k: l[fin - 1]._k, ok: true, t: jusquaFin ? "✅ Terminé" : "✅ Exécutée" });
    } catch (err) { if (vivant()) setTest({ k: l[j]._k, ok: false, t: "⏹ " + err.message }); }
  };
  const stopTest = () => { testeur.current++; setTest(null); };
  const refaire = async () => {
    setOccupe(true); const r = await window.Backend.scriptCapturer(device.udid); setOccupe(false);
    if (r && r.ok) maj({ capture: r.capture }); else setErr((r && r.error) || "capture impossible");
  };
  const sauver = async () => {
    if (s.etapes.some(e => e.k === "texte" && !String(e.texte || "").trim())) { setErr("Une étape « Cliquer sur un texte » est vide."); return; }
    setOccupe(true); setErr("");
    const r = await window.Backend.scriptEnregistrer(device.udid, s);
    setOccupe(false);
    if (r && r.ok) onSauve(r.script); else setErr((r && r.error) || "enregistrement impossible");
  };
  // Saisie libre (« 3. » en cours de frappe) : champ non contrôlé, recréé avec l'étape grâce à _k.
  const num = (val, surChange, titre, largeur) => <input type="number" min="0" step="any" defaultValue={val} title={titre} onChange={ev => surChange(Number(ev.target.value) || 0)} style={{ ...saChamp, width: largeur || 46, padding: "1px 4px", fontSize: 11 }} />;
  const sec = (ms) => +((ms || 0) / 1000).toFixed(1);
  const icone = { background: "none", border: "none", color: "var(--faint)", cursor: "pointer", padding: "0 3px", fontSize: 12 };
  const boutonsAjout = (pos) => (
    <div style={{ display: "flex", gap: 5, flexWrap: "wrap" }}>
      <button type="button" onClick={() => ajouter({ k: "texte", texte: "" }, pos)} style={{ ...saBtn, padding: "5px 9px", fontSize: 11.5 }}>+ Cliquer sur un texte</button>
      <button type="button" onClick={() => viser(ajouter({ k: "action", action: "click", extra: { x: .5, y: .5, duration: 0.1 } }, pos), "nouvelle")} style={{ ...saBtn, padding: "5px 9px", fontSize: 11.5 }}>+ Clic à une position</button>
      <button type="button" onClick={() => ajouter({ k: "action", action: "gesture", extra: { points: saGesteChemin({ sens: "haut", distance: .55, duree: 500 }), reel: true } }, pos)} style={{ ...saBtn, padding: "5px 9px", fontSize: 11.5 }}>+ Glissement</button>
      <button type="button" onClick={() => ajouter({ k: "action", action: "inputText", extra: { content: "" } }, pos)} style={{ ...saBtn, padding: "5px 9px", fontSize: 11.5 }}>+ Taper du texte</button>
    </div>
  );
  return (
    <div style={{ display: "grid", gap: 10 }}>
      <input value={s.nom || ""} onChange={e => maj({ nom: e.target.value })} placeholder="Nom du script (ex. Automatisation limitation d'âge)" style={saChamp} />
      <div style={{ display: "flex", gap: 10, alignItems: "flex-start" }}>
        {s.capture ? <SaCapture udid={device.udid} id={s.capture} style={{ width: 92, height: 190, flex: "none" }} />
          : <div style={{ width: 92, height: 190, flex: "none", display: "grid", placeItems: "center", textAlign: "center", border: "1px dashed var(--border)", borderRadius: 10, color: "var(--faint)", fontSize: 11, padding: 6, boxSizing: "border-box" }}>aucune capture</div>}
        <div style={{ flex: 1, minWidth: 0, display: "grid", gap: 8 }}>
          <div style={{ fontSize: 11.5, color: "var(--faint)", lineHeight: 1.4 }}>L'écran où il faut être avant de lancer. Elle sera montrée pour confirmation.</div>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
            <button type="button" disabled={occupe} onClick={refaire} style={saBtn}>📷 {s.capture ? "Refaire" : "Prendre"} avec l'écran actuel</button>
            {s.capture && <button type="button" onClick={() => maj({ capture: "" })} style={saBtn}>Retirer</button>}
          </div>
          <textarea value={s.depart || ""} onChange={e => maj({ depart: e.target.value })} rows={2} placeholder="Note de départ (optionnel)" style={{ ...saChamp, resize: "vertical", fontSize: 12 }} />
        </div>
      </div>
      <div style={{ maxHeight: "62vh", overflow: "auto", display: "grid", gap: 4 }}>
        {s.etapes.map((e, i) => {
          const glisse = e.action === "gesture" || e.action === "swipe";
          const enTest = test && test.en;
          return (
          <div key={e._k} style={{ display: "grid", gap: 4, fontSize: 11, padding: "5px 7px", borderRadius: 8, background: "var(--surface-2)", boxShadow: test && test.k === e._k && test.en ? "inset 0 0 0 1.5px var(--accent)" : "none" }}>
            <div style={{ display: "flex", alignItems: "center", gap: 6 }}>
              <span className="mono" style={{ color: "var(--faint)", width: 20, flex: "none" }}>{i + 1}</span>
              {e.k === "texte"
                ? <span style={{ flex: 1, minWidth: 0, display: "flex", alignItems: "center", gap: 6 }}>
                    <span style={{ flex: "none" }}>Cliquer sur</span>
                    <input value={e.texte || ""} onChange={ev => etape(i, { texte: ev.target.value })} placeholder="texte affiché à l'écran" style={{ ...saChamp, padding: "2px 6px", fontSize: 11.5, fontWeight: 700 }} />
                  </span>
                : e.action === "inputText"
                ? <span style={{ flex: 1, minWidth: 0, display: "flex", alignItems: "center", gap: 6 }}>
                    <span style={{ flex: "none" }}>Taper</span>
                    <input value={(e.extra && e.extra.content) || ""} onChange={ev => extra(i, { content: ev.target.value })} style={{ ...saChamp, padding: "2px 6px", fontSize: 11.5 }} />
                  </span>
                : ["click", "tap", "hold"].includes(e.action)
                ? <span style={{ flex: 1, minWidth: 0, display: "flex", alignItems: "center", gap: 8 }}>
                    <span style={{ flex: "none", fontWeight: 700 }}>{e.action === "hold" ? "Appui long" : "Clic"}</span>
                    <span title="Endroit visé sur l'écran" style={{ position: "relative", flex: "none", width: 20, height: 40, borderRadius: 4, border: "1px solid var(--border-2, var(--border))", background: "var(--surface)" }}>
                      <span style={{ position: "absolute", left: ((e.extra && e.extra.x) || 0) * 100 + "%", top: ((e.extra && e.extra.y) || 0) * 100 + "%", width: 6, height: 6, marginLeft: -3, marginTop: -3, borderRadius: 99, background: "var(--accent)" }} />
                    </span>
                    {visee === e._k
                      ? <button type="button" onClick={annulerVisee} style={{ ...saBtn, padding: "5px 10px", fontSize: 11.5, background: "var(--accent)", color: "#06281c", border: "none", fontWeight: 800 }}>🎯 Clique sur l'écran… (annuler)</button>
                      : <button type="button" title="Clique ici, puis clique sur l'écran du téléphone à l'endroit voulu" onClick={() => viser(e._k, i + 1)} style={{ ...saBtn, padding: "5px 10px", fontSize: 11.5, fontWeight: 700 }}>🎯 Choisir l'endroit</button>}
                  </span>
                : <span style={{ flex: 1, minWidth: 0, fontWeight: 700, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{saLibelle(e)}</span>}
              <span style={{ flex: "none", display: "inline-flex" }}>
                <button type="button" title="Ajouter une étape après celle-ci" onClick={() => setAjoutApres(a => a === e._k ? null : e._k)} style={icone}>＋</button>
                <button type="button" title="Dupliquer" onClick={() => dupliquer(i)} style={icone}>⧉</button>
                <button type="button" title="Monter" disabled={i === 0} onClick={() => deplacer(i, -1)} style={{ ...icone, opacity: i === 0 ? .3 : 1 }}>▲</button>
                <button type="button" title="Descendre" disabled={i === s.etapes.length - 1} onClick={() => deplacer(i, 1)} style={{ ...icone, opacity: i === s.etapes.length - 1 ? .3 : 1 }}>▼</button>
                <button type="button" title="Supprimer cette étape" onClick={() => maj({ etapes: s.etapes.filter((_, j) => j !== i) })} style={icone}>✕</button>
              </span>
            </div>
            {glisse && <div style={{ paddingLeft: 26, color: "var(--muted)" }}>
              <SaReglage r={saGesteReglage(e.extra && e.extra.points)} onChange={p => { const r = { ...saGesteReglage(s.etapes[i].extra.points), ...p }; extra(i, { points: saGesteChemin(r), reel: true }); }} />
            </div>}
            {e.k === "texte" && <div style={{ paddingLeft: 26, color: "var(--muted)", display: "grid", gap: 3 }}>
              <label style={{ display: "flex", alignItems: "center", gap: 6, cursor: "pointer" }}>
                <input type="checkbox" checked={!!e.defiler} onChange={ev => etape(i, { defiler: ev.target.checked ? { sens: "haut", distance: .5, duree: 600, max: 30 } : undefined })} />
                Si absent, faire défiler jusqu'à le trouver
              </label>
              {e.defiler && <React.Fragment>
                <SaReglage r={e.defiler} onChange={p => etape(i, { defiler: { ...s.etapes[i].defiler, ...p } })} />
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}><b style={{ fontWeight: 700 }}>Grands glissements d'abord :</b> {num(e.defiler.lancers || 0, v => etape(i, { defiler: { ...s.etapes[i].defiler, lancers: Math.max(0, Math.min(20, Math.round(v))), lancer: s.etapes[i].defiler.lancer || { ...SA_LANCER, sens: s.etapes[i].defiler.sens } } }), "Nombre de grands glissements avant le défilement fin")}</div>
                {e.defiler.lancers > 0 && <SaReglage r={{ ...SA_LANCER, ...(e.defiler.lancer || {}) }} onChange={p => etape(i, { defiler: { ...s.etapes[i].defiler, lancer: { ...SA_LANCER, ...(s.etapes[i].defiler.lancer || {}), ...p } } })} />}
                <div style={{ display: "flex", alignItems: "center", gap: 6 }}>Défilements fins au maximum : {num(e.defiler.max, v => etape(i, { defiler: { ...s.etapes[i].defiler, max: Math.max(1, Math.min(80, Math.round(v))) } }), "Nombre maximum de défilements avant d'abandonner")}</div>
              </React.Fragment>}
            </div>}
            <div style={{ display: "flex", alignItems: "center", gap: 4, paddingLeft: 26, color: "var(--muted)", fontSize: 10.5 }}>
              <span title="Temps d'attente AVANT de faire cette action, pour laisser la page se charger" style={{ flex: "none", fontWeight: 700 }}>⏳ Wait</span>
              {(e.attente && typeof e.attente === "object")
                ? <React.Fragment key="plage">
                    {num(sec(e.attente.min), v => etape(i, { attente: { ...s.etapes[i].attente, min: Math.round(v * 1000) } }), "Attente minimale, en secondes")}
                    à
                    {num(sec(e.attente.max), v => etape(i, { attente: { ...s.etapes[i].attente, max: Math.round(v * 1000) } }), "Attente maximale, en secondes")}
                    s
                  </React.Fragment>
                : <React.Fragment key="fixe">{num(sec(e.attente), v => etape(i, { attente: Math.round(v * 1000) }), "Attente avant cette étape, en secondes")} s</React.Fragment>}
              <button type="button" title={(e.attente && typeof e.attente === "object") ? "Passer à une attente fixe" : "Passer à une attente aléatoire"} onClick={() => { const a = s.etapes[i].attente; etape(i, { attente: (a && typeof a === "object") ? a.min : { min: a || 0, max: (a || 0) + 1000 } }); }} style={{ ...icone, opacity: (e.attente && typeof e.attente === "object") ? 1 : .45 }}>🎲</button>
              <span style={{ flex: 1 }} />
              {test && test.k === e._k && test.en
                ? <button type="button" onClick={stopTest} style={{ ...saBtn, padding: "2px 9px", fontSize: 10.5, background: "#c8323a", color: "#fff", border: "none", fontWeight: 800 }}>⏹ Stop</button>
                : <React.Fragment>
                    <button type="button" title="Lance cette étape puis toutes les suivantes" disabled={dead || enTest} onClick={() => executer(i, true)} style={{ ...saBtn, padding: "2px 7px", fontSize: 10.5, opacity: dead || enTest ? .45 : 1 }}>▶▶ Suite</button>
                    <button type="button" title="Lance uniquement cette étape, après son Wait" disabled={dead || enTest} onClick={() => executer(i, false)} style={{ ...saBtn, padding: "2px 8px", fontSize: 10.5, background: "var(--accent-soft)", color: "var(--accent)", borderColor: "var(--accent-line)", fontWeight: 800, opacity: dead || enTest ? .45 : 1 }}>▶ Exécuter</button>
                  </React.Fragment>}
            </div>
            {test && test.k === e._k && !test.en && <div style={{ paddingLeft: 26, fontSize: 11.5, color: test.ok ? "var(--accent)" : "var(--danger, #ff6b6b)" }}>{test.t}</div>}
            {ajoutApres === e._k && <div style={{ paddingLeft: 26 }}>{boutonsAjout(i)}</div>}
          </div>
        ); })}
      </div>
      {boutonsAjout(null)}
      {err && <div style={{ fontSize: 12, color: "var(--danger, #ff6b6b)" }}>{err}</div>}
      <div style={{ display: "flex", gap: 8 }}>
        <button type="button" onClick={onAnnuler} style={{ ...saBtn, flex: 1 }}>Annuler</button>
        <button type="button" disabled={occupe} onClick={sauver} style={{ ...saPrim, flex: 2 }}>Enregistrer le script</button>
      </div>
    </div>
  );
}

function SaEnregistreur({ device, act, dead, onOccupe, famille, onCree, bloque }) {
  const { useState, useRef, useEffect } = React;
  const [enCours, setEnCours] = useState(false);
  const [prep, setPrep] = useState(false);
  const [etapes, setEtapes] = useState([]);
  const [brouillon, setBrouillon] = useState(null);
  const [mot, setMot] = useState("");
  const [saisie, setSaisie] = useState("");
  const [err, setErr] = useState("");
  const dernier = useRef(0);
  const capture = useRef("");
  const vivant = useRef(false);

  const noter = (e) => {
    const n = Date.now(), attente = dernier.current ? Math.min(SA_PAUSE_MAX, n - dernier.current) : 0;
    dernier.current = n;
    setEtapes(x => [...x, { ...e, attente }]);
  };
  const arreterEcoute = () => { vivant.current = false; if (window.Backend._ecouteAction === ecoute.current) window.Backend._ecouteAction = null; };
  const ecoute = useRef(null);
  useEffect(() => () => arreterEcoute(), []);
  useEffect(() => { if (enCours) { setEnCours(false); arreterEcoute(); onOccupe(false); setEtapes([]); } }, [device.udid]);

  const demarrer = async () => {
    setErr(""); setEtapes([]); dernier.current = 0; capture.current = ""; setPrep(true);
    // Prise AVANT d'écouter : c'est l'écran où il faudra se trouver pour relancer le script.
    const r = await window.Backend.scriptCapturer(device.udid);
    setPrep(false);
    if (r && r.ok) capture.current = r.capture;
    vivant.current = true;
    ecoute.current = (udid, action, extra) => {
      if (saClicInterne || udid !== device.udid || !SA_ACTIONS.includes(action)) return;
      const x = { ...(extra || {}) };
      if (x.points) x.points = saAlleger(x.points);
      noter({ k: "action", action, extra: x });
    };
    window.Backend._ecouteAction = ecoute.current;
    setEnCours(true); onOccupe(true);
  };
  const arreter = () => {
    arreterEcoute(); setEnCours(false); onOccupe(false);
    if (!etapes.length) { setErr("Aucune action enregistrée."); return; }
    setBrouillon({ nom: "", famille, etapes, capture: capture.current, depart: "" });
  };
  const cliquerMot = async () => {
    const t = mot.trim(); if (!t) return;
    setErr("");
    try { await saCliquerTexte(device, { texte: t }, () => true); noter({ k: "texte", texte: t }); setMot(""); }
    catch (e) { setErr(e.message); }
  };
  const envoyerSaisie = () => { if (saisie) { act("Clavier", "kb", saisie); setSaisie(""); } };
  const geste = (sens, fort) => window.Backend.action(device.udid, "gesture", { points: saSwipe(sens, fort), reel: true });
  const retour = () => device._cloud ? window.Backend.action(device.udid, "back") : act("Retour", "back");

  if (brouillon) return <SaEditeur device={device} dead={dead} initial={brouillon} onAnnuler={() => setBrouillon(null)} onSauve={(s) => { setBrouillon(null); setEtapes([]); onCree(s); }} />;

  const pad = (id, txt, label) => <button type="button" key={id} disabled={dead} onClick={() => act(label, id)} style={{ ...saBtn, padding: 0, width: 42, height: 42, fontSize: 16 }}>{txt}</button>;
  const libre = !enCours || dead;
  const swipeBtn = (sens, fort, txt) => <button type="button" disabled={libre} onClick={() => geste(sens, fort)} style={{ ...saBtn, padding: "7px 4px", opacity: libre ? .5 : 1 }}>{txt}</button>;
  return (
    <div style={{ display: "grid", gap: 11 }}>
      {enCours
        ? <button type="button" onClick={arreter} style={{ ...saBtn, background: "rgba(255,90,90,.16)", border: "1px solid rgba(255,90,90,.5)", color: "#ff8f96", fontWeight: 800, padding: 11 }}>⏺ Enregistrement… {etapes.length} action(s) · Arrêter</button>
        : <button type="button" disabled={dead || prep || bloque} onClick={demarrer} style={{ ...saPrim, padding: 11, opacity: dead || prep || bloque ? .55 : 1 }}>{prep ? "📷 Capture de l'écran de départ…" : "⏺ Enregistrer un script"}</button>}
      <div style={{ fontSize: 11.5, color: "var(--faint)", lineHeight: 1.4 }}>Clics, glissements et appuis longs sur l'écran du téléphone sont enregistrés automatiquement. Place-toi d'abord sur l'écran de départ.</div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(4, minmax(0,1fr))", gap: 5, fontSize: 11 }}>
        {swipeBtn("droite", true, "⏪ Fort")}{swipeBtn("droite", false, "◀ Doux")}{swipeBtn("gauche", false, "Doux ▶")}{swipeBtn("gauche", true, "Fort ⏩")}
        {swipeBtn("bas", true, "⏫ Fort")}{swipeBtn("bas", false, "▲ Doux")}{swipeBtn("haut", false, "Doux ▼")}{swipeBtn("haut", true, "Fort ⏬")}
      </div>
      <div style={{ display: "flex", gap: 14, alignItems: "center", justifyContent: "center" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,42px)", gridTemplateRows: "repeat(3,42px)", gap: 4 }}>
          <span />{pad("down", "▲", "Joystick haut")}<span />
          {pad("right", "◀", "Joystick gauche")}<span />{pad("left", "▶", "Joystick droite")}
          <span />{pad("up", "▼", "Joystick bas")}<span />
        </div>
        <div style={{ display: "grid", gap: 5 }}>
          <button type="button" disabled={dead} onClick={() => act("Home", "home")} style={saBtn}>Home</button>
          <button type="button" disabled={dead} onClick={retour} style={saBtn}>Retour</button>
        </div>
      </div>
      <div style={{ display: "flex", gap: 6 }}>
        <input value={mot} onChange={e => setMot(e.target.value)} onKeyDown={e => e.key === "Enter" && enCours && cliquerMot()} placeholder="Cliquer sur un texte (ex. Save)" style={saChamp} />
        <button type="button" disabled={libre || !mot.trim()} onClick={cliquerMot} style={{ ...saBtn, flex: "none" }}>Cliquer</button>
      </div>
      <div style={{ display: "flex", gap: 6 }}>
        <input value={saisie} onChange={e => setSaisie(e.target.value)} onKeyDown={e => e.key === "Enter" && enCours && envoyerSaisie()} placeholder="Taper du texte sur le téléphone" style={saChamp} />
        <button type="button" disabled={libre || !saisie} onClick={envoyerSaisie} style={{ ...saBtn, flex: "none" }}>Taper</button>
      </div>
      {err && <div style={{ fontSize: 12, color: "var(--danger, #ff6b6b)" }}>{err}</div>}
    </div>
  );
}

function ScriptsAutoPanneau({ device, user, act, dead, onOccupe }) {
  const { useState, useRef, useEffect } = React;
  const famille = saFamille(device);
  // Lancer : tout le monde. Créer : propriétaire/admin, ou coché dans Team. Le serveur vérifie aussi.
  const estAdmin = (window.ROLE_RANK ? window.ROLE_RANK(user && user.role) : 0) >= 3;
  const [createurs, setCreateurs] = useState([]);
  useEffect(() => { window.Backend.scriptsDroits().then(l => l && setCreateurs(l)); }, [device.udid]);
  const peutEditer = estAdmin || (!!user && createurs.includes(String(user.id)));
  const peutModifier = (s) => estAdmin || (peutEditer && s.auteur === String(user.id));
  const cleRappel = "pl.scripts.norappel." + ((user && user.id) || "local");
  const [scripts, setScripts] = useState(null);
  const [aConfirmer, setAConfirmer] = useState(null);
  const [edition, setEdition] = useState(null);
  const [lecture, setLecture] = useState(null);       // { id, nom, i, n }
  const [msg, setMsg] = useState(null);
  const [sansRappel, setSansRappel] = useState(() => saLire(cleRappel, []));
  const jeton = useRef(0);
  const deadRef = useRef(dead); deadRef.current = dead;

  const recharger = () => window.Backend.scriptsListe(device.udid, famille).then(l => setScripts(l));
  useEffect(() => { setScripts(null); setEdition(null); recharger(); jeton.current++; setLecture(null); }, [device.udid, famille]);
  useEffect(() => () => { jeton.current++; }, []);

  const jouer = async (s) => {
    if (s.famille !== famille) { setMsg({ ok: false, t: "Ce script n'est pas fait pour ce type de téléphone." }); return; }
    const moi = ++jeton.current, vivant = () => jeton.current === moi;
    let panne = "";
    const surEchec = (ev) => { if (ev.detail && ev.detail.udid === device.udid) { panne = "commande refusée (" + ev.detail.raison + ")"; jeton.current++; } };
    window.addEventListener("pl-action-echec", surEchec);
    setMsg(null); onOccupe(true);
    try {
      for (let i = 0; i < s.etapes.length; i++) {
        const e = s.etapes[i];
        setLecture({ id: s.id, nom: s.nom, i: i + 1, n: s.etapes.length });
        const fin = Date.now() + saDuree(e.attente);
        while (Date.now() < fin) { if (!vivant()) break; if (deadRef.current) throw new Error("téléphone déconnecté"); await saSleep(Math.min(150, Math.max(0, fin - Date.now()))); }
        if (!vivant()) break;
        if (deadRef.current) throw new Error("téléphone déconnecté");
        await saExecuter(device, e, vivant);
      }
      if (panne) setMsg({ ok: false, t: "⏹ Arrêté : " + panne });
      else if (vivant()) {
        setMsg({ ok: true, t: "✅ " + s.nom + " terminé" });
        if (window.Backend.logAction) window.Backend.logAction(device.udid, "Script", s.nom, device.tag);
      }
    } catch (err) { setMsg({ ok: false, t: "⏹ Arrêté à l'étape " + ((lectureRef.current && lectureRef.current.i) || "?") + " : " + err.message }); }
    window.removeEventListener("pl-action-echec", surEchec);
    if (jeton.current === moi || panne) { setLecture(null); onOccupe(false); }
  };
  const lectureRef = useRef(null); lectureRef.current = lecture;
  const stop = () => { jeton.current++; setLecture(null); onOccupe(false); setMsg({ ok: false, t: "⏹ Arrêté" }); };
  const lancer = (s) => {
    if (dead || lecture) return;
    if (window.Backend._ecouteAction) { setMsg({ ok: false, t: "Arrête d'abord l'enregistrement en cours." }); return; }
    if ((s.capture || s.depart) && !sansRappel.includes(s.id)) setAConfirmer(s); else jouer(s);
  };
  const confirmer = (neplus) => {
    const s = aConfirmer; setAConfirmer(null);
    if (neplus) { const l = [...sansRappel, s.id]; setSansRappel(l); saEcrire(cleRappel, l); }
    jouer(s);
  };
  const rappeler = (s) => { const l = sansRappel.filter(x => x !== s.id); setSansRappel(l); saEcrire(cleRappel, l); };
  const supprimer = async (s) => { if (window.confirm("Supprimer « " + s.nom + " » pour tous les téléphones de cette famille ?")) { await window.Backend.scriptSupprimer(device.udid, s.id); recharger(); } };

  return (
    <div>
      <div style={{ fontSize: 11.5, fontWeight: 700, color: "var(--muted)", marginBottom: 8 }}>🤖 Automatisations · {SA_FAMILLES[famille]}</div>
      {lecture && <div style={{ background: "rgba(0,224,138,.1)", border: "1px solid rgba(0,224,138,.35)", borderRadius: 12, padding: 12, marginBottom: 12, display: "grid", gap: 8 }}>
        <div style={{ fontSize: 13, fontWeight: 800 }}>{lecture.nom} · étape {lecture.i}/{lecture.n}</div>
        <button type="button" onClick={stop} style={{ ...saBtn, background: "#c8323a", color: "#fff", border: "none", fontWeight: 800, fontSize: 15, padding: 12 }}>⏹ Stop</button>
      </div>}
      <SaBloc id="lancer" titre="Lancer les scripts">
        {edition ? <SaEditeur device={device} dead={dead} initial={edition} onAnnuler={() => setEdition(null)} onSauve={() => { setEdition(null); recharger(); }} /> : <div style={{ display: "grid", gap: 6 }}>
          {scripts === null && <div style={{ fontSize: 12, color: "var(--faint)" }}>Chargement…</div>}
          {scripts && !scripts.length && <div style={{ fontSize: 12, color: "var(--faint)" }}>Aucun script pour ce type de téléphone.</div>}
          {(scripts || []).map(s => (
            <div key={s.id} style={{ display: "flex", alignItems: "center", gap: 8, padding: "7px 8px", borderRadius: 10, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
              <button type="button" title="Lancer" disabled={dead || !!lecture} onClick={() => lancer(s)} style={{ width: 34, height: 34, flex: "none", borderRadius: 99, border: "none", background: "var(--accent)", color: "#06281c", fontSize: 14, cursor: dead || lecture ? "default" : "pointer", opacity: dead || lecture ? .45 : 1 }}>▶</button>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, fontWeight: 700, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }} title={s.nom}>{s.nom}</div>
                <div style={{ fontSize: 10.5, color: "var(--faint)" }}>{s.etapes.length} étape(s)</div>
              </div>
              {sansRappel.includes(s.id) && <button type="button" title="Remettre la confirmation avant de lancer" onClick={() => rappeler(s)} style={{ background: "none", border: "none", cursor: "pointer", fontSize: 13 }}>🔔</button>}
              {peutModifier(s) && <button type="button" title="Renommer ou modifier" onClick={() => setEdition(s)} style={{ background: "none", border: "none", cursor: "pointer", fontSize: 13 }}>✏️</button>}
              {peutModifier(s) && <button type="button" title="Supprimer" onClick={() => supprimer(s)} style={{ background: "none", border: "none", cursor: "pointer", fontSize: 13 }}>🗑</button>}
            </div>
          ))}
        </div>}
        {msg && <div style={{ fontSize: 12, marginTop: 9, color: msg.ok ? "var(--accent)" : "var(--danger, #ff6b6b)" }}>{msg.t}</div>}
      </SaBloc>
      {peutEditer && <SaBloc id="enregistrer" titre="Enregistrer un script">
        <SaEnregistreur device={device} act={act} dead={dead} onOccupe={onOccupe} famille={famille} onCree={recharger} bloque={!!lecture} />
      </SaBloc>}
      {aConfirmer && <SaConfirmer device={device} script={aConfirmer} onAnnuler={() => setAConfirmer(null)} onConfirmer={confirmer} />}
    </div>
  );
}

function ScriptsAutoBouton({ ouvert, occupe, onClick }) {
  return (
    <button type="button" onClick={onClick} title={occupe ? "Script en cours : arrête-le d'abord" : "Automatisations"}
      style={{ marginBottom: 10, display: "inline-flex", alignItems: "center", gap: 5, background: ouvert ? "rgba(0,224,138,.22)" : "rgba(0,224,138,.1)", border: "1px solid rgba(0,224,138,.35)", borderRadius: 9, padding: "7px 12px", fontSize: 15, cursor: occupe ? "not-allowed" : "pointer" }}>
      🤖{occupe && <span style={{ width: 7, height: 7, borderRadius: 99, background: "#ff5a5a" }} />}
    </button>
  );
}

window.ScriptsAutoPanneau = ScriptsAutoPanneau;
window.ScriptsAutoBouton = ScriptsAutoBouton;
