/* ============================================================
   MIMIC SYMBOLS — clickable P&ID-style device glyphs + pipes
   Coordinate space: explicit px inside a sized .mimic box.
   ============================================================ */

/* status color for any device */
function devColor(d) {
  if (d.kind === "valve") return d.fault ? "#d33a2c" : d.travelling ? "#e8a317" : d.open ? "#1e9e5a" : "#5b6b7d";
  if (d.kind === "motor") return d.fault ? "#d33a2c" : d.running ? "#1e9e5a" : "#5b6b7d";
  const q = window.qualOf(d); return q === "alarm" ? "#d33a2c" : q === "warn" ? "#e8a317" : "#3D8BE0";
}

/* ---- Valve glyph (bowtie) ---------------------------------- */
function VSym({ d, x, y, lbl, inline }) {
  const { open: openDev } = useApp();
  const c = devColor(d);
  const wrap = inline ? { display: "inline-flex" } : { position: "absolute", left: x, top: y, transform: "translate(-50%,-50%)" };
  return (
    <div className={inline ? "" : ""} style={wrap} onClick={() => openDev(d)} title={d.tag}>
      <div className="tag-badge">
        <svg width="30" height="20" style={{ filter: d.travelling ? "drop-shadow(0 0 4px #e8a317)" : "none" }}>
          <polygon points="2,3 14,10 2,17" fill={c} stroke="#0a1830" strokeWidth="1" />
          <polygon points="28,3 16,10 28,17" fill={c} stroke="#0a1830" strokeWidth="1" />
          <rect x="13" y="9" width="4" height="2" fill={c} />
          <line x1="15" y1="9" x2="15" y2="2" stroke={c} strokeWidth="1.5" /><circle cx="15" cy="2" r="1.6" fill={c} />
        </svg>
        <div className="mono" style={{ fontSize: 9, color: "var(--hud-text-2)", marginTop: 1, background: "rgba(6,15,31,.7)", padding: "0 3px", borderRadius: 2 }}>{lbl || d.tag.replace(/^\d+-/, "")}</div>
      </div>
    </div>
  );
}

/* ---- Motor / pump glyph ------------------------------------ */
function MSym({ d, x, y, lbl, glyph, inline }) {
  const { open: openDev } = useApp();
  const c = devColor(d);
  const letter = glyph || (d.sub === "fan" ? "V" : d.sub === "compressor" ? "C" : d.sub === "blower" ? "B" : d.sub === "agitator" ? "A" : d.isGenset ? "G" : d.sub === "conveyor" ? "T" : "P");
  const wrap = inline ? { display: "inline-flex" } : { position: "absolute", left: x, top: y, transform: "translate(-50%,-50%)" };
  return (
    <div style={wrap} onClick={() => openDev(d)} title={d.tag}>
      <div className="tag-badge">
        <div style={{ width: 30, height: 30, borderRadius: "50%", border: "2px solid " + c, background: "rgba(6,15,31,.85)",
          display: "flex", alignItems: "center", justifyContent: "center", position: "relative",
          boxShadow: d.running ? "0 0 8px " + c + "66" : "none" }}>
          <span className="mono" style={{ fontWeight: 700, fontSize: 12, color: c }}>{letter}</span>
          {d.running && <svg width="30" height="30" viewBox="0 0 30 30" style={{ position: "absolute", inset: 0, animation: "spin 2.4s linear infinite" }}>
            <path d="M15 3 A12 12 0 0 1 27 15" stroke={c} strokeWidth="1.6" fill="none" strokeLinecap="round" />
          </svg>}
        </div>
        <div className="mono" style={{ fontSize: 9, color: "var(--hud-text-2)", marginTop: 1, background: "rgba(6,15,31,.7)", padding: "0 3px", borderRadius: 2 }}>{lbl || d.tag.replace(/^\d+-/, "")}</div>
      </div>
    </div>
  );
}

