/* global React, Icon, Button, Badge, StatusDot, Avatar, Card, IOSScreen, Logo, STATUS_META, DATA */
// ============================================================
// Opérateur — grille multi-devices
// ============================================================
function OperatorShell({ user, onLogout, onSwitchRole }) {
  const { useState } = React;
  const [device, setDevice] = useState(null);
  const [split, setSplit] = useState(false);
  const inner = split
    ? <SplitPilotage user={user} onClose={() => setSplit(false)} />
    : device
      ? <DeviceView device={device} user={user} onBack={() => setDevice(null)} onLogout={onLogout} />
      : <DeviceGrid user={user} onOpen={setDevice} onLogout={onLogout} onSwitchRole={onSwitchRole} onSplit={() => setSplit(true)} />;
  return (
    <>
      {inner}
      <FloatingChat opId={user.id} as={user.id} />
    </>
  );
}

function TopBar({ user, onLogout, onSwitchRole, children }) {
  const { useState } = React;
  useLang();
  const [menu, setMenu] = useState(false);
  return (
    <header style={{ position: "sticky", top: 0, zIndex: 30, display: "flex", alignItems: "center", gap: 18,
      padding: "13px 24px", background: "color-mix(in srgb, var(--bg) 86%, transparent)", backdropFilter: "blur(14px)",
      borderBottom: "1px solid var(--border)" }}>
      <Logo small />
      <div style={{ flex: 1 }}>{children}</div>
      <LangToggle />
      <OperatorBell user={user} />
      <div style={{ position: "relative" }}>
        <button onClick={() => setMenu(m => !m)} style={{ display: "flex", alignItems: "center", gap: 9, background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 10, padding: "5px 9px 5px 6px" }}>
          <Avatar user={user} size={28} />
          <div style={{ textAlign: "left", lineHeight: 1.2 }}>
            <div style={{ fontSize: 12.5, fontWeight: 600 }}>{user.name.split(" ")[0]}</div>
            <div className="mono" style={{ fontSize: 10, color: "var(--faint)" }}>{user.role}</div>
          </div>
          {React.createElement(Icon.chevDown, { size: 15, color: "var(--faint)" })}
        </button>
        {menu && (
          <>
            <div onClick={() => setMenu(false)} style={{ position: "fixed", inset: 0, zIndex: 40 }} />
            <div style={{ position: "absolute", right: 0, top: "calc(100% + 8px)", zIndex: 41, width: 220, background: "var(--surface)", border: "1px solid var(--border-2)", borderRadius: 12, boxShadow: "var(--shadow-lg)", padding: 7, animation: "appfade .14s ease" }}>
              <div style={{ padding: "9px 11px", borderBottom: "1px solid var(--border)", marginBottom: 6 }}>
                <div style={{ fontSize: 13, fontWeight: 600 }}>{user.name}</div>
                <div className="mono" style={{ fontSize: 11, color: "var(--faint)" }}>{user.email}</div>
              </div>
              <MenuItem icon="settings" label={t("profile_session")} />
              {onSwitchRole && <MenuItem icon="shield" label={t("view_admin")} onClick={() => { setMenu(false); onSwitchRole(); }} />}
              <MenuItem icon="logout" label={t("logout")} danger onClick={onLogout} />
            </div>
          </>
        )}
      </div>
    </header>
  );
}
function MenuItem({ icon, label, onClick, danger }) {
  return (
    <button onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 11, width: "100%", padding: "9px 11px",
      background: "none", border: "none", borderRadius: 8, color: danger ? "var(--danger)" : "var(--text)", fontSize: 13 }}
      onMouseEnter={e => e.currentTarget.style.background = "var(--surface-2)"} onMouseLeave={e => e.currentTarget.style.background = "none"}>
      {React.createElement(Icon[icon], { size: 17, color: danger ? "var(--danger)" : "var(--muted)" })}{label}
    </button>
  );
}

