/* ============================================================
   PAGE — Plant Overview (synoptic flow)
   ============================================================ */
function areaStat(area) {
  const ds = window.devByArea(area);
  const al = window.computeAlarms().filter(a => a.area === area && a.state === "active");
  const motors = ds.filter(d => d.kind === "motor");
  return { count: ds.filter(d => d.kind !== "tunnel").length, alarms: al.length, running: motors.filter(m => m.running).length, motors: motors.length };
}

function StageCard({ area, page, icon, title, metrics, x, y, w, h = 118, accent }) {
  const { t, nav, lang } = useApp();
  const st = areaStat(area);
  const dotc = st.alarms ? "#d33a2c" : "#1e9e5a";
  return (
    <div onClick={() => nav(page)} style={{
      position: "absolute", left: x, top: y, width: w, height: h, cursor: "pointer",
      backgroundImage: accent ? "linear-gradient(180deg,#13315c,#0e2244)" : "linear-gradient(180deg,#0d1f3c,#0a1830)",
      border: "1px solid " + (accent ? "rgba(242,148,31,.4)" : "var(--hud-line)"), borderRadius: 8,
      padding: "10px 12px", display: "flex", flexDirection: "column", boxShadow: "var(--shadow-md)", transition: "all .15s",
    }}
      onMouseEnter={e => { e.currentTarget.style.borderColor = "var(--navy-400)"; e.currentTarget.style.transform = "translateY(-2px)"; }}
      onMouseLeave={e => { e.currentTarget.style.borderColor = accent ? "rgba(242,148,31,.4)" : "var(--hud-line)"; e.currentTarget.style.transform = "none"; }}>
      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        <Icon n={icon} size={16} style={{ color: accent ? "var(--orange-400)" : "#8fb4e6" }} />
        <span style={{ fontSize: 12, fontWeight: 700, color: "#fff", lineHeight: 1.1, flex: 1 }}>{title}</span>
        <span style={{ width: 8, height: 8, borderRadius: "50%", background: dotc, boxShadow: "0 0 6px " + dotc }}></span>
      </div>
      <div style={{ flex: 1, display: "flex", gap: 14, marginTop: 8 }}>
        {metrics.map((m, i) => (
          <div key={i}>
            <div className="mono" style={{ fontSize: m.big ? 19 : 16, fontWeight: 700, color: m.warn ? "#f3c45a" : "#fff", lineHeight: 1 }}>{m.v}<span style={{ fontSize: 9, color: "var(--hud-text-3)", marginLeft: 2 }}>{m.u}</span></div>
            <div style={{ fontSize: 9.5, color: "var(--hud-text-3)", textTransform: "uppercase", letterSpacing: ".05em", marginTop: 3 }}>{m.l}</div>
          </div>
        ))}
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 8, marginTop: 6, paddingTop: 6, borderTop: "1px solid var(--hud-line-soft)" }}>
        <span className="mono" style={{ fontSize: 10, color: "var(--hud-text-3)" }}>{st.count} {t("devices")}</span>
        {st.motors > 0 && <span className="mono" style={{ fontSize: 10, color: "#5fd99a" }}>● {st.running}/{st.motors}</span>}
        {st.alarms > 0 && <span className="ni-badge al" style={{ fontSize: 9, height: 15, minWidth: 15 }}>{st.alarms}</span>}
        <div style={{ flex: 1 }}></div>
        <Icon n="chevR" size={13} style={{ color: "var(--hud-text-3)" }} />
      </div>
    </div>
  );
}

