/* global React, Icon, Button, Badge, Avatar, Card, Modal, StatusDot, PageHead, DeviceCard, DeviceView, WhatsAppBtn, TelegramBtn, TempMsg, DATA */
// ============================================================
// Enregistrements d'écran (stockés, partageables) + Pilotage admin/manager
// ============================================================
const { useState: useRecState, useEffect: useRecEffect, useReducer: useRecReducer, useRef: useRecRef } = React;

function recCopy(t) {
  try { if (navigator.clipboard && navigator.clipboard.writeText) { const p = navigator.clipboard.writeText(t); if (p && p.catch) p.catch(() => {}); } } catch (e) {}
  try { const ta = document.createElement("textarea"); ta.value = t; ta.style.position = "fixed"; ta.style.top = "-1000px"; ta.style.opacity = "0"; document.body.appendChild(ta); ta.select(); document.execCommand("copy"); document.body.removeChild(ta); } catch (e) {}
}
const fmtDur = (s) => `${String(Math.floor(s / 60)).padStart(2, "0")}:${String(s % 60).padStart(2, "0")}`;
function stampDate() { const d = new Date(); const p = n => String(n).padStart(2, "0"); return `${p(d.getDate())}/${p(d.getMonth() + 1)} ${p(d.getHours())}:${p(d.getMinutes())}`; }

const RecStore = (function () {
  let recs = [];   // vidéos RÉELLES enregistrées dans cet onglet (blob webm, en mémoire)
  const ls = new Set(); const emit = () => ls.forEach(f => f()); let seq = 0;
  return {
    sub(cb) { ls.add(cb); return () => ls.delete(cb); },
    list() { return recs; },
    add(rec) { rec.id = "rec" + (seq++); rec.token = Math.random().toString(36).slice(2, 8); recs = [rec, ...recs]; emit(); return rec; },
    remove(id) { const r = recs.find(x => x.id === id); if (r && r.url) { try { URL.revokeObjectURL(r.url); } catch (e) {} } recs = recs.filter(x => x.id !== id); emit(); },
  };
})();
function useRec() { const [, f] = useRecReducer(x => x + 1, 0); useRecEffect(() => RecStore.sub(f), []); return RecStore; }
const recLink = (r) => `https://rec.tempro-corp.io/r/${r.token}`;
const fmtKo = (n) => n > 1048576 ? (n / 1048576).toFixed(1) + " Mo" : Math.max(1, Math.round(n / 1024)) + " Ko";