function DeviceGrid({ user, onOpen, onLogout, onSwitchRole, onSplit }) {
  const { useState } = React;
  useLang();
  const splitP = useSplitPerm();
  const farm = useLiveDevices();
  const [q, setQ] = useState("");
  const [filter, setFilter] = useState("all");
  const [pool, setPool] = useState("all");
  const isOp = user.role === "Opérateur";
  // plus de faux téléphones : on n'affiche que les vrais iPhones du backend.
  const isLive = farm.online;
  // un opérateur ne voit que SES iPhones (assignés à lui) ; manager/admin voient tout le parc.
  let devices = (isLive && farm.list) ? farm.list : [];
  if (isOp) devices = devices.filter(d => d.operator && d.operator.id === user.id);

  const pools = ["all", ...new Set(devices.map(d => d.pool))];
  const counts = { all: devices.length };
  ["online", "busy", "locked", "offline"].forEach(s => counts[s] = devices.filter(d => d.status === s).length);

  const shown = devices.filter(d =>
    (filter === "all" || d.status === filter) &&
    (pool === "all" || d.pool === pool) &&
    (d.tag.toLowerCase().includes(q.toLowerCase()) || d.name.toLowerCase().includes(q.toLowerCase())));

  const activeCount = devices.filter(d => d.status === "online" || d.status === "busy").length;

  return (
    <div>
      <TopBar user={user} onLogout={onLogout} onSwitchRole={isOp ? null : onSwitchRole}>
        <div style={{ position: "relative", maxWidth: 360 }}>
          <span style={{ position: "absolute", left: 12, top: "50%", transform: "translateY(-50%)", color: "var(--faint)", display: "grid" }}>{React.createElement(Icon.search, { size: 17 })}</span>
          <input value={q} onChange={e => setQ(e.target.value)} placeholder={t("search_device")} style={{ width: "100%", padding: "9px 12px 9px 38px", background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 9, color: "var(--text)", fontSize: 13, outline: "none" }} />
        </div>
      </TopBar>

      <div style={{ padding: "26px 24px 60px", maxWidth: 1480, margin: "0 auto" }} className="app-fade">
        {!isLive ? <SyncNotice online={false} ready={farm.ready} variant="operator" onSync={async () => { await window.Backend.resolveBackend(); await farm.refresh(); }} /> : <>
        <div style={{ display: "flex", alignItems: "flex-end", justifyContent: "space-between", flexWrap: "wrap", gap: 16, marginBottom: 22 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            <div>
              <h1 style={{ margin: 0, fontSize: 24, fontWeight: 700, letterSpacing: "-.01em", display: "flex", alignItems: "center", gap: 10 }}>{t("my_devices")}
                <Badge tone={isLive ? "green" : "amber"}>{isLive ? t("live_backend") : t("not_synced")}</Badge>
                <button onClick={farm.refresh} title={t("refresh")} style={{ display: "grid", placeItems: "center", width: 30, height: 30, borderRadius: 9, background: "var(--surface-2)", border: "1px solid var(--border)", color: "var(--muted)", cursor: "pointer" }}>{React.createElement(Icon.refresh, { size: 15 })}</button>
              </h1>
              <p style={{ margin: "6px 0 0", color: "var(--muted)", fontSize: 13.5, display: "flex", alignItems: "center", gap: 9 }}>
                <span style={{ display: "inline-flex", alignItems: "center", gap: 6 }}><StatusDot status="online" pulse /> <b className="num" style={{ color: "var(--text)" }}>{activeCount}</b> {t("active")}</span>
                <span style={{ color: "var(--faint)" }}>/ {devices.length} {t("assigned")}</span>
              </p>
            </div>
            {!!user.split_allowed && <button onClick={onSplit} title={t("split_iphone")} style={{ display: "flex", alignItems: "center", gap: 7, background: "var(--surface-2)", border: "1px solid var(--border-2)", borderRadius: 10, padding: "10px 14px", color: "var(--text)", fontSize: 13.5, fontWeight: 600, whiteSpace: "nowrap" }}>{React.createElement(Icon.switcher, { size: 17 })} {t("split_iphone")}</button>}
          </div>
          <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
            <Segmented value={filter} onChange={setFilter} options={[
              ["all", `${t("f_all")} · ${counts.all}`], ["online", `${t("f_online")} · ${counts.online}`],
              ["busy", `${t("f_busy")} · ${counts.busy}`], ["locked", `${t("f_locked")} · ${counts.locked}`], ["offline", `${t("f_off")} · ${counts.offline}`]]} />
            <select value={pool} onChange={e => setPool(e.target.value)} style={selectStyle}>
              {pools.map(p => <option key={p} value={p}>{p === "all" ? t("all_pods") : p}</option>)}
            </select>
          </div>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(var(--card-min, 230px), 1fr))", gap: 18 }}>
          {shown.map(d => <DeviceCard key={d.id} d={d} onOpen={() => onOpen(d)} />)}
        </div>
        {shown.length === 0 && (
          <div style={{ textAlign: "center", padding: "80px 0", color: "var(--faint)" }}>
            {React.createElement(Icon.phone, { size: 34 })}
            <p style={{ marginTop: 12 }}>{devices.length === 0 ? t("none_assigned") : t("none_filter")}</p>
            {devices.length === 0 && <div style={{ marginTop: 14, display: "grid", justifyItems: "center", gap: 10 }}>
              <Button variant="outline" icon="refresh" onClick={farm.refresh}>{t("refresh")}</Button>
              <span className="mono" style={{ fontSize: 11 }}>{t("ask_manager_assign")}</span>
            </div>}
          </div>
        )}
        </>}
      </div>
    </div>
  );
}

function DeviceCard({ d, onOpen }) {
  const meta = STATUS_META[d.status];
  return (
    <div onClick={onOpen} style={{ background: "var(--surface)", border: "1px solid var(--border)", borderRadius: "var(--r-lg)",
      overflow: "hidden", cursor: "pointer", transition: "transform .16s, border-color .16s, box-shadow .16s", opacity: d.status === "offline" ? .72 : 1 }}
      onMouseEnter={e => { e.currentTarget.style.transform = "translateY(-3px)"; e.currentTarget.style.borderColor = "var(--border-2)"; e.currentTarget.style.boxShadow = "var(--shadow)"; }}
      onMouseLeave={e => { e.currentTarget.style.transform = "none"; e.currentTarget.style.borderColor = "var(--border)"; e.currentTarget.style.boxShadow = "none"; }}>
      <div style={{ position: "relative", aspectRatio: "9 / 14", containerType: "inline-size", background: "#0b1020", borderBottom: "1px solid var(--border)" }}>
        {/* aperçu sobre : écran gris flouté + nom du téléphone en gros (l'écran réel s'ouvre au clic) */}
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(165deg, #2b3245 0%, #1c2233 55%, #141927 100%)", display: "grid", placeItems: "center", overflow: "hidden" }}>
          <div style={{ position: "absolute", width: "75%", height: "48%", left: "-18%", top: "-12%", borderRadius: "50%", background: "rgba(120,140,190,.20)", filter: "blur(30px)" }} />
          <div style={{ position: "absolute", width: "65%", height: "42%", right: "-15%", bottom: "-10%", borderRadius: "50%", background: "rgba(90,115,170,.14)", filter: "blur(34px)" }} />
          <div style={{ textAlign: "center", zIndex: 2, padding: "0 12px", maxWidth: "100%" }}>
            <div style={{ fontSize: "clamp(17px, 13cqw, 30px)", fontWeight: 800, letterSpacing: "-.01em", color: "#e9edf6", textShadow: "0 2px 16px rgba(0,0,0,.45)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{d.tag}</div>
            <div className="mono" style={{ marginTop: 7, fontSize: 11, color: "rgba(195,205,225,.5)" }}>{d.status === "online" ? t("click_to_pilot") : meta.label}</div>
          </div>
        </div>
        <div style={{ position: "absolute", top: 9, left: 9, right: 9, display: "flex", justifyContent: "space-between", alignItems: "flex-start", zIndex: 6 }}>
          <Badge tone={d.status === "online" ? "green" : d.status === "busy" ? "amber" : d.status === "locked" ? "gray" : "red"}>
            <StatusDot status={d.status} /> {meta.label}
          </Badge>
        </div>
      </div>
      <div style={{ padding: "13px 14px" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 8 }}>
          <div style={{ fontWeight: 700, fontSize: 14.5 }}>{d.tag}</div>
          <span className="mono" style={{ fontSize: 11, color: "var(--faint)" }}>{d.name}</span>
        </div>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginTop: 10 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 7, minWidth: 0 }}>
            {d.operator ? <><Avatar user={d.operator} size={20} /><span style={{ fontSize: 12, color: "var(--muted)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{d.operator.name.split(" ")[0]}</span></>
              : <span style={{ fontSize: 12, color: "var(--faint)" }}>— libre —</span>}
          </div>
          <span className="mono" style={{ fontSize: 11, color: "var(--faint)" }}>iOS {d.ios}</span>
        </div>
      </div>
    </div>
  );
}

function Segmented({ value, onChange, options }) {
  return (
    <div style={{ display: "inline-flex", background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 9, padding: 3, gap: 2 }}>
      {options.map(([v, l]) => (
        <button key={v} onClick={() => onChange(v)} style={{ padding: "6px 11px", fontSize: 12, fontWeight: 600, borderRadius: 6, border: "none",
          background: value === v ? "var(--surface-3)" : "transparent", color: value === v ? "var(--text)" : "var(--muted)", whiteSpace: "nowrap" }}>{l}</button>
      ))}
    </div>
  );
}
const selectStyle = { padding: "9px 12px", background: "var(--surface-2)", border: "1px solid var(--border)", borderRadius: 9, color: "var(--text)", fontSize: 12.5, outline: "none" };

Object.assign(window, { OperatorShell, TopBar, MenuItem, DeviceGrid, DeviceCard, Segmented, selectStyle });
