/* Desktop · Macro-Analytics Overview */

function DesktopOverview() {
  const { live, alertState } = useGA();
  const tempV = useTickingValue(alertState === 'frost' ? -0.4 : 14.6, { jitter: 0.2, enabled: live });
  const soilV = useTickingValue(alertState === 'drought' ? 16.2 : 31.8, { jitter: 0.4, enabled: live });

  return (
    <DesktopShell active="overview" kicker="K3 · KAKHETI"
      breadcrumb={['Saperavi K-3', 'Macro Overview']}
      right={
        <>
          <Pill color="ghost" size="sm">Live · 24h</Pill>
          <Pill color="ghost" size="sm">FILTERS · 2</Pill>
        </>
      }>
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 18 }}>
        {/* Hero KPIs */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12 }}>
          <KPICard k="FIELD HEALTH" v={alertState === 'frost' ? 64 : alertState === 'drought' ? 58 : 87} suffix="/100"
            spark={[80,82,79,84,86,85,88,87,86,87,84]} c={alertState === 'calm' ? 'yellow' : 'amber'} big />
          <KPICard k="ZONES · ALERT" v={alertState === 'calm' ? '0' : '2'} suffix={`/ ${FARM.zones.length}`}
            spark={[0,0,1,1,2,2,2,2,2,2,2]} c={alertState === 'calm' ? 'green' : 'amber'} />
          <KPICard k="SOIL · MEAN B" v={soilV} suffix="%" spark={[36,35,34,33,33,32,32,31.8,31.7,31.8,31.8]} c="amber" />
          <KPICard k="AMBIENT" v={tempV} suffix="°C" spark={[2.4,1.8,1.0,0.6,0.2,-0.1,-0.2,-0.3,-0.4,-0.4]} c={alertState === 'frost' ? 'blue' : 'ink'} />
          <KPICard k="FORECAST YIELD" v="6.4" suffix="t/ha" spark={[5.8,5.9,6.0,6.2,6.3,6.3,6.4,6.4,6.4,6.4]} c="yellow" />
        </div>

        {/* Main row */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
          {/* Risk heatmap preview */}
          <DPanel
            kicker="LAYER · SOIL MOISTURE"
            title="Cluster Heatmap"
            subtitle="Hover any cell · drill into the field-level twin"
            right={
              <div style={{ display: 'flex', gap: 6 }}>
                {['SOIL','TEMP','UV','NDVI'].map((l, i) => (
                  <span key={l} style={{
                    fontFamily: 'var(--f-mono)', fontSize: 10, fontWeight: 600, letterSpacing: '0.1em',
                    padding: '5px 9px',
                    background: i === 0 ? 'rgba(255,214,10,0.12)' : 'var(--bg-3)',
                    color: i === 0 ? 'var(--yellow)' : 'var(--ink-2)',
                    borderRadius: 4, border: '1px solid var(--line-2)',
                  }}>{l}</span>
                ))}
              </div>
            }
            padBody={0}
            style={{ height: 360 }}>
            <ClusterHeatmap alertState={alertState} />
          </DPanel>

          {/* Alerts feed */}
          <DPanel
            kicker="LIVE FEED"
            title="Alerts & Events"
            subtitle="Auto-cleared after acknowledgement"
            right={<Pill color="amber" size="sm">2 ACTIVE</Pill>}
            padBody={0}
            style={{ height: 360 }}>
            <AlertsFeed alertState={alertState} />
          </DPanel>
        </div>

        {/* Bottom row */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 18 }}>
          <DPanel
            kicker="7-DAY TREND · ZONE B"
            title="Soil moisture · temperature"
            right={<Pill color="ghost" size="sm">EXPORT CSV</Pill>}
            style={{ height: 260 }}>
            <SoilTempChart alertState={alertState} />
          </DPanel>
          <DPanel
            kicker="MICRO-CLIMATE"
            title="Sensor activity · last 6h"
            style={{ height: 260 }} padBody={0}>
            <SensorActivity />
          </DPanel>
        </div>
      </div>
    </DesktopShell>
  );
}

