// lora.jsx — "Rede" tab: the LoRa mesh (v4). Summary, network diagram (tree by hops,
// or the GPS map), link quality, how each station's rows arrived, and the
// "look for Wi-Fi" request. Data: GET /api/v4/mesh.

const { useState: useStateL, useEffect: useEffectL, useRef: useRefL } = React;

const LORA_CSS = `
  .mesh-svg { width: 100%; height: auto; display: block; touch-action: manipulation; }
  .mesh-map { height: 320px; }
  .lora-grid { display: flex; flex-direction: column; gap: 12px; }
  @media (min-width: 1024px) {
    .lora-grid {
      display: grid; gap: 16px; align-items: start;
      grid-template-columns: minmax(0, 1.75fr) minmax(360px, 1fr);
      grid-template-areas: "diagram summary" "diagram detail" "diagram list";
      grid-template-rows: auto auto 1fr;
    }
    .lora-summary { grid-area: summary; }
    .lora-diagram { grid-area: diagram; position: sticky; top: 84px; }
    .lora-detail { grid-area: detail; }
    .lora-list { grid-area: list; }
    .lora-diagram .mesh-map { height: calc(100vh - 250px); min-height: 480px; margin-bottom: 12px; }
    .lora-diagram .mesh-svg { max-height: calc(100vh - 250px); }
  }
  .mesh-pin { width: 26px; height: 26px; border-radius: 50%; display: grid; place-items: center; box-sizing: border-box;
    font: 600 11px 'JetBrains Mono', monospace; color: var(--fg); background: var(--bg-elev); border: 2.5px solid var(--fg-faint);
    box-shadow: 0 1px 4px rgba(0,0,0,0.35); cursor: pointer; }
  .mesh-pin.online { border-color: var(--ok); }
  .mesh-pin.stale { border-color: var(--warn); }
  .mesh-pin.offline { border-style: dashed; }
  .mesh-pin.sink { background: var(--accent); border-color: var(--accent); color: var(--save-btn-fg); box-shadow: 0 0 0 5px color-mix(in oklch, var(--accent) 30%, transparent); }
  .mesh-pin.sel { outline: 2px solid var(--cool); outline-offset: 2px; }
  .mesh-svg text { font-family: 'JetBrains Mono', monospace; }
  .mesh-edge { fill: none; stroke-width: 2.2; stroke-linecap: round; }
  .mesh-edge.good { stroke: var(--ok); }
  .mesh-edge.fair { stroke: var(--accent); }
  .mesh-edge.weak { stroke: var(--warn); stroke-dasharray: 5 4; }
  .mesh-edge.unknown { stroke: var(--fg-faint); stroke-dasharray: 2 4; }
  .mesh-edge.stale { opacity: 0.35; }
  .mesh-edge-label { font-size: 8.5px; fill: var(--fg-dim); paint-order: stroke; stroke: var(--bg-elev); stroke-width: 3px; stroke-linejoin: round; }
  .mesh-flow { fill: var(--cool); }
  .mesh-node { cursor: pointer; }
  .mesh-node circle.body { fill: var(--bg-elev-2); stroke-width: 2; }
  .mesh-node.online circle.body { stroke: var(--ok); }
  .mesh-node.stale circle.body { stroke: var(--warn); }
  .mesh-node.offline circle.body { stroke: var(--fg-faint); stroke-dasharray: 3 3; }
  .mesh-node.sink circle.body { fill: var(--accent); stroke: var(--accent); }
  .mesh-node.sink circle.halo { fill: none; stroke: var(--accent); stroke-width: 1; opacity: 0.45; }
  .mesh-node.sel circle.body { stroke-width: 3.5; }
  .mesh-node .num { font-size: 11px; font-weight: 600; fill: var(--fg); text-anchor: middle; dominant-baseline: central; }
  .mesh-node.sink .num { fill: var(--save-btn-fg); }
  .mesh-node .name { font-size: 9px; fill: var(--fg-dim); text-anchor: middle; paint-order: stroke; stroke: var(--bg-elev); stroke-width: 3px; stroke-linejoin: round; }
  .mesh-node .batt { font-size: 8px; fill: var(--fg-faint); text-anchor: middle; paint-order: stroke; stroke: var(--bg-elev); stroke-width: 3px; stroke-linejoin: round; }
  .mesh-legend { display: flex; flex-wrap: wrap; gap: 6px 14px; font-size: 10px; color: var(--fg-dim); }
  .mesh-legend i { display: inline-block; width: 18px; height: 0; border-top: 2.2px solid; vertical-align: middle; margin-right: 5px; }
  .mesh-legend i.good { border-color: var(--ok); }
  .mesh-legend i.fair { border-color: var(--accent); }
  .mesh-legend i.weak { border-color: var(--warn); border-top-style: dashed; }
  .mesh-legend i.unknown { border-color: var(--fg-faint); border-top-style: dotted; }
  .mesh-stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; }
  .mesh-stat { background: var(--bg-elev-2); border-radius: 10px; padding: 9px 10px; display: flex; flex-direction: column; gap: 3px; min-width: 0; }
  .mesh-stat .v { font-size: 18px; font-weight: 600; letter-spacing: -0.02em; }
  .mesh-stat .l { font-size: 9px; letter-spacing: 0.12em; text-transform: uppercase; color: var(--fg-faint); font-family: 'JetBrains Mono', monospace; }
  .mesh-list { display: flex; flex-direction: column; }
  .mesh-row { display: grid; grid-template-columns: 26px 1fr auto; gap: 10px; align-items: center; padding: 9px 2px; border-bottom: 1px solid var(--line); cursor: pointer; background: none; border-left: 0; border-right: 0; border-top: 0; color: inherit; text-align: left; font: inherit; width: 100%; }
  .mesh-row:last-child { border-bottom: 0; }
  .mesh-row.sel { background: var(--bg-elev-2); border-radius: 8px; }
  .mesh-badge { width: 24px; height: 24px; border-radius: 50%; display: grid; place-items: center; font-size: 10px; font-weight: 600; border: 2px solid var(--fg-faint); font-family: 'JetBrains Mono', monospace; }
  .mesh-badge.online { border-color: var(--ok); }
  .mesh-badge.stale { border-color: var(--warn); }
  .mesh-badge.sink { background: var(--accent); border-color: var(--accent); color: var(--save-btn-fg); }
  .mesh-row .t1 { font-size: 13px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .mesh-row .t2 { font-size: 10px; color: var(--fg-dim); font-family: 'JetBrains Mono', monospace; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .mesh-row .r { text-align: right; font-size: 11px; font-family: 'JetBrains Mono', monospace; }
  .mesh-bar { height: 4px; border-radius: 2px; background: var(--line-strong); overflow: hidden; display: flex; margin-top: 4px; width: 64px; margin-left: auto; }
  .mesh-bar .lora { background: var(--cool); }
  .mesh-bar .wifi { background: var(--ok); }
`;

