/* ============================================================
   APP SHELL — topbar, alarm ticker, sidebar, footer, router
   ============================================================ */
const { useState, useEffect, useRef } = React;

/* nav structure */
const NAV = [
  { g: "g_supervision", items: [
    { id: "overview", icon: "dashboard" },
    { id: "params",   icon: "sliders" },
    { id: "alarms",   icon: "bell" },
    { id: "trends",   icon: "chart" },
  ]},
  { g: "g_pid", items: [
    { id: "pid",      icon: "factory" },
    { id: "pid_rec",  icon: "inbox",   area: "rec" },
    { id: "pid_tun",  icon: "tunnel",  area: "tun" },
    { id: "pid_per",  icon: "droplets",area: "per" },
    { id: "pid_gas",  icon: "flame",   area: "gas" },
    { id: "pid_chp",  icon: "zap",     area: "chp" },
    { id: "pid_air",  icon: "wind",    area: "air" },
  ]},
  { g: "g_process", items: [
    { id: "reception", icon: "inbox",   area: "rec" },
    { id: "tunnels",   icon: "tunnel",  area: "tun" },
    { id: "percolate", icon: "droplets",area: "per" },
    { id: "biogas",    icon: "flame",   area: "gas" },
    { id: "chp",       icon: "zap",     area: "chp" },
  ]},
  { g: "g_utilities", items: [
    { id: "heat",      icon: "thermo",  area: "heat" },
    { id: "air",       icon: "wind",    area: "air" },
    { id: "biofilter", icon: "leaf",    area: "bio" },
  ]},
];
const PAGE_TITLE = { overview:"nav_overview", pid:"nav_pid_gen", pid_rec:"pid_rec", pid_tun:"pid_tun", pid_per:"pid_per", pid_gas:"pid_gas", pid_chp:"pid_chp", pid_air:"pid_air", params:"nav_params", alarms:"nav_alarms", trends:"nav_trends",
  reception:"nav_reception", tunnels:"nav_tunnels", percolate:"nav_percolate", biogas:"nav_biogas",
  chp:"nav_chp", heat:"nav_heat", air:"nav_air", biofilter:"nav_biofilter" };

/* ---- Top bar ----------------------------------------------- */
function TopBar({ alarms }) {
  const { t, lang, setLang, nav, page } = useApp();
  const [now, setNow] = useState(new Date());
  useEffect(() => { const i = setInterval(() => setNow(new Date()), 1000); return () => clearInterval(i); }, []);
  const unack = alarms.filter(a => !a.ackd && a.state === "active").length;
  return (
    <div className="topbar">
      <img className="tb-logo" src="assets/logo-jit-white.png" alt="JIT" />
      <div className="tb-divider"></div>
      <div className="tb-title">
        <b>{t("plant")}</b>
        <span>{t("plant_sub")}</span>
      </div>
      <div className="tb-spacer"></div>
      <div className="tb-conn"><span className="dot"></span>{t("connected")} · {t("scan")} 200ms</div>
      <div className="tb-divider"></div>
      <button className="iconbtn" onClick={() => nav("alarms")} title={t("alarms")}>
        <Icon n="bell" size={17} />{unack > 0 && <span className="badge">{unack}</span>}
      </button>
      <div className="tb-clock">
        <span>{fmtClock(now)}</span>
        <span className="d">{now.toLocaleDateString("en-CA")}</span>
      </div>
      <div className="tb-divider"></div>
      <div className="lang">
        {["it", "en", "pl"].map(l => <button key={l} className={lang === l ? "on" : ""} onClick={() => setLang(l)}>{l.toUpperCase()}</button>)}
      </div>
      <div className="tb-user">
        <div className="av">MR</div>
        <div className="nm"><b>M. Rossi</b><span>{t("supervisor")} · {t("remote")}</span></div>
      </div>
    </div>
  );
}

