// views/RegionalIndiaView.jsx - Visual 1: India Demand & Supply twin hex maps
// Two panels side-by-side using a stylised hex-grid of states.
//   Panel A - demand side: state fill = supply reliability (poor/med/good);
//             circle marker = peak demand CAGR.
//   Panel B - supply side: state fill = RE generation in GWh (4 buckets, pale→dark green),
//             toggleable to RE as % of total generation; circle marker = BESS pipeline GWh.
// Click any hex → state detail drawer slides in from the right.

const { useState: useStateR, useMemo: useMemoR } = React;

// ─── Hex geometry helpers ───
function hexPointsPointy(cx, cy, r) {
  const pts = [];
  for (let i = 0; i < 6; i++) {
    const a = (Math.PI / 180) * (60 * i - 30);
    pts.push([cx + r * Math.cos(a), cy + r * Math.sin(a)]);
  }
  return pts.map(p => p.join(',')).join(' ');
}

function hexCenter(col, row, r) {
  const w = Math.sqrt(3) * r;
  const h = 1.5 * r;
  const x = col * w + (row % 2 ? w / 2 : 0);
  const y = row * h;
  return { x, y };
}

// ─── Encoding scales ───
const RELIABILITY_FILL = {
  poor: '#bf4f59',
  med:  '#e6a23c',
  good: '#5a8c66',
};
const RELIABILITY_LABEL = {
  poor: 'Poor (<18 h/day)',
  med:  'Medium (18-22 h/day)',
  good: 'Good (>22 h/day)',
};

// 4 RE generation buckets (GWh)
const RE_GWH_BUCKETS = [
  { max:   1000, fill: '#dbe9d6', label: '< 1 GWh-thou (≤ 1,000 GWh)' },
  { max:  10000, fill: '#a6cca2', label: '1,000-10,000 GWh' },
  { max:  30000, fill: '#5a9c69', label: '10,000-30,000 GWh' },
  { max: Infinity, fill: '#0e5e3a', label: '> 30,000 GWh' },
];
// 4 RE % buckets
const RE_PCT_BUCKETS = [
  { max: 10,  fill: '#dbe9d6', label: '< 10%' },
  { max: 25,  fill: '#a6cca2', label: '10-25%' },
  { max: 50,  fill: '#5a9c69', label: '25-50%' },
  { max: Infinity, fill: '#0e5e3a', label: '> 50%' },
];
function bucketFor(value, scale) {
  for (const b of scale) if (value <= b.max) return b;
  return scale[scale.length - 1];
}

// ─── State areas (sq km) and size scaling ───
// Used to scale individual hex radii so big states (RJ, MP, MH) read large
// and small states/UTs (DL, GA, SK) read small.
const AREAS = {
  RJ:342239, MP:308245, MH:307713, UP:240928, GJ:196024, KA:191791,
  AP:162968, OD:155707, CG:135191, TN:130058, TG:112077, BR:94163,
  WB:88752, AR:83743, JH:79714, AS:78438, LA:59146, HP:55673, UK:53483,
  PB:50362, HR:44212, JK:42241, KL:38852, ML:22429, MN:22327, MZ:21081,
  NL:16579, TR:10491, SK:7096, GA:3702, DL:1484,
};
const MAX_AREA = 342239; // Rajasthan
function rForState(code, baseR) {
  const a = AREAS[code];
  if (!a) return baseR * 0.7;
  // sqrt-scaled, clamped 0.42..0.95 of base radius (avoids overlap)
  const f = 0.42 + 0.55 * Math.sqrt(a / MAX_AREA);
  return baseR * Math.min(0.95, Math.max(0.42, f));
}