const SNR_FLOOR_SF9 = -12.5;     // demodulation floor at SF9: margins are measured from it

function useWide() {
  const q = '(min-width: 1024px)';
  const [wide, setWide] = useStateL(() => !!(window.matchMedia && window.matchMedia(q).matches));
  useEffectL(() => {
    if (!window.matchMedia) return;
    const mq = window.matchMedia(q);
    const on = (e) => setWide(e.matches);
    if (mq.addEventListener) mq.addEventListener('change', on); else mq.addListener(on);
    return () => { if (mq.removeEventListener) mq.removeEventListener('change', on); else mq.removeListener(on); };
  }, []);
  return wide;
}

function linkClass(snr) {
  if (snr == null || !Number.isFinite(snr)) return 'unknown';
  const margin = snr - SNR_FLOOR_SF9;
  return margin >= 10 ? 'good' : margin >= 5 ? 'fair' : 'weak';
}

function nodeState(n, nowSec) {
  const ts = n.last?.ts;
  if (ts == null) return 'offline';
  const interval = (n.measure_interval_minutes || 5) * 60;
  const age = nowSec - ts;
  return age <= 2 * interval + 300 ? 'online' : age <= 3600 ? 'stale' : 'offline';
}

function shortName(n) {
  const d = n.description || n.device_id || '';
  return d.length > 14 ? d.slice(0, 13) + '…' : d;
}

function ageText(sec) {
  if (sec == null) return '—';
  if (sec < 90) return `${Math.round(sec)} s`;
  if (sec < 5400) return `${Math.round(sec / 60)} min`;
  if (sec < 86400 * 2) return `${Math.round(sec / 3600)} h`;
  return `${Math.round(sec / 86400)} d`;
}

const fmt = (v, d = 0, unit = '') => (v == null || !Number.isFinite(Number(v)) ? '—' : `${Number(v).toFixed(d)}${unit}`);

