/* Desktop · Geospatial Risk Heatmap — full map view */

function DesktopHeatmap() {
  const { live, alertState } = useGA();
  const [layer, setLayer] = React.useState('soil');
  const [selZone, setSelZone] = React.useState('B');

  return (
    <DesktopShell active="heatmap" kicker="K3 · KAKHETI"
      breadcrumb={['Saperavi K-3', 'Risk Heatmap']}
      right={
        <>
          <Pill color="ghost" size="sm">SAT · SENTINEL-2 · 23 MAR</Pill>
          <Pill color="ghost" size="sm">EXPORT</Pill>
        </>
      }>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 320px', gap: 0, height: '100%' }}>
        {/* Map */}
        <div style={{ position: 'relative',
          background: 'radial-gradient(circle at 50% 50%, #161A18 0%, #0A0C0B 100%)',
          borderRight: '1px solid var(--line)' }}>
          <BigGeoMap layer={layer} selZone={selZone} setSelZone={setSelZone} alertState={alertState} />
          {/* layer chips */}
          <div style={{ position: 'absolute', top: 16, left: 20,
            display: 'flex', gap: 6, padding: 4,
            background: 'rgba(10,10,11,0.7)', backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
            border: '1px solid var(--line-2)', borderRadius: 8 }}>
            {[
              ['soil', 'SOIL · MOISTURE'],
              ['ndvi', 'NDVI · SENTINEL'],
              ['frost', 'FROST · RISK'],
              ['uv', 'UV · INDEX'],
            ].map(([id, l]) => (
              <button key={id} onClick={() => setLayer(id)} style={{
                padding: '7px 12px', fontFamily: 'var(--f-mono)', fontSize: 10.5, fontWeight: 600,
                letterSpacing: '0.08em', textTransform: 'uppercase',
                background: layer === id ? 'rgba(255,214,10,0.15)' : 'transparent',
                color: layer === id ? 'var(--yellow)' : 'var(--ink-2)',
                border: 'none', borderRadius: 5, cursor: 'pointer',
              }}>{l}</button>
            ))}
          </div>
          {/* map controls */}
          <div style={{ position: 'absolute', top: 16, right: 20, display: 'flex', flexDirection: 'column', gap: 4 }}>
            {['+', '−', '⌖'].map((c) => (
              <button key={c} style={{
                width: 32, height: 32, borderRadius: 6,
                background: 'rgba(10,10,11,0.7)',
                backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
                border: '1px solid var(--line-2)',
                color: 'var(--ink)', fontFamily: 'var(--f-mono)', fontSize: 14, fontWeight: 600,
              }}>{c}</button>
            ))}
          </div>
          {/* legend */}
          <div style={{ position: 'absolute', bottom: 16, left: 20, right: 360,
            padding: '12px 14px',
            background: 'rgba(10,10,11,0.8)', backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
            border: '1px solid var(--line-2)', borderRadius: 8,
            display: 'flex', alignItems: 'center', gap: 16, justifyContent: 'space-between' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span className="ga-kicker">DEPLETION · %VMC</span>
              <span style={{ width: 220, height: 8,
                background: 'linear-gradient(to right, #FF453A, #FFA500, #FFD60A, #A6E840, #43D67A)',
                borderRadius: 2 }}/>
            </div>
            <div style={{ display: 'flex', gap: 14, fontFamily: 'var(--f-mono)', fontSize: 10, color: 'var(--ink-3)' }}>
              <span><b style={{ color: 'var(--red)' }}>{'<'}18</b> CRIT</span>
              <span><b style={{ color: 'var(--amber)' }}>18–24</b> STRESS</span>
              <span><b style={{ color: 'var(--yellow)' }}>24–32</b> WATCH</span>
              <span><b style={{ color: 'var(--green)' }}>32+</b> OK</span>
            </div>
          </div>
          {/* compass + coords */}
          <div className="ga-kicker" style={{ position: 'absolute', bottom: 16, right: 360+20,
            fontSize: 9.5, color: 'var(--ink-3)',
            background: 'rgba(10,10,11,0.7)', padding: '4px 8px', borderRadius: 4,
            border: '0.5px solid var(--line-2)' }}>
            41°57′N 45°48′E · ELEV 240–310M
          </div>
        </div>

        {/* Right panel */}
        <div style={{ background: 'var(--bg-2)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          <div style={{ padding: '16px 20px 14px', borderBottom: '1px solid var(--line)' }}>
            <div className="ga-kicker">SELECTED · ZONE {selZone}</div>
            <div className="ga-disp" style={{ fontSize: 22, fontWeight: 600, marginTop: 6,
              letterSpacing: '-0.02em' }}>
              {FARM.zones.find(z => z.id === selZone)?.name}
            </div>
            <div className="ga-mono" style={{ fontSize: 11, color: 'var(--ink-3)', marginTop: 4 }}>
              {FARM.zones.find(z => z.id === selZone)?.nodes} sensors · 1.2 ha · saperavi
            </div>
          </div>

          {/* Zone telemetry */}
          <div style={{ padding: 16, borderBottom: '1px solid var(--line)' }}>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <ZoneMini k="SOIL" v={FARM.zones.find(z => z.id === selZone).soil} u="%vmc" c="amber" />
              <ZoneMini k="AMBIENT" v={FARM.zones.find(z => z.id === selZone).temp} u="°C" c="blue" />
              <ZoneMini k="HUMIDITY" v={FARM.zones.find(z => z.id === selZone).hum} u="%" c="ink" />
              <ZoneMini k="UV" v={FARM.zones.find(z => z.id === selZone).uv} u="idx" c="yellow" />
            </div>
          </div>

          {/* Anomalies */}
          <div style={{ padding: 16, borderBottom: '1px solid var(--line)' }}>
            <div className="ga-kicker" style={{ marginBottom: 10 }}>Detected Anomalies · 7d</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              {[
                { t: 'Soil moisture vector', d: 'Depletion −6%/24h · NDVI −0.04', tone: 'red' },
                { t: 'Frost-radiative', d: 'Dew point −2.1°C · radiative loss high', tone: 'amber' },
                { t: 'Canopy heat retention', d: 'Lower than ridge mean · acceptable', tone: 'green' },
              ].map((a, i) => (
                <div key={i} style={{
                  padding: 10, background: 'var(--bg-3)', borderRadius: 6,
                  borderLeft: `2px solid ${a.tone === 'amber' ? '#FFA500' : a.tone === 'red' ? '#FF453A' : '#43D67A'}`,
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <span style={{ fontSize: 12.5, fontWeight: 500 }}>{a.t}</span>
                    <Pill color={a.tone} size="sm">{a.tone === 'green' ? 'OK' : 'OPEN'}</Pill>
                  </div>
                  <div style={{ marginTop: 4, fontFamily: 'var(--f-mono)', fontSize: 10.5, color: 'var(--ink-3)' }}>{a.d}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Recommendation strip */}
          <div style={{ padding: 16, flex: 1, overflow: 'auto' }}>
            <div className="ga-kicker" style={{ marginBottom: 10 }}>AI Recommendation</div>
            <div style={{
              padding: 14,
              background: 'rgba(255,165,0,0.06)', border: '1px solid rgba(255,165,0,0.4)',
              borderRadius: 8, fontSize: 13, lineHeight: 1.5, color: 'var(--ink)',
            }}>
              Activate <b style={{ color: 'var(--yellow)' }}>5 valves on zone B</b> at 14:30 for a 4.2mm pulse.
              Yield-risk drops 22%. Cost ≈ ₾28, ledger signature already prepared.
              <div style={{ marginTop: 12, display: 'flex', gap: 8 }}>
                <GhostButton color="amber" solid size="sm" style={{ flex: 1 }}>Execute →</GhostButton>
                <GhostButton color="ghost" size="sm">Compare</GhostButton>
              </div>
            </div>
          </div>
        </div>
      </div>
    </DesktopShell>
  );
}

function ZoneMini({ k, v, u, c }) {
  const cm = { amber: '#FFA500', blue: '#4FC3FF', ink: '#FAFAFA', yellow: '#FFD60A' };
  return (
    <div style={{ padding: '10px 12px', background: 'var(--bg-3)', borderRadius: 6 }}>
      <div className="ga-kicker" style={{ fontSize: 9 }}>{k}</div>
      <div className="ga-mono" style={{ fontSize: 18, fontWeight: 600, color: cm[c], marginTop: 4, letterSpacing: '-0.02em' }}>
        {v}<span style={{ fontSize: 10, color: 'var(--ink-3)', marginLeft: 4 }}>{u}</span>
      </div>
    </div>
  );
}

function BigGeoMap({ layer, selZone, setSelZone, alertState }) {
  // Full geospatial map of the K-3 plot with realistic topo lines, satellite imagery feel
  const w = 920, h = 720;
  const zones = [
    { id: 'A', name: 'NORTH SLOPE',  poly: [[80,80],[400,90],[440,250],[420,360],[100,380]], color: '#43D67A' },
    { id: 'B', name: 'LOW RIDGE',    poly: [[440,100],[820,120],[820,300],[800,440],[460,400]], color: '#FFA500', alert: true },
    { id: 'C', name: 'SOUTH TERR.',  poly: [[100,400],[440,400],[460,560],[440,650],[120,650]], color: '#FFD60A' },
    { id: 'D', name: 'EAST BLOCK',   poly: [[460,420],[820,460],[800,640],[460,650]], color: '#FFA500', alert: true },
  ];

  // soil moisture grid
  const grid = [];
  const cellW = 18, cellH = 18;
  const cols = Math.floor(w / cellW), rows = Math.floor(h / cellH);
  for (let y = 0; y < rows; y++) {
    for (let x = 0; x < cols; x++) {
      const cx = x * cellW + cellW / 2;
      const cy = y * cellH + cellH / 2;
      // assign zone-ish moisture
      const isBD = cx > 440;
      const isBottom = cy > 400;
      const base = (cx > 440 && cy < 440) ? 25 : (cx > 460 && cy > 420) ? 22 : (cy > 400 ? 36 : 39);
      const noise = Math.sin(x * 0.3) * 4 + Math.cos(y * 0.4) * 3 + Math.sin(x * 0.1 + y * 0.2) * 2;
      let v = base + noise;
      if (alertState === 'drought' && isBD) v -= 10;
      grid.push({ x: cx, y: cy, v });
    }
  }
  const colorForV = (v) => {
    if (v < 18) return '#FF453A';
    if (v < 24) return '#FFA500';
    if (v < 32) return '#FFD60A';
    if (v < 38) return '#A6E840';
    return '#43D67A';
  };

  // Sensor positions (real-ish across zones)
  const sensors = [
    { x: 140, y: 130, z: 'A' }, { x: 260, y: 110, z: 'A' }, { x: 360, y: 200, z: 'A' }, { x: 200, y: 300, z: 'A' },
    { x: 500, y: 150, z: 'B', alert: true }, { x: 640, y: 170, z: 'B', alert: true }, { x: 760, y: 200, z: 'B' },
    { x: 580, y: 260, z: 'B', alert: true }, { x: 690, y: 340, z: 'B' },
    { x: 180, y: 500, z: 'C' }, { x: 320, y: 540, z: 'C' }, { x: 240, y: 620, z: 'C' },
    { x: 540, y: 480, z: 'D' }, { x: 680, y: 510, z: 'D', alert: true }, { x: 600, y: 580, z: 'D' }, { x: 760, y: 600, z: 'D' },
  ];

  return (
    <div style={{ position: 'absolute', inset: 0 }}>
      <svg width="100%" height="100%" viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="xMidYMid slice"
        style={{ position: 'absolute', inset: 0 }}>
        {/* satellite-feel topo lines */}
        <g opacity="0.18">
          {[80, 160, 240, 320, 400, 480, 560, 640].map((y, i) => (
            <path key={i}
              d={`M0,${y + Math.sin(i)*20} Q200,${y - 25} 400,${y - 10} T800,${y + 15} L${w},${y + 10}`}
              stroke={i === 3 ? '#FFA500' : '#9aa0a6'}
              strokeWidth={i === 3 ? '0.8' : '0.4'} fill="none"/>
          ))}
        </g>

        {/* moisture cells */}
        <g opacity="0.6">
          {grid.map((g, i) => (
            <rect key={i} x={g.x - cellW/2} y={g.y - cellH/2}
              width={cellW - 1} height={cellH - 1}
              fill={colorForV(g.v)} opacity="0.45" />
          ))}
        </g>

        {/* zone polygons */}
        {zones.map((z) => (
          <g key={z.id} style={{ cursor: 'pointer' }} onClick={() => setSelZone(z.id)}>
            <polygon
              points={z.poly.map(p => p.join(',')).join(' ')}
              fill="none"
              stroke={selZone === z.id ? z.color : `${z.color}66`}
              strokeWidth={selZone === z.id ? 2 : 1}
              strokeDasharray={selZone === z.id ? 'none' : '4 4'}
            />
          </g>
        ))}

        {/* paths between sensors (irrigation network feel) */}
        <g stroke="rgba(255,214,10,0.18)" strokeWidth="0.5" fill="none">
          <path d="M140,130 L260,110 L360,200 L200,300 L180,500 L320,540"/>
          <path d="M500,150 L640,170 L760,200 L690,340 L580,260"/>
        </g>

        {/* zone labels */}
        {zones.map((z) => {
          const cx = z.poly.reduce((a, p) => a + p[0], 0) / z.poly.length;
          const cy = z.poly.reduce((a, p) => a + p[1], 0) / z.poly.length;
          return (
            <g key={z.id}>
              <rect x={cx - 60} y={cy - 22} width="120" height="36" rx="4"
                fill="rgba(10,10,11,0.7)" stroke={`${z.color}55`}/>
              <text x={cx} y={cy - 6} textAnchor="middle"
                fontFamily="var(--f-mono)" fontSize="9.5" fontWeight="600"
                letterSpacing="2" fill={z.alert ? z.color : '#FAFAFA'}>
                ZONE {z.id}
              </text>
              <text x={cx} y={cy + 8} textAnchor="middle"
                fontFamily="var(--f-mono)" fontSize="9" fill="rgba(250,250,250,0.5)">{z.name}</text>
            </g>
          );
        })}
      </svg>

      {/* sensor pins (HTML so we can animate) */}
      {sensors.map((s, i) => (
        <div key={i} style={{ position: 'absolute',
          left: `${(s.x/w)*100}%`, top: `${(s.y/h)*100}%`,
          transform: 'translate(-50%,-50%)' }}>
          {s.alert && (
            <span style={{ position: 'absolute', inset: -8, borderRadius: '50%',
              background: '#FFA500', opacity: 0.3,
              animation: 'ga-pulse 1.6s ease-in-out infinite' }}/>
          )}
          <span style={{ display: 'block',
            width: s.alert ? 10 : 8, height: s.alert ? 10 : 8, borderRadius: '50%',
            background: s.alert ? '#FFA500' : '#FFD60A',
            boxShadow: `0 0 8px ${s.alert ? '#FFA500' : '#FFD60A'}` }} />
        </div>
      ))}

      {/* scan line */}
      <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', pointerEvents: 'none' }}>
        <div style={{ position: 'absolute', left: 0, right: 0, height: 80,
          background: 'linear-gradient(to bottom, transparent, rgba(255,214,10,0.06), transparent)',
          animation: 'ga-scan 9s linear infinite' }}/>
      </div>
    </div>
  );
}

Object.assign(window, { DesktopHeatmap });