// ─── State centroids (lat/lon → outer SVG coords) ───
// Approximate state centroids in decimal degrees, projected via equirectangular
// into the same outer-SVG coord system used to render the India outline overlay.
// Calibration: the rendered outline occupies x∈[47, 432], y∈[-34, 373] in outer
// SVG coords, mapping to lon∈[68.1°, 97.4°E] and lat∈[37.1°, 6.7°N].
const LATLON = {
  JK:[33.8,76.0], LA:[34.5,77.7], HP:[31.8,77.2], UK:[30.0,79.0],
  PB:[31.0,75.5], HR:[29.0,76.1], DL:[28.7,77.1], RJ:[27.0,74.0],
  UP:[26.9,80.9], GJ:[22.7,71.6], MP:[23.6,78.7], BR:[25.7,85.3],
  JH:[23.6,85.3], WB:[22.6,87.9], OD:[20.2,85.4], CG:[21.3,81.9],
  MH:[19.7,75.7], TG:[17.9,79.3], AP:[15.9,79.7], KA:[14.9,76.0],
  GA:[15.3,74.1], KL:[10.3,76.4], TN:[11.1,78.7],
  SK:[27.6,88.5], AR:[28.2,94.7], NL:[26.2,94.5], AS:[26.2,92.9],
  ML:[25.5,91.4], MN:[24.7,93.9], TR:[23.8,91.7], MZ:[23.4,92.9],
};
const LON_PER_X = (432 - 47) / (97.4 - 68.1);   // ≈ 13.14 units/°
const LAT_PER_Y = (373 - (-34)) / (37.1 - 6.7); // ≈ 13.39 units/°
function geoCenter(code) {
  const ll = LATLON[code];
  if (!ll) return { x: 0, y: 0 };
  const [lat, lon] = ll;
  return {
    x: 47 + (lon - 68.1) * LON_PER_X,
    y: -34 + (37.1 - lat) * LAT_PER_Y,
  };
}

// Circle marker radius - log-ish scaling to keep tiny states visible without
// the big ones blowing out the map.
function circleR_CAGR(cagr) {
  if (!cagr || cagr <= 0) return 0;
  // 3.5% → 6px, 6% → 11px, 8.5% → 16px (cap 18)
  return Math.min(18, 4 + (cagr - 3) * 2.6);
}
function circleR_BESS(gwh) {
  if (!gwh || gwh <= 0) return 0;
  // 0.3 → 4, 1 → 6, 3 → 10, 8 → 16, cap 20
  return Math.min(20, 3 + Math.sqrt(gwh) * 5.5);
}