// ── demo: the network of the explainer video (sink R, stations E1..E6) ──
function demoMesh(nowSec) {
  const base = [
    { node: 1, id: 'tempolavra-sede', desc: 'Sede (receptora)', role: 'sink', parent: null, dist: 0, lat: -22.0480, lon: -42.6750 },
    { node: 2, id: 'tempolavra-02', desc: 'E1 · Alto da serra', parent: 5, dist: 3, lat: -22.0200, lon: -42.7150, snr: 1.5 },
    { node: 3, id: 'tempolavra-03', desc: 'E2 · Pasto norte', parent: 4, dist: 3, lat: -22.0150, lon: -42.6850, snr: 3.0 },
    { node: 4, id: 'tempolavra-04', desc: 'E3 · Lavoura', parent: 6, dist: 2, lat: -22.0260, lon: -42.6600, snr: -6.5 },
    { node: 5, id: 'tempolavra-05', desc: 'E4 · Curral', parent: 7, dist: 2, lat: -22.0330, lon: -42.7010, snr: 0.5 },
    { node: 6, id: 'tempolavra-06', desc: 'E5 · Represa', parent: 1, dist: 1, lat: -22.0390, lon: -42.6620, snr: -3.0 },
    { node: 7, id: 'tempolavra-07', desc: 'E6 · Estrada', parent: 1, dist: 1, lat: -22.0420, lon: -42.6900, snr: 4.5 },
  ];
  return [{
    lora_net: 1,
    sinks: ['tempolavra-sede'],
    nodes: base.map((b, i) => ({
      device_id: b.id, description: b.desc, role: b.role || 'station', lora_net: 1, lora_node: b.node,
      measure_interval_minutes: 5, last_seen: nowSec - 40,
      last: {
        ts: nowSec - (b.node === 3 ? 1500 : 60 + i * 20), via: b.role === 'sink' ? 'wifi' : 'lora', firmware: '1.0.0',
        battery_voltage: 3.7 + 0.06 * (i % 4), battery_percent: 55 + 7 * (i % 5),
        lora_dist: b.dist, lora_parent: b.parent, lora_rssi: b.snr != null ? -96 + b.snr * 2 : null, lora_snr: b.snr ?? null,
        lora_backlog: b.node === 3 ? 4 : 0, queue_backlog: 1200 + 40 * i,
        lora_hops: b.role === 'sink' ? null : b.dist - 1, lora_last_hop: b.role === 'sink' ? null : (b.dist === 1 ? b.node : (b.node === 4 || b.node === 3 ? 6 : 7)),
        lora_rx_rssi: b.role === 'sink' ? null : -104 + i, lora_rx_snr: b.role === 'sink' ? null : 2.5 - i * 0.5,
      },
      position: { latitude: b.lat, longitude: b.lon },
      day: { rows: b.node === 3 ? 270 : 288, lora: b.role === 'sink' ? 0 : (b.node === 3 ? 270 : 287), wifi: b.role === 'sink' ? 288 : 1, expected: 288 },
    })),
  }];
}

// ── layout: tree by hop distance, or the GPS positions ──
function layoutTree(nodes, W, H) {
  const byNode = new Map(nodes.map(n => [n.lora_node, n]));
  const level = (n) => n.role === 'sink' ? 0 : (n.last?.lora_dist ?? -1);
  const maxLevel = Math.max(1, ...nodes.map(level));
  const rows = new Map();
  nodes.forEach(n => {
    const l = level(n) < 0 ? maxLevel + 1 : level(n);
    if (!rows.has(l)) rows.set(l, []);
    rows.get(l).push(n);
  });
  const levels = [...rows.keys()].sort((a, b) => a - b);
  const pos = new Map();
  const top = 34, bottom = H - 40;
  const dy = levels.length > 1 ? (bottom - top) / (levels.length - 1) : 0;
  levels.forEach((l, li) => {
    const row = rows.get(l);
    // order under the parents to keep the lines from crossing
    row.sort((a, b) => {
      const pa = pos.get(a.last?.lora_parent)?.x ?? 0, pb = pos.get(b.last?.lora_parent)?.x ?? 0;
      return pa - pb || a.lora_node - b.lora_node;
    });
    row.forEach((n, i) => pos.set(n.lora_node, { x: (W * (i + 1)) / (row.length + 1), y: top + li * dy }));
  });
  return { pos, byNode };
}