function KPICard({ k, v, suffix, spark, c = 'ink', big }) {
  const cm = { ink: '#FAFAFA', yellow: '#FFD60A', amber: '#FFA500', green: '#43D67A', red: '#FF453A', blue: '#4FC3FF' };
  const col = cm[c];
  return (
    <div style={{
      position: 'relative', overflow: 'hidden',
      background: big ? 'linear-gradient(135deg, #1A1810 0%, #14140F 100%)' : 'var(--bg-2)',
      border: `1px solid ${big ? 'rgba(255,214,10,0.25)' : 'var(--line-2)'}`,
      borderRadius: 10, padding: 16,
    }}>
      <div className="ga-kicker">{k}</div>
      <div style={{ marginTop: 12, display: 'flex', alignItems: 'baseline', gap: 4 }}>
        <span className="ga-mono ga-tnum ga-tick" key={v} style={{ fontSize: big ? 34 : 26, fontWeight: 600,
          color: col, letterSpacing: '-0.03em', lineHeight: 1 }}>{v}</span>
        <span className="ga-mono" style={{ fontSize: 11, color: 'var(--ink-3)' }}>{suffix}</span>
      </div>
      {spark && (
        <div style={{ marginTop: 10, marginLeft: -4, marginRight: -4 }}>
          <Sparkline data={spark} color={col} width={200} height={22} />
        </div>
      )}
    </div>
  );
}