// ─── One hex map panel ───
function HexPanel({ panel, states, grid, mode, hovered, onHover, onPick }) {
  const r = grid.hexR;
  // Compute bounding box across all states
  const centers = states.map(s => geoCenter(s.code));
  const pad = r + 16;
  const minX = Math.min(...centers.map(c => c.x)) - pad;
  const maxX = Math.max(...centers.map(c => c.x)) + pad;
  const minY = Math.min(...centers.map(c => c.y)) - pad;
  const maxY = Math.max(...centers.map(c => c.y)) + pad;
  const vbW = maxX - minX;
  const vbH = maxY - minY;

  function fillFor(s) {
    if (panel === 'A') {
      return RELIABILITY_FILL[s.demand.reliability] || '#888';
    }
    // panel B
    if (mode === 'pct') return bucketFor(s.supply.rePercent, RE_PCT_BUCKETS).fill;
    return bucketFor(s.supply.reGenerationGWh, RE_GWH_BUCKETS).fill;
  }
  function circleR(s) {
    if (panel === 'A') return circleR_CAGR(s.demand.peakDemandCAGR);
    return circleR_BESS(s.supply.bessPipelineGWh);
  }
  function circleTitle(s) {
    if (panel === 'A') return `Peak demand CAGR ${s.demand.peakDemandCAGR}%`;
    return `BESS pipeline ${s.supply.bessPipelineGWh} GWh`;
  }

  return (
    <svg className="ri-svg" viewBox={`${minX} ${minY} ${vbW} ${vbH}`} preserveAspectRatio="xMidYMid meet">
      {/* Subtle cartographic ground */}
      <defs>
        <pattern id={`ri-grain-${panel}`} width="6" height="6" patternUnits="userSpaceOnUse" patternTransform="rotate(35)">
          <line x1="0" y1="0" x2="0" y2="6" stroke="rgba(255,255,255,0.025)" strokeWidth="1" />
        </pattern>
      </defs>
      <rect x={minX} y={minY} width={vbW} height={vbH} fill={`url(#ri-grain-${panel})`} />

      {/* State shapes (real geographic polygons) */}
      <g>
        {states.map(s => {
          const shape = (window.INDIA_STATE_SHAPES || {})[s.code];
          if (!shape) return null;
          const [cx, cy] = shape.c;
          const sr = rForState(s.code, r);
          const isHover = hovered === s.code;
          return (
            <g key={s.code}
               className={'ri-hex' + (isHover ? ' is-hover' : '')}
               onMouseEnter={() => onHover(s.code)}
               onMouseLeave={() => onHover(null)}
               onClick={() => onPick(s)}
               style={{ cursor: 'pointer' }}>
              {shape.polys.map((pts, i) => (
                <polygon key={i} points={pts}
                  fill={fillFor(s)}
                  stroke={isHover ? '#fdce07' : 'rgba(244,243,237,0.85)'}
                  strokeWidth={isHover ? 1.6 : 0.9}
                  strokeLinejoin="round" />
              ))}
            </g>
          );
        })}
      </g>

      {/* Circle markers */}
      <g>
        {states.map(s => {
          const cr = circleR(s);
          if (cr <= 0) return null;
          const { x, y } = geoCenter(s.code);
          return (
            <circle key={s.code+'c'} cx={x} cy={y} r={cr}
              fill={panel==='A' ? 'rgba(15,15,25,0.55)' : 'rgba(253,206,7,0.78)'}
              stroke={panel==='A' ? 'rgba(255,255,255,0.85)' : 'rgba(20,20,20,0.55)'}
              strokeWidth={1.2}
              style={{ pointerEvents: 'none' }}>
              <title>{circleTitle(s)}</title>
            </circle>
          );
        })}
      </g>

      {/* Hydro symbol - Panel B only, shown when hydro > 10% of total RE generation */}
      {panel === 'B' && (
        <g style={{ pointerEvents: 'none' }}>
          {states.map(s => {
            const hydro = s.supply.reByFuel.hydro;
            const total = s.supply.reGenerationGWh || 1;
            if (hydro / total <= 0.10) return null;
            const shape = (window.INDIA_STATE_SHAPES || {})[s.code];
            if (!shape) return null;
            const [cx, cy] = shape.c;
            return (
              <g key={s.code + '-hydro'} transform={`translate(${cx}, ${cy})`}>
                <title>Hydro in renewables mix ({Math.round(hydro / total * 100)}% · {hydro} GWh)</title>
                <path d="M 0,-5 C 3.5,-1.5 3.5,3 0,5 C -3.5,3 -3.5,-1.5 0,-5 Z"
                  fill="#2a6a86" stroke="rgba(244,243,237,0.9)" strokeWidth="0.8" />
              </g>
            );
          })}
        </g>
      )}
    </svg>
  );
}

