/* ============================================================
   Enterprise mode — preset scenarios + portfolio dashboard
   ============================================================ */
/* global React, EnterpriseMapView, Icon, BarChart, Histogram, AzimuthRose, Sparkline */
const { useState: useStateE, useMemo: useMemoE, useEffect: useEffectE } = React;
const utilsE = window.LEPTON_UTILS;

function ScenarioCards({ scenarios, activeId, onSelect }) {
  return (
    <div className="scenarios">
      <div className="row-flex" style={{ gap: 10 }}>
        <Icon name="diamond" size={13} color="#57574f"/>
        <div>
          <div className="t-label" style={{ marginBottom: 2 }}>Portfolio scenario</div>
          <div className="t-small">Pre-warmed · zero live API calls</div>
        </div>
      </div>
      <div className="scenarios-cards">
        {scenarios.map(s => (
          <div key={s.id} className={`scenario-card ${activeId === s.id ? "is-active" : ""}`} onClick={() => onSelect(s.id)}>
            <div className="icon">
              <Icon name={s.icon === "warehouse" ? "warehouse" : s.icon === "rwa" ? "people" : "home"} size={15} color="currentColor"/>
            </div>
            <div>
              <div className="ti">{s.title}</div>
              <div className="ss">{s.subtitle} · {s.partner}</div>
            </div>
            <div className="ct">{s.count} bldgs</div>
          </div>
        ))}
      </div>
      <div className="row-flex" style={{ gap: 6 }}>
        <span className="tag">Cached · 100%</span>
        <button className="btn"><Icon name="external" size={11} color="currentColor"/> Export CSV</button>
      </div>
    </div>
  );
}

function KpiStrip({ scenario }) {
  const buildings = scenario.buildings;
  const totalKwp = buildings.reduce((s, b) => s + b.kWp, 0);
  const totalGwh = buildings.reduce((s, b) => s + b.yearlyKwh, 0) / 1e6;
  const totalCo2 = buildings.reduce((s, b) => s + b.co2, 0);
  const totalCapex = buildings.reduce((s, b) => s + b.capex, 0);
  const eligible = scenario.suryaGharEligible ? buildings.filter(b => b.kWp <= 10).length : 0;
  const avgPayback = (buildings.reduce((s, b) => s + b.payback, 0) / buildings.length).toFixed(1);

  // sparklines per kpi — sorted buildings by metric
  const kWpSeries = [...buildings].sort((a, b) => a.kWp - b.kWp).map(b => b.kWp);
  const paybackSeries = [...buildings].sort((a, b) => a.payback - b.payback).map(b => b.payback);

  return (
    <div className="kpi-strip">
      <div className="kpi">
        <div className="k">Total installable</div>
        <div className="v">{utilsE.NUM(totalKwp, 0)}<span className="u">kWp</span></div>
        <div className="d"><span className="pos">●</span> {buildings.length} buildings curated</div>
        <div className="micro"><Sparkline data={kWpSeries} height={22} color="#0d0d0c"/></div>
      </div>
      <div className="kpi">
        <div className="k">Aggregate generation</div>
        <div className="v">{totalGwh.toFixed(2)}<span className="u">GWh/yr</span></div>
        <div className="d">{utilsE.NUM(Math.round(totalGwh * 1000), 0)} MWh · 25y</div>
      </div>
      <div className="kpi">
        <div className="k">CO₂ offset / yr</div>
        <div className="v">{(totalCo2 / 1000).toFixed(1)}<span className="u">t</span></div>
        <div className="d">{utilsE.NUM(utilsE.treesEquivalent(totalCo2))} trees equiv.</div>
      </div>
      <div className="kpi">
        <div className="k">CAPEX opportunity</div>
        <div className="v">{utilsE.INR(totalCapex)}</div>
        <div className="d">avg ₹{Math.round(totalCapex/buildings.length/1000)}k / site</div>
      </div>
      <div className="kpi">
        <div className="k">Avg payback</div>
        <div className="v">{avgPayback}<span className="u">yrs</span></div>
        <div className="d"><Sparkline data={paybackSeries} height={22} color="#0d0d0c"/></div>
      </div>
      <div className="kpi">
        <div className="k">Surya Ghar eligible</div>
        <div className="v">{scenario.suryaGharEligible ? `${Math.round(eligible/buildings.length*100)}%` : "—"}</div>
        <div className="d" style={{ color: scenario.suryaGharEligible ? "var(--ink-3)" : "var(--accent-strong)" }}>
          {scenario.suryaGharEligible ? `${eligible}/${buildings.length} residential` : "non-residential scenario"}
        </div>
      </div>
    </div>
  );
}