function MeshDiagram({ nodes, nowSec, selected, onSelect, wide }) {
  const W = wide ? 640 : 360, H = wide ? 460 : 300;
  const { pos, byNode } = layoutTree(nodes, W, H);
  const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  const edges = nodes.filter(n => n.role !== 'sink' && n.last?.lora_parent != null && byNode.has(n.last.lora_parent));

  return (
    <svg className="mesh-svg" viewBox={`0 0 ${W} ${H}`} role="img" aria-label="Diagrama da rede LoRa">
      {edges.map(n => {
        const a = pos.get(n.lora_node), b = pos.get(n.last.lora_parent);
        const st = nodeState(n, nowSec);
        const cls = `mesh-edge ${linkClass(n.last.lora_snr)} ${st === 'online' ? '' : 'stale'}`;
        const d = `M${a.x},${a.y} L${b.x},${b.y}`;
        const mx = a.x + (b.x - a.x) * 0.38, my = a.y + (b.y - a.y) * 0.38;   /* near the child: clear of the parent's labels */
        return (
          <g key={`e${n.lora_node}`}>
            <path className={cls} d={d} />
            {n.last.lora_snr != null && (
              <text className="mesh-edge-label" x={mx + 6} y={my}>{n.last.lora_snr.toFixed(0)} dB</text>
            )}
            {!reduce && st === 'online' && (
              <circle r="2.6" className="mesh-flow">
                <animateMotion dur={`${2.2 + (n.lora_node % 4) * 0.35}s`} repeatCount="indefinite" path={d} />
              </circle>
            )}
          </g>
        );
      })}
      {nodes.map(n => {
        const p = pos.get(n.lora_node);
        const sink = n.role === 'sink';
        const st = nodeState(n, nowSec);
        const r = sink ? 15 : 13;
        return (
          <g key={`n${n.lora_node}`} className={`mesh-node ${sink ? 'sink' : st} ${selected === n.lora_node ? 'sel' : ''}`}
            transform={`translate(${p.x},${p.y})`} onClick={() => onSelect(n.lora_node)}>
            {sink && <circle className="halo" r={r + 6} />}
            <circle className="body" r={r} />
            <text className="num">{sink ? 'R' : n.lora_node}</text>
            <text className="name" y={r + 11}>{shortName(n)}</text>
            {n.last?.battery_percent != null && <text className="batt" y={r + 21}>{n.last.battery_percent.toFixed(0)}%</text>}
          </g>
        );
      })}
    </svg>
  );
}

