// ValueChainView.jsx - Energy Ecosystem Map (schematic diagram)
// Static schematic that mirrors the GGC/GEA whole-energy-ecosystem reference slide.
// Three bands stacked top-to-bottom:
//   1. Influencers - organisation archetypes, coloured to match the Global
//      Initiatives Map (NetworkView) legend.
//   2. Barriers - cross-cutting barriers that influencer initiatives address.
//   3. Energy Ecosystem - physical generation → transmission → distribution →
//      demand flow, plus decentralised RES, cross-cutting tech/grid layers,
//      and policy + commercial-finance bars at the bottom.
// Energy-ecosystem nodes are colour-coded by pillar (Energy access =
// yellow, Grid modernization = green dashed). Click any node for a popup.
// Click a pillar card in the legend to highlight matching ecosystem nodes.
//
// IIFE-wrapped: babel-standalone does NOT actually give each <script> its own
// scope, so identically-named top-level consts in ValueChainIndiaView.jsx
// would clobber the ones declared here. Wrapping each view in an IIFE makes
// the module-level constants truly local.

(function () {
const { useState: useStateVCM } = React;

// ── Layout constants ─────────────────────────────────────────────────────────
const W = 1280;
const H = 840;

// Vertical band geometry.
const Y_INF_BAND_BOT  = 120;   // influencers band: 0 → 120
const Y_BAR_BAND_TOP  = 145;   // barriers band:    145 → 215
const Y_BAR_BAND_BOT  = 215;
const Y_ES_BAND_TOP   = 245;   // energy ecosystem band: 245 → H

// Left-rail width - kept identical across all three bands so the header
// labels line up vertically (Influencers, Barriers, Energy Ecosystem).
const RAIL_W = 180;

// pillar: 'grids' | 'powering' | 'both' (omitted for influencers - they're
// classified by archetype, coloured to match the Global Initiatives Map legend)
const NODES = {
  // Influencers band ───────────────────────────────────────────────────────
  mdb:          { x:  195, y:  30, w: 140, h: 60, label: 'MDB, IFI, or DFI',                              archetype: 'MDB/ IFI / DFI',                                 band: 'influencers' },
  igo:          { x:  345, y:  30, w: 170, h: 60, label: 'Intergovernmental\norganization (IGO)',   archetype: 'Intergovernmental organization (IGO)',     band: 'influencers' },
  bilateral:    { x:  525, y:  30, w: 170, h: 60, label: 'Bilateral development\nagency',           archetype: 'Bilateral development agency',             band: 'influencers' },
  ngo:          { x:  705, y:  30, w: 180, h: 60, label: 'Non-Governmental\nOrganization (NGO)',    archetype: 'NGO',                                      band: 'influencers' },
  coalition:    { x:  895, y:  30, w: 180, h: 60, label: 'Coalition or multi-\nstakeholder platform', archetype: 'Coalition or multi-stakeholder platform', band: 'influencers' },
  philanthropies: { x: 1085, y:  30, w: 170, h: 60, label: 'Philanthropies',                         archetype: 'Philanthropic foundation',                 band: 'influencers' },

  // Barriers band - 5 equal-width boxes across the same span as the influencers row.
  b_finance:    { x:  195, y: 156, w: 180, h: 48, label: 'Finance',                    band: 'barriers', barrier: 'Finance' },
  b_policy:     { x:  415, y: 156, w: 180, h: 48, label: 'Policy &\nregulation',       band: 'barriers', barrier: 'Policy & regulation' },
  b_tech:       { x:  635, y: 156, w: 180, h: 48, label: 'Technology',                 band: 'barriers', barrier: 'Technology' },
  b_skills:     { x:  855, y: 156, w: 180, h: 48, label: 'Skills &\ncapacity',         band: 'barriers', barrier: 'Skills & capacity' },
  b_awareness:  { x: 1075, y: 156, w: 180, h: 48, label: 'Awareness &\ncoordination',  band: 'barriers', barrier: 'Awareness & coordination' },

  // Main horizontal flow (Generation → Transmission → Distribution → Demand)
  generation:   { x:  200, y:  320, w: 150, h: 56, label: 'Generation',     pillar: 'grids' },
  transmission: { x:  390, y:  320, w: 150, h: 56, label: 'Transmission',   pillar: 'grids' },
  distribution: { x:  580, y:  320, w: 150, h: 56, label: 'Distribution',   pillar: 'grids' },
  demand:       { x:  770, y:  320, w: 150, h: 56, label: 'Demand',         pillar: 'powering' },

  // Decentralised RES (below distribution)
  decentralised:{ x:  570, y:  430, w: 170, h: 56, label: 'Decentralised RES', pillar: 'both' },

  // Demand sub-segments (vertical column right of Demand)
  agriculture:  { x: 1020, y:  268, w: 170, h: 54, label: 'Agriculture',     pillar: 'powering' },
  industry:     { x: 1020, y:  330, w: 170, h: 54, label: 'Industry',        pillar: 'powering' },
  transport:    { x: 1020, y:  392, w: 170, h: 54, label: 'Transport',       pillar: 'powering' },
  households:   { x: 1020, y:  454, w: 170, h: 62, label: 'Households &\nCooking', pillar: 'powering' },
  other:        { x: 1020, y:  524, w: 170, h: 54, label: 'Services &\nother', pillar: 'powering' },

  // Cross-cutting bars (full-ecosystem horizontals, with arrows extending left/right)
  storage:      { x:  570, y:  570, w: 170, h: 60, label: 'Grid flexibility &\nenergy storage',    pillar: 'grids' },
  digital:      { x:  770, y:  570, w: 170, h: 60, label: 'Grid digitalisation &\ndata providers', pillar: 'grids' },
  tech:         { x:  670, y:  650, w: 240, h: 44, label: 'Tech providers & manufacturers',        pillar: 'both' },

  // Bottom full-width bars
  policymakers:     { x:  200, y:  710, w: 1050, h: 38, label: 'Policymakers & regulators',           band: 'ecosystem-bar' },
  commercial_banks: { x:  200, y:  760, w: 1050, h: 38, label: 'Commercial banks and private finance', band: 'ecosystem-bar' },
};

// Barrier palette + brief explainers. All barriers now share a single neutral
// dark-green so the row doesn't compete for attention with the ecosystem flow.
const BARRIER_FILL = '#1f6a3f';
const BARRIER_COLORS = {
  'Finance':                  BARRIER_FILL,
  'Policy & regulation':      BARRIER_FILL,
  'Technology':               BARRIER_FILL,
  'Skills & capacity':        BARRIER_FILL,
  'Awareness & coordination': BARRIER_FILL,
};
const BARRIER_EXPLAINERS = {
  'Finance':                  'High capital costs, perceived risk and limited concessional or local-currency finance constrain investment across the energy ecosystem.',
  'Policy & regulation':      'Unclear tariffs, weak regulatory frameworks, slow permitting and unstable policy signals delay project development and deter private capital.',
  'Technology':               'Limited local supply, performance uncertainty and integration challenges restrict deployment of clean energy solutions at scale.',
  'Skills & capacity':        'Shortages of trained technicians, engineers and institutional capacity hold back deployment and long-term operations & maintenance.',
  'Awareness & coordination': 'Fragmented stakeholders, limited data sharing and low end-user awareness keep proven solutions from scaling.',
};

// Influencer archetype palette - mirrors the Global Initiatives Map (NetworkView) legend.
const LEGEND_COLORS = {
  'MDB/ IFI':                                '#2a6a86',
  'Bilateral development agency':            '#aa6227',
  'Intergovernmental organisation (IGO)':    '#8c5983',
  'Coalition or multi-stakeholder platform': '#2e8055',
  'NGO':                                     '#fdce07',
  'Research & Academic institution':         '#8bcdd2',
  'Philanthropic foundation':                '#0e2c66',
};

// Pick readable text color against a hex background (yellow → dark, others → light).
function isLightHex(hex) {
  if (!hex || hex[0] !== '#') return false;
  const c = hex.replace('#', '');
  const r = parseInt(c.substr(0, 2), 16);
  const g = parseInt(c.substr(2, 2), 16);
  const b = parseInt(c.substr(4, 2), 16);
  return (0.299 * r + 0.587 * g + 0.114 * b) > 160;
}

// Lorem ipsum fallback - used only when a description hasn't been provided yet.
const LOREM = 'Description coming soon.';

// Real descriptions per node id (see Global Initiatives Atlas website-copy doc).
const NODE_DESCRIPTIONS = {
  mdb:          'Treaty-based multilateral institutions mandated to support economic development and poverty reduction through financing, technical expertise, and policy engagement.',
  igo:          'Formal intergovernmental institutions created by three or more sovereign states through treaties or international agreements to pursue shared objectives.',
  bilateral:    'A national development agency that delivers official development assistance to partner countries through grants, concessional finance, and technical cooperation.',
  ngo:          'An independent non-profit organization established to pursue public-benefit objectives, including development, humanitarian aid, advocacy, and environmental protection.',
  coalition:    'A formally convened initiative that brings together diverse actors, including governments, international organizations, the private sector, and civil society, to advance a shared agenda through voluntary cooperation rather than binding legal obligations.',
  philanthropies: 'Independent non-profit foundations that deploy grant capital, programme-related investments, and convening power to advance public-benefit objectives - including private and corporate foundations, family offices, and donor-advised funds.',

  generation:   'The first stage of the energy value chain, where energy sources such as fossil fuels, nuclear, solar, wind, and hydropower are converted into usable electricity.',
  transmission: 'The long-distance, high-voltage transport of electricity from generation sources to demand centres or distribution networks.',
  distribution: 'The lower-voltage stage of the electricity supply chain, where power from transmission networks is stepped down and delivered to end consumers.',
  demand:       'The consumption of electricity by end users across households, industry, commercial services, agriculture, and transport, shaping the volume, timing, and quality of supply required from the power system.',
  decentralised:'Off-grid or mini-grid electricity systems that generate power from renewable sources (e.g., solar, wind, or small-scale hydropower) at or near the point of consumption, with limited or no connection to the central grid.',

  agriculture:  'The consumption of energy within the agricultural sector to power irrigation pumps, post-harvest processing equipment, cold storage, and other farm operations.',
  industry:     'Energy consumption by industrial sectors, typically involving large volumes of electricity and thermal energy for machinery, motors, furnaces, and chemical processes.',
  transport:    'Energy consumed to move people and goods by road, rail, air, and sea, currently dominated by liquid fossil fuels but increasingly shifting toward electrification, green hydrogen, and sustainable aviation and maritime fuels.',
  households:   'The energy used in residential settings for lighting, appliances, space heating and cooling, water heating, and cooking.',
  other:        'Energy consumed in the commercial and public services sector, including offices, schools, hospitals, retail, hospitality, and street lighting, as well as residual demand categories not classified elsewhere.',

  policymakers: 'The governmental and statutory bodies responsible for designing and overseeing the legal, regulatory, and institutional framework within which the energy system operates, including energy ministries, independent regulatory commissions, and planning authorities.',
  storage:      'The technologies and operational mechanisms that enable electricity grids to balance supply and demand in real time, maintain system stability, and integrate high shares of variable renewable energy, including battery storage, pumped hydro, demand response, and flexible thermal generation.',
  digital:      'The deployment of digital technologies across generation, transmission, and distribution networks to enable real-time monitoring, automated control, predictive maintenance, and improved system efficiency.',
  tech:         'Companies that design, manufacture, and supply the equipment and technologies used across the energy value chain, including generation technologies, transmission and distribution infrastructure, and end-use equipment such as pumps, appliances, motors, and industrial processing systems.',
  commercial_banks: 'Private financial institutions that mobilise and deploy capital for energy projects, including commercial and investment banks, insurers, pension funds, institutional investors, and private equity and debt funds.',
};

// Sub-categories surfaced under specific Energy Ecosystem nodes (Andrea,
// 2026-05-28). Rendered as labelled sub-boxes inside the node's detail modal.
const NODE_SUBBOXES = {
  policymakers: {
    label: 'Including',
    items: ['Planning', 'Market design', 'Tariffs', 'Standards', 'Incentives'],
  },
  commercial_banks: {
    label: 'Including',
    items: ['Equity providers', 'Pension funds', 'Insurance'],
  },
};

// Pillar palette (matches landing page tokens)
const PILLAR_YELLOW = '#fdce07';   // --solar-yellow
const PILLAR_GREEN  = '#84c98f';   // --mint-green
// Dark-theme palette for the schematic
const BG_BAND_LIGHT = '#1a3a28';   // --lp-bg-card  (Influencers band fill)
const BG_BAND_DEEP  = '#0a1f12';   // --lp-bg-deep  (label strip)
const BG_PANEL_INNER = '#0c5d44';  // --panel-2     (inner content panel)
const NODE_FILL      = '#285a45';  // --fg-90       (muted node fill)
const NODE_FILL_INFL = '#1f4530';  // --lp-bg-hover (influencer node fill, slightly different)
const TEXT_LIGHT     = '#e8f5ee';  // --lp-text
const TEXT_DIM       = '#aed6bc';  // --lp-text2
const ARROW_COLOR    = '#5DCAA5';  // --lp-green
const PANEL_BORDER   = 'rgba(132,201,143,0.32)';

// ── Helpers ─────────────────────────────────────────────────────────────────
function centerOf(n) { return { x: n.x + n.w / 2, y: n.y + n.h / 2 }; }
function rightMid(n) { return { x: n.x + n.w,    y: n.y + n.h / 2 }; }
function leftMid (n) { return { x: n.x,          y: n.y + n.h / 2 }; }
function topMid  (n) { return { x: n.x + n.w/2,  y: n.y         }; }
function bottomMid(n){ return { x: n.x + n.w/2,  y: n.y + n.h   }; }

function ValueChainView({ setActiveView }) {
  const [selected, setSelected] = useStateVCM(null);
  const [activePillars, setActivePillars] = useStateVCM([]);
  const [bandHelp, setBandHelp] = useStateVCM(null);

  // Placeholder copy for the per-band explainer popovers. Replace with the
  // doc's band-level text when it's ready.
  const BAND_HELP = {
    influencers: {
      title: 'Influencers',
      body: 'Organizations that shape the energy ecosystem from outside the value chain - MDBs/IFIs/DFIs, intergovernmental organizations, bilateral development agencies, NGOs and coalitions. They direct funding, set policy, and coordinate action.',
    },
    barriers: {
      title: 'Barriers focused on',
      body: 'Cross-cutting obstacles that the influencer organizations address through their programmes - finance gaps, regulatory uncertainty, technology readiness, skills shortages, and awareness/coordination breakdowns.',
    },
    ecosystem: {
      title: 'Energy ecosystem',
      body: 'The physical energy ecosystem itself - generation, transmission, distribution and end-use demand, together with decentralised RES, the cross-cutting tech and storage layers, and the policy and finance bars at the foundation.',
    },
  };

  const togglePillar = (p) => {
    setActivePillars(activePillars.includes(p)
      ? activePillars.filter(x => x !== p)
      : [...activePillars, p]);
  };

  const matchesActive = (n) => {
    if (!activePillars.length) return true;
    if (n.band === 'influencers' || n.band === 'barriers' || n.band === 'ecosystem-bar') return true; // not pillar-coded
    if (n.pillar === 'both') return activePillars.includes('grids') || activePillars.includes('powering');
    return activePillars.includes(n.pillar);
  };

  const renderNode = (id) => {
    const n = NODES[id];
    const dim = activePillars.length > 0 && !matchesActive(n);
    const lines = n.label.split('\n');
    const isInfluencer = n.band === 'influencers';
    const isBarrier    = n.band === 'barriers';
    const isEcoBar     = n.band === 'ecosystem-bar';

    let fill, stroke, strokeDash, strokeWidth, textColor, drawOuterBoth, fontSize;
    if (isInfluencer) {
      fill = (n.archetype && LEGEND_COLORS[n.archetype]) || NODE_FILL_INFL;
      stroke = 'rgba(0,0,0,0.25)';
      strokeDash = undefined;
      strokeWidth = 1;
      textColor = isLightHex(fill) ? '#1a1a1a' : TEXT_LIGHT;
      drawOuterBoth = false;
      fontSize = 14;
    } else if (isBarrier) {
      fill = BARRIER_COLORS[n.barrier] || BARRIER_FILL;
      stroke = 'rgba(255,255,255,0.18)';
      strokeDash = undefined;
      strokeWidth = 1;
      textColor = TEXT_LIGHT;
      drawOuterBoth = false;
      fontSize = 12.5;
    } else if (isEcoBar) {
      fill = NODE_FILL_INFL;
      stroke = 'rgba(255,255,255,0.20)';
      strokeDash = undefined;
      strokeWidth = 1;
      textColor = TEXT_LIGHT;
      drawOuterBoth = false;
      fontSize = 14;
    } else {
      fill = NODE_FILL;
      stroke = n.pillar === 'grids' ? PILLAR_GREEN : PILLAR_YELLOW;
      strokeDash = n.pillar === 'grids' ? '5 3' : undefined;
      strokeWidth = 2.4;
      textColor = TEXT_LIGHT;
      drawOuterBoth = n.pillar === 'both';
      fontSize = 14;
    }

    return (
      <g
        key={id}
        className={'vcm-node' + (dim ? ' is-dim' : '')}
        onClick={() => setSelected(id)}
        style={{ cursor: 'pointer' }}
      >
        {drawOuterBoth && (
          <rect
            x={n.x - 4} y={n.y - 4}
            width={n.w + 8} height={n.h + 8}
            rx={10} ry={10}
            fill="none"
            stroke={PILLAR_GREEN}
            strokeWidth={2.4}
            strokeDasharray="5 3"
          />
        )}
        <rect
          x={n.x} y={n.y}
          width={n.w} height={n.h}
          rx={8} ry={8}
          fill={fill}
          stroke={stroke}
          strokeWidth={strokeWidth}
          strokeDasharray={strokeDash}
        />
        <text
          x={n.x + n.w / 2}
          y={n.y + n.h / 2 - (lines.length - 1) * 8.5 + 5}
          textAnchor="middle"
          fontSize={fontSize}
          fontWeight="600"
          fill={textColor}
          style={{ pointerEvents: 'none', userSelect: 'none' }}
        >
          {lines.map((line, i) => (
            <tspan key={i} x={n.x + n.w / 2} dy={i === 0 ? 0 : 16}>{line}</tspan>
          ))}
        </text>
      </g>
    );
  };

  // ── Arrows ────────────────────────────────────────────────────────────────
  const arrow = (x1, y1, x2, y2, key) => {
    const headLen = 7;
    const isHorizontal = y1 === y2;
    const isLeft = x2 < x1;
    const isUp = y2 < y1;
    let head;
    if (isHorizontal) {
      head = isLeft
        ? `M ${x2 + headLen} ${y2 - headLen/1.4} L ${x2} ${y2} L ${x2 + headLen} ${y2 + headLen/1.4}`
        : `M ${x2 - headLen} ${y2 - headLen/1.4} L ${x2} ${y2} L ${x2 - headLen} ${y2 + headLen/1.4}`;
    } else {
      head = isUp
        ? `M ${x2 - headLen/1.4} ${y2 + headLen} L ${x2} ${y2} L ${x2 + headLen/1.4} ${y2 + headLen}`
        : `M ${x2 - headLen/1.4} ${y2 - headLen} L ${x2} ${y2} L ${x2 + headLen/1.4} ${y2 - headLen}`;
    }
    return (
      <g key={key}>
        <line x1={x1} y1={y1} x2={x2} y2={y2} stroke={ARROW_COLOR} strokeWidth={2.2} />
        <path d={head} fill="none" stroke={ARROW_COLOR} strokeWidth={2.2} strokeLinecap="round" strokeLinejoin="round" />
      </g>
    );
  };

  // A plain line (no arrowhead) - used for the Influencer → Barriers segment.
  const plainLine = (x1, y1, x2, y2, key) => (
    <line key={key} x1={x1} y1={y1} x2={x2} y2={y2} stroke={ARROW_COLOR} strokeWidth={2.2} />
  );

  // Compute arrow endpoints from node geometry
  const gen = NODES.generation, trans = NODES.transmission, dist = NODES.distribution, dem = NODES.demand;
  const dec = NODES.decentralised;
  const sto = NODES.storage, dig = NODES.digital, techNode = NODES.tech;

  const arrows = [];
  // Main flow
  arrows.push(arrow(gen.x + gen.w,   gen.y + gen.h/2,  trans.x,            trans.y + trans.h/2, 'a1'));
  arrows.push(arrow(trans.x + trans.w, trans.y + trans.h/2, dist.x,        dist.y + dist.h/2,   'a2'));
  arrows.push(arrow(dist.x + dist.w, dist.y + dist.h/2, dem.x,             dem.y + dem.h/2,     'a3'));
  // Decentralised → Distribution (vertical)
  arrows.push(arrow(dec.x + dec.w/2, dec.y, dist.x + dist.w/2, dist.y + dist.h, 'a4'));

  // Decentralised → Demand (right out of Decentralised, then up into Demand's bottom)
  {
    const startX = dec.x + dec.w;
    const midY   = dec.y + dec.h / 2;
    const upX    = dem.x + dem.w / 2;
    const endY   = dem.y + dem.h;
    const head   = `M ${upX - 5} ${endY + 7} L ${upX} ${endY} L ${upX + 5} ${endY + 7}`;
    arrows.push(
      <g key="a5">
        <line x1={startX} y1={midY} x2={upX}  y2={midY} stroke={ARROW_COLOR} strokeWidth={2.2} />
        <line x1={upX}    y1={midY} x2={upX}  y2={endY} stroke={ARROW_COLOR} strokeWidth={2.2} />
        <path d={head} fill="none" stroke={ARROW_COLOR} strokeWidth={2.2} strokeLinecap="round" strokeLinejoin="round" />
      </g>
    );
  }

  // Single fat arrow from Influencers down to the Energy Ecosystem.
  // Rendered separately (see SVG below) so it sits behind the Barriers band
  // background - visually disappearing into the wall and re-emerging on the
  // other side with the arrowhead.
  const bigArrow = (() => {
    const cx = (RAIL_W + W) / 2;
    const top = Y_INF_BAND_BOT + 4;
    const bot = Y_ES_BAND_TOP - 3;
    const bodyHalfW = 48;
    const headHalfW = 80;
    const headHeight = 38;
    const headStart = bot - headHeight;
    const pts = [
      [cx - bodyHalfW, top],
      [cx + bodyHalfW, top],
      [cx + bodyHalfW, headStart],
      [cx + headHalfW, headStart],
      [cx, bot],
      [cx - headHalfW, headStart],
      [cx - bodyHalfW, headStart],
    ].map(([x, y]) => `${x},${y}`).join(' ');
    return (
      <polygon
        key="big-arrow"
        points={pts}
        fill={ARROW_COLOR}
        fillOpacity="0.45"
        stroke={ARROW_COLOR}
        strokeOpacity="0.85"
        strokeWidth={2}
        strokeLinejoin="round"
      />
    );
  })();

  // Inner panel left/right edges, used as anchors for the cross-cutting arrows.
  const INNER_LEFT  = RAIL_W + 15;     // 195
  const INNER_RIGHT = W - 25;          // 1255

  // Storage / Digital row: arrowheads pointing outward (left of storage, right of digital)
  const stoY = sto.y + sto.h / 2;
  arrows.push(arrow(sto.x, stoY, INNER_LEFT, stoY, 'sd-l'));
  arrows.push(plainLine(sto.x + sto.w, stoY, dig.x, stoY, 'sd-mid'));
  arrows.push(arrow(dig.x + dig.w, stoY, INNER_RIGHT, stoY, 'sd-r'));

  // Tech providers row: arrowheads pointing outward
  const techY = techNode.y + techNode.h / 2;
  arrows.push(arrow(techNode.x, techY, INNER_LEFT, techY, 'tech-l'));
  arrows.push(arrow(techNode.x + techNode.w, techY, INNER_RIGHT, techY, 'tech-r'));

  // Demand bracket: Demand right → vertical stem → 5 horizontal lines into each branch node
  const stemX = 970;
  const demRight = dem.x + dem.w;
  const demCY = dem.y + dem.h/2;
  const branches = ['agriculture','industry','transport','households','other'];
  const branchYs = branches.map(id => NODES[id].y + NODES[id].h/2);
  const stemTop = Math.min(...branchYs);
  const stemBot = Math.max(...branchYs);

  // ── Render ────────────────────────────────────────────────────────────────
  return (
    <div className="vcm-view">
      <div className="vcm-layout">
        {/* The schematic */}
        <div className="vcm-diagram">
        <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet" width="100%" height="auto">
          {/* Influencers band background */}
          <rect x={0} y={0} width={W}      height={Y_INF_BAND_BOT} fill={BG_BAND_LIGHT} rx={8} />
          <rect x={0} y={0} width={RAIL_W} height={Y_INF_BAND_BOT} fill={BG_BAND_DEEP}  rx={8} />
          <text x={RAIL_W / 2} y={65} textAnchor="middle" fontSize="20" fontWeight="700" fill={TEXT_LIGHT} style={{ userSelect: 'none', letterSpacing: '0.02em' }}>Influencers</text>
          <g onClick={() => setBandHelp('influencers')} style={{ cursor: 'pointer' }}>
            <circle cx={RAIL_W - 18} cy={18} r={10} fill="rgba(255,255,255,0.06)" stroke={TEXT_DIM} strokeWidth={1.2} />
            <text x={RAIL_W - 18} y={22} textAnchor="middle" fontSize="13" fontWeight="700" fill={TEXT_LIGHT} style={{ userSelect: 'none', pointerEvents: 'none' }}>?</text>
          </g>

          {/* Big arrow - drawn here so the Barriers band background covers it. */}
          {bigArrow}

          {/* Barriers band background */}
          <rect x={0} y={Y_BAR_BAND_TOP} width={W}      height={Y_BAR_BAND_BOT - Y_BAR_BAND_TOP} fill={BG_BAND_LIGHT} rx={8} />
          <rect x={0} y={Y_BAR_BAND_TOP} width={RAIL_W} height={Y_BAR_BAND_BOT - Y_BAR_BAND_TOP} fill={BG_BAND_DEEP}  rx={8} />
          <text x={RAIL_W / 2} y={(Y_BAR_BAND_TOP + Y_BAR_BAND_BOT) / 2 - 4} textAnchor="middle" fontSize="17" fontWeight="700" fill={TEXT_LIGHT} style={{ userSelect: 'none', letterSpacing: '0.02em' }}>
            <tspan x={RAIL_W / 2}>Barriers</tspan>
            <tspan x={RAIL_W / 2} dy={20}>focused on</tspan>
          </text>
          <g onClick={() => setBandHelp('barriers')} style={{ cursor: 'pointer' }}>
            <circle cx={RAIL_W - 18} cy={Y_BAR_BAND_TOP + 12} r={10} fill="rgba(255,255,255,0.06)" stroke={TEXT_DIM} strokeWidth={1.2} />
            <text x={RAIL_W - 18} y={Y_BAR_BAND_TOP + 16} textAnchor="middle" fontSize="13" fontWeight="700" fill={TEXT_LIGHT} style={{ userSelect: 'none', pointerEvents: 'none' }}>?</text>
          </g>

          {/* Energy Ecosystem band: outer container + rail */}
          <rect x={0} y={Y_ES_BAND_TOP} width={W}      height={H - Y_ES_BAND_TOP} fill={BG_BAND_LIGHT} rx={8} />
          <rect x={0} y={Y_ES_BAND_TOP} width={RAIL_W} height={H - Y_ES_BAND_TOP} fill={BG_BAND_DEEP}  rx={8} />
          {/* Horizontal label, stacked Energy / ecosystem */}
          <text x={RAIL_W / 2} y={(Y_ES_BAND_TOP + H) / 2 - 10} textAnchor="middle" fontSize="20" fontWeight="700" fill={TEXT_LIGHT} style={{ userSelect: 'none', letterSpacing: '0.02em' }}>
            <tspan x={RAIL_W / 2}>Energy</tspan>
            <tspan x={RAIL_W / 2} dy={26}>ecosystem</tspan>
          </text>
          <g onClick={() => setBandHelp('ecosystem')} style={{ cursor: 'pointer' }}>
            <circle cx={RAIL_W - 18} cy={Y_ES_BAND_TOP + 18} r={10} fill="rgba(255,255,255,0.06)" stroke={TEXT_DIM} strokeWidth={1.2} />
            <text x={RAIL_W - 18} y={Y_ES_BAND_TOP + 22} textAnchor="middle" fontSize="13" fontWeight="700" fill={TEXT_LIGHT} style={{ userSelect: 'none', pointerEvents: 'none' }}>?</text>
          </g>

          {/* Inner content panel */}
          <rect x={RAIL_W + 10} y={Y_ES_BAND_TOP + 15} width={W - RAIL_W - 30} height={H - Y_ES_BAND_TOP - 35} fill={BG_PANEL_INNER} stroke={PANEL_BORDER} strokeWidth={1.5} rx={8} />

          {/* Arrows (rendered before nodes so nodes overlay them) */}
          {arrows}

          {/* Demand bracket */}
          <g key="bracket">
            <line x1={demRight} y1={demCY} x2={stemX} y2={demCY} stroke={ARROW_COLOR} strokeWidth={2.2} />
            <line x1={stemX} y1={stemTop} x2={stemX} y2={stemBot} stroke={ARROW_COLOR} strokeWidth={2.2} />
            {branches.map((id) => {
              const n = NODES[id];
              const cy = n.y + n.h / 2;
              const x2 = n.x;
              const head = `M ${x2 - 7} ${cy - 5} L ${x2} ${cy} L ${x2 - 7} ${cy + 5}`;
              return (
                <g key={'br-' + id}>
                  <line x1={stemX} y1={cy} x2={x2} y2={cy} stroke={ARROW_COLOR} strokeWidth={2.2} />
                  <path d={head} fill="none" stroke={ARROW_COLOR} strokeWidth={2.2} strokeLinecap="round" strokeLinejoin="round" />
                </g>
              );
            })}
          </g>

          {/* Nodes */}
          {Object.keys(NODES).map(renderNode)}

        </svg>
        </div>

        {/* Pillar filter - compact cards beside the energy-ecosystem band */}
        <div className="vcm-sidebar-col">
          {setActiveView && (
            <button
              type="button"
              className="vcm-india-link"
              onClick={() => setActiveView('india-value-chain')}
              title="Open the India regional version of this map"
            >
              View India version →
            </button>
          )}
          <div className="vcm-legend-wrap">
            <button
              type="button"
              className={'vcm-pillar vcm-pillar--grids' + (activePillars.includes('grids') ? ' is-active' : '')}
              onClick={() => togglePillar('grids')}
              aria-pressed={activePillars.includes('grids')}
            >
              <div className="vcm-pillar-icon">⚡</div>
              <div className="vcm-pillar-name">Grid modernization</div>
              <div className="vcm-pillar-state">{activePillars.includes('grids') ? '✓ Active' : 'Click to highlight'}</div>
              <div className="vcm-pillar-tooltip" role="tooltip">
                <div className="vcm-pillar-tooltip-tag">Infrastructure</div>
                <div className="vcm-pillar-tooltip-desc">Expanding and modernising power grids to enable affordable, reliable clean electricity - focusing on grid investment, energy storage, digitalisation and transmission.</div>
              </div>
            </button>
            <button
              type="button"
              className={'vcm-pillar vcm-pillar--powering' + (activePillars.includes('powering') ? ' is-active' : '')}
              onClick={() => togglePillar('powering')}
              aria-pressed={activePillars.includes('powering')}
            >
              <div className="vcm-pillar-icon">🌱</div>
              <div className="vcm-pillar-name">Energy access</div>
              <div className="vcm-pillar-state">{activePillars.includes('powering') ? '✓ Active' : 'Click to highlight'}</div>
              <div className="vcm-pillar-tooltip" role="tooltip">
                <div className="vcm-pillar-tooltip-tag">Productive use</div>
                <div className="vcm-pillar-tooltip-desc">Enabling economic growth and job creation through reliable electricity access - focusing on productive use across agriculture, industry, services and households.</div>
              </div>
            </button>
            <div className="vcm-legend-hint">Click a pillar to highlight matching nodes · click again to clear</div>
          </div>
        </div>
      </div>

      {/* Node detail modal */}
      {selected && (() => {
        const n = NODES[selected];
        const isInf = n.band === 'influencers';
        const isBar = n.band === 'barriers';
        const isEcoBar = n.band === 'ecosystem-bar';
        const initiatives = (isInf && window.INITIATIVES_DATA)
          ? window.INITIATIVES_DATA.initiatives.filter(o =>
              n.archetype
                ? o.type === n.archetype
                : (o.influencer || []).includes('Policymakers & regulators')
            )
          : [];
        return (
          <div className="vcm-modal-scrim" onClick={() => setSelected(null)}>
            <div className="vcm-modal" onClick={(e) => e.stopPropagation()}>
              <button className="vcm-modal-close" onClick={() => setSelected(null)} aria-label="Close">×</button>
              {isInf
                ? (n.archetype && <div className="vcm-modal-pillar">{n.archetype}</div>)
                : isBar
                  ? <div className="vcm-modal-pillar" style={{ background: 'rgba(168,98,52,0.18)', color: '#e0a679', border: '1px solid rgba(168,98,52,0.45)' }}>Barrier</div>
                  : isEcoBar
                    ? <div className="vcm-modal-pillar" style={{ background: 'rgba(174,214,188,0.18)', color: TEXT_DIM, border: '1px solid rgba(174,214,188,0.35)' }}>Energy Ecosystem</div>
                    : null}
              <h2 className="vcm-modal-title">{n.label.split('\n').join(' ')}</h2>
              {isBar
                ? <p className="vcm-modal-desc">{BARRIER_EXPLAINERS[n.barrier] || LOREM}</p>
                : <p className="vcm-modal-desc">{NODE_DESCRIPTIONS[selected] || LOREM}</p>}
              {NODE_SUBBOXES[selected] && (
                <div className="vcm-modal-subboxes">
                  <div className="vcm-modal-subboxes-label">{NODE_SUBBOXES[selected].label}</div>
                  <div className="vcm-modal-subboxes-grid">
                    {NODE_SUBBOXES[selected].items.map((item, i) => (
                      <span key={i} className="vcm-modal-subbox">{item}</span>
                    ))}
                  </div>
                </div>
              )}
              {isInf && initiatives.length > 0 && (
                <div className="vcm-modal-pill-section">
                  <div className="vcm-modal-pill-label">Initiatives in this archetype · {initiatives.length}</div>
                  <div className="vcm-modal-pills">
                    {initiatives.map(o => (
                      <span key={o.id} className="ip-chip ip-chip--initiatives" title={o.description || o.name}>
                        <span className="ip-chip-dot" style={{ background: LEGEND_COLORS[o.type] || '#5a8c66' }}></span>
                        <span className="ip-chip-name">{o.name}</span>
                      </span>
                    ))}
                  </div>
                </div>
              )}
            </div>
          </div>
        );
      })()}

      {/* Band explainer modal */}
      {bandHelp && (
        <div className="vcm-modal-scrim" onClick={() => setBandHelp(null)}>
          <div className="vcm-modal" onClick={(e) => e.stopPropagation()}>
            <button className="vcm-modal-close" onClick={() => setBandHelp(null)} aria-label="Close">×</button>
            <div className="vcm-modal-pillar" style={{ background: 'rgba(174,214,188,0.18)', color: TEXT_DIM, border: '1px solid rgba(174,214,188,0.35)' }}>About this band</div>
            <h2 className="vcm-modal-title">{BAND_HELP[bandHelp].title}</h2>
            <p className="vcm-modal-desc">{BAND_HELP[bandHelp].body}</p>
          </div>
        </div>
      )}
    </div>
  );
}

window.ValueChainView = ValueChainView;
})();
