// MethodologyView.jsx - explains how the atlas categorises organisations:
// the sources, the inclusion criteria, and the definitions behind every tag.
// Copy is taken verbatim from the agreed methodology (2026.06 Methodology).
//
// Deep-linking: the ? bubbles across the tool call onOpenMethodology(sectionId),
// which switches to this tab and scrolls/flashes the matching <section id>.
// Keep the section ids below in sync with those bubbles - in particular
// methodology-scope, methodology-barriers, methodology-geography and
// methodology-access-metric are referenced from MatrixView.

const { useEffect: useEffectMth } = React;

// Section model. Each section renders a list of `blocks`; block shapes:
//   { lead }       - lead paragraph
//   { p }          - body paragraph
//   { parts: [...] } - paragraph interleaving strings with { text, link }
//   { sub }        - subheading within the section
//   { ul: [...] }  - bullet list
//   { defsLabel }  - label introducing a group of definitions / a scope note
//   { defs: [[term, definition], ...] } - definition list
//   { source }     - small source-citation line
const MTH_SECTIONS = [
  {
    id: 'methodology-overview',
    title: 'Overview and how to read this page',
    blocks: [
      { lead:
        'Building credible maps of the energy ecosystem means making hundreds of small ' +
        'decisions - who’s in, who’s out, and what tags are applied. This page documents ' +
        'how those decisions were made: the sources that were drawn on, the criteria that ' +
        'were applied, and the definitions that underpin every entry.' },
    ],
  },
  {
    id: 'methodology-pillars',
    title: 'Built around two pillars: Grids of the Future and Powering Opportunity',
    blocks: [
      { p:
        'The map sets out to capture every part of the value chain from generation through ' +
        'to end use, with particular focus on GEA’s two pillars. These are two sides of the ' +
        'same transformation. Grids of the Future relates to the supply side: building the ' +
        'renewables-ready, digitalised power systems that carry electricity, along with the ' +
        'financing and flexibility to deliver them. Powering Opportunity relates more to the ' +
        'demand side: turning that electricity into productive use across businesses, farms, ' +
        'jobs, and economic growth.' },
    ],
  },
  {
    id: 'methodology-sources',
    title: 'How we built the maps: sourcing and AI-assisted research',
    blocks: [
      { p:
        'This map draws on three main sources: AI-assisted online research (primarily ' +
        'Claude) drawing on organizational websites, annual reports, and official ' +
        'announcements, interviews with stakeholders in the energy ecosystem, and expertise ' +
        'from within Global Energy Alliance and Systemiq, including manual quality checking ' +
        'of AI-assisted results. That combination gives broad coverage - but it has limits. ' +
        'Where activity is undocumented or not publicly disclosed, gaps will exist.' },
      { p:
        'The map is static, updated only in response to feedback. It was last updated in ' +
        'June 2026.' },
    ],
  },
  {
    id: 'methodology-scope',
    title: 'General scope: what do we map (and what not)?',
    blocks: [
      { sub: 'Mapping the field, not ranking it' },
      { p:
        'The map plots the spread of players across value chain segments, barriers, and ' +
        'geographies. The aim is to reflect where coverage is concentrated, or where fewer ' +
        'initiatives and programs appear to be active, not where impact or capital is lacking.' },
      { sub: 'Tags are organization-wide, not regional' },
      { p:
        'Value chain tags are organization-wide, not region-specific. An organization that ' +
        'has evidenced activity in a value-chain segment is assumed to be working on it, or ' +
        'willing to work on it, across all regions the organization targets.' },
      { sub: 'Who’s in and who’s out?' },
      { p: 'The map covers organizations that advance Grids of the Future or Powering Opportunity related work through:' },
      { ul: [
        'Channeling a traceable funding envelope into external energy projects or programs. ' +
          'Private investors only qualify when they have an impact mandate and a documented ' +
          'portfolio over 1BUSD in assets, and have multi-region (following World Bank ' +
          'definitions) reach and/or',
        'Shaping the energy ecosystem through financing coordination, policy design, ' +
          'standard-setting, market data, technical assistance or program deliverable. They ' +
          'operate a cross-regional or global scale.',
      ] },
      { p:
        'The global map excludes: sovereign governments, universities, global consultancies ' +
        'and contractors and utilities and operators. The deep-dive for India contains more ' +
        'players, refer to section 5 of the methodology.' },
      { sub: 'What relationships exist in the collaboration networks' },
      { p: 'Relationships are included when there is an online (through for example, an organization’s own website or third party online documents), publicly announced:' },
      { ul: [
        'Joint publication',
        'Formal MoU or partnership',
        'Joint program',
        'Consortium or multi-stakeholder platform with a clear deliverable where both ' +
          'organizations are an active member',
      ] },
      { p:
        'Relationships from coalition co-memberships with no clear joint initiative, ' +
        'sponsoring the same initiative, or board roles are excluded. These types of ' +
        'relationships are excluded because they reflect shared affiliation rather than a ' +
        'documented joint commitment between the two organizations.' },
    ],
  },
  {
    id: 'methodology-india',
    title: 'Scope: what do we map in the India deep-dive?',
    blocks: [
      { p: 'The Indian deep-dive consists of:' },
      { ul: [
        'Initiatives and programs that fit the global criteria, but on a national or ' +
          'multi-regional level in India',
        'System actors that build, operate, finance or regulate the system on a national or ' +
          'multi-regional level. They are only included if they have major market share, ' +
          'hold a bottleneck position in the value chain or materially advance ‘Grids of the ' +
          'Future’ or ‘Powering Opportunity’. This is validated by Systemiq knowledge of the ' +
          'India system, in addition to interview with relevant stakeholders.',
      ] },
    ],
  },
  {
    id: 'methodology-types',
    title: 'Organization types',
    blocks: [
      { lead: 'The definitions that were used to tag the organizations.' },
      { defsLabel: 'Global and India deep-dive' },
      { defs: [
        ['Intergovernmental organization (IGO)',
          'A body established by treaty between sovereign states to cooperate on shared ' +
          'issues, with standing under international law'],
        ['Multilateral Development Bank (MDB) / International Financial Institution (IFI) / Development Finance Institution (DFI)',
          'Institutions deploying capital with a development mandate, whether owned by ' +
          'multiple governments, structured as climate or blended finance funds, or ' +
          'operating bilaterally with their own balance sheet'],
        ['Bilateral development agency',
          'A single donor country’s government agency channelling that country’s development ' +
          'assistance'],
        ['Non-Governmental Organization (NGO)',
          'A non-profit group independent of government control'],
        ['Coalition or multi-stakeholder platform',
          'A structured, usually mission-specific arrangement bringing together actors from ' +
          'two or more sectors around a shared goal'],
        ['Private investor',
          'A private investor citing impact or sustainable development in its mission, with ' +
          'a documented energy portfolio, over USD 1bn in assets, and multi-region reach'],
        ['Philanthropy',
          'A private foundation or grant-making body deploying private wealth for public ' +
          'benefit without expecting financial return'],
        ['Commercial system actor',
          'A commercial company whose activities shape the two pillars, mentioned by DFIs ' +
          'and multilaterals as a system-shaper rather than a vendor'],
      ] },
      { defsLabel: 'Regional' },
      { defs: [
        ['Policymakers and regulators',
          'Bodies setting policy, rules, and standards for the energy sector'],
        ['Financial intermediary (domestic)',
          'Domestic state-owned or private lenders and infra-finance vehicles funding ' +
          'national energy projects, distinct from MDBs, DFI’s and IFIs'],
        ['Tech provision & manufacturer',
          'Organizations whose main function is manufacturing equipment and hardware'],
        ['Regulated infrastructure operator',
          'Entities that own and run energy infrastructure under regulatory oversight'],
        ['Industry player',
          'Commercial firms operating across the energy value chain'],
      ] },
    ],
  },
  {
    id: 'methodology-segments',
    title: 'Value chain segments',
    blocks: [
      { defsLabel: 'Global and India deep-dive' },
      { lead:
        'Value chain tags reflect each organization’s main activities, as stated on its ' +
        'website or in its annual report; one-off projects don’t qualify - the activity ' +
        'must be one the organization itself emphasises.' },
      { defs: [
        ['Generation', 'Large-scale production of electricity feeding the bulk power system'],
        ['Transmission', 'High-voltage networks moving power from generation to distribution'],
        ['Distribution', 'Lower-voltage networks delivering power to end users'],
        ['Decentralised RES', 'Distributed renewable generation sited close to demand'],
        ['Grid flexibility & energy storage',
          'Balancing supply and demand through storage and flexible capacity'],
        ['Grid digitalisation and data provision',
          'Software, sensing, and data that make grids observable and controllable or ' +
          'providing energy-system data and analytics'],
        ['Demand - Agriculture', 'Energy use and electrification across farming and irrigation'],
        ['Demand - Industry', 'Energy use and electrification across industrial processes'],
        ['Demand - Transport', 'Energy use and electrification across mobility'],
        ['Demand - Households & cooking', 'Residential energy use, including clean cooking'],
        ['Demand - Services & other', 'Energy use across commercial, public, and other end uses'],
        ['Tech provision & manufacturers',
          'Supply of equipment, components, and hardware for energy systems'],
        ['Commercial Banks and Private Finance',
          'Privately sourced capital for energy projects and companies'],
        ['Policymakers & Regulators', 'Bodies setting rules, standards, and market structure'],
      ] },
    ],
  },
  {
    id: 'methodology-geography',
    title: 'Geography and regional assignment',
    blocks: [
      { defsLabel: 'Global only' },
      { parts: [
        'Regions reflect where each organization has documented energy activity - ' +
        'programs, financing, or substantial published engagement - not headquarters ' +
        'location. They follow ',
        { text: 'World Bank definitions',
          link: 'https://ourworldindata.org/grapher/world-regions-according-to-the-world-bank' },
        ', with Europe and Central Asia split, and Global marks organizations whose ' +
        'activity genuinely spans all regions.',
      ] },
    ],
  },
  {
    id: 'methodology-barriers',
    title: 'Barriers addressed',
    blocks: [
      { defsLabel: 'Global and India deep-dive' },
      { lead:
        'Barriers capture the main obstacles each organization actively works to clear on ' +
        'the path to the energy transition. An organization can work on multiple barriers, ' +
        'but only the primary barriers that an organization works on are included.' },
      { defs: [
        ['Finance',
          'Deploying or mobilising capital for energy projects - through direct financing, ' +
          'blended finance, de-risking instruments, or financial market development'],
        ['Policy & Regulation',
          'Strengthening, reforming, or aligning energy policies, regulations, market ' +
          'rules, or governance frameworks - including utility reform, market structure, ' +
          'and policy-based lending'],
        ['Technical',
          'Closing gaps in infrastructure, technology, data, or engineering - through ' +
          'investment, technical assistance, research, or standards development'],
        ['Coordination',
          'Bringing governments, donors, developers, and other actors together to align ' +
          'efforts, share knowledge, and avoid duplication'],
        ['Capabilities & Skills',
          'Building the human capital, institutional capacity, and workforce skills needed ' +
          'to plan, deliver, and manage energy systems'],
      ] },
    ],
  },
  {
    id: 'methodology-access-metric',
    title: 'Energy access and reliability metrics',
    blocks: [
      { defsLabel: 'Global map' },
      { lead:
        'The energy access and reliability metrics add context to the heat map. They are ' +
        'kept as separate measures because they answer different questions: access tells ' +
        'you who is connected, reliability tells you whether that connection delivers.' },
      { p:
        'Energy access is the share of each region’s population with the possibility of ' +
        'accessing electricity, for 2023 (the latest year available). Figures are the ' +
        'official regional aggregates and are reported as approximate.' },
      { source:
        'Source: World Bank, Access to Electricity (% of population), indicator ' +
        'EG.ELC.ACCS.ZS, drawn from the Sustainable Energy for All (SE4ALL) Global ' +
        'Electrification Database and the Tracking SDG 7 report (IEA, IRENA, UN Statistics ' +
        'Division, World Bank, WHO).' },
      { p:
        'Reliability of supply is scored qualitatively as Low, Medium, or High. The ' +
        'underlying measure is the World Bank’s Reliability of Supply and Transparency of ' +
        'Tariffs Index (scored 0-8), which combines the actual duration and frequency of ' +
        'power outages with the strength of the regulatory framework around them. A simple ' +
        'unweighted average of this index across the economies in each region was ' +
        'calculated, then grouped the regions into Low, Medium, and High bands based on ' +
        'where their scores naturally cluster.' },
      { source:
        'Source: World Bank, Doing Business 2020, Getting Electricity topic - Reliability ' +
        'of Supply and Transparency of Tariffs Index. Data collection was completed in ' +
        'May 2019 (archive.doingbusiness.org), and the series was discontinued in ' +
        'September 2021 (worldbank.org); 2020 is therefore the final edition and the ' +
        'figures are not updated.' },
    ],
  },
];