// The real map: each station at the GPS position it measured and reported
// (last fix in the dataset), the mesh links drawn between them. OpenStreetMap
// tiles, inverted in the dark theme like the station map of the Tempo tab.
function MeshMap({ nodes, nowSec, dark, selected, onSelect }) {
  const boxRef = useRefL(null);
  const mapRef = useRefL(null);
  const layerRef = useRefL(null);
  const fittedRef = useRefL(false);

  useEffectL(() => {
    if (!window.L || !boxRef.current) return;
    const L = window.L;
    if (!mapRef.current) {
      mapRef.current = L.map(boxRef.current, { zoomControl: true, attributionControl: true, scrollWheelZoom: false });
      L.tileLayer('https://tile.openstreetmap.org/{z}/{x}/{y}.png', { maxZoom: 19, attribution: '© OpenStreetMap' })
        .addTo(mapRef.current);
      L.control.scale({ imperial: false, position: 'bottomleft' }).addTo(mapRef.current);
      layerRef.current = L.layerGroup().addTo(mapRef.current);
    }
    const css = getComputedStyle(document.documentElement);
    const color = (v) => css.getPropertyValue(v).trim() || '#888';
    const COLORS = { good: color('--ok'), fair: color('--accent'), weak: color('--warn'), unknown: color('--fg-faint') };

    const layer = layerRef.current;
    layer.clearLayers();
    const at = new Map(nodes.filter(n => n.position?.latitude != null)
      .map(n => [n.lora_node, [n.position.latitude, n.position.longitude]]));

    nodes.forEach(n => {
      if (n.role === 'sink' || n.last?.lora_parent == null) return;
      const a = at.get(n.lora_node), b = at.get(n.last.lora_parent);
      if (!a || !b) return;
      const cls = linkClass(n.last.lora_snr);
      const km = L.latLng(a).distanceTo(L.latLng(b)) / 1000;
      L.polyline([a, b], {
        color: COLORS[cls], weight: 3, opacity: nodeState(n, nowSec) === 'online' ? 0.9 : 0.35,
        dashArray: cls === 'weak' ? '6 5' : cls === 'unknown' ? '2 6' : null,
      }).bindTooltip(`${km.toFixed(2)} km · ${n.last.lora_snr != null ? n.last.lora_snr.toFixed(1) + ' dB' : 'sem SNR'}`, { sticky: true })
        .addTo(layer);
    });

    nodes.forEach(n => {
      const p = at.get(n.lora_node);
      if (!p) return;
      const sink = n.role === 'sink';
      const st = sink ? 'sink' : nodeState(n, nowSec);
      const icon = L.divIcon({
        className: '',
        html: `<span class="mesh-pin ${st} ${selected === n.lora_node ? 'sel' : ''}">${sink ? 'R' : n.lora_node}</span>`,
        iconSize: [26, 26], iconAnchor: [13, 13],
      });
      const lat = p[0].toFixed(5), lon = p[1].toFixed(5);
      L.marker(p, { icon, title: n.description || n.device_id })
        .bindTooltip(`<b>${n.description || n.device_id}</b><br>${lat}, ${lon}${n.position.altitude_m != null ? ` · ${Math.round(n.position.altitude_m)} m` : ''}`,
          { direction: 'top', offset: [0, -12] })
        .on('click', () => onSelect(n.lora_node))
        .addTo(layer);
    });

    if (!fittedRef.current && at.size) {
      mapRef.current.fitBounds(L.latLngBounds([...at.values()]).pad(0.25), { maxZoom: 15 });
      fittedRef.current = true;
    }
    setTimeout(() => mapRef.current && mapRef.current.invalidateSize(), 200);
  }, [nodes, nowSec, dark, selected]);

  useEffectL(() => () => {
    if (mapRef.current) { mapRef.current.remove(); mapRef.current = null; layerRef.current = null; }
  }, []);

  const missing = nodes.filter(n => n.position?.latitude == null);
  return (
    <>
      <div ref={boxRef} className={`map-placeholder mesh-map ${dark ? 'dark' : ''}`} />
      {missing.length > 0 && (
        <p className="config-help">Sem posição GPS ainda: {missing.map(n => n.role === 'sink' ? 'R' : `nó ${n.lora_node}`).join(', ')}.</p>
      )}
    </>
  );
}

