/* ============================================================
   DEVICE POPUPS — valve (EV) / motor / instrument faceplates
   ============================================================ */

function Field({ label, children }) {
  return <div className="pcell"><div className="pl">{label}</div><div className="pv">{children}</div></div>;
}
function LimRow({ label, v, unit, on, kind }) {
  return (
    <div className="ir" style={on ? { background: "rgba(211,58,44,.10)" } : null}>
      <span className={"di " + (on ? "no" : "ok")} style={kind === "warn" && on ? { background: "var(--status-warn)" } : null}></span>
      <span className="nm">{label}</span>
      <span className={"st " + (on ? "no" : "ok")}>{v == null ? "—" : v + " " + unit}</span>
    </div>
  );
}

/* interlock synthesis ---------------------------------------- */
function interlocksFor(d, t) {
  const air = window.devById("70PT01"); const airOk = air ? air.v > 5.5 : true;
  const list = [];
  if (d.kind === "valve") {
    list.push({ nm: t("pilot_air") + " ≥ 5.5 bar", ok: d.sub === "ev" ? airOk : true });
    list.push({ nm: "ESD / Emergency stop", ok: true });
    list.push({ nm: t("valve_perm"), ok: !d.fault });
  } else if (d.kind === "motor") {
    list.push({ nm: t("thermal") + " OK", ok: !d.fault });
    list.push({ nm: "ESD / Emergency stop", ok: true });
    list.push({ nm: t("vfd") + " " + (d.hasVfd ? "ready" : "—"), ok: true });
    if (d.sub === "pump") list.push({ nm: t("valve") + " " + t("st_open"), ok: true });
  }
  return list;
}

/* ===== VALVE FACEPLATE ====================================== */
function ValveFace({ d, t, force }) {
  const ints = interlocksFor(d, t);
  const blocked = ints.some(i => !i.ok);
  const stClass = d.fault ? "alarm" : d.travelling ? "warn" : d.open ? "run" : "idle";
  const stLbl = d.fault ? t("st_fault") : d.travelling ? t("st_travelling") : d.open ? t("st_open") : t("st_closed");
  const cmd = (open) => { if (d.mode !== "man" || blocked) return; d.open = open; window.toastMsg(t("cmd_sent") + " · " + (open ? t("open") : t("close"))); force(); };
  const air = window.devById("70PT01");
  return (
    <>
      <div className={"statebox " + stClass}>
        <div style={{ flex: 1 }}>
          <div className="eyebrow" style={{ marginBottom: 4 }}>{t("status")}</div>
          <div className="big">{stLbl}</div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div className="eyebrow" style={{ marginBottom: 4 }}>{t("position")}</div>
          <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: "#fff" }}>{Math.round(d.pos)}<span style={{ fontSize: 12, color: "var(--hud-text-3)" }}>%</span></div>
        </div>
      </div>

      {/* position bar */}
      <div style={{ height: 10, borderRadius: 5, background: "#13284a", border: "1px solid var(--hud-line)", overflow: "hidden", marginBottom: 14 }}>
        <div style={{ height: "100%", width: d.pos + "%", background: d.open ? "var(--status-run)" : "var(--navy-400)", transition: "width .3s" }}></div>
      </div>

      <div className="subhead">{t("mode")} & {t("commands")}</div>
      <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 12 }}>
        <div className="modetog">
          <button className={d.mode === "auto" ? "on auto" : ""} onClick={() => { d.mode = "auto"; window.toastMsg(t("mode_changed") + " · " + t("auto")); force(); }}>{t("auto")}</button>
          <button className={d.mode === "man" ? "on man" : ""} onClick={() => { d.mode = "man"; window.toastMsg(t("mode_changed") + " · " + t("manual")); force(); }}>{t("manual")}</button>
        </div>
        <div style={{ flex: 1 }}></div>
        <button className="btn btn-run btn-sm" disabled={d.mode !== "man" || d.open || blocked} onClick={() => cmd(true)}><Icon n="unlock" size={14} />{t("open")}</button>
        <button className="btn btn-stop btn-sm" disabled={d.mode !== "man" || !d.open || blocked} onClick={() => cmd(false)}><Icon n="lock" size={14} />{t("close")}</button>
      </div>
      <div style={{ fontSize: 11.5, color: blocked ? "#f08478" : "var(--hud-text-3)", marginBottom: 14, display: "flex", alignItems: "center", gap: 6 }}>
        <Icon n={blocked ? "alert" : "checkc"} size={13} />{blocked ? t("interlock_block") : (d.mode === "auto" ? t("auto") + " — " + t("no_interlock_block") : t("no_interlock_block"))}
      </div>

      <div className="subhead">{t("parameters")}</div>
      <div className="pgrid" style={{ marginBottom: 14 }}>
        <Field label={t("valve_open_fb")}>{d.pos > 98 ? <span style={{ color: "#5fd99a" }}>● 1</span> : <span style={{ color: "var(--hud-text-3)" }}>○ 0</span>}</Field>
        <Field label={t("valve_close_fb")}>{d.pos < 2 ? <span style={{ color: "#5fd99a" }}>● 1</span> : <span style={{ color: "var(--hud-text-3)" }}>○ 0</span>}</Field>
        <Field label={t("pilot_air")}>{air ? fmtNum(air.v, 2) : "—"}<span className="u">bar</span></Field>
        <Field label={t("valve_travel")}>{d.travel.toFixed(1)}<span className="u">s</span></Field>
        <Field label={t("actuator")}>{d.sub === "ev" ? t("ev_valve") : t("motor_valve")}</Field>
        <Field label={t("last_cmd")}>{d.open ? t("cmd_open") : t("cmd_close")}</Field>
      </div>

      <div className="subhead">{t("interlocks")}</div>
      <div className="ilist">
        {ints.map((i, k) => <div className="ir" key={k}><span className={"di " + (i.ok ? "ok" : "no")}></span><span className="nm">{i.nm}</span><span className={"st " + (i.ok ? "ok" : "no")}>{i.ok ? "OK" : t("interlock_block")}</span></div>)}
      </div>
    </>
  );
}

