// Devices.jsx
const DEVICES = [
  { id: "A4F7-2200-EE91", name: "Gateway-AHL-001",  type: "Gateway",     zone: "Теплица 1",     rssi: "−62", batt: "сеть",  status: "ok",   statusLbl: "Онлайн", fw: "v2.4.1", icon: "ri-router-line" },
  { id: "B221-9911-04A2", name: "TDS-Sensor-12",    type: "TDS-сенсор",  zone: "5 станция",     rssi: "—",   batt: "12 %", status: "cri",  statusLbl: "Нет связи", fw: "v1.8.0", icon: "ri-temp-cold-line" },
  { id: "C771-3308-1100", name: "Hive-Gate-B06",    type: "Задвижка",    zone: "AB1 · B-06",    rssi: "−74", batt: "84 %", status: "ok",   statusLbl: "Онлайн", fw: "v3.0.2", icon: "ri-door-open-line" },
  { id: "D102-4471-22F0", name: "Humidity-09",      type: "Влажность",   zone: "2 ряд",         rssi: "−81", batt: "28 %", status: "warn", statusLbl: "Низкий заряд", fw: "v1.4.3", icon: "ri-drop-line" },
  { id: "E990-1213-AA5C", name: "Hive-Gate-B09",    type: "Задвижка",    zone: "AB1 · B-09",    rssi: "−68", batt: "71 %", status: "alert",statusLbl: "Замена улья", fw: "v3.0.2", icon: "ri-door-open-line" },
  { id: "F441-2200-DD08", name: "Activity-B06",     type: "Активность",  zone: "AB1 · B-06",    rssi: "−71", batt: "63 %", status: "ok",   statusLbl: "Онлайн", fw: "v2.1.0", icon: "ri-pulse-line" },
  { id: "G880-7711-04C9", name: "Temp-Air-AB1",     type: "Темп. возд.", zone: "AB1 · север",   rssi: "−58", batt: "сеть",  status: "ok",   statusLbl: "Онлайн", fw: "v2.0.4", icon: "ri-temp-hot-line" },
  { id: "H551-6622-1188", name: "Camera-AB1-01",    type: "Камера",      zone: "AB1 · вход",    rssi: "−67", batt: "сеть",  status: "ok",   statusLbl: "Онлайн", fw: "v4.2.0", icon: "ri-camera-line" },
];

function normalizeRouteStateContext(routeState) {
  if (!routeState || typeof routeState !== "object") return null;
  return {
    greenhouseId: routeState.greenhouseId ?? routeState.greenhouse_id ?? null,
    zoneId: routeState.zoneId ?? routeState.zone_id ?? null,
    deviceId: routeState.deviceId ?? routeState.device_id ?? null,
  };
}

function normalizeDeviceRow(raw) {
  const deviceId = raw?.id || raw?.device_id || raw?.deviceId || null;
  if (!deviceId) return null;
  return {
    id: String(deviceId),
    name: raw?.name || raw?.device_name || String(deviceId),
    type: raw?.type || raw?.device_type || "Устройство",
    zone: raw?.zone || raw?.zone_id || raw?.zoneId || "—",
    zoneId: raw?.zone_id || raw?.zoneId || null,
    greenhouseId: raw?.greenhouse_id || raw?.greenhouseId || null,
    rssi: raw?.rssi || "—",
    batt: raw?.batt
      || (raw?.battery != null ? String(raw.battery) : null)
      || (raw?.battery_pct != null ? String(raw.battery_pct) : "—"),
    status: raw?.status || "ok",
    statusLbl: raw?.statusLbl || raw?.status_label || "Онлайн",
    fw: raw?.fw || raw?.firmware_version || "—",
    icon: raw?.icon || "ri-router-line",
  };
}