/* ---- Instrument glyph -------------------------------------- */
function ISym({ d, x, y, showVal = true, inline }) {
  const { open: openDev } = useApp();
  const c = devColor(d);
  const code = d.tag.split("-")[1] || "XT";
  const wrap = inline ? { display: "inline-flex" } : { position: "absolute", left: x, top: y, transform: "translate(-50%,-50%)" };
  return (
    <div style={wrap} onClick={() => openDev(d)} title={d.tag}>
      <div className="tag-badge">
        <div style={{ width: 34, height: 34, borderRadius: "50%", border: "1.8px solid " + c, background: "rgba(6,15,31,.85)",
          display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", lineHeight: 1 }}>
          <span className="mono" style={{ fontWeight: 700, fontSize: 10, color: c }}>{code.slice(0, 2)}</span>
          <span className="mono" style={{ fontSize: 7.5, color: "var(--hud-text-3)" }}>{d.tag.split("-")[2]}</span>
        </div>
        {showVal && <div className={"lv" + (window.qualOf(d) === "alarm" ? " al" : window.qualOf(d) === "warn" ? " hi" : "")} style={{ marginTop: 3, padding: "1px 5px" }}>
          <span className="n" style={{ fontSize: 10.5 }}>{fmtNum(d.v, d.fmt)}</span><span className="u" style={{ fontSize: 8 }}>{d.unit}</span>
        </div>}
      </div>
    </div>
  );
}

/* ---- Mimic container --------------------------------------- */
function Mimic({ w = 1140, h = 460, children, svg }) {
  return (
    <div style={{ overflowX: "auto", overflowY: "hidden" }}>
      <div className="mimic" style={{ position: "relative", width: w, height: h, margin: "0 auto" }}>
        <svg width={w} height={h} style={{ position: "absolute", inset: 0 }} viewBox={`0 0 ${w} ${h}`}>
          <defs>
            <pattern id="grid" width="34" height="34" patternUnits="userSpaceOnUse">
              <path d="M34 0H0V34" fill="none" stroke="rgba(122,160,209,0.05)" strokeWidth="1" />
            </pattern>
          </defs>
          <rect width={w} height={h} fill="url(#grid)" />
          {svg}
        </svg>
        {children}
      </div>
    </div>
  );
}

/* ---- SVG pipe helper (used inside Mimic svg) --------------- */
function pipe(dStr, color, flow, key, gas) {
  return [
    React.createElement("path", { key: key + "b", d: dStr, className: "pipe", stroke: "#13284a", strokeWidth: 7, fill: "none" }),
    React.createElement("path", { key: key + "f", d: dStr, className: "pipe", stroke: color, strokeWidth: 3, fill: "none" }),
    flow ? React.createElement("path", { key: key + "fl", d: dStr, className: "pipe flow" + (gas ? " gas" : ""), stroke: "#bcdcff", strokeWidth: 2.4, fill: "none", opacity: 0.85 }) : null,
  ];
}

/* ---- vessel/tank shapes ------------------------------------ */
function Tank({ x, y, w, h, fill, label, level, color = "#3D8BE0", rounded = 6 }) {
  const lvH = level != null ? (h - 4) * level / 100 : 0;
  return (
    <g>
      <rect x={x} y={y} width={w} height={h} rx={rounded} className="eq" stroke="rgba(122,160,209,0.3)" strokeWidth="1.5" />
      {level != null && <rect x={x + 2} y={y + h - 2 - lvH} width={w - 4} height={lvH} rx={2} fill={color} opacity="0.32" />}
      {level != null && <line x1={x + 2} y1={y + h - 2 - lvH} x2={x + w - 2} y2={y + h - 2 - lvH} stroke={color} strokeWidth="1.5" opacity="0.7" />}
    </g>
  );
}

/* section panel scaffold for pages */
function MimicPanel({ title, tag, children, legend }) {
  const { t } = useApp();
  return (
    <div className="panel" style={{ marginBottom: 14 }}>
      <div className="panel-h"><Icon n="factory" size={15} /><div className="pt">{title}{tag && <small>{tag}</small>}</div>
        {legend && <div className="right">{legend}</div>}
      </div>
      <div className="panel-b" style={{ padding: "12px 6px" }}>{children}</div>
    </div>
  );
}

/* device list table (reused) */
function DeviceTable({ devs, cols }) {
  const { t, lang, open } = useApp();
  return (
    <div className="panel">
      <div className="panel-h"><Icon n="database" size={15} /><div className="pt">{t("devices")}<small>{devs.length}</small></div></div>
      <div style={{ maxHeight: 360, overflow: "auto" }}>
        <table className="tbl">
          <thead><tr>
            <th>Tag</th><th>{t("description")}</th><th>{t("status")}</th><th style={{ textAlign: "right" }}>{t("value")}</th><th>{t("mode")}</th>
          </tr></thead>
          <tbody>
            {devs.map(d => {
              const s = deviceStatus(d, t);
              const val = d.kind === "instrument" ? fmtNum(d.v, d.fmt) + " " + d.unit
                : d.kind === "motor" ? (d.isGenset ? fmtNum(d.powerKw != null ? d.powerKw : (window.devById("50JT01") || {}).v || 0, 0) + " kW" : fmtNum(d.A, 1) + " A")
                : Math.round(d.pos) + " %";
              return (
                <tr className="clickrow" key={d.id} onClick={() => open(d)}>
                  <td className="mono">{d.tag}</td>
                  <td className="dim">{d.desc[lang]}</td>
                  <td><StatusChip kind={s.k} label={s.l} /></td>
                  <td className="mono" style={{ textAlign: "right" }}>{val}</td>
                  <td className="mono dim">{d.kind === "instrument" ? "—" : t(d.mode === "auto" ? "auto" : "manual")}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

/* small page header */
function PageHead({ titleKey, sub, tag, children }) {
  const { t } = useApp();
  return (
    <div className="page-head">
      <div className="ph-t">
        <h1>{t(titleKey)}</h1>
        {sub && <span className="sub">{sub}</span>}
      </div>
      {tag && <span className="ph-tag">{tag}</span>}
      {children && <div className="ph-actions">{children}</div>}
    </div>
  );
}

Object.assign(window, { devColor, VSym, MSym, ISym, Mimic, pipe, Tank, MimicPanel, DeviceTable, PageHead });

/* spin keyframe injection */
(function () { const s = document.createElement("style"); s.textContent = "@keyframes spin{to{transform:rotate(360deg)}}"; document.head.appendChild(s); })();