/* ===== MOTOR FACEPLATE ====================================== */
function MotorFace({ d, t, force }) {
  const ints = interlocksFor(d, t);
  const blocked = ints.some(i => !i.ok);
  const stClass = d.fault ? "alarm" : d.running ? "run" : "idle";
  const stLbl = d.fault ? t("st_fault") : d.running ? t("st_running") : t("st_stopped");
  const cmd = (run) => { if (d.mode !== "man" || (run && blocked)) return; d.running = run; if (run) d.starts = (d.starts || 0) + 1; window.toastMsg(t("cmd_sent") + " · " + (run ? t("start") : t("stop"))); force(); };
  const setHz = (e) => { d.hzBase = +e.target.value; d.hz = +e.target.value; force(); };
  const genPower = d.isGenset ? (d.powerKw != null ? d.powerKw : (window.devById("50JT01") || {}).v || 0) : 0;
  const loadPct = d.isGenset ? (d.loadPct || 0) : Math.round((d.A / (d.kW * 2)) * 100);
  return (
    <>
      <div className={"statebox " + stClass}>
        <div style={{ flex: 1 }}>
          <div className="eyebrow" style={{ marginBottom: 4 }}>{t("status")}</div>
          <div className="big">{stLbl}</div>
        </div>
        <div style={{ textAlign: "right" }}>
          <div className="eyebrow" style={{ marginBottom: 4 }}>{d.isGenset ? t("el_power") : t("plant_load")}</div>
          <div className="mono" style={{ fontSize: 22, fontWeight: 700, color: "#fff" }}>
            {d.isGenset ? fmtNum(genPower, 0) : loadPct}<span style={{ fontSize: 12, color: "var(--hud-text-3)" }}>{d.isGenset ? " kW" : "%"}</span>
          </div>
        </div>
      </div>

      <div className="subhead">{t("mode")} & {t("commands")}</div>
      <div style={{ display: "flex", gap: 10, alignItems: "center", marginBottom: 14 }}>
        <div className="modetog">
          <button className={d.mode === "auto" ? "on auto" : ""} onClick={() => { d.mode = "auto"; window.toastMsg(t("mode_changed") + " · " + t("auto")); force(); }}>{t("auto")}</button>
          <button className={d.mode === "man" ? "on man" : ""} onClick={() => { d.mode = "man"; window.toastMsg(t("mode_changed") + " · " + t("manual")); force(); }}>{t("manual")}</button>
        </div>
        <div style={{ flex: 1 }}></div>
        <button className="btn btn-run btn-sm" disabled={d.mode !== "man" || d.running || blocked} onClick={() => cmd(true)}><Icon n="play" size={14} />{t("start")}</button>
        <button className="btn btn-stop btn-sm" disabled={d.mode !== "man" || !d.running} onClick={() => cmd(false)}><Icon n="stop" size={14} />{t("stop")}</button>
      </div>

      <div className="subhead">{t("parameters")}</div>
      <div className="pgrid three" style={{ marginBottom: 12 }}>
        {!d.isGenset && <Field label={t("current")}>{fmtNum(d.A, 1)}<span className="u">A</span></Field>}
        <Field label={t("power")}>{d.isGenset ? fmtNum(genPower, 0) : fmtNum(d.A * 0.4 * 1.73 * 0.85 / 1000 * 1000, 1)}<span className="u">kW</span></Field>
        <Field label={t("speed")}>{d.running ? fmtNum(d.rpm + (d.hasVfd ? (d.hz - 50) * 29 : 0), 0) : 0}<span className="u">rpm</span></Field>
        {d.hasVfd && <Field label={t("frequency")}>{d.running ? fmtNum(d.hz, 1) : "0.0"}<span className="u">Hz</span></Field>}
        <Field label={t("temp_winding")}><span className={d.tWind > 85 ? "pv wrn" : ""}>{fmtNum(d.tWind, 1)}</span><span className="u">°C</span></Field>
        <Field label={t("temp_bearing")}>{fmtNum(d.tBear, 1)}<span className="u">°C</span></Field>
        <Field label={t("vibration")}>{fmtNum(d.vib, 1)}<span className="u">mm/s</span></Field>
        <Field label={t("runtime")}>{fmtNum(d.runH, 0)}<span className="u">h</span></Field>
        <Field label={t("starts_today")}>{d.starts}</Field>
      </div>

      {d.hasVfd && (
        <div style={{ marginBottom: 14 }}>
          <div className="subhead">{t("vfd")} — {t("setpoint")}</div>
          <div className="sp-row">
            <input type="range" className="sp" min="20" max="50" step="0.5" value={d.hzBase || d.hz || 50} onChange={setHz} disabled={!d.running} />
            <span className="mono" style={{ minWidth: 64, textAlign: "right", color: "#fff", fontWeight: 600 }}>{fmtNum(d.hzBase || d.hz || 50, 1)} Hz</span>
          </div>
        </div>
      )}

      <div className="subhead">{t("current")} — {t("trend")}</div>
      <div style={{ background: "#0a1830", border: "1px solid var(--hud-line)", borderRadius: 6, padding: "8px 4px 2px", marginBottom: 14 }}>
        <Sparkline id={d.id} w={494} h={48} color="#3D8BE0" />
      </div>

      <div className="subhead">{t("interlocks")}</div>
      <div className="ilist">
        {ints.map((i, k) => <div className="ir" key={k}><span className={"di " + (i.ok ? "ok" : "no")}></span><span className="nm">{i.nm}</span><span className={"st " + (i.ok ? "ok" : "no")}>{i.ok ? "OK" : "—"}</span></div>)}
      </div>
    </>
  );
}