// Render a paragraph whose content may interleave strings with { link, text }
// objects, e.g. [ 'They follow ', { text: 'World Bank definitions', link: '...' }, '.' ].
function mthParts(parts) {
  return parts.map((part, i) =>
    typeof part === 'string'
      ? part
      : <a key={i} href={part.link} target="_blank" rel="noopener noreferrer">{part.text}</a>
  );
}

function MthBlock({ block }) {
  if (block.lead) return <p className="mth-lead">{block.lead}</p>;
  if (block.parts) return <p className="mth-para">{mthParts(block.parts)}</p>;
  if (block.p)    return <p className="mth-para">{block.p}</p>;
  if (block.sub)  return <h4 className="mth-sub">{block.sub}</h4>;
  if (block.source) return <p className="mth-source">{block.source}</p>;
  if (block.defsLabel) return <div className="mth-defs-label">{block.defsLabel}</div>;
  if (block.ul) {
    return (
      <ul className="mth-list">
        {block.ul.map((item, i) => <li key={i}>{item}</li>)}
      </ul>
    );
  }
  if (block.defs) {
    return (
      <dl className="mth-defs">
        {block.defs.map(([term, def], i) => (
          <div className="mth-def" key={i}>
            <dt>{term}</dt>
            <dd>{def}</dd>
          </div>
        ))}
      </dl>
    );
  }
  return null;
}