// ---- Bouton d'enregistrement (sous le téléphone) — capture RÉELLE du flux live ----
// Dessine les frames live (window.__LIVE_FRAME[udid]) sur un canvas -> MediaRecorder -> webm.
function RecordButton({ device, by, dead }) {
  const [recording, setRecording] = useRecState(false);
  const [paused, setPaused] = useRecState(false);
  const [sec, setSec] = useRecState(0);
  const [share, setShare] = useRecState(null);
  const tick = useRecRef(null);
  const rig = useRecRef(null);   // { recorder, canvas, drawTimer, chunks }

  useRecEffect(() => {
    if (recording && !paused) { tick.current = setInterval(() => setSec(s => s + 1), 1000); }
    else { clearInterval(tick.current); }
    return () => clearInterval(tick.current);
  }, [recording, paused]);
  // sécurité : stop propre si on quitte la vue en plein REC
  useRecEffect(() => () => { const r = rig.current; if (r) { try { r.recorder.stop(); } catch (e) {} clearInterval(r.drawTimer); } }, []);

  const liveRec = !!(device.live && device.udid && window.MediaRecorder);

  const start = () => {
    setSec(0); setPaused(false);
    if (!liveRec) { setRecording(true); return; }   // device démo : timer seul
    try {
      const canvas = document.createElement("canvas");
      const ctx = canvas.getContext("2d");
      let sized = false;
      const draw = () => {
        // dessine directement l'<img> du FLUX live (déjà en train de décoder le MJPEG)
        const im = (window.__LIVE_IMG || {})[device.udid];
        if (!im || !im.naturalWidth) return;
        if (!sized) { canvas.width = im.naturalWidth; canvas.height = im.naturalHeight; sized = true; }
        try { ctx.drawImage(im, 0, 0, canvas.width, canvas.height); } catch (e) {}
      };
      draw();
      const drawTimer = setInterval(draw, 100);     // ~10 fps d'enregistrement
      const stream = canvas.captureStream(8);
      const mime = MediaRecorder.isTypeSupported("video/webm;codecs=vp9") ? "video/webm;codecs=vp9" : "video/webm";
      const recorder = new MediaRecorder(stream, { mimeType: mime, videoBitsPerSecond: 1200000 });
      const chunks = [];
      recorder.ondataavailable = (e) => { if (e.data && e.data.size) chunks.push(e.data); };
      recorder.start(1000);
      rig.current = { recorder, canvas, drawTimer, chunks };
      setRecording(true);
    } catch (e) {
      rig.current = null; setRecording(true);       // fallback : timer seul
    }
  };

  const togglePause = () => {
    const r = rig.current;
    setPaused(p => {
      const next = !p;
      if (r) { try { next ? r.recorder.pause() : r.recorder.resume(); } catch (e) {} }
      return next;
    });
  };

  const stop = () => {
    setRecording(false); setPaused(false);
    const dur = sec || 1; setSec(0);
    const meta = { deviceTag: device.tag, byName: by.name, at: stampDate(), duration: dur, note: "" };
    const r = rig.current;
    if (r) {
      clearInterval(r.drawTimer);
      r.recorder.onstop = () => {
        const blob = new Blob(r.chunks, { type: "video/webm" });
        rig.current = null;
        const rec = RecStore.add({ ...meta, url: blob.size ? URL.createObjectURL(blob) : null, size: blob.size });
        setShare(rec);
      };
      try { r.recorder.stop(); } catch (e) { rig.current = null; setShare(RecStore.add(meta)); }
    } else {
      setShare(RecStore.add(meta));
    }
  };

  if (recording) {
    return (
      <div style={{ display: "grid", gap: 9 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "10px 13px", borderRadius: 12,
          background: "rgba(255,92,108,.12)", border: "1px solid rgba(255,92,108,.35)" }}>
          <span style={{ width: 11, height: 11, borderRadius: 3, background: paused ? "var(--busy)" : "var(--danger)", animation: paused ? "none" : "streamPulse 1s infinite", flex: "none" }} />
          <span style={{ fontSize: 13.5, fontWeight: 700, color: paused ? "var(--busy)" : "var(--danger)" }}>{paused ? "PAUSE" : "REC"}</span>
          <span className="num" style={{ fontSize: 13.5, fontWeight: 700, color: "var(--text)" }}>{fmtDur(sec)}</span>
          {rig.current && <span style={{ marginLeft: "auto", fontSize: 10.5, color: "var(--accent)", fontFamily: "var(--mono)" }}>● vidéo réelle</span>}
        </div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
          <RecCtl icon={paused ? "play" : "clock"} label={paused ? "Reprendre" : "Pause"} active={paused} onClick={togglePause} tone="amber" />
          <RecCtl icon="x" label="Arrêter" onClick={stop} tone="danger" />
        </div>
      </div>
    );
  }
  return (
    <>
      <button onClick={() => !dead && start()} disabled={dead} style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 9, width: "100%", padding: "12px", borderRadius: 12,
        background: "var(--surface-2)", border: "1px solid var(--border-2)", color: "var(--text)", fontSize: 13.5, fontWeight: 600, opacity: dead ? .45 : 1 }}>
        <span style={{ width: 11, height: 11, borderRadius: 99, background: "var(--danger)" }} /> {window.t ? t("record_screen") : "Enregistrer l'écran"}
      </button>
      {share && <ShareRecModal rec={share} onClose={() => setShare(null)} />}
    </>
  );
}

// ---- Lecteur d'un enregistrement ----
function PlayRecModal({ rec, onClose }) {
  return (
    <Modal title={`${rec.deviceTag} · ${fmtDur(rec.duration)} — par ${rec.byName}`} onClose={onClose} width={560}
      footer={<>
        {rec.url && <a href={rec.url} download={`rec-${rec.deviceTag}-${rec.token}.webm`} style={{ textDecoration: "none" }}><Button variant="outline" icon="download">Télécharger</Button></a>}
        <Button variant="primary" icon="check" onClick={onClose}>Fermer</Button>
      </>}>
      {rec.url
        ? <video src={rec.url} controls autoPlay style={{ width: "100%", maxHeight: "60vh", borderRadius: 12, background: "#000" }} />
        : <div style={{ padding: "30px 0", textAlign: "center", color: "var(--faint)", fontSize: 13 }}>Pas de vidéo pour cet enregistrement (flux indisponible pendant le REC).</div>}
    </Modal>
  );
}

