// Hospital Dashboard — Root App

const { useState, useEffect, useMemo } = React;

const HOSP_TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "dark": false,
  "density": "comfy",
  "sidebar": "full",
  "live": true,
  "cardStyle": "elevated",
  "accent": "#4F46E5"
}/*EDITMODE-END*/;

function App() {
  const [t, setTweak] = window.useTweaks(HOSP_TWEAK_DEFAULTS);
  const [current, setCurrent] = useState('ward');
  const [selectedBed, setSelectedBed] = useState(null);
  const [search, setSearch] = useState('');
  const [alerts, setAlerts] = useState(window.HOSP_ALERTS);
  const toast = window.useToast();

  // Apply theme to <html>
  useEffect(() => {
    document.documentElement.classList.toggle('dark', t.dark);
  }, [t.dark]);

  // Apply accent
  useEffect(() => {
    document.documentElement.style.setProperty('--h-primary', t.accent);
  }, [t.accent]);

  // Spontaneously emit alerts when live
  useEffect(() => {
    if (!t.live) return;
    const id = setInterval(() => {
      if (Math.random() < 0.4) {
        const events = [
          { sev: 'success', title: 'Bed 05 stabilized', body: 'SpO₂ recovered to 97%' },
          { sev: 'alert', title: 'New alert — Bed 04', body: 'HR sustained > 120 bpm' },
          { sev: 'info', title: 'Patient checked in', body: 'P. Sharma → Bed 17' },
        ];
        const e = events[Math.floor(Math.random() * events.length)];
        toast.push(e);
      }
    }, 18000);
    return () => clearInterval(id);
  }, [t.live, toast]);

  const onSelectBed = (bed) => { setSelectedBed(bed); setCurrent('vitals'); };
  const onNav = (id) => { setCurrent(id); if (id === 'ward') setSelectedBed(null); };

  const breadcrumb = useMemo(() => {
    const map = {
      ward: ['Apollo General', 'Ward Grid'],
      vitals: ['Apollo General', 'Ward Grid', selectedBed?.name || 'Live Vitals'],
      hospitals: ['Network', 'Hospitals'],
      patients: ['Apollo General', 'Patients'],
      devices: ['Apollo General', 'Devices'],
      alerts: ['Apollo General', 'Alerts'],
      map: ['Apollo General', 'Floor Plan'],
    };
    return map[current];
  }, [current, selectedBed]);

  const titles = {
    ward: { title: 'Ward Grid', subtitle: '12 active beds · 4 wards · live monitoring' },
    vitals: { title: selectedBed?.patient || 'Live Vitals', subtitle: `${selectedBed?.name || ''} · ${selectedBed?.device || ''}` },
    hospitals: { title: 'Hospital Network', subtitle: '4 facilities · 94 active beds' },
    patients: { title: 'Patient Management', subtitle: `${window.HOSP_PATIENTS.length} active admissions` },
    devices: { title: 'Devices', subtitle: `${window.HOSP_DEVICES.length} edge monitors · 11 online` },
    alerts: { title: 'Alert History', subtitle: `${alerts.filter(a => !a.ack).length} unacknowledged · ${alerts.length} total` },
    map: { title: 'Floor Plan', subtitle: 'Apollo General · Floor 3 · live positions' },
  };

  const alertCount = alerts.filter(a => !a.ack).length;
  const handleAck = (id) => {
    setAlerts(prev => prev.map(a => a.id === id ? { ...a, ack: true } : a));
    toast.push({ sev: 'success', title: 'Alert acknowledged' });
  };

  return (
    <div className={`app density-${t.density} sb-mode-${t.sidebar}`}>
      <window.Sidebar current={current} onNav={onNav} mode={t.sidebar} alertCount={alertCount} accent={t.accent}/>

      <main className="main">
        <window.Header
          title={titles[current].title}
          subtitle={titles[current].subtitle}
          breadcrumb={breadcrumb}
          dark={t.dark}
          onToggleDark={() => setTweak('dark', !t.dark)}
          accent={t.accent}
          search={search}
          onSearch={setSearch}
          live={t.live}
          onToggleLive={() => setTweak('live', !t.live)}
        />

        <div className="screen" key={current}>
          {current === 'ward' && <window.WardGridScreen onSelectBed={onSelectBed} live={t.live} cardStyle={t.cardStyle} density={t.density} accent={t.accent}/>}
          {current === 'vitals' && <window.LiveVitalsScreen bed={selectedBed} onBack={() => onNav('ward')} live={t.live} cardStyle={t.cardStyle} accent={t.accent}/>}
          {current === 'hospitals' && <window.HospitalsScreen onSelect={() => onNav('ward')} cardStyle={t.cardStyle} accent={t.accent}/>}
          {current === 'patients' && <window.PatientsScreen cardStyle={t.cardStyle}/>}
          {current === 'devices' && <window.DevicesScreen cardStyle={t.cardStyle}/>}
          {current === 'alerts' && <window.AlertsScreen alerts={alerts} onAck={handleAck} cardStyle={t.cardStyle}/>}
          {current === 'map' && <window.FloorPlanScreen onSelectBed={onSelectBed} live={t.live} cardStyle={t.cardStyle}/>}
        </div>
      </main>

      <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={['#4F46E5', '#0EA5E9', '#10b981', '#f59e0b', '#ec4899']} 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>
  );
}

// Mount with toast provider
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <window.ToastProvider>
    <App />
  </window.ToastProvider>
);
