// Page-level views for each sidebar destination

const DD = window.EDGE_DATA;

const tier = (v) => {
  if (v <= 50)  return { label: 'Good',      color: 'var(--good)' };
  if (v <= 100) return { label: 'Moderate',  color: 'oklch(70% 0.16 92)' };
  if (v <= 150) return { label: 'Sensitive', color: 'var(--warn)' };
  return { label: 'Unhealthy', color: 'var(--bad)' };
};

const PanelHead = ({ eyebrow, title, right }) => (
  <div style={{ display: 'flex', alignItems: 'center', marginBottom: 16, gap: 16 }}>
    <div>
      <div style={{ fontSize: 11, fontFamily: 'Geist Mono', textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-3)' }}>{eyebrow}</div>
      <h2 style={{ margin: '4px 0 0', fontWeight: 500, fontSize: 22, letterSpacing: '-0.01em' }}>{title}</h2>
    </div>
    {right && <div style={{ marginLeft: 'auto' }}>{right}</div>}
  </div>
);

// ── Zones & Map ─────────────────────────────────────────────────────────────
const ZoneMap = ({ selected, onSelect }) => {
  // hand-placed floor-plan blocks: x/y/w/h in a 100×64 grid
  const plan = [
    { id: 'lab-a',  x: 4,  y: 4,  w: 26, h: 26 },
    { id: 'lab-b',  x: 4,  y: 34, w: 26, h: 26 },
    { id: 'atrium', x: 34, y: 4,  w: 34, h: 38 },
    { id: 'cafe',   x: 34, y: 46, w: 34, h: 14 },
    { id: 'park',   x: 72, y: 4,  w: 24, h: 26 },
    { id: 'lot',    x: 72, y: 34, w: 24, h: 26 },
  ];
  return (
    <div style={{ position: 'relative', width: '100%', height: 460, background: 'var(--bg)', border: '1px solid var(--line)', borderRadius: 12, overflow: 'hidden' }}>
      {/* faint grid */}
      <svg viewBox="0 0 100 64" preserveAspectRatio="none" style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }}>
        {Array.from({ length: 21 }).map((_, i) => <line key={'v'+i} x1={i*5} x2={i*5} y1="0" y2="64" stroke="var(--line)" strokeWidth="0.15" />)}
        {Array.from({ length: 14 }).map((_, i) => <line key={'h'+i} x1="0" x2="100" y1={i*5} y2={i*5} stroke="var(--line)" strokeWidth="0.15" />)}
      </svg>
      {plan.map(p => {
        const z = DD.zones.find(x => x.id === p.id);
        const t = tier(z.aqi);
        const on = selected === z.id;
        const short = p.h <= 16;
        return (
          <button key={p.id} onClick={() => onSelect(z.id)} style={{
            position: 'absolute',
            left: `${p.x}%`, top: `${p.y / 64 * 100}%`,
            width: `${p.w}%`, height: `${p.h / 64 * 100}%`,
            border: `1.5px solid ${on ? 'var(--ink)' : 'var(--line-strong)'}`,
            background: on ? 'var(--bg-elev)' : `color-mix(in oklab, ${t.color} 14%, transparent)`,
            borderRadius: 10, cursor: 'pointer', textAlign: 'left',
            padding: short ? '8px 10px' : 10, display: 'flex', overflow: 'hidden',
            flexDirection: short ? 'row' : 'column',
            alignItems: short ? 'center' : 'stretch', gap: short ? 10 : 4,
            transition: 'border-color .15s, background .15s',
          }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5, fontWeight: 500, lineHeight: 1.2, minWidth: 0 }}>
              <span style={{ width: 7, height: 7, borderRadius: '50%', background: t.color, flexShrink: 0 }} />
              <span style={{ overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: short ? 'nowrap' : 'normal' }}>{z.name}</span>
            </span>
            <span className="mono" style={{ fontSize: 20, fontWeight: 500, letterSpacing: '-0.02em', lineHeight: 1, marginLeft: short ? 'auto' : 0, flexShrink: 0 }}>{z.aqi}</span>
            {!short && (
              <span style={{ marginTop: 'auto', fontSize: 10, color: 'var(--ink-4)', fontFamily: 'Geist Mono', whiteSpace: 'nowrap' }}>{z.devices} nodes · {z.temp}°C</span>
            )}
          </button>
        );
      })}
    </div>
  );
};