function RecCtl({ icon, label, active, onClick, tone }) {
  const c = tone === "danger" ? "var(--danger)" : tone === "amber" ? "var(--busy)" : "var(--accent)";
  return (
    <button onClick={onClick} style={{ display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", gap: 5, padding: "9px 4px", borderRadius: 10,
      background: active ? "color-mix(in srgb," + c + " 16%, transparent)" : "var(--surface-2)", border: "1px solid " + (active ? c : "var(--border)"), color: active ? c : "var(--text)", fontSize: 11, fontWeight: 600 }}>
      {React.createElement(Icon[icon], { size: 17 })}{label}
    </button>
  );
}

// ---- Modal de partage d'un enregistrement ----
function ShareRecModal({ rec, onClose }) {
  const [copied, setCopied] = useRecState(false);
  const [sentTo, setSentTo] = useRecState([]);
  const link = recLink(rec);
  const team = DATA.realTeam().filter(o => o.role !== "Admin");
  const sendTo = (o) => { TempMsg.send(o.id, "admin", `📹 Tuto vidéo (${fmtDur(rec.duration)}) — regarde comment piloter : ${link}`); setSentTo(s => [...s, o.id]); };

  return (
    <Modal title="Partager l'enregistrement" onClose={onClose} width={500}
      footer={<Button variant="primary" icon="check" onClick={onClose}>Terminé</Button>}>
      <div style={{ display: "grid", gap: 16 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "12px 14px", borderRadius: 11, background: "var(--surface-2)", border: "1px solid var(--border)" }}>
          <span style={{ width: 44, height: 44, borderRadius: 10, background: "rgba(255,92,108,.14)", color: "var(--danger)", display: "grid", placeItems: "center", flex: "none" }}>{React.createElement(Icon.play, { size: 20 })}</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 13.5, fontWeight: 700 }}>{rec.deviceTag} · {fmtDur(rec.duration)}</div>
            <div className="mono" style={{ fontSize: 11, color: "var(--faint)", marginTop: 2 }}>par {rec.byName} · {rec.at}</div>
          </div>
          <Badge tone="green">enregistré ✓</Badge>
        </div>

        <div>
          <label style={recLab}>Lien de partage</label>
          <div style={{ display: "flex", gap: 9, marginTop: 7 }}>
            <input readOnly value={link} onFocus={e => e.target.select()} style={{ ...recFld, fontFamily: "var(--mono)", fontSize: 12 }} />
            <Button variant={copied ? "primary" : "outline"} icon={copied ? "check" : "copy"} onClick={() => { recCopy(link); setCopied(true); setTimeout(() => setCopied(false), 1400); }}>{copied ? "Copié" : "Copier"}</Button>
          </div>
          <div className="mono" style={{ fontSize: 11, color: "var(--faint)", marginTop: 7 }}>n'importe qui avec le lien peut regarder la vidéo.</div>
        </div>

        <div>
          <label style={recLab}>Envoyer à un membre <span className="mono" style={{ color: "var(--faint)", fontWeight: 400 }}>· message in-app avec le lien</span></label>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 8, marginTop: 9 }}>
            {team.map(o => {
              const sent = sentTo.includes(o.id);
              return (
                <button key={o.id} onClick={() => !sent && sendTo(o)} style={{ display: "flex", alignItems: "center", gap: 9, padding: "9px 11px", borderRadius: 10, textAlign: "left",
                  background: sent ? "var(--accent-soft)" : "var(--surface-2)", border: "1px solid " + (sent ? "var(--accent-line)" : "var(--border)") }}>
                  <Avatar user={o} size={26} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600 }}>{o.name.split(" ")[0]}</div>
                    <div className="mono" style={{ fontSize: 10, color: "var(--faint)" }}>{o.role}</div>
                  </div>
                  {sent ? <span style={{ color: "var(--accent)", display: "grid" }}>{React.createElement(Icon.check, { size: 16 })}</span> : React.createElement(Icon.send, { size: 14, color: "var(--faint)" })}
                </button>
              );
            })}
          </div>
        </div>
      </div>
    </Modal>
  );
}
const recLab = { fontSize: 12.5, fontWeight: 600, color: "var(--muted)" };
const recFld = { flex: 1, width: "100%", padding: "11px 13px", background: "var(--bg-2)", border: "1px solid var(--border-2)", borderRadius: 9, color: "var(--text)", fontSize: 13.5, outline: "none" };