/* ===== INSTRUMENT FACEPLATE ================================= */
function InstrumentFace({ d, t }) {
  const q = window.qualOf(d);
  const L = d.lim || {};
  const stClass = q === "alarm" ? "alarm" : q === "warn" ? "warn" : "run";
  const stLbl = q === "alarm" ? t("st_alarm") : q === "warn" ? t("st_warn") : t("st_ok");
  const raw = 4 + ((d.v - d.range[0]) / (d.range[1] - d.range[0])) * 16; // 4-20mA
  return (
    <>
      <div className={"statebox " + stClass}>
        <div style={{ flex: 1 }}>
          <div className="eyebrow" style={{ marginBottom: 4 }}>{t("measure")}</div>
          <div className="mono" style={{ fontSize: 30, fontWeight: 700, color: "#fff", lineHeight: 1 }}>{fmtNum(d.v, d.fmt)}<span style={{ fontSize: 14, color: "var(--hud-text-3)", marginLeft: 5 }}>{d.unit}</span></div>
        </div>
        <StatusChip kind={stClass === "run" ? "run" : stClass} label={stLbl} />
      </div>

      <div className="subhead">{t("trend")} · {t("last_h")}</div>
      <div style={{ background: "#0a1830", border: "1px solid var(--hud-line)", borderRadius: 6, padding: "8px 4px 2px", marginBottom: 14 }}>
        <Sparkline id={d.id} w={494} h={70} color={q === "alarm" ? "#f08478" : q === "warn" ? "#f3c45a" : "#3D8BE0"} />
      </div>

      <div className="subhead">{t("parameters")}</div>
      <div className="pgrid three" style={{ marginBottom: 14 }}>
        <Field label={t("range")}>{d.range[0]}–{d.range[1]}<span className="u">{d.unit}</span></Field>
        <Field label={t("raw")}>{fmtNum(raw, 2)}<span className="u">mA</span></Field>
        <Field label={t("signal")}>4–20 mA</Field>
      </div>

      <div className="subhead">{t("range")} — {t("interlocks")}</div>
      <div className="ilist" style={{ marginBottom: 14 }}>
        <LimRow label={t("hi_hi") + " (HH)"} v={L.HH} unit={d.unit} on={L.HH != null && d.v >= L.HH} />
        <LimRow label={t("hi") + " (H)"} v={L.H} unit={d.unit} on={L.H != null && d.v >= L.H} kind="warn" />
        <LimRow label={t("lo") + " (L)"} v={L.L} unit={d.unit} on={L.L != null && d.v <= L.L} kind="warn" />
        <LimRow label={t("lo_lo") + " (LL)"} v={L.LL} unit={d.unit} on={L.LL != null && d.v <= L.LL} />
      </div>

      <div className="pgrid" style={{ marginBottom: 4 }}>
        <Field label={t("sensor")}>{d.tag.split("-")[1]}-type</Field>
        <Field label={t("last_cal")}>2026-03-12</Field>
      </div>
    </>
  );
}