function Devices({ routeState = null, onNav }) {
  const context = normalizeRouteStateContext(routeState);
  const baseRows = (Array.isArray(DATA?.devices) && DATA.devices.length ? DATA.devices : DEVICES)
    .map(normalizeDeviceRow)
    .filter(Boolean);

  const filteredRows = baseRows.filter((row) => {
    if (context?.deviceId && String(row.id) !== String(context.deviceId)) return false;
    if (context?.zoneId) {
      const byZoneId = row.zoneId && String(row.zoneId) === String(context.zoneId);
      const byZoneLabel = String(row.zone || "").includes(String(context.zoneId));
      if (!byZoneId && !byZoneLabel) return false;
    }
    if (context?.greenhouseId) {
      const byGreenhouseId = row.greenhouseId && String(row.greenhouseId) === String(context.greenhouseId);
      const byZoneLabel = String(row.zone || "").includes(String(context.greenhouseId));
      if (!byGreenhouseId && !byZoneLabel) return false;
    }
    return true;
  });

  const rows = filteredRows.length ? filteredRows : baseRows;
  const showScopedBanner = Boolean(context?.deviceId || context?.zoneId || context?.greenhouseId);
  const onlineCount = rows.filter((item) => !["critical", "crit", "offline", "off"].includes(String(item.status || "").toLowerCase())).length;
  const warnCount = rows.filter((item) => ["warn", "warning", "alert"].includes(String(item.status || "").toLowerCase())).length;
  const critCount = rows.filter((item) => ["critical", "crit", "offline", "off"].includes(String(item.status || "").toLowerCase())).length;

  return (
    <div className="page">
      <div className="page-head">
        <div>
          <div className="page-title">Устройства</div>
          <div className="page-sub">{rows.length} устройств · {onlineCount} онлайн · {warnCount} предупреждения · {critCount} аварии</div>
        </div>
        <div className="actions">
          {showScopedBanner && (
            <button
              className="btn btn--secondary"
              onClick={() => onNav && onNav("hives", {
                greenhouseId: context?.greenhouseId ?? null,
                zoneId: context?.zoneId ?? null,
                deviceId: context?.deviceId ?? null,
              })}
            >
              <i className="ri-arrow-left-line"></i>К карте
            </button>
          )}
          <button className="btn btn--secondary"><i className="ri-download-line"></i>CSV</button>
          <button className="btn btn--secondary"><i className="ri-tools-line"></i>Диагностика</button>
          <button className="btn btn--primary"><i className="ri-add-line"></i>Добавить устройство</button>
        </div>
      </div>

      {showScopedBanner && (
        <div className="banner" style={{ marginBottom: 10 }}>
          <i className="ri-compass-3-line"></i>
          Контекст: {context?.greenhouseId ? `теплица ${context.greenhouseId}` : "теплица —"}
          {context?.zoneId ? ` · зона ${context.zoneId}` : ""}
          {context?.deviceId ? ` · устройство ${context.deviceId}` : ""}
        </div>
      )}

      <div style={{display:"flex",gap:8}}>
        <div className="search" style={{maxWidth:300}}>
          <i className="ri-search-line"></i>
          <input placeholder="ID, имя, серийный…" />
        </div>
        <button className="btn btn--secondary"><i className="ri-filter-line"></i>Тип</button>
        <button className="btn btn--secondary"><i className="ri-map-pin-line"></i>Зона</button>
        <button className="btn btn--secondary"><i className="ri-pulse-line"></i>Статус</button>
      </div>

      <div className="card" style={{padding:0,overflow:"hidden"}}>
        <table>
          <thead><tr>
            <th>ID</th><th>Устройство</th><th>Тип</th><th>Зона</th><th>Связь</th><th>Батарея</th><th>Прошивка</th><th>Статус</th>
          </tr></thead>
          <tbody>
            {rows.map(d => (
              <tr key={d.id} style={context?.deviceId && String(context.deviceId) === String(d.id) ? { background: "rgba(0,123,251,.08)" } : undefined}>
                <td className="id-mono">{d.id}</td>
                <td><div style={{display:"flex",gap:10,alignItems:"center"}}><i className={d.icon} style={{fontSize:16,color:"var(--fg-muted)"}}></i><b style={{font:"600 13px Inter",color:"var(--fg-strong)"}}>{d.name}</b></div></td>
                <td>{d.type}</td>
                <td>{d.zone}</td>
                <td>{d.rssi}</td>
                <td style={{color: d.batt.includes("%") && parseInt(d.batt) < 30 ? "#E5342B" : "var(--fg)", fontWeight: d.batt.includes("%") && parseInt(d.batt) < 30 ? 600 : 400}}>{d.batt}</td>
                <td className="id-mono">{d.fw}</td>
                <td><span className={"status status--" + d.status}><span className="dot"></span>{d.statusLbl}</span></td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}
window.Devices = Devices;