function MethodologyView({ methodologyTarget, setActiveView }) {
  const target = methodologyTarget && methodologyTarget.section;
  const nonce  = methodologyTarget && methodologyTarget.nonce;

  // Scroll + flash the requested section when arrived via a ? bubble.
  useEffectMth(() => {
    if (!target) return;
    const el = document.getElementById(target);
    if (!el) return;
    el.scrollIntoView({ behavior: 'smooth', block: 'start' });
    el.classList.add('is-flash');
    const t = setTimeout(() => el.classList.remove('is-flash'), 1600);
    return () => clearTimeout(t);
  }, [target, nonce]);

  const jumpTo = (id) => {
    const el = document.getElementById(id);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <div className="mth">
      <div className="mth-layout">
        {/* Sticky table of contents */}
        <nav className="mth-toc" aria-label="Methodology contents">
          <div className="mth-toc-head">On this page</div>
          <ol>
            {MTH_SECTIONS.map(s => (
              <li key={s.id}>
                <button type="button" className="mth-toc-link" onClick={() => jumpTo(s.id)}>
                  {s.title}
                </button>
              </li>
            ))}
          </ol>
        </nav>

        {/* Sections */}
        <div className="mth-body">
          {MTH_SECTIONS.map(s => (
            <section key={s.id} id={s.id} className="mth-section">
              <h3 className="mth-section-title">{s.title}</h3>
              {s.blocks.map((block, i) => <MthBlock key={i} block={block} />)}
            </section>
          ))}

          <p className="mth-foot">
            Questions about the methodology, or a category that doesn’t fit your
            organization? Reach out via the{' '}
            <a href="https://energyalliance.org/" target="_blank" rel="noopener noreferrer">Global Energy Alliance</a>.
          </p>
        </div>
      </div>
    </div>
  );
}

window.MethodologyView = MethodologyView;