/* ===== Popup shell ========================================== */
function DevicePopup({ d, onClose }) {
  const { t } = useApp();
  const [, setTick] = React.useState(0);
  const force = () => setTick(x => x + 1);
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === "Escape") onClose(); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);
  const icon = d.kind === "valve" ? "valve" : d.kind === "motor" ? (d.sub === "fan" ? "fan" : d.sub === "blower" ? "wind" : d.sub === "compressor" ? "cpu" : d.isGenset ? "zap" : "pump") : "gauge";
  const kindLbl = d.kind === "valve" ? (d.sub === "ev" ? t("ev_valve") : t("motor_valve")) : d.kind === "motor" ? t(d.sub === "fan" ? "fan" : d.sub === "blower" ? "blower" : d.sub === "compressor" ? "compressor" : d.sub === "agitator" ? "agitator" : d.isGenset ? "chp_engine" : "pump") : t("instrument");
  return (
    <div className="scrim" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className={"modal" + (d.kind !== "valve" ? " wide" : "")}>
        <div className="m-head">
          <div className="m-ic"><Icon n={icon} size={20} /></div>
          <div className="m-ttl">
            <div className="tag">{d.tag}</div>
            <div className="desc">{kindLbl} · {d.desc[useApp().lang]}</div>
          </div>
          <button className="m-x" onClick={onClose}><Icon n="x" size={16} /></button>
        </div>
        <div className="m-body">
          {d.kind === "valve" && <ValveFace d={d} t={t} force={force} />}
          {d.kind === "motor" && <MotorFace d={d} t={t} force={force} />}
          {d.kind === "instrument" && <InstrumentFace d={d} t={t} />}
        </div>
        <div className="m-foot">
          <span className="mono" style={{ fontSize: 11, color: "var(--hud-text-3)" }}>{d.tag}</span>
          <div style={{ flex: 1 }}></div>
          <button className="btn btn-sm" onClick={onClose}>{t("close_win")}</button>
        </div>
      </div>
    </div>
  );
}

window.DevicePopup = DevicePopup;
