/* ============================================================
   PAGES — Process Parameters · Alarms · Trends
   ============================================================ */

/* ---------- derived biogas KPIs (animated from live data) ---- */
function derived() {
  const g = id => window.devById(id);
  const flow = g("40FT01").v, ch4 = g("40AT01").v;
  const inputKW = flow * (ch4 / 100) * 9.97;            // CH4 LHV ≈ 9.97 kWh/Nm³
  const el = g("50JT01").v, th = g("50JT02").v;
  const elEff = inputKW > 0 ? (el / inputKW) * 100 : 0;
  const thEff = inputKW > 0 ? (th / inputKW) * 100 : 0;
  const tunsT = window.MODEL.DEVICES.filter(d => /^20TT/.test(d.id) && g(d.id));
  const avgT = window.MODEL.DEVICES.filter(d => /^20TT/.test(d.id)).reduce((s, d) => s + d.v, 0) / window.N_TUN;
  return {
    daily: flow * 24 / 1000,            // k Nm³/d
    inputKW, el, th, elEff, thEff, avgT,
    lhv: (ch4 / 100) * 9.97,            // kWh/Nm³
    fosTac: 0.27 + (g("30QT01").v - 7.6) * -0.05 + Math.sin(Date.now() / 9000) * 0.004,
    olr: 3.18 + Math.sin(Date.now() / 12000) * 0.05,
    hrt: 28,
    feed: 94 + Math.sin(Date.now() / 15000) * 2.4,
  };
}

function ParamTile({ label, value, unit, dp = 1, warn, alarm, sparkId, gauge, min, max, warnAt, alarmAt, sub }) {
  const col = alarm ? "#f08478" : warn ? "#f3c45a" : "#fff";
  return (
    <div className="kpi" style={{ display: "flex", flexDirection: "column" }}>
      <div className="k-l">{label}</div>
      {gauge ? (
        <div style={{ marginTop: 4 }}><Gauge value={value} min={min} max={max} unit={unit} size={120} warnAt={warnAt} alarmAt={alarmAt} dp={dp} /></div>
      ) : (
        <>
          <div className="k-v" style={{ color: col }}>{fmtNum(value, dp)}{unit && <span className="u">{unit}</span>}</div>
          {sub && <div className="k-d">{sub}</div>}
          {sparkId && <div className="k-spark"><Sparkline id={sparkId} w={240} h={28} color={alarm ? "#f08478" : warn ? "#f3c45a" : "#3D8BE0"} /></div>}
        </>
      )}
    </div>
  );
}

function ParamGroup({ icon, title, children }) {
  return (
    <div className="panel" style={{ marginBottom: 14 }}>
      <div className="panel-h"><Icon n={icon} size={15} /><div className="pt">{title}</div></div>
      <div className="panel-b" style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12 }}>{children}</div>
    </div>
  );
}

