// Device Management — Root App

const { useState, useEffect } = React;

const DM_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "dark": true,
  "density": "comfy",
  "sidebar": "full",
  "live": true,
  "cardStyle": "elevated",
  "accent": "#00D4FF"
}/*EDITMODE-END*/;

function DMApp() {
  const [t, setTweak] = window.useTweaks(DM_TWEAK_DEFAULTS);
  const [current, setCurrent] = useState('fleet');
  const [search, setSearch] = useState('');
  const [openDevice, setOpenDevice] = useState(null);
  const toast = window.useDMToast();

  useEffect(() => { document.documentElement.classList.toggle('dark', t.dark); }, [t.dark]);
  useEffect(() => { document.documentElement.style.setProperty('--dm-primary', t.accent); }, [t.accent]);

  useEffect(() => {
    if (!t.live) return;
    const id = setInterval(() => {
      if (Math.random() < 0.5) {
        const events = [
          { sev: 'success', title: 'OTA batch finished', body: 'OTA-0412 · 119/412 complete · 6 failures' },
          { sev: 'alert',   title: 'Device offline', body: 'FCC-RPI-0009 · no heartbeat 6h+' },
          { sev: 'info',    title: 'Release uploaded', body: 'v1.3.1-rc.1 · awaiting approval' },
        ];
        toast.push(events[Math.floor(Math.random() * events.length)]);
      }
    }, 20000);
    return () => clearInterval(id);
  }, [t.live, toast]);

  const alertCount = window.DM_ALERTS.filter(a => a.sev !== 'info').length;

  const titles = {
    fleet:    { title: 'Fleet Overview',     subtitle: '1,284 connected units · 6 hospitals · streaming' },
    topology: { title: 'Network Topology',   subtitle: '6 hospital sites · live data center connectivity' },
    ota:      { title: 'OTA Update Jobs',    subtitle: '6 jobs · 1 active rollout · 412 devices in flight' },
    release: { title: 'Release Catalog',   subtitle: '5 packages · 1 pending approval' },
    alerts:   { title: 'Alerts',             subtitle: `${alertCount} active · last hour` },
    users:    { title: 'User Management',    subtitle: '4 accounts · admin-only access' },
    settings: { title: 'Settings',           subtitle: 'Account, preferences, thresholds' },
  };

  return (
    <div className={`dm-app density-${t.density} dm-sb-mode-${t.sidebar}`}>
      <window.DMSidebar current={current} onNav={setCurrent} mode={t.sidebar} accent={t.accent} alertCount={alertCount}/>
      <main className="dm-main">
        <window.DMHeader
          title={titles[current].title}
          subtitle={titles[current].subtitle}
          dark={t.dark}
          onToggleDark={() => setTweak('dark', !t.dark)}
          live={t.live}
          onToggleLive={() => setTweak('live', !t.live)}
          search={search}
          onSearch={setSearch}
        />
        <div className="dm-screen" key={current}>
          {current === 'fleet'    && <window.FleetOverview accent={t.accent} cardStyle={t.cardStyle} live={t.live} onOpenDevice={setOpenDevice}/>}
          {current === 'topology' && <window.TopologyScreen cardStyle={t.cardStyle} live={t.live}/>}
          {current === 'ota'      && <window.OTAScreen cardStyle={t.cardStyle} live={t.live}/>}
          {current === 'release' && <window.ReleaseScreen cardStyle={t.cardStyle}/>}
          {current === 'alerts'   && <window.AlertsScreen cardStyle={t.cardStyle}/>}
          {current === 'users'    && <window.UsersScreen cardStyle={t.cardStyle}/>}
          {current === 'settings' && <window.SettingsScreen cardStyle={t.cardStyle} dark={t.dark}/>}
        </div>
      </main>

      {openDevice && <window.DeviceModal device={openDevice} onClose={() => setOpenDevice(null)} cardStyle={t.cardStyle} live={t.live}/>}

      <window.TweaksPanel>
        <window.TweakSection label="Theme" />
        <window.TweakToggle label="Dark mode" value={t.dark} onChange={(v) => setTweak('dark', v)} />
        <window.TweakColor label="Accent" value={t.accent} options={['#00D4FF', '#0EA5E9', '#10b981', '#a855f7', '#f59e0b']} onChange={(v) => setTweak('accent', v)} />

        <window.TweakSection label="Layout" />
        <window.TweakRadio label="Density" value={t.density} options={['compact', 'comfy', 'spacious']} onChange={(v) => setTweak('density', v)} />
        <window.TweakRadio label="Sidebar" value={t.sidebar} options={['icon', 'full', 'floating']} onChange={(v) => setTweak('sidebar', v)} />
        <window.TweakRadio label="Card style" value={t.cardStyle} options={['flat', 'elevated', 'glass']} onChange={(v) => setTweak('cardStyle', v)} />

        <window.TweakSection label="Simulation" />
        <window.TweakToggle label="Live data" value={t.live} onChange={(v) => setTweak('live', v)} />
      </window.TweaksPanel>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <window.DMToastProvider>
    <DMApp />
  </window.DMToastProvider>
);