// ---- Section stockage des enregistrements (panel admin) ----
function RecordingsStore() {
  const store = useRec();
  const [share, setShare] = useRecState(null);
  const [play, setPlay] = useRecState(null);
  const recs = store.list();
  return (
    <Card pad={20} style={{ marginTop: 8 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 4 }}>
        {React.createElement(Icon.play, { size: 17, color: "var(--danger)" })}
        <div style={{ fontSize: 15, fontWeight: 700 }}>Enregistrements d'écran</div>
        <Badge tone="neutral"><span className="num">{recs.length}</span></Badge>
      </div>
      <p style={{ margin: "0 0 16px", fontSize: 12.5, color: "var(--muted)" }}>Clique sur un enregistrement pour le regarder, le télécharger ou l'envoyer à un membre. <span className="mono" style={{ color: "var(--faint)" }}>(vidéos gardées dans cet onglet — télécharge pour conserver)</span></p>
      <div style={{ display: "grid", gap: 9 }}>
        {recs.length === 0 && <div style={{ color: "var(--faint)", fontSize: 13 }}>Aucun enregistrement pour l'instant. Lance un REC depuis le pilotage d'un iPhone.</div>}
        {recs.map(r => (
          <div key={r.id} onClick={() => setPlay(r)} style={{ display: "flex", alignItems: "center", gap: 13, padding: "11px 13px", borderRadius: 11, background: "var(--surface-2)", border: "1px solid var(--border)", cursor: "pointer" }}
            onMouseEnter={e => e.currentTarget.style.borderColor = "var(--border-2)"} onMouseLeave={e => e.currentTarget.style.borderColor = "var(--border)"}>
            <span style={{ width: 56, height: 38, borderRadius: 8, background: "linear-gradient(135deg,#1b2a4a,#221a3a)", display: "grid", placeItems: "center", color: "#fff", flex: "none", position: "relative" }}>
              {React.createElement(Icon.play, { size: 16 })}
              <span className="num" style={{ position: "absolute", bottom: 2, right: 3, fontSize: 8.5, background: "rgba(0,0,0,.5)", padding: "0 3px", borderRadius: 3 }}>{fmtDur(r.duration)}</span>
            </span>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600 }}>{r.note || `Pilotage ${r.deviceTag}`}</div>
              <div className="mono" style={{ fontSize: 10.5, color: "var(--faint)", marginTop: 2 }}>{r.deviceTag} · {r.byName} · {r.at}{r.size ? ` · ${fmtKo(r.size)}` : ""}</div>
            </div>
            {r.url && <a href={r.url} download={`rec-${r.deviceTag}-${r.token}.webm`} onClick={e => e.stopPropagation()} title="Télécharger" style={{ ...recIconBtn, display: "grid", textDecoration: "none" }}>{React.createElement(Icon.download, { size: 15 })}</a>}
            <button onClick={e => { e.stopPropagation(); setShare(r); }} title="Partager / envoyer" style={recIconBtn}>{React.createElement(Icon.send, { size: 15 })}</button>
            <button onClick={e => { e.stopPropagation(); store.remove(r.id); }} title="Supprimer" style={{ ...recIconBtn, color: "var(--danger)" }}>{React.createElement(Icon.x, { size: 15 })}</button>
          </div>
        ))}
      </div>
      {share && <ShareRecModal rec={share} onClose={() => setShare(null)} />}
      {play && <PlayRecModal rec={play} onClose={() => setPlay(null)} />}
    </Card>
  );
}
const recIconBtn = { display: "grid", placeItems: "center", width: 32, height: 32, borderRadius: 8, background: "var(--surface)", border: "1px solid var(--border)", color: "var(--muted)", flex: "none" };