function ParamsPage() {
  const { t } = useApp();
  const g = id => window.devById(id);
  const dv = derived();
  return (
    <div className="page">
      <PageHead titleKey="nav_params" sub={t("plant_sub")} tag="PROCESS · KPI" />

      <ParamGroup icon="gauge" title={t("biogas_quality")}>
        <ParamTile label={t("ch4")} value={g("40AT01").v} unit="%" gauge min={0} max={75} warnAt={50} alarmAt={45} dp={1} />
        <ParamTile label={t("co2")} value={g("40AT02").v} unit="%" gauge min={0} max={60} warnAt={46} dp={1} />
        <ParamTile label={t("h2s")} value={g("40AT03").v} unit="ppm" gauge min={0} max={800} warnAt={400} alarmAt={600} dp={0} />
        <ParamTile label={t("o2")} value={g("40AT04").v} unit="%" gauge min={0} max={5} warnAt={1.5} alarmAt={2.5} dp={2} />
      </ParamGroup>

      <ParamGroup icon="flame" title={t("gas_production")}>
        <ParamTile label={t("gas_flow")} value={g("40FT01").v} unit="Nm³/h" dp={0} sparkId="40FT01" sub={<>{t("calorific")}: {fmtNum(dv.lhv, 2)} kWh/Nm³</>} />
        <ParamTile label={t("gas_total")} value={dv.daily} unit="k Nm³/d" dp={2} sub={<>≈ {fmtNum(dv.daily * 1000 * dv.lhv / 1000, 1)} MWh/d</>} />
        <ParamTile label={t("holder_fill")} value={g("40LT01").v} unit="%" dp={0} sparkId="40LT01" sub={<>{t("gas_press")}: {fmtNum(g("40PT01").v, 1)} mbar</>} />
        <ParamTile label={t("gas_press")} value={g("40PT01").v} unit="mbar" dp={1} sparkId="40PT01" warn={window.qualOf(g("40PT01")) === "warn"} />
      </ParamGroup>

      <ParamGroup icon="droplets" title={t("digestion")}>
        <ParamTile label={t("digester_temp")} value={dv.avgT} unit="°C" gauge min={20} max={55} warnAt={44} alarmAt={48} dp={1} />
        <ParamTile label={t("ph")} value={g("30QT01").v} unit="pH" dp={2} sparkId="30QT01" sub={<>{t("range")} 6.8 – 8.0</>} />
        <ParamTile label={t("fos_tac")} value={dv.fosTac} dp={3} sub={<>{t("st_ok")} &lt; 0.40</>} warn={dv.fosTac > 0.4} />
        <ParamTile label={t("olr")} value={dv.olr} unit="kg VS/m³·d" dp={2} sub={<>{t("hrt")}: {dv.hrt} d</>} />
      </ParamGroup>

      <ParamGroup icon="zap" title={t("energy")}>
        <ParamTile label={t("el_power")} value={dv.el} unit="kW" dp={0} sparkId="50JT01" sub={<>{t("grid_export")} · 15 kV</>} />
        <ParamTile label={t("th_power")} value={dv.th} unit="kW" dp={0} sub={<>{t("digester_temp")} + ORC</>} />
        <ParamTile label={t("el_eff")} value={dv.elEff} unit="%" dp={1} sub={<>{t("thermal")}: {fmtNum(dv.thEff, 1)} %</>} />
        <ParamTile label={t("op_hours")} value={g("50GG01").runH} unit="h" dp={0} sub={<>{g("50GG01").starts} {t("starts_today").toLowerCase()}</>} />
      </ParamGroup>

      <ParamGroup icon="leaf" title={t("substrate") + " · " + t("environment")}>
        <ParamTile label={t("feed_rate")} value={dv.feed} unit="t/d" dp={1} sub={<>{t("feed_hopper")}: {fmtNum(g("10LT01").v, 0)} %</>} />
        <ParamTile label={t("active_tunnels")} value={window.devByArea("tun").filter(d => d.kind === "tunnel" && d.phase === "run").length} unit={"/ " + window.N_TUN} dp={0} sub={<>HRT {dv.hrt} d</>} />
        <ParamTile label={t("h2s") + " — " + t("reception_hall")} value={g("10QT01").v} unit="ppm" dp={1} sparkId="10QT01" warn={window.qualOf(g("10QT01")) === "warn"} />
        <ParamTile label={t("uptime")} value={98.6} unit="%" dp={1} sub={<>30 d</>} />
      </ParamGroup>
    </div>
  );
}

/* ============================================================
   ALARMS
   ============================================================ */