function ClusterHeatmap({ alertState }) {
  // 14x9 grid heatmap with cluster overlay
  const cols = 16, rows = 10;
  const cells = [];
  // synthetic moisture field with zones B/D drier
  for (let y = 0; y < rows; y++) {
    for (let x = 0; x < cols; x++) {
      const isBD = (x > 9 && y < 5) || (x > 9 && y > 5);
      const base = isBD ? 24 : 38;
      const noise = (Math.sin(x * 1.3 + y * 0.7) * 3 + Math.cos(x * 0.8 + y * 1.1) * 2);
      let v = base + noise;
      if (alertState === 'drought' && isBD) v -= 10;
      if (alertState === 'frost' && isBD) v -= 4;
      cells.push({ x, y, 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';
  };
  return (
    <div style={{ position: 'relative', width: '100%', height: '100%', padding: 18 }}>
      <div style={{ position: 'relative', width: '100%', height: '100%', display: 'grid',
        gridTemplateColumns: `repeat(${cols}, 1fr)`, gridTemplateRows: `repeat(${rows}, 1fr)`, gap: 2 }}>
        {cells.map((c, i) => (
          <div key={i} style={{
            background: colorForV(c.v),
            opacity: 0.85,
            borderRadius: 2,
          }} title={`${c.v.toFixed(1)}%`} />
        ))}
      </div>
      {/* Zone overlay */}
      <div style={{ position: 'absolute', inset: 18, pointerEvents: 'none' }}>
        {[
          { id: 'A', x: 8, y: 8, w: 51, h: 42, alert: false },
          { id: 'B', x: 60, y: 8, w: 32, h: 42, alert: true },
          { id: 'C', x: 8, y: 52, w: 51, h: 40, alert: false },
          { id: 'D', x: 60, y: 52, w: 32, h: 40, alert: true },
        ].map((z) => (
          <div key={z.id} style={{
            position: 'absolute', left: `${z.x}%`, top: `${z.y}%`,
            width: `${z.w}%`, height: `${z.h}%`,
            border: `1.5px solid ${z.alert ? 'rgba(255,69,58,0.7)' : 'rgba(255,255,255,0.3)'}`,
            borderRadius: 4,
          }}>
            <span style={{ position: 'absolute', top: 6, left: 8,
              fontFamily: 'var(--f-mono)', fontSize: 10, fontWeight: 600, letterSpacing: '0.1em',
              color: z.alert ? '#FF453A' : 'var(--ink)',
              background: 'rgba(10,10,11,0.7)', padding: '2px 6px', borderRadius: 3 }}>
              ZONE {z.id}
            </span>
          </div>
        ))}
      </div>
      {/* legend */}
      <div style={{ position: 'absolute', bottom: 10, left: 18, right: 18,
        display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        fontFamily: 'var(--f-mono)', fontSize: 10, color: 'var(--ink-3)' }}>
        <span>UPDATED 23 MAR · 14:14</span>
        <div style={{ display: 'flex', gap: 4, alignItems: 'center' }}>
          <span>{'<'}18%</span>
          <div style={{ width: 100, height: 6, background:
            'linear-gradient(to right, #FF453A, #FFA500, #FFD60A, #A6E840, #43D67A)' }}/>
          <span>40+%</span>
        </div>
      </div>
    </div>
  );
}

function AlertsFeed({ alertState }) {
  const feed = [
    { time: '14:14', kind: 'FROST', tone: 'amber', zone: 'B', title: 'Frost risk · −1.2°C in 90m', open: true },
    { time: '13:58', kind: 'DROUGHT', tone: 'red', zone: 'D', title: 'Moisture < 20% sustained · 6h', open: alertState === 'drought' },
    { time: '11:02', kind: 'EVENT', tone: 'green', zone: 'A', title: 'Fertilizer applied · 12 kg N' },
    { time: '08:18', kind: 'EVENT', tone: 'green', zone: 'B', title: 'Drip pulse · 3.2 mm complete' },
    { time: '04:46', kind: 'HEALTH', tone: 'blue', zone: '—', title: 'Node K3-A-017 · battery 73%' },
    { time: '02:30', kind: 'SAT', tone: 'blue', zone: '—', title: 'Sentinel-2 pass · NDVI updated' },
  ];
  const toneMap = { amber: 'var(--amber)', red: 'var(--red)', green: 'var(--green)', blue: 'var(--blue)' };
  return (
    <div>
      {feed.map((f, i) => (
        <div key={i} style={{
          padding: '14px 18px',
          borderBottom: i < feed.length - 1 ? '1px solid var(--line)' : 'none',
          display: 'flex', alignItems: 'flex-start', gap: 12,
          background: f.open ? 'rgba(255,165,0,0.05)' : 'transparent',
        }}>
          <span className="ga-mono ga-tnum" style={{ fontSize: 11, color: 'var(--ink-3)', width: 38, paddingTop: 1 }}>{f.time}</span>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: toneMap[f.tone], marginTop: 6,
            boxShadow: f.open ? `0 0 8px ${toneMap[f.tone]}` : 'none' }} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', gap: 8, alignItems: 'baseline' }}>
              <span className="ga-kicker" style={{ color: toneMap[f.tone], fontSize: 9 }}>{f.kind}</span>
              {f.zone !== '—' && <span className="ga-kicker" style={{ fontSize: 9 }}>· ZONE {f.zone}</span>}
            </div>
            <div style={{ marginTop: 3, fontSize: 12.5, color: 'var(--ink)', lineHeight: 1.4 }}>{f.title}</div>
          </div>
          {f.open && <GhostButton color={f.tone === 'red' ? 'red' : 'amber'} size="sm" solid>Act</GhostButton>}
        </div>
      ))}
    </div>
  );
}

function SoilTempChart({ alertState }) {
  // 7d twin trace: soil + temp
  const soil = [38, 38, 37, 36, 35, 33, alertState === 'drought' ? 16 : 31];
  const temp = [13, 11, 9, 7, 5, 2, alertState === 'frost' ? -0.4 : 14];
  const w = 700, h = 180;
  const yScale = (v, min, max) => h - ((v - min) / (max - min)) * h;
  const days = ['Mon','Tue','Wed','Thu','Fri','Sat','Today'];
  const soilPath = soil.map((v, i) => `${i === 0 ? 'M' : 'L'} ${(i/6)*w} ${yScale(v, 0, 45)}`).join(' ');
  const tempPath = temp.map((v, i) => `${i === 0 ? 'M' : 'L'} ${(i/6)*w} ${yScale(v, -5, 25)}`).join(' ');
  return (
    <div>
      <div style={{ display: 'flex', gap: 18, marginBottom: 10 }}>
        <LegendDot color="#FFA500" label="Soil moisture · %vmc" />
        <LegendDot color="#4FC3FF" label="Ambient · °C" />
      </div>
      <svg width="100%" height={h + 24} viewBox={`0 0 ${w} ${h + 24}`}>
        {/* grid */}
        {[0,0.25,0.5,0.75,1].map((p, i) => (
          <line key={i} x1="0" x2={w} y1={p*h} y2={p*h} stroke="rgba(255,255,255,0.05)" strokeWidth="0.5"/>
        ))}
        {/* zero band for frost */}
        <line x1="0" x2={w} y1={yScale(0, -5, 25)} y2={yScale(0, -5, 25)} stroke="rgba(255,69,58,0.3)" strokeDasharray="2 3"/>
        <path d={`${soilPath} L ${w} ${h} L 0 ${h} Z`} fill="#FFA500" fillOpacity="0.12"/>
        <path d={soilPath} stroke="#FFA500" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
        <path d={tempPath} stroke="#4FC3FF" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="0"/>
        {/* day labels */}
        {days.map((d, i) => (
          <text key={d} x={(i/6)*w} y={h+18} textAnchor={i === 0 ? 'start' : i === 6 ? 'end' : 'middle'}
            fontFamily="var(--f-mono)" fontSize="10" fill={i === 6 ? 'var(--yellow)' : 'var(--ink-3)'}>{d}</text>
        ))}
        {/* now markers */}
        <circle cx={w} cy={yScale(soil[6], 0, 45)} r="3.5" fill="#FFA500" stroke="var(--bg-2)" strokeWidth="2"/>
        <circle cx={w} cy={yScale(temp[6], -5, 25)} r="3.5" fill="#4FC3FF" stroke="var(--bg-2)" strokeWidth="2"/>
      </svg>
    </div>
  );
}

function LegendDot({ color, label }) {
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6,
      fontFamily: 'var(--f-mono)', fontSize: 11, color: 'var(--ink-2)' }}>
      <span style={{ width: 8, height: 8, borderRadius: '50%', background: color }}/> {label}
    </span>
  );
}