// ---- Page Pilotage iPhone (owner + manager) ----
function AdminPilotage({ user }) {
  const [device, setDevice] = useRecState(null);
  const [q, setQ] = useRecState("");
  const [split, setSplit] = useRecState(false);
  const farm = useLiveDevices();
  if (split) return <SplitPilotage user={user} onClose={() => setSplit(false)} />;
  if (device) return <DeviceView device={device} user={user} admin onBack={() => setDevice(null)} />;

  const isLive = farm.online;
  const all = (isLive && farm.list) ? farm.list : [];
  const devices = all.filter(d => d.tag.toLowerCase().includes(q.toLowerCase()) || (d.name || "").toLowerCase().includes(q.toLowerCase()));
  const online = all.filter(d => d.status === "online" || d.status === "busy").length;

  return (
    <div>
      <PageHead title="Pilotage iPhone" sub={isLive ? `prenez la main sur n'importe quel iPhone du parc · ${online} en ligne` : "parc non synchronisé"}>
        {isLive && <>
          <div style={{ position: "relative" }}>
            <span style={{ position: "absolute", left: 11, top: "50%", transform: "translateY(-50%)", color: "var(--faint)", display: "grid" }}>{React.createElement(Icon.search, { size: 16 })}</span>
            <input value={q} onChange={e => setQ(e.target.value)} placeholder="Rechercher un iPhone…" style={{ padding: "9px 12px 9px 34px", background: "var(--surface)", border: "1px solid var(--border)", borderRadius: 9, color: "var(--text)", fontSize: 13, outline: "none", width: 240 }} />
          </div>
          <Button variant="outline" icon="switcher" onClick={() => setSplit(true)}>Split iPhone</Button>
        </>}
      </PageHead>

      {!isLive
        ? <SyncNotice online={false} ready={farm.ready} variant="admin" onSync={farm.refresh} />
        : devices.length === 0
          ? <div style={{ textAlign: "center", padding: "70px 0", color: "var(--faint)" }}>{React.createElement(Icon.phone, { size: 32 })}<p style={{ marginTop: 12 }}>Aucun iPhone détecté — branche et déverrouille un iPhone.</p></div>
          : <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(210px, 1fr))", gap: 16, marginBottom: 26 }}>
              {devices.map(d => <DeviceCard key={d.id} d={d} onOpen={() => setDevice(d)} />)}
            </div>}

      <RecordingsStore />
    </div>
  );
}

// ---- Split : piloter jusqu'à 2 iPhones côte à côte ----
function SplitPilotage({ user, onClose }) {
  const farm = useLiveDevices();
  const all = (farm.online && farm.list) ? farm.list : [];
  // un opérateur ne split QUE ses iPhones assignés ; manager/owner = tout le parc
  const devices = (user && user.role === "Opérateur")
    ? all.filter(d => d.operator && d.operator.id === user.id)
    : all;
  const online = devices.filter(d => d.status === "online" || d.status === "busy");
  const [picking, setPicking] = useRecState(true);
  const [slots, setSlots] = useRecState([online[0]?.id, online[1]?.id]);

  if (!farm.online) return (
    <div style={{ paddingBottom: 40 }}>
      <div style={{ padding: "14px 14px 0" }}><PageHead title="Split iPhone" sub="parc non synchronisé"><Button variant="outline" icon="back" onClick={onClose}>Retour</Button></PageHead></div>
      <SyncNotice online={false} ready={farm.ready} variant="admin" onSync={farm.refresh} />
    </div>
  );

  if (picking) return <SplitPicker initial={slots} devices={devices} onCancel={onClose} onConfirm={(ids) => { setSlots(ids); setPicking(false); }} />;

  return (
    <div style={{ paddingBottom: 40 }}>
      <div style={{ position: "sticky", top: 0, zIndex: 20, background: "color-mix(in srgb, var(--bg) 90%, transparent)", backdropFilter: "blur(14px)", borderBottom: "1px solid var(--border)", padding: "14px 14px 0" }}>
        <PageHead title="Split iPhone" sub="2 iPhones en parallèle · contrôles compacts">
          <Button variant="outline" icon="switcher" onClick={() => setPicking(true)}>Changer les iPhones</Button>
          <Button variant="outline" icon="back" onClick={onClose}>Quitter le split</Button>
        </PageHead>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, padding: "14px 14px 0", alignItems: "start" }} className="ov-grid">
        {slots.map((id, i) => <SplitSlot key={i} deviceId={id} devices={devices} user={user} onPick={(v) => setSlots(s => s.map((x, j) => j === i ? v : x))} />)}
      </div>
    </div>
  );
}

