/* Desktop · Sensor Fleet Manager */

function DesktopFleet() {
  const [selSensor, setSelSensor] = React.useState('GA-K3-014');
  const sel = SENSORS.find(s => s.id === selSensor);

  return (
    <DesktopShell active="fleet" kicker="K3 · KAKHETI"
      breadcrumb={['Saperavi K-3', 'Sensor Fleet']}
      right={
        <>
          <Pill color="ghost" size="sm">ADD NODE +</Pill>
          <Pill color="ghost" size="sm">FIRMWARE · 2.6.1</Pill>
        </>
      }>
      <div style={{ padding: 24, display: 'flex', flexDirection: 'column', gap: 18, height: 'calc(100% - 0px)' }}>
        {/* Fleet KPIs */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12 }}>
          <KPICard k="DEPLOYED" v={SENSORS.length + 6} suffix="nodes" spark={[8,9,10,12,14,15,16]} c="yellow" big />
          <KPICard k="ONLINE" v={`${SENSORS.length + 6}`} suffix="/ 16" spark={[16,16,16,16,16,16,16]} c="green" />
          <KPICard k="LOW BATTERY" v="3" suffix="< 75%" spark={[1,1,2,2,3,3,3]} c="amber" />
          <KPICard k="MEDIAN SYNC" v="4" suffix="min · 15 target" spark={[6,5,5,4,4,4,4]} c="ink" />
          <KPICard k="UPLINK ↑↓" v="9.8" suffix="MB · 24h" spark={[8,8.4,9,9.2,9.5,9.7,9.8]} c="ink" />
        </div>

        {/* Body */}
        <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 18, flex: 1, minHeight: 0 }}>
          {/* Sensor table */}
          <DPanel
            kicker="FLEET · K-3"
            title="All Nodes"
            subtitle="Click any node to inspect telemetry · health · firmware"
            right={
              <div style={{ display: 'flex', gap: 6 }}>
                <Pill color="ghost" size="sm">ZONE ▾</Pill>
                <Pill color="ghost" size="sm">KIND ▾</Pill>
                <Pill color="ghost" size="sm">STATUS ▾</Pill>
              </div>
            }
            padBody={0}>
            <FleetTable selected={selSensor} onSelect={setSelSensor} />
          </DPanel>

          {/* Sensor detail */}
          <DPanel
            kicker={`NODE · ${sel.id}`}
            title={`${sel.kind} · Zone ${sel.zone}`}
            subtitle={`Depth ${sel.depth} · last sync ${sel.sync} ago`}
            right={
              <Pill color={sel.status === 'ok' ? 'green' : 'amber'} size="sm">
                <LiveDot color={sel.status === 'ok' ? 'green' : 'amber'} size={5} />
                {sel.status === 'ok' ? 'ONLINE' : 'ATTENTION'}
              </Pill>
            }>
            <SensorDetail sensor={sel} />
          </DPanel>
        </div>
      </div>
    </DesktopShell>
  );
}

