/* R3T Monitor — app shell, fleet ↔ detail navigation.
   Data is loaded from /api/meter (live) with a mock fallback (see live-data.js).
   Appearance is fixed (the design-tool Tweaks panel is omitted for the public page). */
const { useState: useS, useEffect: useE } = React;

/* ---------- single-device detail ---------- */
function DetailView({ device, now, period, setPeriod, theme, onBack }){
  const base = baseFor(device, period);
  const latest = base[0];
  // theme drives the chart re-init so its colours follow the light/dark toggle
  const themeKey = `${theme}-${period}`;

  return (
    <div>
      <DeviceHeader device={device} now={now} showLive={true}
        period={period} setPeriod={setPeriod} onBack={onBack} />
      <Metrics latest={latest} history={base} period={period} />
      <MainChart history={base} chartStyle="area" period={period} themeKey={themeKey} />
      <ReadingsTable history={base} period={period} />
    </div>
  );
}

function CenterNote({ children }){
  return (
    <div style={{ padding: "70px 20px", textAlign: "center", color: "var(--text-3)",
      fontFamily: "var(--font-mono)", fontSize: 14 }}>{children}</div>
  );
}

function App(){
  const [data, setData] = useS(null);   // { fleet, now, summary, source }
  const [failed, setFailed] = useS(false);
  const [selId, setSelId] = useS(null);
  const [period, setPeriod] = useS("today");
  const [theme, setTheme] = useS(()=>
    (typeof document !== "undefined" && document.body.dataset.theme) || "light");

  // accent + density are fixed
  useE(()=>{
    document.body.dataset.accent = "blue";
    document.body.dataset.density = "regular";
  }, []);
  // theme is user-toggleable and persisted
  useE(()=>{
    document.body.dataset.theme = theme;
    try { localStorage.setItem("wm-theme", theme); } catch(e){}
  }, [theme]);
  const toggleTheme = ()=> setTheme(v => v === "dark" ? "light" : "dark");

  useE(()=>{
    let alive = true;
    window.R3T_loadFleet().then(
      (d)=>{ if(alive) setData(d); },
      ()=>{ if(alive) setFailed(true); }
    );
    return ()=>{ alive = false; };
  }, []);

  if(failed) return (
    <div className="wrap"><AppBar now={null} theme={theme} onToggleTheme={toggleTheme} /><CenterNote>Gagal memuat data. Coba muat ulang halaman.</CenterNote></div>
  );
  if(!data) return (
    <div className="wrap"><AppBar now={null} theme={theme} onToggleTheme={toggleTheme} /><CenterNote>Memuat data…</CenterNote></div>
  );

  const { fleet, now, summary, source } = data;
  const device = selId != null ? fleet.find(d=>d.id===selId) : null;
  const openDevice = (d)=>{ setSelId(d.id); setPeriod("today"); window.scrollTo(0,0); };
  const backToFleet = ()=>{ setSelId(null); window.scrollTo(0,0); };

  return (
    <div className="wrap">
      <AppBar now={now} theme={theme} onToggleTheme={toggleTheme} />
      {fleet.length === 0
        ? <CenterNote>Belum ada data pembacaan. Data akan muncul otomatis saat perangkat mengirim laporan.</CenterNote>
        : device
        ? <DetailView device={device} now={now} period={period} setPeriod={setPeriod}
            theme={theme} onBack={backToFleet} />
        : <FleetView fleet={fleet} summary={summary} now={now} onOpen={openDevice} />}

      <footer>
        <span>Data refreshes automatically every few minutes by the R3T system.</span>
        <span className="sep"></span>
        <span style={{fontFamily:"var(--font-mono)"}}>
          R3T Monitor v1.0 · {fleet.length} device{fleet.length===1?"":"s"}
          {source === "demo" && " · demo data"}
        </span>
      </footer>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