// ─── Detail drawer ───
function StateDrawer({ state, panel, mode, national, onClose }) {
  if (!state) return null;
  const d = state.demand, s = state.supply;
  const fuels = s.reByFuel;
  const total = (fuels.solar + fuels.wind + fuels.hydro + fuels.other) || 1;
  const fuelRows = [
    { k:'Solar', v:fuels.solar, c:'#fdce07' },
    { k:'Wind',  v:fuels.wind,  c:'#8bcdd2' },
    { k:'Hydro', v:fuels.hydro, c:'#2a6a86' },
    { k:'Other', v:fuels.other, c:'#aa6227' },
  ];

  return (
    <div className="ri-drawer-overlay" onClick={onClose}>
    <aside className="ri-drawer" onClick={(e) => e.stopPropagation()}>
      <header className="ri-drawer-head">
        <div className="ri-drawer-eyebrow">Panel {panel} · State detail</div>
        <h3>{state.name}</h3>
        <div className="ri-drawer-sub"><span className="ri-drawer-code">{state.code}</span> · {state.zone === 'NE' ? 'Northeast' : state.zone === 'N' ? 'North' : state.zone === 'W' ? 'West' : state.zone === 'S' ? 'South' : state.zone === 'E' ? 'East' : 'Central'} India</div>
        <button className="ri-drawer-close" onClick={onClose} aria-label="Close">×</button>
      </header>

      <section className="ri-drawer-section">
        <h4>Demand side</h4>
        <div className="ri-kv-row">
          <div className="ri-kv">
            <span className="ri-kv-label">Peak demand</span>
            <b>{d.peakDemandMW.toLocaleString()} <em>MW</em></b>
          </div>
          <div className="ri-kv">
            <span className="ri-kv-label">Peak demand CAGR</span>
            <b>{d.peakDemandCAGR}<em>%</em></b>
          </div>
          <div className="ri-kv">
            <span className="ri-kv-label">Hours of supply / day</span>
            <b style={{ color: RELIABILITY_FILL[d.reliability] }}>{d.hoursPerDay}</b>
          </div>
          <div className="ri-kv">
            <span className="ri-kv-label">Energy deficit</span>
            <b>{d.energyDeficitMU.toLocaleString()} <em>MU</em></b>
          </div>
        </div>
        <p className="ri-note">Reliability self-reported by state to 24×7 Power for All - indicative.</p>
      </section>

      <section className="ri-drawer-section">
        <h4>Supply side</h4>
        <div className="ri-kv-row">
          <div className="ri-kv">
            <span className="ri-kv-label">RE generation</span>
            <b>{s.reGenerationGWh.toLocaleString()} <em>GWh</em></b>
          </div>
          <div className="ri-kv">
            <span className="ri-kv-label">RE % of total</span>
            <b>{s.rePercent}<em>%</em></b>
          </div>
          <div className="ri-kv">
            <span className="ri-kv-label">Installed RE capacity</span>
            <b>{s.installedReGW} <em>GW</em></b>
          </div>
          <div className="ri-kv">
            <span className="ri-kv-label">AT&amp;C losses</span>
            <b>{s.atcLossesPct}<em>%</em></b>
          </div>
        </div>

        <div className="ri-stack-wrap">
          <div className="ri-stack-label">RE generation by fuel</div>
          <div className="ri-stack">
            {fuelRows.map(f => (
              <div key={f.k} className="ri-stack-seg" style={{ width: (f.v/total*100)+'%', background: f.c }}
                   title={`${f.k}: ${f.v.toLocaleString()} GWh`}></div>
            ))}
          </div>
          <div className="ri-stack-legend">
            {fuelRows.map(f => (
              <span key={f.k}><i style={{ background: f.c }}></i>{f.k}<em>{f.v.toLocaleString()} GWh</em></span>
            ))}
          </div>
        </div>
      </section>

      <section className="ri-drawer-section">
        <h4>BESS pipeline</h4>
        <div className="ri-kv-row">
          <div className="ri-kv">
            <span className="ri-kv-label">Pipeline total</span>
            <b>{s.bessPipelineGWh ? s.bessPipelineGWh + ' GWh' : <span className="ri-nopipe">no pipeline data</span>}</b>
          </div>
          <div className="ri-kv">
            <span className="ri-kv-label">National target (2030)</span>
            <b>{national.bessTarget2030GWh} <em>GWh</em></b>
          </div>
        </div>
        {s.bessProjects.length ? (
          <ul className="ri-projlist">
            {s.bessProjects.map((p, i) => (
              <li key={i}><b>{p.name}</b> · {p.gwh} GWh · <span className={'ri-status ri-status--'+p.status.replace(/\s+/g,'-')}>{p.status}</span></li>
            ))}
          </ul>
        ) : <p className="ri-note">No tracked BESS projects (energymap.in / SECI).</p>}
      </section>

      {s.pumpedHydro.length > 0 && (
        <section className="ri-drawer-section">
          <h4>Pumped hydro</h4>
          <ul className="ri-projlist">
            {s.pumpedHydro.map((p, i) => (
              <li key={i}><b>{p.name}</b> · {p.mw} MW · <span className={'ri-status ri-status--'+p.status.replace(/\s+/g,'-')}>{p.status}</span></li>
            ))}
          </ul>
        </section>
      )}

      {state.initiatives.length > 0 && (
        <section className="ri-drawer-section">
          <h4>Active initiatives</h4>
          <div className="ri-tags">
            {state.initiatives.map(i => <span key={i} className="ri-tag">{i}</span>)}
          </div>
        </section>
      )}

      <footer className="ri-drawer-foot">
        For illustrative purposes only · numbers to be validated · Systemiq 2026
      </footer>
    </aside>
    </div>
  );
}