function SplitPicker({ initial, devices, onCancel, onConfirm }) {
  const list = devices || [];   // uniquement les iPhones réels fournis (assignés pour un opérateur)
  const [picked, setPicked] = useRecState((initial || []).filter(Boolean).slice(0, 2));
  const toggle = (id) => setPicked(p => p.includes(id) ? p.filter(x => x !== id) : (p.length >= 2 ? [p[1], id] : [...p, id]));
  return (
    <Modal title="Choisir 2 iPhones à piloter" onClose={onCancel} width={560}
      footer={<><Button variant="ghost" onClick={onCancel}>Annuler</Button>
        <Button variant="primary" icon="switcher" disabled={picked.length !== 2} onClick={() => onConfirm(picked)}>Lancer le split ({picked.length}/2)</Button></>}>
      {list.length < 2 && <div style={{ color: "var(--faint)", fontSize: 13, textAlign: "center", padding: "16px 0 6px" }}>Il faut au moins 2 iPhones assignés pour utiliser le split.</div>}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(2,1fr)", gap: 8, maxHeight: 360, overflow: "auto", paddingRight: 2 }}>
        {list.map(d => {
          const on = picked.includes(d.id);
          const idx = picked.indexOf(d.id);
          return (
            <button key={d.id} onClick={() => toggle(d.id)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: 10, textAlign: "left",
              background: on ? "var(--accent-soft)" : "var(--surface-2)", border: "1px solid " + (on ? "var(--accent-line)" : "var(--border)") }}>
              <StatusDot status={d.status} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{d.tag}</div>
                <div className="mono" style={{ fontSize: 10, color: "var(--faint)" }}>{d.name} · {d.model}</div>
              </div>
              {on && <span className="num" style={{ width: 20, height: 20, borderRadius: 99, background: "var(--accent)", color: "#06281c", fontSize: 11, fontWeight: 700, display: "grid", placeItems: "center" }}>{idx + 1}</span>}
            </button>
          );
        })}
      </div>
    </Modal>
  );
}

function SBtn({ ic, label, onAct, dead, center, wide }) {
  return (
    <button disabled={dead && ic !== "refresh"} onClick={onAct} title={label} style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 5,
      height: wide ? 32 : undefined, aspectRatio: wide ? undefined : "1", borderRadius: 8,
      background: center ? "var(--surface-3)" : "var(--surface-2)", color: center ? "var(--accent)" : "var(--text)",
      border: "1px solid " + (center ? "var(--accent-line)" : "var(--border)"), opacity: (dead && ic !== "refresh") ? .4 : 1, fontSize: 10.5, fontWeight: 600 }}>
      {React.createElement(Icon[ic], { size: 15 })}{wide && label}
    </button>
  );
}

function SplitSlot({ deviceId, devices, onPick, user }) {
  const list = devices || [];
  const device = list.find(d => d.id === deviceId) || list[0];
  if (!device) return <Card pad={10}><div style={{ color: "var(--faint)", fontSize: 12.5, textAlign: "center", padding: "20px 0" }}>Aucun iPhone disponible.</div></Card>;
  return (
    <Card pad={10}>
      <div style={{ display: "flex", alignItems: "center", gap: 9, marginBottom: 12 }}>
        <StatusDot status={device.status} pulse />
        <select value={device.id} onChange={e => onPick(e.target.value)} style={{ flex: 1, padding: "7px 10px", background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 9, color: "var(--text)", fontSize: 12.5, fontWeight: 600, outline: "none" }}>
          {list.map(d => <option key={d.id} value={d.id}>{d.tag} · {d.name}</option>)}
        </select>
        <span className="mono" style={{ fontSize: 10.5, color: "var(--faint)" }}>{device.battery}%</span>
      </div>
      <DeviceView device={device} user={user} admin embedded />
    </Card>
  );
}
function splitNow() { const d = new Date(); return [d.getHours(), d.getMinutes(), d.getSeconds()].map(n => String(n).padStart(2, "0")).join(":"); }

// store : autorisation d'utiliser le Split iPhone, par opérateur
const SplitPerm = (function () {
  const map = { u3: false, u4: true, u7: false };
  try { const s = JSON.parse(localStorage.getItem("tampro.splitperm") || "null"); if (s) Object.assign(map, s); } catch (e) {}
  const ls = new Set();
  return { sub(cb) { ls.add(cb); return () => ls.delete(cb); }, can(id) { return !!map[id]; }, set(id, v) { map[id] = !!v; try { localStorage.setItem("tampro.splitperm", JSON.stringify(map)); } catch (e) {} ls.forEach(f => f()); } };
})();
function useSplitPerm() { const [, f] = useRecReducer(x => x + 1, 0); useRecEffect(() => SplitPerm.sub(f), []); return SplitPerm; }

Object.assign(window, { RecStore, useRec, RecordButton, ShareRecModal, RecordingsStore, AdminPilotage, SplitPilotage, SplitPerm, useSplitPerm });
