// ValueChainIndiaView.jsx - Regional Energy Ecosystem Map · India (schematic diagram)
// Copy of ValueChainView.jsx; scoped to the India regional context so the
// content can later diverge from the global energy-ecosystem map without
// touching the original.
//
// IIFE-wrapped: babel-standalone does NOT actually give each <script> its own
// scope, so identically-named top-level consts here would clobber the ones in
// ValueChainView.jsx. Wrapping in an IIFE makes them truly local.

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

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

const Y_INF_BAND_BOT  = 120;
const Y_BAR_BAND_TOP  = 145;
const Y_BAR_BAND_BOT  = 215;
const Y_ES_BAND_TOP   = 245;

const RAIL_W = 180;

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 ─────────────────────────────────────────────────────────
  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' },

  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:{ x:  570, y:  430, w: 170, h: 56, label: 'Decentralised RES', pillar: 'both' },

  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' },

  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' },

  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' },
};

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.',
};

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',
};

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;
}

const LOREM = 'Description coming soon.';

// Node descriptions for the India map. Where India-specific copy exists from
// the doc, it's used. For nodes without India-specific text (influencers,
// philanthropies, tech providers), we fall back to the general descriptions
// from the global doc rather than show "Description coming soon".
const NODE_DESCRIPTIONS = {
  // General descriptions (no India-specific copy provided yet) - same text as
  // the global Energy Ecosystem Infographic uses.
  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.',
  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.',

  // India-specific descriptions from the doc.
  generation:   'India’s installed generation capacity reached 532 GW in March 2026, with the private sector accounting for 52.3% of total capacity, followed by state utilities at 24.4% and central utilities at 23.3%. Non-fossil sources, including solar, wind, hydro, and nuclear, now make up 53.2% of installed capacity, while coal continues to dominate actual electricity generation, providing baseload power and system stability as renewable capacity expands.',
  transmission: 'India’s inter-state transmission system is primarily operated by the state-owned Power Grid Corporation of India Limited, which manages the national grid backbone, while intra-state networks are owned and operated by State Transmission Utilities. Expanding and modernising transmission infrastructure is critical to integrating remote renewable energy zones and achieving India’s clean energy targets.',
  distribution: 'Electricity distribution in India is led primarily by state-owned Distribution Companies (DISCOMs), supported by selective private participation through distribution licensees and franchisee models in urban areas. Ongoing reforms aim to improve operational efficiency, reduce network losses, and strengthen the financial sustainability of the sector.',
  demand:       'India’s rising electricity demand reflects its economic growth, urbanisation, and improving living standards. As demand continues to increase, the power system will need to scale supply while also improving efficiency and managing peak load more effectively.',
  decentralised:'India’s decentralised renewable energy sector plays a growing role in expanding clean, reliable, and locally generated power, particularly for rural communities, farmers, and small enterprises. Supported by government programmes, state partnerships, and private developers, the sector is increasingly focused on productive uses such as solar irrigation and agro-processing, linking energy access with livelihoods and local economic growth.',

  agriculture:  'India’s agricultural electricity demand is driven primarily by irrigation, creating a major opportunity to expand clean, reliable, and cost-effective energy for farmers. The PM KUSUM (a solar irrigation programme) scheme is supporting this transition by promoting solar irrigation, solar power generation on farmland, and the solarisation of existing grid-connected pumps, helping reduce reliance on diesel and grid power while strengthening rural energy access.',
  industry:     'India’s industrial sector will play a defining role in the country’s energy transition. Captive industrial power already represents roughly 15% of total electricity consumption, while emissions-intensive sectors such as steel, cement, aluminium, and refining account for 28% of national GHG emissions. As the world’s second-largest steel producer, India has a unique opportunity to shape the future of low-carbon industrialisation by accelerating green hydrogen-based steelmaking, electrification, and renewable-powered captive generation at scale.',
  transport:    'India’s transport sector accounts for around 10% of national GHG emissions, with more than 300 million vehicles on the road and a system historically reliant on liquid fossil fuels. Indian Railways has made significant progress, electrifying 58% of its 68,000 km network and setting a net-zero target. Road transport electrification, however, remains at an early stage due to high vehicle costs, limited charging infrastructure, and the fossil-fuel-heavy electricity grid currently supplying EVs.',
  households:   'India has achieved near-universal household electricity connections through the Saubhagya scheme, but electricity access remains uneven in practice. Many rural households still face gaps in supply reliability, adequacy, and service quality, with significant variation across states. At the same time, around 681 million people continue to rely on traditional biomass for cooking, creating major health, gender, and energy access challenges. The PM Surya Ghar Muft Bijli Yojana, launched in 2024 with an allocation of approximately USD 9.0 billion, aims to accelerate rooftop solar adoption across 10 million households, offering up to 300 free electricity units per month. Clean cooking remains a parallel priority, as reducing biomass dependence is essential for improving indoor air quality, lowering health burdens, and ensuring India’s household energy transition delivers both climate and development benefits.',
  other:        'India’s commercial and services sector is emerging as a major source of electricity demand growth, with space cooling representing a key load driver. Air conditioning currently accounts for approximately 60% of cooling-related energy consumption and is projected to constitute 28% of total national electricity demand by 2050, driven by urbanisation, rising household incomes, and increasing ambient temperatures. India’s National Cooling Action Plan (NCAP, 2019) establishes a target to reduce cooling energy demand by 20-25% by 2037/38 through appliance efficiency standards, refrigerant transitions toward lower-GWP alternatives, and deployment of district cooling infrastructure.',

  policymakers: 'India’s power sector is governed through a two-tier regulatory framework established under the Electricity Act 2003. The Central Electricity Regulatory Commission (CERC) regulates inter-state transmission and wholesale electricity markets, while State Electricity Regulatory Commissions (SERCs) oversee intra-state tariffs, distribution licensing, and retail electricity supply. At the policy level, the Ministry of Power and the Ministry of New and Renewable Energy (MNRE) provide strategic direction, supported by state energy departments and the Central Electricity Authority (CEA), which play important roles in system planning, technical standards, and implementation oversight.',
  storage:      'India’s energy transition is driving a rapid increase in demand for grid flexibility and energy storage. The Central Electricity Authority (CEA) projects national storage requirements to rise from 16 GW by 2026-27 to 73.93 GW by 2031-32, reflecting the large-scale integration of variable solar and wind generation. Battery Energy Storage Systems (BESS) and Pumped Storage Projects (PSPs) are emerging as the primary technologies, supported by policy measures including Viability Gap Funding and Energy Storage Obligations (ESO), which require distribution licensees to procure storage capacity starting at 1% in FY 2023-24 and increasing to 4% by FY 2029-30. Additional flexibility measures include flexible operation of coal-fired power plants, demand response programmes, and expansion of wholesale electricity markets to support inter-state balancing.',
  digital:      'India is accelerating grid digitalisation through the Revamped Distribution Sector Scheme (RDSS), which aims to deploy smart consumer meters, distribution transformer meters, and feeder meters across 32 states and union territories. Backed by an investment of approximately USD 18 billion and targeted for implementation by FY 2025-26, early deployments - including in Assam - have already demonstrated measurable reductions in billing inaccuracies and distribution losses. Alongside smart metering, utilities are deploying Advanced Metering Infrastructure (AMI), Geographic Information System (GIS)-based SCADA systems, IoT-enabled transformer monitoring, and Distributed Energy Resource Management Systems (DERMS) to strengthen real-time grid visibility, improve fault detection and outage management, and support the integration of distributed renewable energy resources.',
  commercial_banks: 'India’s energy transition financing ecosystem is anchored by domestic public sector institutions such as the State Bank of India (SBI), Power Finance Corporation (PFC), and REC Limited (formerly Rural Electrification Corporation), which serve as the primary lenders to the power sector. Alongside these institutions, a growing network of non-banking financial companies (NBFCs), green bond issuers, and international development finance institutions is expanding access to concessional and blended capital for clean energy investments. To accelerate private investment, the Government of India has proposed a Market-Based Low Carbon Finance Corporation and is promoting blended finance mechanisms that combine public risk capital with private debt and equity - intended to attract institutional investors, lower financing costs, and improve bankability for renewable energy, battery storage, and grid modernisation projects, particularly in higher-risk segments such as distributed solar and mini-grids.',
};