function NodeDetail({ n, nodes, nowSec, demo, onToast }) {
  const [busy, setBusy] = useStateL(false);
  if (!n) return null;
  const sink = n.role === 'sink';
  const L = n.last || {};
  const byNode = new Map(nodes.map(x => [x.lora_node, x]));
  const parent = byNode.get(L.lora_parent);
  const lastHop = byNode.get(L.lora_last_hop);
  const st = nodeState(n, nowSec);
  const day = n.day || {};
  const pct = day.expected ? Math.min(100, (100 * (day.rows || 0)) / day.expected) : null;
  const margin = L.lora_snr != null ? L.lora_snr - SNR_FLOOR_SF9 : null;

  const askWifi = async () => {
    if (demo) return;
    setBusy(true);
    try {
      await window.AS_API.wifiRequest(n.device_id);
      onToast('Pedido enviado: vai no próximo beacon da receptora. Ligue o hotspot do celular perto da estação.');
    } catch (err) {
      onToast(`Erro: ${err.message}`);
    } finally {
      setBusy(false);
    }
  };

  const sdReleased = sink && n.sd_eject_until != null && n.sd_eject_until > nowSec;
  const releaseCard = async (minutes) => {
    if (demo) return;
    setBusy(true);
    try {
      await window.AS_API.sdEject(n.device_id, minutes);
      onToast(minutes
        ? 'Pedido enviado: em até 2 min a receptora desmonta o cartão e acende o LED branco fixo. Troque o cartão só com o LED fixo.'
        : 'Cancelado: a receptora volta a usar o cartão na próxima consulta.');
    } catch (err) {
      onToast(`Erro: ${err.message}`);
    } finally {
      setBusy(false);
    }
  };

  return (
    <section className="config-card lora-detail">
      <div className="section-head">
        <span className="section-title">{sink ? 'RECEPTORA' : `ESTAÇÃO · NÓ ${n.lora_node}`}</span>
        <span className={`status-pill ${st === 'online' ? 'ok' : 'stale'}`}>{st === 'online' ? 'ONLINE' : st === 'stale' ? 'ATRASADA' : 'OFFLINE'}</span>
      </div>
      <div className="kv-list">
        <div className="kv-row"><span>ID</span><span className="mono">{n.device_id}</span></div>
        {n.description && <div className="kv-row"><span>Local</span><span>{n.description}</span></div>}
        {!sink && (
          <>
            <div className="kv-row"><span>Até a receptora</span><span className="mono">
              {L.lora_dist == null ? 'sem beacon' : `${L.lora_dist} salto${L.lora_dist === 1 ? '' : 's'}`}
              {parent ? ` · via ${parent.role === 'sink' ? 'R' : 'nó ' + parent.lora_node}` : ''}
            </span></div>
            <div className="kv-row"><span>Beacon ouvido</span><span className="mono">
              {fmt(L.lora_rssi, 0, ' dBm')} · {fmt(L.lora_snr, 1, ' dB')}{margin != null ? ` (margem ${margin.toFixed(0)} dB)` : ''}
            </span></div>
            <div className="kv-row"><span>Último pacote</span><span className="mono">
              {L.via === 'lora' ? `LoRa · ${L.lora_hops ?? '?'} repetidor${L.lora_hops === 1 ? '' : 'es'}` : L.via === 'wifi' ? 'Wi-Fi (linha completa)' : '—'}
            </span></div>
            {L.via === 'lora' && (
              <div className="kv-row"><span>Chegou na receptora</span><span className="mono">
                {lastHop && lastHop.lora_node !== n.lora_node ? `de nó ${lastHop.lora_node} · ` : 'direto · '}
                {fmt(L.lora_rx_rssi, 0, ' dBm')} · {fmt(L.lora_rx_snr, 1, ' dB')}
              </span></div>
            )}
            <div className="kv-row"><span>Fila LoRa</span><span className="mono">{L.lora_backlog == null ? '—' : `${L.lora_backlog} leitura${L.lora_backlog === 1 ? '' : 's'} sem confirmação`}</span></div>
          </>
        )}
        <div className="kv-row"><span>Fila Wi-Fi (cartão)</span><span className="mono">{L.queue_backlog == null ? '—' : `${L.queue_backlog} linhas`}</span></div>
        {sink && (
          <div className="kv-row"><span>Cartão</span><span className="mono">
            {sdReleased ? `liberado para troca por mais ${ageText(n.sd_eject_until - nowSec)}` : 'em uso'}
          </span></div>
        )}
        <div className="kv-row"><span>Entregas em 24 h</span><span className="mono">
          {day.rows ?? 0}/{day.expected ?? '—'}{pct != null ? ` (${pct.toFixed(0)}%)` : ''} · LoRa {day.lora ?? 0} · Wi-Fi {day.wifi ?? 0}
        </span></div>
        <div className="kv-row"><span>Bateria</span><span className="mono">{fmt(L.battery_voltage, 2, ' V')}{L.battery_percent != null ? ` · ${L.battery_percent.toFixed(0)}%` : ''}</span></div>
        <div className="kv-row"><span>Firmware</span><span className="mono">{L.firmware ? `v${L.firmware}` : '—'}</span></div>
        <div className="kv-row"><span>Última leitura</span><span className="mono">{L.ts ? `há ${ageText(nowSec - L.ts)}` : '—'}</span></div>
      </div>
      {!sink && (
        <>
          <p className="config-help">
            Sem Wi-Fi no local, a estação manda as leituras pela mesh e guarda no cartão as fotos e as colunas completas.
            Para descarregar tudo (e atualizar o firmware), peça Wi-Fi: no próximo beacon a estação passa a procurar a rede salva
            ou o hotspot do técnico.
          </p>
          <button className={`save-btn ${busy ? 'saving' : ''}`} onClick={askWifi} disabled={busy || demo}>
            {demo ? 'INDISPONÍVEL NA DEMONSTRAÇÃO' : busy ? 'ENVIANDO…' : 'PEDIR WI-FI A ESTA ESTAÇÃO'}
          </button>
        </>
      )}
      {sink && (
        <>
          <p className="config-help">
            A receptora grava no cartão a cada 30 s, então ele não deve sair a quente. Peça para liberar: em até 2 min ela
            desmonta o cartão e acende o LED branco fixo. Com o LED fixo, troque o cartão (FAT32). No fim do prazo ela monta
            o cartão que estiver no soquete e o LED volta a bater. Enquanto isso, os pacotes da mesh esperam no módulo LoRa.
          </p>
          <button className={`save-btn ${busy ? 'saving' : ''}`} onClick={() => releaseCard(sdReleased ? 0 : 15)} disabled={busy || demo}>
            {demo ? 'INDISPONÍVEL NA DEMONSTRAÇÃO' : busy ? 'ENVIANDO…' : sdReleased ? 'CANCELAR: VOLTAR A USAR O CARTÃO' : 'LIBERAR CARTÃO POR 15 MIN'}
          </button>
        </>
      )}
    </section>
  );
}

