/* ATLAS — Plant Network view. The front door: every plant site rendered as its own
   isometric diagram card, all in one view. Each card computes that plant's live values
   from the formula engine and previews its site (site-scene.js). Click a card to open
   the full interactive plant site (SiteView) and drill into asset detail. */
(function () {
  "use strict";
  const { useState } = React;
  const h = React.createElement;
  const FONT_MONO = "var(--font-mono)";

  function Hoverable({ tag, hover, style, ...rest }) {
    const [over, setOver] = useState(false);
    return h(tag || "div", 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 Kpi({ label, value, unit, accent }) {
    return h("div", { style: { display: "flex", flexDirection: "column", gap: 3, minWidth: 0 } },
      h("span", { style: { fontFamily: FONT_MONO, fontSize: 8.5, letterSpacing: ".1em", color: "#9CA3AF",
        whiteSpace: "nowrap" } }, label),
      h("div", { style: { display: "flex", alignItems: "baseline", gap: 4 } },
        h("span", { style: { fontFamily: FONT_MONO, fontSize: 16, fontWeight: 600, color: accent ? "#074D47" : "#111827",
          lineHeight: 1, fontFeatureSettings: '"tnum" 1' } }, value),
        h("span", { style: { fontFamily: FONT_MONO, fontSize: 8.5, color: "#9CA3AF", whiteSpace: "nowrap" } }, unit),
      ),
    );
  }

  function PlantCard({ plant, model, onOpen }) {
    const A = window.ATLAS, PL = window.ATLAS_PLANTS;
    const inputs = PL.inputsFor(plant.id, model);
    const derived = A.compute(inputs);
    const head = {};
    A.FINAL_METRICS.forEach((m) => { if (m.headline) head[m.id] = m; });

    // compact, fixed-width labels/units so all four KPIs sit on one line in a 3-up card
    const KPI_SPEC = [
      { id: "thermalSEC", label: "THERMAL SEC", unit: "KCAL/KG", accent: true },
      { id: "elecSEC", label: "ELEC SEC", unit: "KWH/T", accent: true },
      { id: "gei", label: "GEI", unit: "tCO₂/t", accent: true },
    ];
    const kpis = KPI_SPEC.filter((k) => head[k.id]).map((k) => ({
      label: k.label, unit: k.unit, accent: k.accent, value: head[k.id].fmt(derived[k.id]),
    }));
    kpis.push({ label: "CEMENT", value: A.fmtNum(derived.totalCement, 0), unit: "T/YR", accent: false });

    return h(Hoverable, {
      tag: "div", role: "button", tabIndex: 0,
      onClick: () => onOpen(plant.id, null),
      onKeyDown: (e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); onOpen(plant.id, null); } },
      hover: { border: "1px solid #074D47", boxShadow: "0 14px 34px rgba(6, 63, 57, 0.10)", transform: "translateY(-2px)" },
      style: {
        border: "1px solid #E5E7EB", background: "#FFFFFF", display: "flex", flexDirection: "column",
        cursor: "pointer", transition: "border-color .16s ease, box-shadow .16s ease, transform .16s ease",
        minWidth: 0,
      },
    },
      // header
      h("div", { style: { display: "flex", alignItems: "flex-start", justifyContent: "space-between", gap: 12,
        padding: "16px 18px 14px", borderBottom: "1px solid #F3F4F6" } },
        h("div", { style: { minWidth: 0 } },
          h("div", { style: { display: "flex", alignItems: "center", gap: 8 } },
            h("span", { style: { fontSize: 17, fontWeight: 600, letterSpacing: "-0.01em" } }, plant.fullName),
          ),
          h("div", { style: { fontFamily: FONT_MONO, fontSize: 10, letterSpacing: ".04em", color: "#6B7280",
            marginTop: 6, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" } },
            plant.location),
        ),
        h("span", { style: { fontFamily: FONT_MONO, fontSize: 10.5, fontWeight: 600, letterSpacing: ".08em",
          color: "#074D47", whiteSpace: "nowrap", flex: "0 0 auto", marginTop: 4 } }, "OPEN ▸"),
      ),
      // kpi strip — one clean line, evenly distributed
      h("div", { style: { display: "flex", gap: 14, padding: "13px 18px", borderBottom: "1px solid #F3F4F6",
        justifyContent: "space-between", flexWrap: "nowrap" } }, kpis.map((k, i) => h(Kpi, Object.assign({ key: i }, k)))),
      // isometric diagram preview (display-only; the card click opens the full site)
      h("div", { style: { position: "relative", width: "100%", aspectRatio: "952 / 701",
        background: "#FAFBFB", borderTop: "1px solid #F3F4F6", pointerEvents: "none", overflow: "hidden" } },
        h(window.AtlasSiteScene, { plant, derived, selectedId: null, onSelect: () => {} }),
      ),
    );
  }

  function NetworkView({ plants, model, onOpenPlant }) {
    const ready = window.ATLAS && window.ATLAS_PLANTS && window.AtlasSiteScene && window.crystalPolys && window.ATLAS_SITE;
    const list = ready ? plants : [];

    return h("div", { "data-screen-label": "Plant Network", style: {
      flex: 1, minWidth: 0, background: "var(--gray-50)",
      fontFamily: "var(--font-sans, 'IBM Plex Sans', sans-serif)", color: "#000000" } },
      h("div", { style: { maxWidth: 1760, margin: "0 auto", padding: "32px 32px 56px",
        display: "flex", flexDirection: "column", gap: 24 } },

        // gallery grid
        h("div", { style: { display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(430px, 1fr))", gap: 22 } },
          list.map((p) => h(PlantCard, { key: p.id, plant: p, model, onOpen: onOpenPlant })),
        ),

        // footer
        h("div", { style: { display: "flex", justifyContent: "flex-end", gap: 24, fontFamily: FONT_MONO,
          fontSize: 10, letterSpacing: ".08em", color: "#9CA3AF", flexWrap: "wrap" } },
          h("span", null, "CLICK A SITE TO OPEN ITS FULL ISOMETRIC EXPLORER ▸"),
        ),
      ),
    );
  }

  window.NetworkView = NetworkView;
})();