// Sub-categories surfaced under specific Energy Ecosystem nodes (Andrea,
// 2026-05-28). Same sub-boxes as the global view - the categories aren't
// India-specific.
const NODE_SUBBOXES = {
  policymakers: {
    label: 'Including',
    items: ['Planning', 'Market design', 'Tariffs', 'Standards', 'Incentives'],
  },
  commercial_banks: {
    label: 'Including',
    items: ['Equity providers', 'Pension funds', 'Insurance'],
  },
};

const PILLAR_YELLOW = '#fdce07';
const PILLAR_GREEN  = '#84c98f';
// India palette - cool teal shift from the global view so the two Energy
// Ecosystem maps read as related but visually distinct.
const BG_BAND_LIGHT = '#1a3a3a';   // was #1a3a28 (global) - teal-green band fill
const BG_BAND_DEEP  = '#0a1f20';   // was #0a1f12 (global) - cool dark rail
const BG_PANEL_INNER = '#0c5258';  // was #0c5d44 (global) - deeper teal panel
const NODE_FILL      = '#285a45';
const NODE_FILL_INFL = '#1f4530';
const TEXT_LIGHT     = '#e8f5ee';
const TEXT_DIM       = '#aed6bc';
const ARROW_COLOR    = '#5DCAA5';
const PANEL_BORDER   = 'rgba(132,201,143,0.32)';

function ValueChainIndiaView() {
  const [selected, setSelected] = useStateVCMI(null);
  const [activePillars, setActivePillars] = useStateVCMI([]);
  const [bandHelp, setBandHelp] = useStateVCMI(null);

  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;
    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>
    );
  };

  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>
    );
  };

  const plainLine = (x1, y1, x2, y2, key) => (
    <line key={key} x1={x1} y1={y1} x2={x2} y2={y2} stroke={ARROW_COLOR} strokeWidth={2.2} />
  );

  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 = [];
  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'));
  arrows.push(arrow(dec.x + dec.w/2, dec.y, dist.x + dist.w/2, dist.y + dist.h, 'a4'));

  {
    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>
    );
  }

  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"
      />
    );
  })();

  const INNER_LEFT  = RAIL_W + 15;
  const INNER_RIGHT = W - 25;

  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'));

  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'));

  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);

  return (
    <div className="vcm-view">
      <div className="vcm-layout">
        <div className="vcm-diagram">
        <svg viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="xMidYMid meet" width="100%" height="auto">
          <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>

          {bigArrow}

          <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>

          <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} />
          <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>

          <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}

          <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>

          {Object.keys(NODES).map(renderNode)}

        </svg>
        </div>

        <div className="vcm-sidebar-col">
          <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>

      {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>
        );
      })()}

      {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.ValueChainIndiaView = ValueChainIndiaView;
})();
