/* global React */

function Hex({ cx, cy, r, fill = 'none', stroke = '#ecefe8', sw = 1, fillOpacity = 1 }) {
  const pts = [];
  for (let i = 0; i < 6; i++) {
    const a = (Math.PI / 3) * i + Math.PI / 6;
    pts.push(`${(cx + Math.cos(a) * r).toFixed(2)},${(cy + Math.sin(a) * r).toFixed(2)}`);
  }
  return <polygon points={pts.join(' ')} fill={fill} fillOpacity={fillOpacity} stroke={stroke} strokeWidth={sw} />;
}

function AggregationDiagram() {
  const [active, setActive] = React.useState(4);

  const layers = [
    { res: 'res 11', name: 'Building',     area: '~10 m²',     tier: 'detail',  pop: '12',     credits: '180' },
    { res: 'res 9',  name: 'Block',        area: '0.10 km²',   tier: 'detail',  pop: '430',    credits: '14k' },
    { res: 'res 7',  name: 'District',     area: '5.2 km²',    tier: 'detail',  pop: '12.4k',  credits: '380k' },
    { res: 'res 6',  name: 'City',         area: '36 km²',     tier: 'player',  pop: '92.3k',  credits: '2.8M', highlight: true },
    { res: 'res 5',  name: 'Metropolitan', area: '253 km²',    tier: 'agg',     pop: '640k',   credits: '19M' },
    { res: 'res 4',  name: 'Region',       area: '1,770 km²',  tier: 'agg',     pop: '4.4M',   credits: '130M' },
    { res: 'res 3',  name: 'Country',      area: '12,393 km²', tier: 'agg',     pop: '31M',    credits: '900M' },
    { res: 'res 2',  name: 'Continental',  area: '86,801 km²', tier: 'planet',  pop: '215M',   credits: '6.2B' },
  ];

  const cur = layers[active];

  const renderVis = () => {
    if (cur.tier === 'detail') {
      return (
        <svg viewBox="0 0 280 280">
          <rect x="0" y="0" width="280" height="280" fill="#0a0f0d" />
          <g stroke="rgba(236,239,232,0.05)" strokeWidth="1">
            {Array.from({length:14}).map((_,i)=>(<line key={'h'+i} x1="0" y1={i*20} x2="280" y2={i*20} />))}
            {Array.from({length:14}).map((_,i)=>(<line key={'v'+i} x1={i*20} y1="0" x2={i*20} y2="280" />))}
          </g>
          {Array.from({length: cur.res === 'res 11' ? 1 : 28}).map((_, i) => {
            const seed = i * 9301 + 49297;
            const bx = 30 + (seed % 200), by = 30 + ((seed * 7) % 200);
            const bw = 12 + (seed % 28), bh = 12 + ((seed * 3) % 28);
            return <rect key={i} x={bx} y={by} width={bw} height={bh} fill="rgba(236,199,129,0.55)" stroke="#ecc781" strokeWidth="0.5" />;
          })}
          <text x="140" y="266" textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="9" fill="#8b918a" letterSpacing="0.14em">FOOTPRINTS · OSM</text>
        </svg>
      );
    }
    if (cur.tier === 'player') {
      return (
        <svg viewBox="0 0 280 280">
          <rect x="0" y="0" width="280" height="280" fill="#0a0f0d" />
          <Hex cx={140} cy={140} r={120} fill="rgba(108,212,154,0.05)" stroke="#6cd49a" sw={1.2} />
          {[[140,140],[140,82],[140,198],[90,111],[90,169],[190,111],[190,169]].map(([x,y], i) => (
            <Hex key={i} cx={x} cy={y} r={32} fill="rgba(108,212,154,0.13)" stroke="rgba(108,212,154,0.7)" sw={1.2} />
          ))}
          <text x="140" y="146" textAnchor="middle" fontFamily="Outfit" fontSize="13" fill="#ecefe8" fontWeight="500">RES 6</text>
          <text x="140" y="162" textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="9" fill="#8b918a" letterSpacing="0.14em">36 km² · 7 CHILDREN</text>
        </svg>
      );
    }
    if (cur.tier === 'agg') {
      return (
        <svg viewBox="0 0 280 280">
          <rect x="0" y="0" width="280" height="280" fill="#0a0f0d" />
          {(() => {
            const out = [];
            const r = 18, w = r * Math.sqrt(3), h = r * 1.5;
            for (let row = 0; row < 9; row++) for (let col = 0; col < 9; col++) {
              const x = 20 + col * w + (row % 2) * w / 2, y = 20 + row * h;
              if (x < 10 || x > 270 || y < 10 || y > 270) continue;
              const seed = (row * 17 + col * 31) % 100;
              const hue = seed > 70 ? '#ecc781' : seed > 40 ? '#8b7fcf' : seed > 20 ? '#6cd49a' : '#5ec5d4';
              const op = 0.22 + (seed / 100) * 0.5;
              out.push(<Hex key={`${row}-${col}`} cx={x} cy={y} r={r * 0.92} fill={hue} fillOpacity={op} stroke="rgba(0,0,0,0.4)" sw={0.5} />);
            }
            return out;
          })()}
          <text x="140" y="270" textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="9" fill="#8b918a" letterSpacing="0.14em">COLOR = PRICE INDEX</text>
        </svg>
      );
    }
    return (
      <svg viewBox="0 0 280 280">
        <rect x="0" y="0" width="280" height="280" fill="#0a0f0d" />
        <defs><radialGradient id="p1" cx="40%" cy="35%"><stop offset="0%" stopColor="#1a221c" /><stop offset="100%" stopColor="#050807" /></radialGradient></defs>
        <circle cx="140" cy="140" r="100" fill="url(#p1)" stroke="rgba(108,212,154,0.4)" />
        {Array.from({length: 18}).map((_, i) => {
          const a = (i / 18) * Math.PI * 2;
          const r = 60 + (i % 3) * 18;
          const x = 140 + Math.cos(a) * r;
          const y = 140 + Math.sin(a) * r * 0.5;
          return <Hex key={i} cx={x} cy={y} r={9} fill="rgba(108,212,154,0.18)" stroke="#6cd49a" sw={0.6} />;
        })}
        <text x="140" y="270" textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontSize="9" fill="#8b918a" letterSpacing="0.14em">CONTINENTAL ROLL-UP · 122 HEXES</text>
      </svg>
    );
  };

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.3fr) minmax(0, 1fr)', gap: 32, alignItems: 'start' }}>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
        {layers.map((L, i) => (
          <div
            key={i}
            className={`agg-row ${i === active ? 'active' : ''}`}
            onMouseEnter={() => setActive(i)}
            onClick={() => setActive(i)}
          >
            <div style={{ fontFamily: 'var(--og-font-mono)', fontSize: 11, color: 'var(--og-bone-mute)', letterSpacing: '0.14em', textTransform: 'uppercase' }}>{L.res}</div>
            <svg width="36" height="36" viewBox="-20 -20 40 40">
              <Hex cx={0} cy={0} r={14} fill={i === active ? 'rgba(108,212,154,0.20)' : 'rgba(236,239,232,0.04)'} stroke={i === active ? '#6cd49a' : 'rgba(199,204,195,0.3)'} sw={1.2} />
            </svg>
            <div>
              <div style={{ fontFamily: 'var(--og-font-ui)', fontSize: 16, color: 'var(--og-bone)', fontWeight: 500 }}>
                {L.name}
                {L.highlight && <span style={{ marginLeft: 10, fontFamily: 'var(--og-font-mono)', fontSize: 9, padding: '2px 6px', borderRadius: 3, background: 'rgba(108,212,154,0.15)', color: 'var(--og-bloom-300)', letterSpacing: '0.12em' }}>YOUR HEX</span>}
              </div>
              <div style={{ fontFamily: 'var(--og-font-mono)', fontSize: 11, color: 'var(--og-bone-mute)', letterSpacing: '0.06em', marginTop: 2 }}>{L.area}</div>
            </div>
            <div style={{ textAlign: 'right', fontFamily: 'var(--og-font-mono)', fontSize: 11 }}>
              <div style={{ color: 'var(--og-bone-mute)' }}>POP {L.pop}</div>
              <div style={{ color: 'var(--og-ember-300)', marginTop: 2 }}>¢ {L.credits}/T</div>
            </div>
          </div>
        ))}
        <div style={{ marginTop: 14, fontFamily: 'var(--og-font-mono)', fontSize: 10, color: 'var(--og-bone-soft)', letterSpacing: '0.12em', textTransform: 'uppercase' }}>
          ↑ aggregation every 10 ticks · price signals propagate within 1–N
        </div>
      </div>

      <div style={{ position: 'sticky', top: 100, background: 'var(--og-soil)', border: '1px solid var(--og-line-strong)', borderRadius: 6, overflow: 'hidden' }}>
        <div className="og-panel-header">
          <div className="og-panel-title">{cur.res} · {cur.name}</div>
          <span className="og-panel-badge"><span className="og-dot og-dot-live" />LIVE</span>
        </div>
        <div style={{ padding: 18 }}>
          <div style={{ aspectRatio: '1', background: 'var(--og-void)', borderRadius: 6, overflow: 'hidden', border: '1px solid var(--og-line)' }}>
            {renderVis()}
          </div>
          <div style={{ marginTop: 14, fontSize: 13, color: 'var(--og-bone-dim)', lineHeight: 1.6 }}>
            {cur.tier === 'player' && 'The unit a player claims and tends. Aggregates 7 child Res-7 districts; rolls up into a Res-5 metro market.'}
            {cur.tier === 'detail' && 'Full simulation — individual entities, citizen aggregates, granular production chains.'}
            {cur.tier === 'agg' && 'Statistical aggregate — population, wealth, production sums; no individual citizens.'}
            {cur.tier === 'planet' && 'Planetary spot prices that feed back to producing hexes within 1–N ticks.'}
          </div>
        </div>
      </div>
    </div>
  );
}

window.AggregationDiagram = AggregationDiagram;
window.HexShape = Hex;