function RankedTable({ scenario, selectedId, onSelect, hoveredId, onHover, sort, setSort, colorMode }) {
  let rows = [...scenario.buildings];
  rows.sort((a, b) => {
    const dir = sort.dir === "asc" ? 1 : -1;
    return (a[sort.key] - b[sort.key]) * dir;
  });

  const maxKwp = Math.max(...rows.map(b => b.kWp));

  const headerCell = (key, label, num = false) => (
    <th
      className={num ? "num" : ""}
      style={{ cursor: "pointer", userSelect: "none" }}
      onClick={() => setSort({ key, dir: sort.key === key && sort.dir === "desc" ? "asc" : "desc" })}
    >
      {label}
      <span style={{ opacity: sort.key === key ? 1 : 0.2, marginLeft: 4 }}>
        {sort.key === key ? (sort.dir === "asc" ? "↑" : "↓") : "↕"}
      </span>
    </th>
  );

  return (
    <div className="ranked-table-wrap">
      <table className="ranked-table">
        <thead>
          <tr>
            <th>building</th>
            <th>cluster</th>
            {headerCell("kWp", "kWp", true)}
            {headerCell("yearlyKwh", "MWh / yr", true)}
            {headerCell("payback", "payback", true)}
            {headerCell("co2", "CO₂ t/yr", true)}
            {headerCell("suitability", "fit", true)}
            <th>quality</th>
          </tr>
        </thead>
        <tbody>
          {rows.slice(0, 60).map(b => (
            <tr
              key={b.id}
              className={selectedId === b.id ? "is-selected" : ""}
              onMouseEnter={() => onHover(b.id)}
              onMouseLeave={() => onHover(null)}
              onClick={() => onSelect(b.id)}
            >
              <td><span className="b-id">{b.id}</span></td>
              <td><span className="sublabel">{b.cluster}</span> {b.clusterName.split(" ")[0]}</td>
              <td className="num">
                <span className="bar" style={{ width: (b.kWp / maxKwp) * 28 }}></span>
                {b.kWp.toFixed(1)}
              </td>
              <td className="num">{(b.yearlyKwh / 1000).toFixed(1)}</td>
              <td className={"num " + (b.payback <= 4.5 ? "ok" : b.payback > 6 ? "warn" : "")}>{b.payback}</td>
              <td className="num">{(b.co2 / 1000).toFixed(1)}</td>
              <td className="num">{b.suitability}</td>
              <td><span className={"tag " + (b.imageryQuality === "BASE" ? "" : "accent")}>{b.imageryQuality}</span></td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function ChartsRow({ scenario }) {
  // kWp histogram
  const kwps = scenario.buildings.map(b => b.kWp);
  const max = Math.max(...kwps);
  const binCount = 10;
  const bins = new Array(binCount).fill(0);
  const binLabels = [];
  for (let i = 0; i < binCount; i++) {
    const lo = (max / binCount) * i;
    const hi = (max / binCount) * (i + 1);
    binLabels.push(`${Math.round(lo)}`);
  }
  kwps.forEach(v => {
    const b = Math.min(binCount - 1, Math.floor(v / (max / binCount)));
    bins[b]++;
  });
  const histData = bins.map((v, i) => ({ label: binLabels[i], value: v }));

  return (
    <div className="charts-row">
      <div className="chart-card">
        <div className="chart-head">
          <div>
            <div className="t-label">kWp distribution</div>
            <div className="t-small">peak at {binLabels[bins.indexOf(Math.max(...bins))]} kWp</div>
          </div>
          <div className="t-tag">n={scenario.buildings.length}</div>
        </div>
        <Histogram buckets={histData} height={130} />
      </div>
      <div className="chart-card">
        <div className="chart-head">
          <div>
            <div className="t-label">Azimuth rose</div>
            <div className="t-small">south-bias = better yield (north India)</div>
          </div>
          <div className="t-tag">flat-roof excluded</div>
        </div>
        <AzimuthRose buildings={scenario.buildings} height={130} />
      </div>
    </div>
  );
}

/* ============================================================
   Enterprise main
   ============================================================ */
function EnterpriseMode() {
  const data = window.useLeptonData();
  const SCENARIOS = data.SCENARIOS;
  const [scenarioId, setScenarioId] = useStateE("mundra");
  const [colorMode, setColorMode] = useStateE("kwp");
  const [selectedId, setSelectedId] = useStateE(null);
  const [hoveredId, setHoveredId] = useStateE(null);
  const [sort, setSort] = useStateE({ key: "kWp", dir: "desc" });

  // Lazy-load full scenario detail (buildings[]) on selection.
  useEffectE(() => {
    if (scenarioId && !data.SCENARIO_DETAILS[scenarioId] && data.loading.scenario !== scenarioId) {
      window.LEPTON_LOAD.loadScenario(scenarioId).catch(() => {});
    }
  }, [scenarioId, data.SCENARIO_DETAILS[scenarioId], data.loading.scenario]);

  const summary = SCENARIOS.find(s => s.id === scenarioId);
  const detail = data.SCENARIO_DETAILS[scenarioId];
  const scenario = detail || summary;

  // pick a default selected once scenario detail loads
  useEffectE(() => {
    if (detail && detail.buildings && detail.buildings.length) {
      const sorted = [...detail.buildings].sort((a, b) => b.kWp - a.kWp);
      setSelectedId(sorted[0].id);
    }
  }, [scenarioId, !!detail]);

  if (!SCENARIOS.length) {
    return (
      <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center" }}>
        <div className="t-small">Loading scenarios…</div>
      </div>
    );
  }
  if (!scenario || !scenario.buildings) {
    return (
      <div className="enterprise">
        <ScenarioCards scenarios={SCENARIOS} activeId={scenarioId} onSelect={setScenarioId} />
        <div style={{ padding: 40, textAlign: "center" }}>
          <div className="t-small">
            {data.loading.scenario === scenarioId
              ? `Pre-warming ${summary?.title} (${summary?.count || ""} buildings)… first run only.`
              : (data.error.scenario || "Loading scenario…")}
          </div>
        </div>
      </div>
    );
  }

  const selected = scenario.buildings.find(b => b.id === selectedId);

  return (
    <div className="enterprise">
      <ScenarioCards scenarios={SCENARIOS} activeId={scenarioId} onSelect={setScenarioId} />
      <KpiStrip scenario={scenario}/>
      <div className="entgrid">
        <div className="entgrid-map">
          <EnterpriseMapView
            scenario={scenario}
            colorMode={colorMode}
            selectedId={selectedId}
            onSelect={setSelectedId}
            hoveredId={hoveredId}
            onHover={setHoveredId}
          />
          {/* color mode controls */}
          <div style={{ position: "absolute", top: 12, left: 12, zIndex: 1000, display: "flex", gap: 8, alignItems: "center" }}>
            <div style={{
              background: "var(--bg-elev)", border: "1px solid var(--line-strong)", borderRadius: 7,
              padding: "6px 10px", display: "flex", gap: 8, alignItems: "center"
            }}>
              <span className="t-label" style={{ color: "var(--ink-3)" }}>Color by</span>
              <div className="seg">
                <button className={colorMode === "kwp" ? "is-active" : ""} onClick={() => setColorMode("kwp")}>kWp</button>
                <button className={colorMode === "payback" ? "is-active" : ""} onClick={() => setColorMode("payback")}>Payback</button>
                <button className={colorMode === "suitability" ? "is-active" : ""} onClick={() => setColorMode("suitability")}>Suitability</button>
              </div>
            </div>
          </div>
          {/* Legend */}
          <div className="maplegend" style={{ top: 12, right: 12 }}>
            <div className="head">{colorMode === "kwp" ? "kWp" : colorMode === "payback" ? "Payback (yrs)" : "Suitability"}</div>
            <div className="ramp"></div>
            <div className="axis">
              <span>{colorMode === "payback" ? "long" : "low"}</span>
              <span>{colorMode === "payback" ? "short" : "high"}</span>
            </div>
            <div style={{ marginTop: 8, fontSize: 10.5, color: "var(--ink-3)", fontFamily: "var(--font-mono)" }}>
              {scenario.buildings.length} buildings · BASE quality
            </div>
          </div>
          {/* selected building inspector */}
          {selected && (
            <div style={{ position: "absolute", left: 12, bottom: 14, zIndex: 1000, width: 260 }}>
              <div className="bldg-popup">
                <div className="h">{selected.id} <span style={{ color: "var(--ink-3)", fontWeight: 400 }}>· {selected.clusterName}</span></div>
                <div className="row"><span>kWp</span><span className="v">{selected.kWp}</span></div>
                <div className="row"><span>annual</span><span className="v">{(selected.yearlyKwh/1000).toFixed(2)} MWh</span></div>
                <div className="row"><span>azimuth · tilt</span><span className="v">{selected.azimuth}° · {selected.tilt}°</span></div>
                <div className="row"><span>payback</span><span className="v">{selected.payback} yrs</span></div>
                <div className="row"><span>CAPEX</span><span className="v">{utilsE.INR(selected.capex)}</span></div>
                <div className="row"><span>area</span><span className="v">{selected.areaM2} m²</span></div>
                <button className="btn open" style={{ width: "100%", justifyContent: "center" }}>
                  Open building view <Icon name="chevron" size={11} color="currentColor"/>
                </button>
              </div>
            </div>
          )}
          <div className="mapcorner">
            <div className="item">{scenario.center[0].toFixed(4)}°N · {scenario.center[1].toFixed(4)}°E</div>
            <div className="item">{scenario.tariffNote} · ₹{scenario.tariff.toFixed(2)}/kWh</div>
          </div>
        </div>

        <div className="entgrid-right">
          <div style={{ padding: "12px 16px 6px", borderBottom: "1px solid var(--line)" }}>
            <div className="sp-section-head">
              <div className="t-label">Ranked roofs · click to drop into homeowner view</div>
              <div className="row-flex" style={{ gap: 6 }}>
                <span className="tag">{scenario.buildings.length} rows</span>
                <span className="tag">sort {sort.key} {sort.dir}</span>
              </div>
            </div>
          </div>
          <RankedTable
            scenario={scenario}
            selectedId={selectedId}
            onSelect={setSelectedId}
            hoveredId={hoveredId}
            onHover={setHoveredId}
            sort={sort}
            setSort={setSort}
            colorMode={colorMode}
          />
          <ChartsRow scenario={scenario}/>
        </div>
      </div>
    </div>
  );
}

window.EnterpriseMode = EnterpriseMode;
