// Inventories — Pillar 02
// Map of substations + station table.

// Inventory map — embeds the live D3 map with satellite zoom
const InventoryMap = ({ filter, hovered, setHovered, profile }) => {
  if (!profile.map_src) {
    return (
      <div className="map-svg-wrap" style={{minHeight: 660, display: "flex", alignItems: "center", justifyContent: "center", background: "#fafbfc", borderRadius: 12, border: "1px dashed var(--rule)"}}>
        <div style={{textAlign: "center", maxWidth: 460, padding: 32}}>
          <div style={{fontFamily: "JetBrains Mono, monospace", fontSize: 11, color: "var(--fg-3)", fontWeight: 700, letterSpacing: "0.1em", marginBottom: 12}}>NO SITE-LEVEL MAP YET</div>
          <h3 style={{margin: 0, color: "var(--ink-900)", fontSize: 20}}>{profile.name}</h3>
          <p style={{marginTop: 12, fontSize: 14, color: "var(--fg-3)", lineHeight: 1.55}}>{profile.inv_lede}</p>
          {profile.code === "ken" && (
            <div style={{marginTop: 18, padding: 16, background: "#fff", border: "1px solid var(--rule)", borderRadius: 10, textAlign: "left", fontSize: 13}}>
              <div style={{fontWeight: 700, color: "var(--ink-900)", marginBottom: 8}}>Kenya fleet (24 000 kg confirmed)</div>
              {KENYA_INVENTORY.map((k, i) => (
                <div key={i} style={{display: "flex", justifyContent: "space-between", padding: "4px 0", borderBottom: i < KENYA_INVENTORY.length - 1 ? "1px dotted var(--rule)" : "none"}}>
                  <span><b>{k.utility}</b> <span style={{color: "var(--fg-3)"}}>· {k.scope}</span></span>
                  <span className="mono" style={{color: "var(--orange-700)", fontWeight: 700}}>{k.kg.toLocaleString()} kg · {k.pct}%</span>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    );
  }
  return (
    <div className="map-svg-wrap" style={{minHeight: 620, padding: 0}}>
      <iframe src={profile.map_src} title={"Map · " + profile.name}
        style={{width: "100%", height: 660, border: "none", display: "block", background: "#fafbfc"}} />
    </div>
  );
};

// Composition bar
const CompoBar = () => {
  const counts = {
    sf6:      STATIONS.filter(s => s.status === "sf6").length,
    retrofit: STATIONS.filter(s => s.status === "retrofit").length,
    clean:    STATIONS.filter(s => s.status === "clean").length,
    decom:    STATIONS.filter(s => s.status === "decom").length,
  };
  const total = STATIONS.length;
  return (
    <div className="stat-block" style={{gridColumn: "span 2"}}>
      <div className="accent-tile" style={{background: "var(--blue-700)"}}><IconChart size={18} color="#fff"/></div>
      <div className="l" style={{marginTop: 0, fontSize: 13, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--fg-3)"}}>Fleet composition by status</div>
      <div className="compo-bar" style={{marginTop: 14, height: 18}}>
        <div className="compo-seg" style={{width: `${100*counts.sf6/total}%`,      background: "var(--orange)"}}/>
        <div className="compo-seg" style={{width: `${100*counts.retrofit/total}%`, background: "var(--orange-300)"}}/>
        <div className="compo-seg" style={{width: `${100*counts.clean/total}%`,    background: "var(--heat-green)"}}/>
        <div className="compo-seg" style={{width: `${100*counts.decom/total}%`,    background: "var(--fg-3)"}}/>
      </div>
      <div className="compo-legend" style={{marginTop: 14}}>
        <span><span className="dot" style={{background:"var(--orange)"}}></span>Legacy SF₆ · <b>{counts.sf6}</b></span>
        <span><span className="dot" style={{background:"var(--orange-300)"}}></span>Retrofit · <b>{counts.retrofit}</b></span>
        <span><span className="dot" style={{background:"var(--heat-green)"}}></span>SF₆-free · <b>{counts.clean}</b></span>
        <span><span className="dot" style={{background:"var(--fg-3)"}}></span>Decomm. · <b>{counts.decom}</b></span>
      </div>
    </div>
  );
};

// Main inventories pillar
const Inventories = ({ country = 'sen' }) => {
  const profile = COUNTRY_PROFILES[country] || COUNTRY_PROFILES.sen;
  const [filter, setFilter] = React.useState("all");
  const [hovered, setHovered] = React.useState(null);
  const countryRows = React.useMemo(() => {
    if (country === 'all') return STATIONS;
    if (country === 'sen') return STATIONS.filter(s => s.country === 'Senegal');
    if (country === 'ken') return STATIONS.filter(s => s.country === 'Kenya');
    return [];  // Other countries have no per-site data yet
  }, [country]);
  const rows = React.useMemo(
    () => (filter === "all" ? countryRows : countryRows.filter(s => s.status === filter)),
    [filter, countryRows]
  );

  return (
    <>
      <section className="band band-paper pillar-anchor" id="inventories">
        <div className="section-head">
          <div>
            <div className="eyebrow orange"><span className="swatch"></span>Pillar 02 · Inventories &amp; Sites</div>
            <h1 className="headline">
              <span className="num">{profile.stations}</span> substations.
              <br/>
              <span className="em-cyan"><span className="num">{profile.mass_kg.toLocaleString()}</span> kg</span> of SF₆ in service.
            </h1>
            <p className="lede">Live inventory across six operators, joined to the asset register. Each pin represents one gas-insulated bay; tap to drill into nameplate data, leak history and replacement candidate scoring.</p>
          </div>
          <div className="meta">
            <b>Reporting period</b>
            2026 Q2 baseline
            <div className="pill-meta">Verified · Public-source draft</div>
          </div>
        </div>

        <div className="row-4" style={{marginTop: 44}}>
          <div className="stat-block">
            <div className="accent-tile"><IconMap size={18} color="#fff"/></div>
            <div className="n"><span className="num">{profile.stations}</span></div>
            <div className="l">Total <b>gas-insulated substations</b> mapped in the Senegal pilot (Senelec + IPP + OMVS interconnection).</div>
            <div className="delta down">+ 3 new (last 12m)</div>
          </div>
          <div className="stat-block orange">
            <div className="accent-tile"><IconAtom size={18} color="#fff"/></div>
            <div className="n"><span className="num">{profile.mass_kg.toLocaleString()}</span><span className="unit"> kg</span></div>
            <div className="l">Installed <b>SF₆ mass</b> quantified to date. 26 stations pending nameplate verification.</div>
            <div className="delta down">−2.1 % YoY</div>
          </div>
          <div className="stat-block orange">
            <div className="accent-tile"><IconBolt size={18} color="#fff"/></div>
            <div className="n"><span className="num">0.70</span><span className="unit"> %/yr</span></div>
            <div className="l">Fleet-average <b>leakage rate</b>. Best-in-class: 0.21 %/yr · worst single station: 4.8 %/yr.</div>
            <div className="delta down">−0.08 pp YoY</div>
          </div>
          <div className="stat-block">
            <div className="accent-tile" style={{background: "var(--ink-700)"}}><IconChart size={18} color="#fff"/></div>
            <div className="n"><span className="num">14</span><span className="unit"> yrs</span></div>
            <div className="l">Mean <b>fleet age</b>. 64 bays will reach 45-yr design life by 2034 — replacement window.</div>
            <div className="delta up">Aging fleet</div>
          </div>
        </div>
      </section>

      <section className="band band-paper-2">
        <div className="section-head">
          <div>
            <div className="eyebrow"><span className="swatch"></span>Geographic distribution</div>
            <h2 className="section-h">Where the fleet sits — and what's already moved.</h2>
            <p className="lede">Filter to focus the map and the inventory table together. Pulsing pins flag <b>legacy SF₆</b> assets — the active perimeter for the next phase of replacement.</p>
          </div>
          <div className="meta">
            <b>Coverage</b>
            {profile.short} · {profile.stations} substations · {profile.mass_kg.toLocaleString()} kg SF₆
          </div>
        </div>

        <div className="map-shell">
          {/* Map */}
          <div className="map-card">
            <div className="map-head">
              <div>
                <h3>Transformation station network</h3>
                <div className="sub">{profile.name}</div>
              </div>
              <div style={{display: "flex", gap: 8}}>
                {FILTER_CHIPS.slice(0, 4).map(c => (
                  <button
                    key={c.id}
                    className={`chip-btn ${filter === c.id ? "active" : ""}`}
                    onClick={() => setFilter(c.id)}
                  >
                    {c.label}<span className="count">{c.count}</span>
                  </button>
                ))}
              </div>
            </div>
            <InventoryMap filter={filter} hovered={hovered} setHovered={setHovered} profile={profile} />
            <div className="map-legend">
              <span className="legend-dot"><span className="d"></span>Legacy SF₆ (pulsing)</span>
              <span className="legend-dot"><span className="d amber"></span>Retrofit candidate</span>
              <span className="legend-dot"><span className="d green"></span>SF₆-free in service</span>
              <span className="legend-dot"><span className="d muted"></span>Decommissioned</span>
              <span style={{marginLeft: "auto", color: "var(--fg-3)", fontFamily: "JetBrains Mono, monospace", fontSize: 11}}>WGS84 · ESRI imagery © Maxar</span>
            </div>
          </div>

          {/* Side panel: composition + table preview */}
          <div style={{display: "flex", flexDirection: "column", gap: 24}}>
            <div className="row-3" style={{marginTop: 0, gridTemplateColumns: "1fr 1fr", gap: 16}}>
              <CompoBar />
            </div>

            <div className="table-card" style={{flex: 1}}>
              <div className="table-head">
                <h3>Station inventory · {rows.length}</h3>
                <a className="row-link" href="#" onClick={e => e.preventDefault()}>Export CSV</a>
              </div>
              <div className="table-scroll" style={{maxHeight: 420}}>
                <table className="inv">
                  <thead>
                    <tr>
                      <th>Station</th>
                      <th style={{textAlign: "right"}}>kV</th>
                      <th style={{textAlign: "right"}}>SF₆ (kg)</th>
                      <th>Status</th>
                    </tr>
                  </thead>
                  <tbody>
                    {rows.slice(0, 12).map(s => {
                      const meta = STATUS_LABEL[s.status];
                      return (
                        <tr key={s.id}
                            className={hovered === s.id ? "row-hl" : ""}
                            onMouseEnter={() => setHovered(s.id)}
                            onMouseLeave={() => setHovered(null)}>
                          <td className="name">
                            <div><b>{s.name}</b></div>
                            <div className="sub mono">{s.id} · {s.op}</div>
                          </td>
                          <td className="num" style={{textAlign: "right"}}>{s.voltage}</td>
                          <td className="num" style={{textAlign: "right"}}>{s.mass}</td>
                          <td><span className={`status-pill ${meta.cls}`}><span className="d"></span>{meta.label}</span></td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>

        {/* Full inventory table below */}
        <div className="table-card" style={{marginTop: 32}}>
          <div className="table-head">
            <h3>Full inventory · gas-insulated assets</h3>
            <div className="filter-chips">
              {FILTER_CHIPS.map(c => (
                <button
                  key={c.id}
                  className={`chip-btn ${filter === c.id ? "active" : ""}`}
                  onClick={() => setFilter(c.id)}
                >
                  {c.label}<span className="count">{c.count}</span>
                </button>
              ))}
            </div>
          </div>
          <div style={{overflowX: "auto"}}>
            <table className="inv">
              <thead>
                <tr>
                  <th>Station ID</th>
                  <th>Name &amp; operator</th>
                  <th>Region</th>
                  <th style={{textAlign: "right"}}>Voltage</th>
                  <th style={{textAlign: "right"}}>SF₆ mass</th>
                  <th style={{textAlign: "right"}} title="* = estimated · ◦ = planned/under construction">In service</th>
                  <th>Status</th>
                  <th style={{textAlign: "right"}}>Next action</th>
                </tr>
              </thead>
              <tbody>
                {rows.map(s => {
                  const meta = STATUS_LABEL[s.status];
                  const action = {
                    sf6:      "Replacement assessment",
                    retrofit: "Gas conversion pilot",
                    clean:    "In service",
                    decom:    "Recovery report filed",
                  }[s.status];
                  return (
                    <tr key={s.id}>
                      <td className="mono">{s.id}</td>
                      <td className="name">
                        <div><b>{s.name}</b></div>
                        <div className="sub">{s.op}</div>
                      </td>
                      <td>{s.region}</td>
                      <td className="num" style={{textAlign: "right"}}>{s.voltage} kV</td>
                      <td className="num" style={{textAlign: "right"}}>{s.mass} kg</td>
                      <td className="num" style={{textAlign: "right"}}>{s.year}</td>
                      <td><span className={`status-pill ${meta.cls}`}><span className="d"></span>{meta.label}</span></td>
                      <td className="row-link" style={{textAlign: "right"}}>{action}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </section>
    </>
  );
};

window.Inventories = Inventories;