function FleetTable({ selected, onSelect }) {
  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      <div style={{
        display: 'grid', gridTemplateColumns: '120px 60px 90px 1fr 1fr 1fr 80px',
        gap: 10, padding: '11px 18px',
        background: 'var(--bg-3)',
        borderBottom: '1px solid var(--line-2)',
        fontFamily: 'var(--f-mono)', fontSize: 9.5, fontWeight: 600,
        letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-3)',
      }}>
        <span>ID</span><span>Zone</span><span>Kind</span><span>Battery</span><span>Signal</span><span>Last sync</span><span>Status</span>
      </div>
      <div style={{ flex: 1, overflow: 'auto' }} className="ga-scroll">
        {SENSORS.map((s, i) => {
          const isSel = s.id === selected;
          return (
            <div key={s.id} onClick={() => onSelect(s.id)} style={{
              display: 'grid', gridTemplateColumns: '120px 60px 90px 1fr 1fr 1fr 80px',
              gap: 10, padding: '12px 18px', alignItems: 'center', cursor: 'pointer',
              background: isSel ? 'rgba(255,214,10,0.06)' : 'transparent',
              borderLeft: `2px solid ${isSel ? 'var(--yellow)' : 'transparent'}`,
              borderBottom: '1px solid var(--line)',
            }}>
              <span className="ga-mono" style={{ fontSize: 11, color: isSel ? 'var(--yellow)' : 'var(--ink-2)' }}>{s.id}</span>
              <span className="ga-mono" style={{ fontSize: 12, fontWeight: 600, color: 'var(--ink)' }}>{s.zone}</span>
              <span className="ga-mono" style={{ fontSize: 11, color: 'var(--ink-2)' }}>{s.kind.toUpperCase()}</span>
              <BatteryBar v={s.bat} />
              <SignalBars v={s.sig} />
              <span className="ga-mono" style={{ fontSize: 11, color: s.status === 'low' ? 'var(--amber)' : 'var(--ink-2)' }}>{s.sync} ago</span>
              <Pill color={s.status === 'ok' ? 'green' : 'amber'} size="sm">{s.status === 'ok' ? 'OK' : 'LOW'}</Pill>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function BatteryBar({ v }) {
  const c = v > 0.75 ? '#43D67A' : v > 0.5 ? '#FFD60A' : '#FFA500';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <span style={{ position: 'relative', display: 'inline-block',
        width: 28, height: 12, border: `1px solid ${c}`, borderRadius: 2 }}>
        <span style={{ position: 'absolute', right: -3, top: 3, width: 2, height: 6, background: c, borderRadius: 1 }} />
        <span style={{ position: 'absolute', inset: 1, width: `${v * 100}%`, background: c, opacity: 0.85 }} />
      </span>
      <span className="ga-mono" style={{ fontSize: 11, color: 'var(--ink-2)' }}>{(v * 100).toFixed(0)}%</span>
    </div>
  );
}
function SignalBars({ v }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <span style={{ display: 'inline-flex', alignItems: 'flex-end', gap: 1.5, height: 12 }}>
        {[0.25, 0.5, 0.75, 1].map((t, i) => (
          <span key={i} style={{ width: 3, height: `${(i + 1) * 3}px`,
            background: v >= t ? (v > 0.7 ? '#43D67A' : '#FFD60A') : 'var(--bg-4)',
            borderRadius: 1 }} />
        ))}
      </span>
      <span className="ga-mono" style={{ fontSize: 11, color: 'var(--ink-2)' }}>{Math.round(-100 + v * 35)} dBm</span>
    </div>
  );
}

function SensorDetail({ sensor }) {
  // 24h reading trace
  const data = Array.from({ length: 48 }, (_, i) =>
    sensor.kind === 'Soil' ? 32 + Math.sin(i * 0.2) * 2 + Math.cos(i * 0.4) * 1.2
    : sensor.kind === 'Canopy' ? 11 + Math.sin(i * 0.13) * 3
    : 2 + Math.sin(i * 0.15) * 1.5
  );
  const w = 340, h = 100;
  const min = Math.min(...data) - 1, max = Math.max(...data) + 1;
  const rng = max - min;
  const points = data.map((v, i) => [(i / (data.length - 1)) * w, h - ((v - min) / rng) * h]);
  const d = points.map((p, i) => `${i === 0 ? 'M' : 'L'} ${p[0].toFixed(1)} ${p[1].toFixed(1)}`).join(' ');

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
      {/* Hardware spec card */}
      <div style={{
        padding: 14, background: 'var(--bg-3)',
        border: '1px solid var(--line-2)', borderRadius: 8,
        display: 'grid', gridTemplateColumns: '90px 1fr', gap: 14,
      }}>
        {/* Node illustration */}
        <NodeIllustration kind={sensor.kind} />
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {[
            ['MODEL', 'GA-Node 2.6'],
            ['UPLINK', 'NB-IoT / GSM'],
            ['SAMPLE RATE', '15 min'],
            ['DEPTH', sensor.depth],
            ['BATTERY', `${(sensor.bat * 100).toFixed(0)}% · est 4.2 yr`],
            ['BOM', '$38.40'],
          ].map(([k, v]) => (
            <div key={k}>
              <div className="ga-kicker" style={{ fontSize: 8.5 }}>{k}</div>
              <div className="ga-mono" style={{ fontSize: 11.5, color: 'var(--ink)', marginTop: 2 }}>{v}</div>
            </div>
          ))}
        </div>
      </div>

      {/* 24h trace */}
      <div>
        <div className="ga-kicker" style={{ marginBottom: 8 }}>24h · {sensor.kind === 'Soil' ? 'moisture %vmc' : sensor.kind === 'Canopy' ? 'temperature °C' : 'UV index'}</div>
        <svg width="100%" height={h + 16} viewBox={`0 0 ${w} ${h + 16}`}>
          {[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"/>
          ))}
          <path d={`${d} L ${w} ${h} L 0 ${h} Z`} fill="#FFD60A" fillOpacity="0.15"/>
          <path d={d} stroke="#FFD60A" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          <circle cx={w} cy={points[points.length - 1][1]} r="3" fill="#FFD60A" stroke="var(--bg-2)" strokeWidth="1.5"/>
        </svg>
      </div>

      {/* Firmware + logs */}
      <div>
        <div className="ga-kicker" style={{ marginBottom: 8 }}>Recent Diagnostics</div>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {[
            { t: '14:14', ok: true, m: 'Heartbeat · battery 3.7V · rssi −76 dBm' },
            { t: '13:59', ok: true, m: 'Reading · 31.8 %vmc · t-soil 8.4°C' },
            { t: '13:44', ok: true, m: 'Reading · 31.6 %vmc · t-soil 8.6°C' },
            { t: '13:29', ok: false, m: 'GSM fallback · NB-IoT retry · 2/3' },
            { t: '13:14', ok: true, m: 'Reading · 31.8 %vmc · t-soil 8.5°C' },
          ].map((l, i, arr) => (
            <div key={i} style={{ display: 'flex', gap: 10, padding: '8px 0',
              borderBottom: i < arr.length - 1 ? '0.5px solid var(--line)' : 'none',
              fontFamily: 'var(--f-mono)', fontSize: 11, color: 'var(--ink-2)' }}>
              <span style={{ color: 'var(--ink-3)', width: 38 }}>{l.t}</span>
              <span style={{ width: 6, height: 6, marginTop: 4, borderRadius: '50%',
                background: l.ok ? 'var(--green)' : 'var(--amber)' }} />
              <span>{l.m}</span>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: 'flex', gap: 8 }}>
        <GhostButton color="ghost" size="md" style={{ flex: 1 }}>Calibrate</GhostButton>
        <GhostButton color="ghost" size="md" style={{ flex: 1 }}>Reboot</GhostButton>
        <GhostButton color="yellow" solid size="md" style={{ flex: 1 }}>OTA push →</GhostButton>
      </div>
    </div>
  );
}

function NodeIllustration({ kind }) {
  // Sleek techy node illustration — solar cap, stalk, sensor head
  return (
    <div style={{
      width: 80, height: 110, position: 'relative',
      background: 'radial-gradient(circle at 50% 30%, rgba(255,214,10,0.10), transparent 60%)',
      borderRadius: 6, display: 'flex', alignItems: 'center', justifyContent: 'center',
    }}>
      <svg width="60" height="100" viewBox="0 0 60 100">
        {/* solar panel */}
        <rect x="6" y="6" width="48" height="14" rx="1.5" fill="#1a1a1f" stroke="rgba(255,214,10,0.6)" strokeWidth="0.6"/>
        <g stroke="rgba(255,214,10,0.4)" strokeWidth="0.4">
          <line x1="18" y1="6" x2="18" y2="20"/>
          <line x1="30" y1="6" x2="30" y2="20"/>
          <line x1="42" y1="6" x2="42" y2="20"/>
          <line x1="6" y1="13" x2="54" y2="13"/>
        </g>
        {/* stalk */}
        <rect x="28" y="20" width="4" height="42" fill="#2a2a32"/>
        {/* circuit module */}
        <rect x="18" y="42" width="24" height="18" rx="1.5" fill="#1a1a1f" stroke="rgba(255,214,10,0.4)" strokeWidth="0.5"/>
        <circle cx="24" cy="51" r="1" fill="#43D67A" />
        <line x1="28" y1="46" x2="38" y2="46" stroke="rgba(255,255,255,0.3)" strokeWidth="0.3"/>
        <line x1="28" y1="52" x2="35" y2="52" stroke="rgba(255,255,255,0.3)" strokeWidth="0.3"/>
        <line x1="28" y1="56" x2="36" y2="56" stroke="rgba(255,255,255,0.3)" strokeWidth="0.3"/>
        {/* spike */}
        <path d="M28 62 L30 62 L32 62 L34 95 L30 100 L26 95 Z" fill="#3a3a42" stroke="rgba(255,255,255,0.18)" strokeWidth="0.4"/>
        {/* ground line */}
        <line x1="0" y1="78" x2="60" y2="78" stroke="rgba(255,165,0,0.5)" strokeDasharray="2 2" strokeWidth="0.5"/>
        {/* LED */}
        <circle cx="44" cy="36" r="1.3" fill="#FFD60A">
          <animate attributeName="opacity" values="1;0.3;1" dur="1.6s" repeatCount="indefinite" />
        </circle>
      </svg>
    </div>
  );
}

Object.assign(window, { DesktopFleet });