function LoraTab({ demo, nowSec, onToast, dark }) {
  const wide = useWide();
  const [networks, setNetworks] = useStateL(null);
  const [err, setErr] = useStateL(null);
  const [view, setView] = useStateL(new URLSearchParams(window.location.search).get('view') === 'tree' ? 'tree' : 'map');
  const [selected, setSelected] = useStateL(() => Number(new URLSearchParams(window.location.search).get('node')) || null);
  const [netIdx, setNetIdx] = useStateL(0);

  useEffectL(() => {
    if (demo) { setNetworks(demoMesh(Math.floor(Date.now() / 1000))); return; }
    let cancelled = false;
    const load = async () => {
      try {
        const n = await window.AS_API.fetchMesh();
        if (!cancelled) { setNetworks(n); setErr(null); }
      } catch (e) { if (!cancelled) setErr(e.message); }
    };
    load();
    const id = window.setInterval(load, 60 * 1000);
    return () => { cancelled = true; window.clearInterval(id); };
  }, [demo]);

  if (err && !networks) return <div className="tab-content"><div className="empty-state"><span className="empty-eyebrow mono">REDE LORA</span><p>Erro ao carregar: <span className="mono">{err}</span></p></div></div>;
  if (!networks) return <div className="tab-content"><div className="empty-state"><span className="empty-eyebrow mono">REDE LORA</span><p>Carregando…</p></div></div>;
  if (!networks.length) {
    return (
      <div className="tab-content">
        <div className="empty-state">
          <span className="empty-eyebrow mono">REDE LORA</span>
          <p>Nenhuma estação está numa rede LoRa ainda. Cadastre a receptora e as estações com
            <span className="mono"> scripts/add-device.sh &lt;id&gt; "local" --net 1 --node N</span> (e <span className="mono">--sink</span> na receptora).</p>
        </div>
      </div>
    );
  }

  const net = networks[Math.min(netIdx, networks.length - 1)];
  const nodes = net.nodes;
  const stations = nodes.filter(n => n.role !== 'sink');
  const sink = nodes.find(n => n.role === 'sink');
  const online = stations.filter(n => nodeState(n, nowSec) === 'online').length;
  const exp = stations.reduce((s, n) => s + (n.day?.expected || 0), 0);
  const got = stations.reduce((s, n) => s + Math.min(n.day?.rows || 0, n.day?.expected || 0), 0);
  const viaLora = stations.reduce((s, n) => s + (n.day?.lora || 0), 0);
  const maxHops = Math.max(0, ...stations.map(n => n.last?.lora_dist ?? 0));
  const hasMap = nodes.filter(n => n.position?.latitude != null).length >= 2;
  const sel = nodes.find(n => n.lora_node === selected) || null;

  return (
    <div className="tab-content wide">
     <div className="lora-grid">
      <section className="config-card lora-summary">
        <div className="section-head">
          <span className="section-title">REDE LORA {networks.length > 1 ? `· ${net.lora_net}` : ''}</span>
          <span className={`status-pill ${sink && nodeState(sink, nowSec) === 'online' ? 'ok' : 'stale'}`}>
            RECEPTORA {sink && nodeState(sink, nowSec) === 'online' ? 'ONLINE' : 'OFFLINE'}
          </span>
        </div>
        {networks.length > 1 && (
          <div className="seg-control">
            {networks.map((n, i) => <button key={n.lora_net} className={`seg-btn ${i === netIdx ? 'active' : ''}`} onClick={() => setNetIdx(i)}>rede {n.lora_net}</button>)}
          </div>
        )}
        <div className="mesh-stats">
          <div className="mesh-stat"><span className="v mono">{online}/{stations.length}</span><span className="l">online</span></div>
          <div className="mesh-stat"><span className="v mono">{exp ? `${Math.round((100 * got) / exp)}%` : '—'}</span><span className="l">entrega 24 h</span></div>
          <div className="mesh-stat"><span className="v mono">{maxHops}</span><span className="l">saltos máx.</span></div>
        </div>
        <p className="config-help">
          {viaLora} leituras chegaram pela mesh nas últimas 24 h. Cada estação repassa as das outras até a receptora,
          que confirma o recebimento; sem confirmação, a leitura fica no cartão e vai de novo na janela seguinte.
        </p>
      </section>

      <section className="config-card lora-diagram">
        <div className="section-head">
          <span className="section-title">DIAGRAMA</span>
          {hasMap ? (
            <div className="seg-control" style={{ margin: 0 }}>
              <button className={`seg-btn ${view === 'tree' ? 'active' : ''}`} onClick={() => setView('tree')}>saltos</button>
              <button className={`seg-btn ${view === 'map' ? 'active' : ''}`} onClick={() => setView('map')}>mapa</button>
            </div>
          ) : <span className="section-sub mono">por saltos</span>}
        </div>
        {hasMap && view === 'map' ? (
          <MeshMap nodes={nodes} nowSec={nowSec} dark={dark} selected={selected}
            onSelect={(k) => setSelected(k === selected ? null : k)} />
        ) : (
          <MeshDiagram nodes={nodes} nowSec={nowSec} selected={selected} wide={wide}
            onSelect={(k) => setSelected(k === selected ? null : k)} />
        )}
        <div className="mesh-legend mono">
          <span><i className="good" />margem ≥ 10 dB</span>
          <span><i className="fair" />5–10 dB</span>
          <span><i className="weak" />&lt; 5 dB</span>
          <span><i className="unknown" />sem dado</span>
        </div>
        <p className="config-help">
          Cada linha liga a estação ao vizinho de quem ela ouve o beacon (o próximo salto até a receptora R).
          A cor é a margem do sinal sobre o limite do SF9 ({SNR_FLOOR_SF9} dB).
          {hasMap ? ' No mapa, cada estação fica na coordenada do seu GPS (último fix no dataset); passe o dedo numa linha para ver a distância.' : ''}
          {' '}Toque numa estação para ver os detalhes.
        </p>
      </section>

      {sel && <NodeDetail n={sel} nodes={nodes} nowSec={nowSec} demo={demo} onToast={onToast} />}

      <section className="config-card lora-list">
        <div className="section-head">
          <span className="section-title">ESTAÇÕES</span>
          <span className="section-sub mono">entrega 24 h</span>
        </div>
        <div className="mesh-list">
          {nodes.map(n => {
            const st = nodeState(n, nowSec);
            const L = n.last || {};
            const d = n.day || {};
            const e = d.expected || 1;
            return (
              <button key={n.lora_node} className={`mesh-row ${selected === n.lora_node ? 'sel' : ''}`} onClick={() => setSelected(n.lora_node === selected ? null : n.lora_node)}>
                <span className={`mesh-badge ${n.role === 'sink' ? 'sink' : st}`}>{n.role === 'sink' ? 'R' : n.lora_node}</span>
                <span style={{ minWidth: 0 }}>
                  <div className="t1">{n.description || n.device_id}</div>
                  <div className="t2">
                    {n.role === 'sink' ? 'receptora · Wi-Fi/4G' : L.lora_dist == null ? 'sem beacon' : `${L.lora_dist} salto${L.lora_dist === 1 ? '' : 's'} · ${fmt(L.lora_snr, 0, ' dB')}`}
                    {L.ts ? ` · há ${ageText(nowSec - L.ts)}` : ''}
                  </div>
                </span>
                <span className="r">
                  {d.expected ? `${Math.round((100 * Math.min(d.rows || 0, e)) / e)}%` : '—'}
                  <div className="mesh-bar">
                    <span className="lora" style={{ width: `${(100 * Math.min(d.lora || 0, e)) / e}%` }} />
                    <span className="wifi" style={{ width: `${(100 * Math.min(d.wifi || 0, e - Math.min(d.lora || 0, e))) / e}%` }} />
                  </div>
                </span>
              </button>
            );
          })}
        </div>
        <div className="mesh-legend mono" style={{ marginTop: 8 }}>
          <span><i style={{ borderColor: 'var(--cool)' }} />pela mesh</span>
          <span><i style={{ borderColor: 'var(--ok)' }} />pelo Wi-Fi</span>
        </div>
      </section>
     </div>
    </div>
  );
}

const loraStyle = document.createElement('style');
loraStyle.textContent = LORA_CSS;
document.head.appendChild(loraStyle);

Object.assign(window, { LoraTab });