const ZonesPage = () => {
  const [sel, setSel] = React.useState('atrium');
  const z = DD.zones.find(x => x.id === sel);
  const t = tier(z.aqi);
  return (
    <>
      <div className="split-2" style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.7fr) minmax(0, 1fr)', gap: 16 }}>
        <Card style={{ padding: 20, minWidth: 0 }}>
          <PanelHead eyebrow="Campus floor plan" title="Zone map" right={
            <div style={{ display: 'flex', gap: 10, fontSize: 11, color: 'var(--ink-3)', fontFamily: 'Geist Mono', alignItems: 'center' }}>
              {[['Good','var(--good)'],['Moderate','oklch(70% 0.16 92)'],['Poor','var(--bad)']].map(([l,c]) => (
                <span key={l} style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
                  <span style={{ width: 8, height: 8, borderRadius: 2, background: c }} />{l}
                </span>
              ))}
            </div>
          } />
          <ZoneMap selected={sel} onSelect={setSel} />
        </Card>
        <Card style={{ padding: 20, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 14 }}>
          <PanelHead eyebrow="Selected zone" title={z.name} />
          <div style={{ display: 'flex', alignItems: 'flex-end', gap: 14 }}>
            <span className="serif" style={{ fontSize: 76, lineHeight: 0.8, letterSpacing: '-0.04em' }}>{z.aqi}</span>
            <div style={{ paddingBottom: 6 }}>
              <div style={{ fontSize: 16, fontWeight: 500 }}>{t.label}</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-3)', fontFamily: 'Geist Mono' }}>AQI · live</div>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            {[['Temperature', `${z.temp} °C`], ['Humidity', `${z.hum} %`], ['Nodes', `${z.devices}`], ['Uptime', '99.8 %']].map(([k, v]) => (
              <div key={k} style={{ padding: '10px 12px', border: '1px solid var(--line)', borderRadius: 10, background: 'var(--bg)' }}>
                <div style={{ fontSize: 10.5, color: 'var(--ink-4)', fontFamily: 'Geist Mono', textTransform: 'uppercase', letterSpacing: '0.06em' }}>{k}</div>
                <div className="mono" style={{ fontSize: 17, marginTop: 3, fontWeight: 500 }}>{v}</div>
              </div>
            ))}
          </div>
          <div style={{ marginTop: 'auto' }}>
            <div style={{ fontSize: 10.5, color: 'var(--ink-4)', fontFamily: 'Geist Mono', textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: 6 }}>Last 24h</div>
            <Sparkline data={DD.series.pm25} color={t.color} height={54} />
          </div>
        </Card>
      </div>
      <ZonesPanel />
      <HeatmapPanel />
    </>
  );
};