function AlarmsPage({ alarms }) {
  const { t, lang, nav, open } = useApp();
  const [filter, setFilter] = React.useState("all");
  const [, force] = React.useState(0);
  const prCol = { high: "#d33a2c", med: "#e8a317", low: "#75828f" };
  const prLbl = { high: t("pri_high"), med: t("pri_med"), low: t("pri_low") };
  let list = alarms;
  if (filter === "unack") list = list.filter(a => !a.ackd && a.state === "active");
  if (filter === "high") list = list.filter(a => a.pri === "high");
  const counts = {
    high: alarms.filter(a => a.pri === "high" && a.state === "active").length,
    med: alarms.filter(a => a.pri === "med" && a.state === "active").length,
    unack: alarms.filter(a => !a.ackd && a.state === "active").length,
  };
  return (
    <div className="page">
      <PageHead titleKey="nav_alarms" sub={alarms.filter(a => a.state === "active").length + " " + t("active_alarms")} tag="ISA-18.2">
        <button className="btn btn-sm btn-accent" onClick={() => { window.ackAllAlarms(); force(x => x + 1); }}><Icon n="check" size={14} />{t("ack_all")}</button>
      </PageHead>

      <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12, marginBottom: 14 }}>
        <KPI icon="alert" label={t("pri_high")} value={counts.high} accent={counts.high > 0} />
        <KPI icon="bell" label={t("pri_med")} value={counts.med} />
        <KPI icon="lock" label={t("filter_unack")} value={counts.unack} />
        <KPI icon="checkc" label={t("uptime")} value="98.6" unit="%" />
      </div>

      <div className="panel">
        <div className="panel-h"><Icon n="bell" size={15} /><div className="pt">{t("alarm_list")}</div>
          <div className="right" style={{ display: "flex", gap: 6 }}>
            {[["all", t("filter_all")], ["unack", t("filter_unack")], ["high", t("pri_high")]].map(([k, l]) => (
              <button key={k} className={"btn btn-sm" + (filter === k ? " btn-primary" : "")} onClick={() => setFilter(k)}>{l}</button>
            ))}
          </div>
        </div>
        <div style={{ maxHeight: "calc(100vh - 320px)", overflow: "auto" }}>
          <table className="tbl">
            <thead><tr>
              <th style={{ width: 70 }}>{t("priority")}</th><th style={{ width: 90 }}>{t("time")}</th>
              <th style={{ width: 110 }}>{t("source")}</th><th>{t("description")}</th>
              <th style={{ width: 110 }}>{t("alarm_state")}</th><th style={{ width: 90 }}></th>
            </tr></thead>
            <tbody>
              {list.length === 0 && <tr><td colSpan="6" style={{ textAlign: "center", padding: 30, color: "var(--hud-text-3)" }}>{t("no_alarms")}</td></tr>}
              {list.map(a => (
                <tr key={a.key} className={a.devId ? "clickrow" : ""} onClick={() => a.devId && open(window.devById(a.devId))}>
                  <td><span className="chip" style={{ background: prCol[a.pri] + "22", color: prCol[a.pri] }}><span className="d" style={{ background: prCol[a.pri], animation: a.pri === "high" && !a.ackd ? "blink 1s steps(2) infinite" : "none" }}></span>{prLbl[a.pri]}</span></td>
                  <td className="mono dim">{fmtClock(a.ts)}</td>
                  <td className="mono">{a.tag}</td>
                  <td>{a.desc[lang]}</td>
                  <td>{a.state === "cleared" ? <StatusChip kind="info" label={t("al_cleared")} /> : a.ackd ? <StatusChip kind="idle" label={t("al_ackd")} /> : <StatusChip kind="alarm" label={t("al_active")} />}</td>
                  <td>{!a.ackd && a.state === "active" && <button className="btn btn-sm" onClick={(e) => { e.stopPropagation(); window.ackAlarm(a.key); force(x => x + 1); }}>{t("ack")}</button>}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

/* ============================================================
   TRENDS
   ============================================================ */
const TREND_VARS = [
  { id: "50JT01", c: "#F2941F" }, { id: "40FT01", c: "#3D8BE0" }, { id: "40AT01", c: "#5fd99a" },
  { id: "40AT03", c: "#f3c45a" }, { id: "40LT01", c: "#9aa6b2" }, { id: "40PT01", c: "#6E97C4" },
  { id: "20TT01", c: "#f08478" }, { id: "30QT01", c: "#8fb4e6" }, { id: "50TT02", c: "#caa05a" }, { id: "70PT01", c: "#7BA0D1" },
];
function BigChart({ id, color }) {
  const d = window.devById(id);
  const hist = (window.HIST && window.HIST[id]) || [];
  const W = 920, H = 280, padL = 52, padB = 24, padT = 14, padR = 14;
  if (hist.length < 2) return <svg width={W} height={H}></svg>;
  const mn = Math.min(...hist), mx = Math.max(...hist), rng = (mx - mn) || 1;
  const lo = mn - rng * 0.1, hi = mx + rng * 0.1, span = hi - lo;
  const x = i => padL + i / (hist.length - 1) * (W - padL - padR);
  const y = v => padT + (1 - (v - lo) / span) * (H - padT - padB);
  const line = hist.map((v, i) => (i ? "L" : "M") + x(i).toFixed(1) + " " + y(v).toFixed(1)).join(" ");
  const area = line + ` L ${x(hist.length - 1)} ${H - padB} L ${padL} ${H - padB} Z`;
  const ticks = 4;
  return (
    <svg width={W} height={H}>
      <defs><linearGradient id="bcg" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stopColor={color} stopOpacity="0.28" /><stop offset="1" stopColor={color} stopOpacity="0" /></linearGradient></defs>
      {Array.from({ length: ticks + 1 }).map((_, i) => {
        const vy = padT + i / ticks * (H - padT - padB), val = hi - i / ticks * span;
        return <g key={i}><line x1={padL} y1={vy} x2={W - padR} y2={vy} stroke="rgba(122,160,209,0.1)" /><text x={padL - 8} y={vy + 3} textAnchor="end" fill="#647a98" style={{ font: "500 10px var(--font-mono)" }}>{fmtNum(val, d.fmt)}</text></g>;
      })}
      <path d={area} fill="url(#bcg)" />
      <path d={line} fill="none" stroke={color} strokeWidth="2" strokeLinejoin="round" />
      <circle cx={x(hist.length - 1)} cy={y(hist[hist.length - 1])} r="3.5" fill={color} />
    </svg>
  );
}
function TrendsPage() {
  const { t, lang } = useApp();
  const [sel, setSel] = React.useState("50JT01");
  const d = window.devById(sel);
  const hist = (window.HIST && window.HIST[sel]) || [d.v];
  const cur = d.v, mn = Math.min(...hist), mx = Math.max(...hist), avg = hist.reduce((a, b) => a + b, 0) / hist.length;
  const color = (TREND_VARS.find(v => v.id === sel) || {}).c || "#3D8BE0";
  return (
    <div className="page">
      <PageHead titleKey="nav_trends" sub={t("last_h")} tag="HISTORIAN">
        <button className="btn btn-sm"><Icon n="download" size={14} />{t("export_csv")}</button>
      </PageHead>
      <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", gap: 14 }}>
        <div className="panel" style={{ alignSelf: "start" }}>
          <div className="panel-h"><Icon n="chart" size={15} /><div className="pt">{t("select_var")}</div></div>
          <div style={{ padding: 6 }}>
            {TREND_VARS.map(v => {
              const dv = window.devById(v.id);
              return (
                <a key={v.id} className={"nav-item" + (sel === v.id ? " on" : "")} onClick={() => setSel(v.id)} style={{ margin: "2px 0" }}>
                  <span style={{ width: 9, height: 9, borderRadius: 2, background: v.c, flexShrink: 0 }}></span>
                  <span style={{ flex: 1, lineHeight: 1.2 }}>
                    <span className="mono" style={{ fontSize: 11, display: "block", color: "var(--hud-text)" }}>{dv.tag}</span>
                    <span style={{ fontSize: 10, color: "var(--hud-text-3)" }}>{dv.desc[lang].slice(0, 26)}</span>
                  </span>
                </a>
              );
            })}
          </div>
        </div>
        <div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(4,1fr)", gap: 12, marginBottom: 12 }}>
            <KPI label={t("live")} value={cur} dp={d.fmt} unit={d.unit} accent />
            <KPI label="MIN" value={mn} dp={d.fmt} unit={d.unit} />
            <KPI label="MAX" value={mx} dp={d.fmt} unit={d.unit} />
            <KPI label="⌀ AVG" value={avg} dp={d.fmt} unit={d.unit} />
          </div>
          <div className="panel">
            <div className="panel-h"><Icon n="activity" size={15} /><div className="pt">{d.tag}<small>{d.desc[lang]}</small></div><div className="right"><StatusChip kind={window.qualOf(d) === "ok" ? "run" : window.qualOf(d)} label={d.unit} /></div></div>
            <div className="panel-b"><BigChart id={sel} color={color} /></div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ParamsPage, AlarmsPage, TrendsPage });