function OverviewPage() {
  const { t, lang } = useApp();
  const g = id => window.devById(id);
  const tuns = window.devByArea("tun").filter(d => d.kind === "tunnel");
  const activeTun = tuns.filter(x => x.phase === "run").length;
  const avgCh4 = window.MODEL.DEVICES.filter(d => /^20AT/.test(d.id)).reduce((s, d) => s + d.v, 0) / window.N_TUN;
  const W = 1180, H = 500;
  return (
    <div className="page">
      <PageHead titleKey="nav_overview" sub={t("overview_sub")} tag="P&ID · 101-GEN-S-001U">
        <button className="btn btn-sm"><Icon n="refresh" size={14} />{t("live")}</button>
      </PageHead>

      {/* KPI strip */}
      <div style={{ display: "grid", gridTemplateColumns: "repeat(6,1fr)", gap: 12, marginBottom: 16 }}>
        <KPI icon="zap" label={t("el_power")} value={g("50JT01").v} dp={0} unit="kW" accent sparkId="50JT01" color="#F2941F" sub={<><Icon n="activity" size={11} />{fmtNum(g("50JT02").v, 0)} kW th.</>} />
        <KPI icon="flame" label={t("gas_flow")} value={g("40FT01").v} dp={0} unit="Nm³/h" sparkId="40FT01" sub={<>{fmtNum(g("40FT01").v * 24 / 1000, 1)} k Nm³/d</>} />
        <KPI icon="gauge" label={t("ch4")} value={g("40AT01").v} dp={1} unit="%" sparkId="40AT01" sub={<>H₂S {fmtNum(g("40AT03").v, 0)} ppm</>} />
        <KPI icon="database" label={t("holder_fill")} value={g("40LT01").v} dp={0} unit="%" sparkId="40LT01" sub={<>{fmtNum(g("40PT01").v, 1)} mbar</>} />
        <KPI icon="tunnel" label={t("active_tunnels")} value={activeTun + " / " + window.N_TUN} sub={<>CH₄ ⌀ {fmtNum(avgCh4, 1)} %</>} />
        <KPI icon="leaf" label={t("uptime")} value="98.6" unit="%" sub={<>30 {t("op_hours").toLowerCase().slice(0, 8)}.</>} />
      </div>

      {/* synoptic */}
      <div className="panel">
        <div className="panel-h"><Icon n="factory" size={15} /><div className="pt">{t("nav_overview")}<small>{t("overview_sub")}</small></div>
          <div className="right"><div className="legend">
            <span className="lg"><span className="d" style={{ background: "#1e9e5a" }}></span>{t("st_run")}</span>
            <span className="lg"><span className="d" style={{ background: "#e8a317" }}></span>{t("st_warn")}</span>
            <span className="lg"><span className="d" style={{ background: "#d33a2c" }}></span>{t("st_alarm")}</span>
            <span className="lg"><span className="d" style={{ background: "#5b6b7d" }}></span>{t("st_idle")}</span>
          </div></div>
        </div>
        <div className="panel-b" style={{ padding: "10px 6px" }}>
          <div style={{ overflowX: "auto" }}>
            <div style={{ position: "relative", width: W, height: H, margin: "0 auto" }}>
              <svg width={W} height={H} style={{ position: "absolute", inset: 0 }}>
                <defs><pattern id="gridov" width="34" height="34" patternUnits="userSpaceOnUse"><path d="M34 0H0V34" fill="none" stroke="rgba(122,160,209,0.045)" strokeWidth="1" /></pattern></defs>
                <rect width={W} height={H} fill="url(#gridov)" />
                {/* main process line */}
                {pipe("M 212 150 H 248", "#7BA0D1", true, "p1")}
                {pipe("M 470 150 H 512", "#7BA0D1", true, "p2")}
                {pipe("M 724 150 H 760", "#F2941F", true, "p3", true)}
                {pipe("M 942 150 H 980", "#F2941F", true, "p4", true)}
                {pipe("M 1080 150 H 1120", "#F2941F", true, "p5", true)}
                {/* percolate recirculation loop tunnels<->percolate */}
                {pipe("M 360 268 V 330", "#3D8BE0", true, "pp1")}
                {pipe("M 300 330 V 268", "#3D8BE0", true, "pp2")}
                {/* heat recovery CHP down to tunnels */}
                {pipe("M 845 268 V 330", "#d33a2c", true, "ph1")}
                {pipe("M 612 380 H 470 V 268", "#d33a2c", true, "ph2")}
                {/* biofilter from reception/tunnels */}
                {pipe("M 110 268 V 330", "#9aa6b2", true, "pb1")}
                {/* air to plant */}
                {pipe("M 845 380 V 360 M 800 345 H 360", "#6E97C4", false, "pa1")}
                {/* labels */}
                <text x="430" y="143" fill="#647a98" style={{ font: "600 9px var(--font-mono)" }}>BIOGAS</text>
                <text x="735" y="143" fill="#caa05a" style={{ font: "600 9px var(--font-mono)" }}>CH₄</text>
              </svg>
              {/* main row */}
              <StageCard area="rec" page="reception" icon="inbox" title={t("nav_reception")} x={24} y={92} w={188}
                metrics={[{ l: t("feed_hopper"), v: fmtNum(g("10LT01").v, 0), u: "%", big: true }, { l: t("st_run"), v: areaStat("rec").running + "/" + areaStat("rec").motors, u: "" }]} />
              <StageCard area="tun" page="tunnels" icon="tunnel" title={t("nav_tunnels")} x={248} y={92} w={222}
                metrics={[{ l: t("active_tunnels"), v: activeTun + "/" + window.N_TUN, u: "", big: true }, { l: "CH₄ ⌀", v: fmtNum(avgCh4, 1), u: "%" }, { l: "T ⌀", v: "40.4", u: "°C" }]} />
              <StageCard area="gas" page="biogas" icon="flame" title={t("nav_biogas")} x={512} y={92} w={212}
                metrics={[{ l: t("holder_fill"), v: fmtNum(g("40LT01").v, 0), u: "%", big: true }, { l: "CH₄", v: fmtNum(g("40AT01").v, 1), u: "%" }, { l: "H₂S", v: fmtNum(g("40AT03").v, 0), u: "ppm" }]} />
              <StageCard area="chp" page="chp" icon="zap" title={t("nav_chp")} x={760} y={92} w={182} accent
                metrics={[{ l: t("el_power"), v: fmtNum(g("50JT01").v, 0), u: "kW", big: true }, { l: t("th_power"), v: fmtNum(g("50JT02").v, 0), u: "kW" }]} />
              {/* grid terminal */}
              <div style={{ position: "absolute", left: 980, top: 110, width: 168, height: 82, background: "linear-gradient(180deg,#0d1f3c,#0a1830)", border: "1px solid var(--hud-line)", borderRadius: 8, padding: "10px 12px" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}><Icon n="power" size={15} style={{ color: "#5fd99a" }} /><span style={{ fontSize: 11.5, fontWeight: 700, color: "#fff" }}>{t("grid_export")}</span></div>
                <div className="mono" style={{ fontSize: 20, fontWeight: 700, color: "#5fd99a", marginTop: 8 }}>{fmtNum(g("50JT01").v, 0)}<span style={{ fontSize: 10, color: "var(--hud-text-3)" }}> kW</span></div>
                <div style={{ fontSize: 9.5, color: "var(--hud-text-3)", marginTop: 3 }}>15 kV · 50.0 Hz · cosφ 0.99</div>
              </div>
              {/* utilities row */}
              <StageCard area="per" page="percolate" icon="droplets" title={t("nav_percolate")} x={248} y={330} w={222}
                metrics={[{ l: "PR1", v: fmtNum(g("30LT01").v, 0), u: "%", big: true }, { l: t("gas_flow").slice(0, 8), v: fmtNum(g("30FT01").v, 0), u: "m³/h" }, { l: "pH", v: fmtNum(g("30QT01").v, 2), u: "" }]} />
              <StageCard area="heat" page="heat" icon="thermo" title={t("nav_heat")} x={512} y={330} w={212}
                metrics={[{ l: t("digester_temp").slice(0, 8), v: fmtNum(g("60TT01").v, 1), u: "°C", big: true }, { l: t("flow_rate"), v: fmtNum(g("60FT01").v, 0), u: "m³/h" }]} />
              <StageCard area="air" page="air" icon="wind" title={t("nav_air")} x={760} y={330} w={182}
                metrics={[{ l: t("gas_press"), v: fmtNum(g("70PT01").v, 2), u: "bar", big: true }, { l: t("st_run"), v: areaStat("air").running + "/" + areaStat("air").motors, u: "" }]} />
              <StageCard area="bio" page="biofilter" icon="leaf" title={t("nav_biofilter")} x={24} y={330} w={188}
                metrics={[{ l: "H₂S out", v: fmtNum(g("80QT01").v, 1), u: "ppm", big: true }, { l: "Δp", v: fmtNum(g("80PT01").v, 0), u: "Pa" }]} />
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}
window.OverviewPage = OverviewPage;
