/* ATLAS — Plant Site page. The main workspace screen: a prominent multi-plant tab
   bar over one isometric site (site-scene.js / site-layout.js). Plant selection,
   the live model and the AI agent are all driven from app.jsx — this view receives
   the already-selected plant + derived values and renders the diagram, hover cards,
   a click-to-inspect panel, and a drill-through into the asset detail explorer. */
(function () {
  "use strict";
  const { useState, useEffect } = React;
  const h = React.createElement;
  const FONT_MONO = "var(--font-mono)";

  // small hover-aware element: merges `hover` style props while pointer is over it
  function Hoverable({ tag, hover, style, ...rest }) {
    const [over, setOver] = useState(false);
    return h(tag || "button", Object.assign({}, rest, {
      style: Object.assign({}, style, over ? hover : null),
      onMouseEnter: (e) => { setOver(true); rest.onMouseEnter && rest.onMouseEnter(e); },
      onMouseLeave: (e) => { setOver(false); rest.onMouseLeave && rest.onMouseLeave(e); },
    }));
  }

  function SiteView({ plant, derived, onBack, onOpenAsset }) {
    const [selected, setSelected] = useState(null);
    // close any open inspector when the plant changes (the asset values are now stale)
    useEffect(() => { setSelected(null); }, [plant && plant.id]);

    const A = window.ATLAS, PL = window.ATLAS_PLANTS;
    const ready = A && PL && plant && window.AtlasSiteScene && window.crystalPolys && window.ATLAS_SITE && derived;

    // ---- inspector panel data ----
    const asset = (ready && selected) ? A.ASSETS[selected] : null;
    const finalsById = {};
    if (ready) A.FINAL_METRICS.forEach((m) => { finalsById[m.id] = m.label; });
    const panelRows = asset ? (asset.outputs || []).map((o) => ({
      label: o.label,
      value: A.fmtNum(derived[o.id], o.fmtDp == null ? undefined : o.fmtDp),
      unit: o.unit, formula: o.formula || "",
    })) : [];
    const panelDrives = asset && asset.drives && asset.drives.length
      ? asset.drives.map((d) => finalsById[d] || d) : ["—"];

    const plantFull = plant ? plant.fullName : "";

    return h("div", { "data-screen-label": "Plant Site", style: {
      flex: 1, minWidth: 0, display: "flex", flexDirection: "column",
      background: "var(--gray-50)", fontFamily: "var(--font-sans, 'IBM Plex Sans', sans-serif)", color: "#000000" } },

      h("div", { style: { flex: 1, width: "100%", padding: "24px 32px 40px", display: "flex", flexDirection: "column", gap: 16 } },

        // ============ Back + single-plant identity ============
        h("div", { style: { display: "flex", flexDirection: "column", gap: 12 } },
          h(Hoverable, { tag: "button", onClick: onBack,
            hover: { border: "1px solid #074D47", color: "#074D47" },
            style: { alignSelf: "flex-start", background: "#FFFFFF", border: "1px solid #D1D5DB", color: "#374151",
              fontFamily: FONT_MONO, fontSize: 11, fontWeight: 600, letterSpacing: ".08em", padding: "8px 14px",
              cursor: "pointer" } }, "← ALL PLANT SITES"),
          h("div", { style: { display: "flex", alignItems: "flex-end", justifyContent: "space-between", gap: 24, flexWrap: "wrap" } },
            h("div", null,
              h("div", { style: { display: "flex", alignItems: "center", gap: 10 } },
                h("span", { style: { fontFamily: FONT_MONO, fontSize: 11, fontWeight: 600, letterSpacing: ".12em",
                  color: "#FFFFFF", background: "#074D47", padding: "3px 9px" } }, plant ? plant.code : ""),
                h("h1", { style: { fontSize: 30, fontWeight: 600, letterSpacing: "-0.02em", lineHeight: 1.05, margin: 0 } },
                  plantFull || (plant ? plant.name : "")),
              ),
              h("div", { style: { fontFamily: FONT_MONO, fontSize: 11, letterSpacing: ".06em", color: "#6B7280", marginTop: 8 } },
                (plant ? plant.name : "") + (plant ? " · " + plant.location : "")),
            ),
          ),
        ),

        // ============ The site ============
        h("div", { "data-screen-label": "Site Scene", style: { position: "relative", background: "#FFFFFF", border: "1px solid #E5E7EB" } },
          h("div", { style: { position: "relative", height: 700, overflow: "hidden" } },
            ready ? h(window.AtlasSiteScene, { plant, derived, selectedId: selected, onSelect: (id) => setSelected(id) }) : null,

            // ============ Asset inspector panel ============
            asset ? h("div", { "data-screen-label": "Asset Inspector", style: {
              position: "absolute", top: 16, right: 16, bottom: 16, width: 348, background: "#FFFFFF",
              border: "1px solid #063F39", zIndex: 25, display: "flex", flexDirection: "column",
              boxShadow: "0 20px 45px rgba(15, 23, 42, 0.08)" } },
              h("div", { style: { display: "flex", alignItems: "flex-start", justifyContent: "space-between",
                gap: 12, padding: "16px 18px 12px", borderBottom: "1px solid #E5E7EB" } },
                h("div", null,
                  h("div", { style: { display: "flex", alignItems: "center", gap: 8 } },
                    h("span", { style: { fontFamily: FONT_MONO, fontSize: 9.5, fontWeight: 600, letterSpacing: ".12em",
                      color: "#FFFFFF", background: "#074D47", padding: "2px 7px" } }, asset.code),
                    h("span", { style: { fontSize: 16, fontWeight: 600, letterSpacing: "-0.01em" } }, asset.name),
                  ),
                  h("div", { style: { fontFamily: FONT_MONO, fontSize: 10, letterSpacing: ".04em", color: "#6B7280", marginTop: 6 } }, asset.subtitle),
                ),
                h("button", { onClick: () => setSelected(null), style: { border: "1px solid #D1D5DB", background: "#FFFFFF",
                  color: "#374151", fontFamily: FONT_MONO, fontSize: 12, width: 26, height: 26, cursor: "pointer",
                  flex: "0 0 auto", lineHeight: 1 } }, "×"),
              ),
              h("div", { style: { display: "flex", flexWrap: "wrap", gap: 6, padding: "10px 18px", borderBottom: "1px solid #F3F4F6" } },
                h("span", { style: { fontFamily: FONT_MONO, fontSize: 8.5, letterSpacing: ".1em", color: "#9CA3AF", alignSelf: "center" } }, "DRIVES"),
                panelDrives.map((pd, i) => h("span", { key: i, style: { fontFamily: FONT_MONO, fontSize: 9, letterSpacing: ".06em",
                  color: "#074D47", background: "#EDF7F5", border: "1px solid #BFE3DC", padding: "3px 8px" } }, pd)),
              ),
              h("div", { style: { flex: 1, overflowY: "auto", padding: "6px 18px 10px" } },
                panelRows.map((pr, i) => h("div", { key: i, style: { display: "flex", flexDirection: "column", gap: 3,
                  padding: "10px 0", borderBottom: "1px solid #F3F4F6" } },
                  h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "baseline", gap: 10 } },
                    h("span", { style: { fontSize: 12.5, fontWeight: 600, color: "#111827" } }, pr.label),
                    h("span", { style: { fontFamily: FONT_MONO, fontSize: 13, fontWeight: 600, color: "#074D47", whiteSpace: "nowrap" } },
                      pr.value, " ", h("span", { style: { fontSize: 9, fontWeight: 400, color: "#9CA3AF" } }, pr.unit)),
                  ),
                  h("div", { style: { fontFamily: FONT_MONO, fontSize: 9.5, color: "#9CA3AF", letterSpacing: ".02em" } }, pr.formula),
                )),
              ),
              h(Hoverable, { tag: "button", onClick: () => onOpenAsset(selected), hover: { background: "#000000" },
                style: { display: "block", width: "auto", textAlign: "center", background: "#074D47", color: "#FFFFFF",
                  border: "none", fontFamily: FONT_MONO, fontSize: 11, fontWeight: 600,
                  letterSpacing: ".1em", padding: "13px 16px", margin: "12px 18px 16px", cursor: "pointer" } }, "OPEN IN EXPLORER ▸"),
            ) : null,
          ),
        ),

        // ============ Footer ============
        h("div", { style: { display: "flex", justifyContent: "space-between", gap: 24, fontFamily: FONT_MONO,
          fontSize: 10, letterSpacing: ".08em", color: "#9CA3AF", flexWrap: "wrap" } },
          h("span", null, "SOURCE — FORM-Sb (BEE PAT) · VALUES RECOMPUTED LIVE BY THE ATLAS FORMULA ENGINE"),
          h("span", null, "DISTRICTS — 01 RAW MATERIALS · 02 MILLING & PYRO · 03 GRINDING & DISPATCH · 04 ENERGY ISLAND"),
        ),
      ),
    );
  }

  window.SiteView = SiteView;
})();