// ─── Main view ───
function RegionalIndiaView() {
  const data = window.INDIA_STATES;
  const states = data.states;
  const grid = data.grid;

  const [hovered, setHovered] = useStateR(null);
  const [selected, setSelected] = useStateR(null);
  const [selectedPanel, setSelectedPanel] = useStateR('A');
  const [bMode, setBMode] = useStateR('gwh'); // 'gwh' | 'pct'

  const reScale = bMode === 'pct' ? RE_PCT_BUCKETS : RE_GWH_BUCKETS;

  return (
    <div className="ri-view" onClick={() => setSelected(null)}>
      <div className="ri-banner">
        <span className="ri-banner-pill">Illustrative</span>
        State numbers shaped to the strategic narrative - to be replaced with primary-source data (CEA · Ember · MoP · energymap.in) before publication.
      </div>

      <div className="ri-stage" onClick={(e) => e.stopPropagation()}>
        <div className="ri-panels">
          {/* Panel A */}
          <section className="ri-panel">
            <header className="ri-panel-head">
              <div className="ri-panel-tag">Panel A · Demand</div>
              <h3><strong>Northern India</strong> faces a challenge: some of the country's highest demand growth and lower grid performance and supply reliability.</h3>
              <p>Fill = hours of supply per day. Marker = peak demand CAGR.</p>
            </header>

            <div className="ri-panel-body">
            <div className="ri-panel-map" onClick={(e) => { e.stopPropagation(); }}>
              <HexPanel
                panel="A" states={states} grid={grid} mode="reliability"
                hovered={hovered} onHover={setHovered}
                onPick={(s) => { setSelected(s); setSelectedPanel('A'); }}
              />
            </div>

            <div className="ri-legend">
              <div className="ri-legend-block">
                <span className="ri-legend-title">Fill - supply reliability</span>
                <div className="ri-legend-items">
                  {Object.entries(RELIABILITY_LABEL).map(([k, l]) => (
                    <span key={k} className="ri-legend-item">
                      <i className="ri-swatch" style={{ background: RELIABILITY_FILL[k] }}></i>{l}
                    </span>
                  ))}
                </div>
                <span className="ri-legend-source">Source: MoP 24×7 Power for All (self-reported)</span>
              </div>
              <div className="ri-legend-block">
                <span className="ri-legend-title">Marker - peak demand CAGR</span>
                <div className="ri-legend-bubbles">
                  <span><svg width="20" height="20"><circle cx="10" cy="10" r={circleR_CAGR(4)} fill="rgba(15,15,25,0.55)" stroke="white" strokeWidth="1.2"/></svg>4%</span>
                  <span><svg width="28" height="28"><circle cx="14" cy="14" r={circleR_CAGR(6)} fill="rgba(15,15,25,0.55)" stroke="white" strokeWidth="1.2"/></svg>6%</span>
                  <span><svg width="40" height="40"><circle cx="20" cy="20" r={circleR_CAGR(8.5)} fill="rgba(15,15,25,0.55)" stroke="white" strokeWidth="1.2"/></svg>8.5%</span>
                </div>
                <span className="ri-legend-source">Source: CEA National Electricity Plan</span>
              </div>
            </div>
            </div>
          </section>

          {/* Panel B */}
          <section className="ri-panel">
            <header className="ri-panel-head">
              <div className="ri-panel-tag">Panel B · Supply</div>
              <h3><strong>North-East India</strong> is trailing on renewables, and the BESS pipeline is following the same pattern, concentrating in the states that already lead on clean energy.</h3>
              <p>Fill = {bMode==='pct' ? 'RE as % of total generation' : 'RE generation in GWh'}. Marker = BESS pipeline (GWh).</p>
              <div className="ri-toggle" role="group">
                <button type="button" className={'ri-toggle-btn' + (bMode==='gwh' ? ' is-on':'')} onClick={() => setBMode('gwh')}>GWh</button>
                <button type="button" className={'ri-toggle-btn' + (bMode==='pct' ? ' is-on':'')} onClick={() => setBMode('pct')}>% of total</button>
              </div>
            </header>

            <div className="ri-panel-body">
            <div className="ri-panel-map" onClick={(e) => { e.stopPropagation(); }}>
              <HexPanel
                panel="B" states={states} grid={grid} mode={bMode}
                hovered={hovered} onHover={setHovered}
                onPick={(s) => { setSelected(s); setSelectedPanel('B'); }}
              />
            </div>

            <div className="ri-legend">
              <div className="ri-legend-block">
                <span className="ri-legend-title">Fill - {bMode==='pct' ? 'RE as % of total generation' : 'RE generation (GWh)'}</span>
                <div className="ri-legend-items">
                  {reScale.map((b, i) => (
                    <span key={i} className="ri-legend-item">
                      <i className="ri-swatch" style={{ background: b.fill }}></i>{b.label}
                    </span>
                  ))}
                </div>
                <span className="ri-legend-source">Source: Ember India Electricity Data Explorer</span>
              </div>
              <div className="ri-legend-block">
                <span className="ri-legend-title">Symbol - hydro in RE mix</span>
                <div className="ri-legend-items">
                  <span className="ri-legend-item">
                    <svg width="14" height="14" style={{ verticalAlign: 'middle', marginRight: 4 }}>
                      <path d="M 7,-1 C 10.5,3 10.5,9 7,11 C 3.5,9 3.5,3 7,-1 Z" transform="translate(0,2)" fill="#2a6a86" stroke="rgba(244,243,237,0.9)" strokeWidth="0.8"/>
                    </svg>
                    Hydro &gt; 10% of RE generation
                  </span>
                </div>
              </div>
              <div className="ri-legend-block">
                <span className="ri-legend-title">Marker - BESS pipeline (GWh)</span>
                <div className="ri-legend-bubbles">
                  <span><svg width="20" height="20"><circle cx="10" cy="10" r={circleR_BESS(0.5)} fill="rgba(253,206,7,0.78)" stroke="rgba(20,20,20,0.55)" strokeWidth="1.2"/></svg>0.5</span>
                  <span><svg width="32" height="32"><circle cx="16" cy="16" r={circleR_BESS(2)} fill="rgba(253,206,7,0.78)" stroke="rgba(20,20,20,0.55)" strokeWidth="1.2"/></svg>2</span>
                  <span><svg width="44" height="44"><circle cx="22" cy="22" r={circleR_BESS(6)} fill="rgba(253,206,7,0.78)" stroke="rgba(20,20,20,0.55)" strokeWidth="1.2"/></svg>6</span>
                </div>
                <span className="ri-legend-source">Sources: energymap.in/storage · SECI</span>
                <div className="ri-context-pill">National BESS target · {data.national.bessTarget2030GWh} GWh by 2030 (CEA)</div>
              </div>
            </div>
            </div>
          </section>
        </div>

        {selected && (
          <StateDrawer
            state={selected}
            panel={selectedPanel}
            mode={bMode}
            national={data.national}
            onClose={() => setSelected(null)}
          />
        )}
      </div>

      <div className="ri-foot">
        <strong>The market-making story.</strong> RE generation is concentrated in the west and south (Rajasthan, Gujarat, Karnataka, Tamil Nadu). Demand growth and poor reliability are concentrated in the east (Bihar, Jharkhand, Odisha). The gap between Panel A and Panel B is the investable opportunity.
      </div>
    </div>
  );
}

window.RegionalIndiaView = RegionalIndiaView;