/* ---- Alarm ticker ------------------------------------------ */
function AlarmBar({ alarms }) {
  const { t, lang, nav } = useApp();
  const active = alarms.filter(a => a.state === "active");
  const ok = active.length === 0;
  const prCol = { high: "#d33a2c", med: "#e8a317", low: "#75828f" };
  const items = active.length ? active : [{ key: "ok", desc: { it: t("no_alarms"), en: t("no_alarms"), pl: t("no_alarms") }, ts: new Date(), pri: "low", tag: "" }];
  const doubled = items.concat(items);
  return (
    <div className={"alarmbar" + (ok ? " ok" : "")} onClick={() => nav("alarms")} style={{ cursor: "pointer" }}>
      <div className="ab-tag">
        <Icon n={ok ? "checkc" : "alert"} size={13} />{ok ? t("st_ok") : (active.length + " " + t("active_alarms"))}
      </div>
      <div className="ab-track">
        <div className="ab-move">
          {doubled.map((a, i) => (
            <span className={"ab-it" + (a.ackd ? " ack" : "")} key={i}>
              <span className="pri" style={{ background: prCol[a.pri] }}></span>
              <span className="t">{fmtClock(a.ts)}</span>
              {a.tag && <b className="mono" style={{ color: "#fff", fontWeight: 600 }}>{a.tag}</b>}
              {a.desc[lang]}
            </span>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ---- Sidebar ----------------------------------------------- */
function Sidebar({ alarms }) {
  const { t, page, nav } = useApp();
  const badge = (area) => alarms.filter(a => a.area === area && a.state === "active" && !a.ackd);
  return (
    <div className="sidebar">
      {NAV.map(grp => (
        <div className="nav-group" key={grp.g}>
          <div className="gl">{t(grp.g)}</div>
          {grp.items.map(it => {
            const b = it.area ? badge(it.area) : (it.id === "alarms" ? alarms.filter(a => a.state === "active" && !a.ackd) : []);
            const hi = b.some(a => a.pri === "high");
            return (
              <a className={"nav-item" + (page === it.id ? " on" : "")} key={it.id} onClick={() => nav(it.id)}>
                <Icon n={it.icon} size={17} />{t(PAGE_TITLE[it.id])}
                {b.length > 0 && <span className={"ni-badge " + (hi ? "al" : "wn")}>{b.length}</span>}
              </a>
            );
          })}
        </div>
      ))}
      <div className="sb-foot">
        <div className="row"><span>OPC-UA</span><b>● {t("online")}</b></div>
        <div className="row"><span>Runtime</span><b>JIT-SCADA 4.2</b></div>
        <div className="row"><span>{t("owner").split(" ")[0]}</span><b>Bierkowo · PL</b></div>
      </div>
    </div>
  );
}

/* ---- Footer status bar ------------------------------------- */
function FootBar() {
  const { t } = useApp();
  const ch4 = window.devById("40AT01"), flow = window.devById("40FT01"), fill = window.devById("40LT01"), pwr = window.devById("50JT01");
  const motors = window.MODEL.DEVICES.filter(d => d.kind === "motor");
  const running = motors.filter(m => m.running).length;
  const cell = (lbl, val, unit, q) => (
    <div className="fb-cell"><span className="lbl">{lbl}</span><span className="val" style={q ? { color: q } : null}>{val}{unit && <span className="u">{unit}</span>}</span></div>
  );
  return (
    <div className="footbar">
      {cell(t("ch4"), fmtNum(ch4.v, 1), "%", window.qualOf(ch4) !== "ok" ? "#f3c45a" : null)}
      {cell(t("gas_flow"), fmtNum(flow.v, 0), "Nm³/h")}
      {cell(t("holder_fill"), fmtNum(fill.v, 0), "%")}
      {cell(t("el_power"), fmtNum(pwr.v, 0), "kW", "#f3c45a")}
      {cell(t("running_now"), running + " / " + motors.length, "")}
      <div className="fb-spacer"></div>
      <div className="fb-mode"><Icon n="wifi" size={13} style={{ color: "#5fd99a" }} />OPC-UA · 200 ms</div>
      <div className="fb-cell" style={{ borderRight: "none", borderLeft: "1px solid var(--hud-line-soft)" }}><span className="lbl">{t("mode")}</span><span className="val" style={{ color: "#8fb4e6" }}>{t("remote")} · {t("auto")}</span></div>
    </div>
  );
}

/* ---- Toast ------------------------------------------------- */
function Toast({ msg }) {
  if (!msg) return null;
  return <div className="toast"><span className="ti" style={{ background: "var(--status-run)" }}></span>{msg}</div>;
}

/* ---- Root -------------------------------------------------- */
function AppRoot() {
  const [lang, setLang] = useState("it");
  const validPages = ["overview","pid","pid_rec","pid_tun","pid_per","pid_gas","pid_chp","pid_air","params","alarms","trends","reception","tunnels","percolate","biogas","chp","heat","air","biofilter"];
  const initial = (typeof location !== "undefined" && validPages.includes((location.hash || "").replace("#", ""))) ? location.hash.replace("#", "") : "overview";
  const [page, setPage] = useState(initial);
  const [openDev, setOpenDev] = useState(null);
  const [ver, setVer] = useState(0);
  const [toast, setToast] = useState(null);
  const toastTimer = useRef(null);
  const t = makeT(lang);

  // expose toast globally for popups
  useEffect(() => {
    window.toastMsg = (m) => {
      setToast(m);
      clearTimeout(toastTimer.current);
      toastTimer.current = setTimeout(() => setToast(null), 2200);
    };
  }, []);

  // simulation loop + history capture
  useEffect(() => {
    if (!window.HIST) window.HIST = {};
    const cap = () => {
      for (const d of window.MODEL.DEVICES) {
        let v = null;
        if (d.kind === "instrument") v = d.v;
        else if (d.kind === "motor") v = d.isGenset ? (d.powerKw != null ? d.powerKw : (window.devById("50JT01") || {}).v || 0) : d.A;
        if (v == null) continue;
        (window.HIST[d.id] = window.HIST[d.id] || []).push(v);
        if (window.HIST[d.id].length > 120) window.HIST[d.id].shift();
      }
    };
    // seed history
    for (let i = 0; i < 40; i++) { window.simTick(); cap(); }
    const iv = setInterval(() => { window.simTick(); cap(); setVer(x => x + 1); }, window.TICK_MS);
    return () => clearInterval(iv);
  }, []);

  const alarms = window.computeAlarms();
  const nav = (p) => { setPage(p); setOpenDev(null); if (typeof location !== "undefined") location.hash = p; };
  window.operionNav = nav;
  const ctx = { t, lang, setLang, page, nav, open: (d) => setOpenDev(d), ver };

  const PageComp = (window.PAGES && window.PAGES[page]) || FallbackPage;

  return (
    <window.AppCtx.Provider value={ctx}>
      <div className="app">
        <TopBar alarms={alarms} />
        <AlarmBar alarms={alarms} />
        <Sidebar alarms={alarms} />
        <div className="main"><PageComp alarms={alarms} /></div>
        <FootBar />
      </div>
      {openDev && <DevicePopup d={openDev} onClose={() => setOpenDev(null)} />}
      <Toast msg={toast} />
    </window.AppCtx.Provider>
  );
}

function FallbackPage() {
  const { t, page } = useApp();
  return <div className="page"><div className="page-head"><div className="ph-t"><h1>{t(PAGE_TITLE[page] || "plant")}</h1></div></div>
    <div className="panel"><div className="panel-b" style={{ color: "var(--hud-text-3)" }}>—</div></div></div>;
}

window.AppRoot = AppRoot;