function SensorActivity() {
  // mini per-sensor bar
  const sensors = SENSORS.slice(0, 8);
  return (
    <div style={{ padding: '12px 14px' }}>
      {sensors.map((s, i) => (
        <div key={s.id} style={{ display: 'flex', alignItems: 'center', gap: 10,
          padding: '8px 0',
          borderBottom: i < sensors.length - 1 ? '0.5px solid var(--line)' : 'none' }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%',
            background: s.status === 'ok' ? 'var(--green)' : 'var(--amber)' }} className="ga-pulse-dot" />
          <span className="ga-mono" style={{ fontSize: 10.5, width: 96, color: 'var(--ink-2)' }}>{s.id}</span>
          <span style={{ flex: 1, height: 18, position: 'relative' }}>
            {/* 24 ticks · sparse */}
            <div style={{ position: 'absolute', inset: 0, display: 'grid', gridTemplateColumns: 'repeat(24, 1fr)', gap: 2 }}>
              {Array.from({ length: 24 }, (_, j) => (
                <span key={j} style={{
                  height: '100%',
                  background: (j > 18) ? (s.status === 'ok' ? 'rgba(67,214,122,0.8)' : 'rgba(255,165,0,0.8)') :
                    j > 14 ? 'rgba(67,214,122,0.4)' : 'rgba(255,255,255,0.06)',
                  borderRadius: 1,
                }} />
              ))}
            </div>
          </span>
          <span className="ga-mono" style={{ fontSize: 10, color: 'var(--ink-3)', width: 38, textAlign: 'right' }}>
            {s.sync}
          </span>
        </div>
      ))}
    </div>
  );
}

Object.assign(window, { DesktopOverview });