// ── History ─────────────────────────────────────────────────────────────────
const HistoryPage = () => {
  const days = ['Sat 20', 'Fri 19', 'Thu 18', 'Wed 17', 'Tue 16', 'Mon 15', 'Sun 14'];
  const rows = days.map((d, i) => {
    const w = DD.weekly;
    const slice = (arr) => arr.slice(i * 24, i * 24 + 24);
    const avg = (a) => a.reduce((s, v) => s + v, 0) / a.length;
    const aqi = Math.round(avg(slice(w.pm25)) * 4.2 + 8);
    return {
      day: d, aqi,
      temp: avg(slice(w.temperature)), hum: avg(slice(w.humidity)),
      co2: avg(slice(w.co2)), pm25: avg(slice(w.pm25)),
      peak: Math.round(Math.max(...slice(w.pm25)) * 4.2 + 8),
      spark: slice(w.pm25),
    };
  });
  return (
    <>
      <TrendsPanel />
      <Card style={{ padding: 20 }}>
        <PanelHead eyebrow="Daily rollup" title="Last 7 days" right={
          <span style={{ fontSize: 11, color: 'var(--ink-3)', fontFamily: 'Geist Mono' }}>hourly means · 168 samples</span>
        } />
        <div className="tbl-history" style={{ display: 'grid', gridTemplateColumns: '78px 62px minmax(0, 1fr) 62px 60px 68px 66px', columnGap: 12, rowGap: 0, alignItems: 'center', fontSize: 12.5 }}>
          {['Day', 'Avg AQI', 'PM2.5 shape', 'Peak AQI', 'Temp', 'Humidity', 'CO₂'].map(h => (
            <div key={h} style={{ fontSize: 10, fontFamily: 'Geist Mono', textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-4)', paddingBottom: 8, borderBottom: '1px solid var(--line)' }}>{h}</div>
          ))}
          {rows.map(r => {
            const t = tier(r.aqi);
            return (
              <React.Fragment key={r.day}>
                <div style={{ padding: '11px 0', borderBottom: '1px solid var(--line)', fontWeight: 500 }}>{r.day}</div>
                <div style={{ padding: '11px 0', borderBottom: '1px solid var(--line)', display: 'flex', alignItems: 'center', gap: 7 }}>
                  <span style={{ width: 7, height: 7, borderRadius: '50%', background: t.color }} />
                  <span className="mono" style={{ fontWeight: 500 }}>{r.aqi}</span>
                </div>
                <div style={{ padding: '6px 0', borderBottom: '1px solid var(--line)' }}>
                  <Sparkline data={r.spark} color={t.color} height={26} fill={false} />
                </div>
                <div className="mono" style={{ padding: '11px 0', borderBottom: '1px solid var(--line)', color: 'var(--ink-3)' }}>{r.peak}</div>
                <div className="mono" style={{ padding: '11px 0', borderBottom: '1px solid var(--line)', color: 'var(--ink-3)' }}>{r.temp.toFixed(1)}°</div>
                <div className="mono" style={{ padding: '11px 0', borderBottom: '1px solid var(--line)', color: 'var(--ink-3)' }}>{r.hum.toFixed(0)}%</div>
                <div className="mono" style={{ padding: '11px 0', borderBottom: '1px solid var(--line)', color: 'var(--ink-3)' }}>{r.co2.toFixed(0)}</div>
              </React.Fragment>
            );
          })}
        </div>
      </Card>
      <HeatmapPanel />
    </>
  );
};

// ── Forecast ────────────────────────────────────────────────────────────────
const ForecastPage = () => {
  const f = DD.forecast.aqi;
  const peak = Math.max(...f), peakAt = f.indexOf(peak);
  const outlook = [
    { d: 'Today',  hi: 68, lo: 33, label: 'Good → Moderate', note: 'Evening westerly shift' },
    { d: 'Sun 21', hi: 74, lo: 38, label: 'Moderate',        note: 'Construction nearby' },
    { d: 'Mon 22', hi: 52, lo: 26, label: 'Good',            note: 'Rain expected 04:00' },
    { d: 'Tue 23', hi: 47, lo: 22, label: 'Good',            note: 'Clear, low traffic' },
    { d: 'Wed 24', hi: 61, lo: 31, label: 'Moderate',        note: 'Term resumes' },
  ];
  const drivers = [
    { k: 'Outdoor infiltration', w: 42 },
    { k: 'Occupancy / CO₂',      w: 27 },
    { k: 'HVAC duty cycle',      w: 18 },
    { k: 'Wind direction',       w: 9 },
    { k: 'Residual / noise',     w: 4 },
  ];
  return (
    <>
      <Card style={{ padding: 24 }}>
        <PanelHead eyebrow="Model v3.2 · 24 hour horizon" title="Predicted air quality" right={
          <span style={{ fontSize: 11, fontFamily: 'Geist Mono', padding: '5px 10px', borderRadius: 999, border: '1px solid var(--line)', color: 'var(--ink-3)', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <Icon name="sparkles" size={11} /> MAE 4.8 AQI · 30d
          </span>
        } />
        <div style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: 28, alignItems: 'center' }}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {[['now', Math.round(f[0])], ['peak', Math.round(peak)], ['avg', Math.round(f.reduce((s,v)=>s+v,0)/f.length)]].map(([k, v]) => (
              <div key={k} style={{ display: 'flex', alignItems: 'baseline', gap: 10 }}>
                <span className="mono" style={{ fontSize: 34, fontWeight: 500, letterSpacing: '-0.03em', minWidth: 58 }}>{v}</span>
                <span style={{ fontSize: 11, fontFamily: 'Geist Mono', textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-4)' }}>{k}{k === 'peak' ? ` +${peakAt}h` : ''}</span>
              </div>
            ))}
          </div>
          <div>
            <ForecastBars data={f} height={150} />
          </div>
        </div>
      </Card>
      <div className="split-2" style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1.4fr) minmax(0, 1fr)', gap: 16 }}>
        <Card style={{ padding: 20, minWidth: 0 }}>
          <PanelHead eyebrow="Extended" title="5-day outlook" />
          <div style={{ display: 'flex', flexDirection: 'column' }}>
            {outlook.map((o, i) => {
              const t = tier(o.hi);
              return (
                <div key={o.d} style={{ display: 'grid', gridTemplateColumns: '68px minmax(0, 1fr) minmax(0, 120px) 58px', gap: 12, alignItems: 'center', padding: '12px 0', borderTop: i ? '1px solid var(--line)' : 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500 }}>{o.d}</div>
                  <div style={{ position: 'relative', height: 6, background: 'var(--bg-sunk)', borderRadius: 3 }}>
                    <div style={{ position: 'absolute', left: `${(o.lo / 120) * 100}%`, width: `${((o.hi - o.lo) / 120) * 100}%`, top: 0, bottom: 0, background: t.color, borderRadius: 3 }} />
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{o.note}</div>
                  <div className="mono" style={{ fontSize: 12.5, textAlign: 'right', color: 'var(--ink-2)' }}>{o.lo}–{o.hi}</div>
                </div>
              );
            })}
          </div>
        </Card>
        <Card style={{ padding: 20, minWidth: 0 }}>
          <PanelHead eyebrow="Explainability" title="What drives it" />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {drivers.map(d => (
              <div key={d.k}>
                <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5, marginBottom: 5 }}>
                  <span style={{ color: 'var(--ink-2)' }}>{d.k}</span>
                  <span className="mono" style={{ color: 'var(--ink-3)' }}>{d.w}%</span>
                </div>
                <div style={{ height: 6, background: 'var(--bg-sunk)', borderRadius: 3, overflow: 'hidden' }}>
                  <div style={{ width: `${d.w}%`, height: '100%', background: 'var(--accent-deep)', borderRadius: 3 }} />
                </div>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </>
  );
};

// ── Alerts ──────────────────────────────────────────────────────────────────
const AlertsPage = () => {
  const rules = [
    { metric: 'PM2.5',  op: '>', th: '35 µg/m³', win: '15 min', zones: 'All zones',    on: true },
    { metric: 'CO₂',    op: '>', th: '1000 ppm', win: '10 min', zones: 'Labs, Café',   on: true },
    { metric: 'VOC',    op: '>', th: '0.6 ppm',  win: '5 min',  zones: 'Lab B',        on: true },
    { metric: 'Temp',   op: '∉', th: '19–26 °C', win: '30 min', zones: 'Cleanroom',    on: true },
    { metric: 'Noise',  op: '>', th: '70 dBA',   win: '5 min',  zones: 'Atrium',       on: false },
  ];
  const stats = [['Open', 3, 'var(--warn)'], ['Acknowledged', 1, 'var(--info)'], ['Resolved 7d', 24, 'var(--good)'], ['Time to clear', '18m', 'var(--ink-3)']];
  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        {stats.map(([k, v, c]) => (
          <Card key={k} style={{ padding: 16 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 11, fontFamily: 'Geist Mono', textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--ink-3)' }}>
              <span style={{ width: 7, height: 7, borderRadius: '50%', background: c, flexShrink: 0 }} />{k}
            </div>
            <div className="mono" style={{ fontSize: 28, fontWeight: 500, letterSpacing: '-0.03em', marginTop: 8, whiteSpace: 'nowrap' }}>{v}</div>
          </Card>
        ))}
      </div>
      <AlertsFeed />
      <Card style={{ padding: 20 }}>
        <PanelHead eyebrow="Configuration" title="Alert rules" right={
          <button style={{ ...iconBtn, width: 'auto', padding: '6px 12px', gap: 6, fontSize: 12, display: 'inline-flex', alignItems: 'center' }}>
            <Icon name="plus" size={12} /> New rule
          </button>
        } />
        <div style={{ display: 'grid', gridTemplateColumns: '90px 40px 110px 80px 1fr 70px', columnGap: 14, alignItems: 'center', fontSize: 12.5 }}>
          {['Metric', 'Op', 'Threshold', 'Window', 'Scope', 'Enabled'].map(h => (
            <div key={h} style={{ fontSize: 10, fontFamily: 'Geist Mono', textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--ink-4)', paddingBottom: 8, borderBottom: '1px solid var(--line)' }}>{h}</div>
          ))}
          {rules.map((r, i) => (
            <React.Fragment key={r.metric}>
              <div style={{ padding: '12px 0', borderBottom: '1px solid var(--line)', fontWeight: 500 }}>{r.metric}</div>
              <div className="mono" style={{ padding: '12px 0', borderBottom: '1px solid var(--line)', color: 'var(--ink-3)' }}>{r.op}</div>
              <div className="mono" style={{ padding: '12px 0', borderBottom: '1px solid var(--line)' }}>{r.th}</div>
              <div className="mono" style={{ padding: '12px 0', borderBottom: '1px solid var(--line)', color: 'var(--ink-3)' }}>{r.win}</div>
              <div style={{ padding: '12px 0', borderBottom: '1px solid var(--line)', color: 'var(--ink-3)' }}>{r.zones}</div>
              <div style={{ padding: '12px 0', borderBottom: '1px solid var(--line)' }}>
                <span style={{ display: 'inline-block', width: 30, height: 17, borderRadius: 999, background: r.on ? 'var(--accent-deep)' : 'var(--line-strong)', position: 'relative' }}>
                  <span style={{ position: 'absolute', top: 2.5, left: r.on ? 15 : 2.5, width: 12, height: 12, borderRadius: '50%', background: 'var(--bg-elev)' }} />
                </span>
              </div>
            </React.Fragment>
          ))}
        </div>
      </Card>
    </>
  );
};

// ── Devices ─────────────────────────────────────────────────────────────────
const DevicesPage = () => {
  const fleet = [['Online', '19', '/ 19'], ['Avg battery', '68', '%'], ['Avg RSSI', '−64', 'dBm'], ['On latest FW', '17', '/ 19']];
  return (
    <>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        {fleet.map(([k, v, u], i) => (
          <Card key={k} style={{ padding: 16 }}>
            <div style={{ fontSize: 11, fontFamily: 'Geist Mono', textTransform: 'uppercase', letterSpacing: '0.07em', color: 'var(--ink-3)', whiteSpace: 'nowrap' }}>{k}</div>
            <div style={{ display: 'flex', alignItems: 'baseline', gap: 5, marginTop: 8, whiteSpace: 'nowrap' }}>
              <span className="mono" style={{ fontSize: 24, fontWeight: 500, letterSpacing: '-0.03em' }}>{v}</span>
              <span className="mono" style={{ fontSize: 12, color: 'var(--ink-3)' }}>{u}</span>
            </div>
            <div style={{ marginTop: 8 }}>
              <Sparkline data={DD.series.pressure.map(x => x + i * 3)} color="var(--accent-deep)" height={26} fill={false} />
            </div>
          </Card>
        ))}
      </div>
      <DevicesPanel />
      <Card style={{ padding: 20 }}>
        <PanelHead eyebrow="Telemetry" title="Node signal & battery" />
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
          {DD.devices.map(d => (
            <div key={d.id} style={{ padding: 14, border: '1px solid var(--line)', borderRadius: 12, background: 'var(--bg)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                <Icon name="cpu" size={14} />
                <span style={{ fontSize: 13, fontWeight: 500 }}>{d.id}</span>
                <span style={{ marginLeft: 'auto', fontSize: 11, color: 'var(--ink-3)', fontFamily: 'Geist Mono' }}>{d.zone}</span>
              </div>
              <Sparkline data={DD.series.no2} color={d.battery < 30 ? 'var(--bad)' : 'var(--good)'} height={40} />
            </div>
          ))}
        </div>
      </Card>
    </>
  );
};

Object.assign(window, { PanelHead, ZonesPage, HistoryPage, ForecastPage, AlertsPage, DevicesPage });
