// Heim-Portal — expanded with Medikationsplan, Vitals, richer Visite + Reports + Audit views.

const HeimPortal = ({ ctx }) => {
  if (window.useStoreVersion) window.useStoreVersion();
  const [view, setView] = React.useState("dashboard");
  const [selectedAnfrage, setSelectedAnfrage] = React.useState("A-2812");
  const [tab, setTab] = React.useState("offen");
  const [selectedBewohner, setSelectedBewohner] = React.useState("b1");
  const [bewohnerTab, setBewohnerTab] = React.useState("uebersicht");
  const [selectedVisite, setSelectedVisite] = React.useState("V-104");
  const [newOpen, setNewOpen] = React.useState(false);
  const [cmdOpen, setCmdOpen] = React.useState(false);
  const [voiceOpen, setVoiceOpen] = React.useState(false);

  React.useEffect(() => {
    const h = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { e.preventDefault(); setCmdOpen(true); }
      if (e.key.toLowerCase() === "n" && !e.metaKey && !e.ctrlKey && e.target.tagName !== "INPUT" && e.target.tagName !== "TEXTAREA") { setNewOpen(true); }
      if (e.key.toLowerCase() === "v" && !e.metaKey && !e.ctrlKey && e.target.tagName !== "INPUT" && e.target.tagName !== "TEXTAREA") { setVoiceOpen(true); }
    };
    const inLight = () => document.body.classList.contains("ml-mode");
    const v = () => { if (!inLight()) setVoiceOpen(true); };
    const s = () => { if (!inLight()) setCmdOpen(true); };
    const sv = (e) => { if (e.detail?.portal === "heim" && e.detail?.view) setView(e.detail.view); };
    window.addEventListener("keydown", h);
    window.addEventListener("medlink:openvoice", v);
    window.addEventListener("medlink:search", s);
    window.addEventListener("medlink:setView", sv);
    return () => {
      window.removeEventListener("keydown", h);
      window.removeEventListener("medlink:openvoice", v);
      window.removeEventListener("medlink:search", s);
      window.removeEventListener("medlink:setView", sv);
    };
  }, []);

  const heim = HEIMS.find(h => h.id === ctx.heim) || HEIMS[1];
  const scoped = ctx.heim === "alle" ? ANFRAGEN : ANFRAGEN.filter(a => a.heim === ctx.heim);

  const counts = {
    offen:       scoped.filter(a => a.status === "offen").length,
    bearbeitung: scoped.filter(a => a.status === "bearbeitung").length,
    freigegeben: scoped.filter(a => a.status === "freigegeben").length,
    geliefert:   scoped.filter(a => a.status === "geliefert").length,
    abgelehnt:   scoped.filter(a => a.status === "abgelehnt").length,
    alle: scoped.length,
  };

  const bewohnerScoped = ctx.heim === "alle" ? BEWOHNER : BEWOHNER.filter(b => b.heim === ctx.heim);

  const sections = [
    { label: "", items: [
      { id: "dashboard", label: "Dashboard",  icon: "home" },
      { id: "anfragen",  label: "Anfragen",   icon: "inbox", badge: counts.offen + counts.bearbeitung },
      { id: "bewohner",  label: "Bewohner",   icon: "users", badge: bewohnerScoped.length },
      { id: "visiten",   label: "Visiten",    icon: "stethoscope", badge: VISITEN.filter(v => v.status === "geplant").length },
      { id: "voice",     label: "Sprach-Doku", icon: "mic", badge: "KI" },
      { id: "therapien", label: "Therapien",  icon: "activity" },
      { id: "rezepte",   label: "Rezepte",    icon: "pill" },
    ]},
    { label: "Verwaltung", items: [
      { id: "reports",   label: "Reports",         icon: "barChart" },
      { id: "audit",     label: "Audit-Log",       icon: "shield" },
      { id: "benutzer",  label: "Benutzer",        icon: "user" },
      { id: "settings",  label: "Einstellungen",   icon: "settings" },
    ]},
  ];

  return (
    <>
      <Topbar
        portal="Pflegeheim"
        portalIcon="home"
        onBrand={ctx.onBrandClick}
        onToggleSidebar={ctx.onPortalSwitch}
        crumbs={[viewLabel(view)]}
        heim={ctx.heim}
        onSearchClick={() => setCmdOpen(true)}
        userName="Maria Lehmann"
        userRole="Pflegeleitung"
        userEmail="maria.lehmann@rosenhof.de"
        onLogout={ctx.onLogout}
        onAdmin={ctx.onAdmin}
      />
      <Sidebar
        scopeMark={heim.mark}
        scopeTitle={heim.name}
        scopeSub={`${heim.residents} Bewohner · ${heim.city}`}
        onScopeClick={ctx.onHeimSwitch}
        sections={sections}
        active={view}
        onNav={setView}
        compliance="DSGVO · DE-Hosting · Extra-Schutz aktiv"
      />
      <main className="content">
        {view === "dashboard" && <DashboardView heim={heim} counts={counts} scoped={scoped} onJumpAnfragen={() => setView("anfragen")} onNew={() => setNewOpen(true)} />}
        {view === "anfragen" && (
          <AnfragenView
            scoped={scoped} counts={counts}
            tab={tab} onTab={setTab}
            selected={selectedAnfrage} onSelect={setSelectedAnfrage}
            onNew={() => setNewOpen(true)}
          />
        )}
        {view === "bewohner" && (
          <BewohnerView
            bewohner={bewohnerScoped}
            selected={selectedBewohner} onSelect={setSelectedBewohner}
            tab={bewohnerTab} onTab={setBewohnerTab}
            onNewAnfrage={(b) => { setSelectedBewohner(b); setNewOpen(true); }}
          />
        )}
        {view === "visiten" && <VisitenView heim={ctx.heim} selected={selectedVisite} onSelect={setSelectedVisite} />}
        {view === "voice" && <VoiceLibraryView onOpenNew={() => setVoiceOpen(true)} onJumpBewohner={(bid) => { setView("bewohner"); setSelectedBewohner(bid); }} />}
        {view === "therapien" && <TherapienView heim={ctx.heim} />}
        {view === "rezepte" && <RezepteView scoped={scoped} />}
        {view === "reports" && <ReportsView scoped={scoped} heim={heim} />}
        {view === "audit" && <AuditView />}
        {view === "benutzer" && <BenutzerView />}
        {view === "settings" && <SettingsView />}
      </main>

      <NewAnfrage
        open={newOpen}
        onClose={() => setNewOpen(false)}
        onSubmit={(data) => {
          if (window.STORE?.createAnfrage) {
            window.STORE.createAnfrage({ ...data, von: "Maria Lehmann" });
            setView("anfragen");
          } else {
            ctx.toast(`Anfrage an ${DOCTORS.find(d => d.id === BEWOHNER.find(b => b.id === data.bewohner)?.arzt)?.name} gesendet`);
          }
        }}
        bewohnerId={selectedBewohner}
      />
      <VoiceLauncher onOpen={() => setVoiceOpen(true)} />
      <VoiceSheet
        open={voiceOpen}
        onClose={() => setVoiceOpen(false)}
        bewohnerOptions={bewohnerScoped}
        defaultBewohner={selectedBewohner}
        onSaved={() => ctx.toast("Sprach-Notiz gespeichert · 3 Aktionen ausgelöst")}
      />
      <CmdK
        open={cmdOpen}
        onClose={() => setCmdOpen(false)}
        onRun={(id) => {
          if (id === "new:anfrage") setNewOpen(true);
          else if (id.startsWith("nav:")) setView(id.slice(4));
          else if (id.startsWith("portal:")) ctx.setPortal(id.slice(7));
          else if (id.startsWith("bewohner:")) { setView("bewohner"); setSelectedBewohner(id.slice(9)); }
        }}
      />
    </>
  );
};

const viewLabel = (v) => ({
  dashboard: "Dashboard", anfragen: "Anfragen", bewohner: "Bewohner",
  visiten: "Visiten", voice: "Sprach-Dokumentation", therapien: "Therapien", rezepte: "Rezepte",
  reports: "Reports", audit: "Audit-Log", benutzer: "Benutzer", settings: "Einstellungen"
}[v] || v);

// ---------- Dashboard ----------
const DashboardView = ({ heim, counts, scoped, onJumpAnfragen, onNew }) => {
  const hourBuckets = [3,5,4,7,9,6,4,3,5,7,8,6]; // mock: requests per 2h
  const statusMix = [
    { key: "offen",       label: "Offen",          n: counts.offen },
    { key: "bearbeitung", label: "In Bearbeitung", n: counts.bearbeitung },
    { key: "freigegeben", label: "Freigegeben",    n: counts.freigegeben },
    { key: "geliefert",   label: "Geliefert",      n: counts.geliefert },
    { key: "abgelehnt",   label: "Abgelehnt",      n: counts.abgelehnt },
  ];
  const total = statusMix.reduce((s, x) => s + x.n, 0) || 1;
  return (
    <>
      <div className="content-head">
        <div>
          <h1>Dashboard</h1>
          <div className="sub">Übersicht · {heim.name} · Montag, 20. April 2026</div>
        </div>
        <div className="right">
          <Btn icon="printer">Schicht-Übergabe</Btn>
          <Btn variant="primary" icon="plus" kbd="N" onClick={onNew}>Neue Anfrage</Btn>
        </div>
      </div>
      <div className="kpi-grid" data-tour="heim-kpi">
        <Kpi label="Offene Anfragen"   value={counts.offen + counts.bearbeitung} icon="inbox"       trend="↑ 3 seit gestern"    points={[2,4,3,5,7,6,9,7]} />
        <Kpi label="Heute bearbeitet"  value={counts.freigegeben + counts.geliefert} icon="check"  trend="Ø 2:14 bis Freigabe" points={[8,6,9,10,7,12,11,14]} />
        <Kpi label="Bewohner"          value={heim.residents} icon="users"  trend={`Belegung ${heim.occupancy}%`} points={[80,81,82,82,83,83,84,84]} />
        <Kpi label="Visiten geplant"   value="3" icon="stethoscope" trend="Di · Mi · Do diese Woche" points={[1,2,1,3,2,2,1,3]} />
      </div>

      <div style={{padding: "16px 24px", display: "grid", gridTemplateColumns: "1.6fr 1fr", gap: 16, flex: 1, minHeight: 0}}>
        <div className="col" style={{gap: 16, minHeight: 0}}>
          <div className="card">
            <div className="card-head">
              Dringend · benötigt Arzt-Freigabe
              <div className="right"><Btn onClick={onJumpAnfragen} icon="arrowRight">Alle Anfragen</Btn></div>
            </div>
            <table className="table">
              <thead><tr><th>P</th><th>#</th><th>Bewohner</th><th>Medikation</th><th>Typ</th><th>Wartezeit</th><th>Status</th></tr></thead>
              <tbody>
                {scoped.filter(a => a.status === "offen" || a.status === "bearbeitung").slice(0, 7).map(a => {
                  const b = BEWOHNER.find(x => x.id === a.bewohner);
                  return (
                    <tr key={a.id}>
                      <td><Prio level={a.prio} /></td>
                      <td><span className="mono muted">{a.id}</span></td>
                      <td data-bewohner={b?.id}>{b?.name}</td>
                      <td className="mono">{a.med}</td>
                      <td><TypBadge typ={a.typ} /></td>
                      <td className="muted">{a.erstellt}</td>
                      <td><StatusBadge status={a.status} /></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>

          <div style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16}}>
            <div className="card">
              <div className="card-head">Anfragen heute · nach Stunde</div>
              <div className="card-body" style={{display: "flex", alignItems: "flex-end", gap: 4, height: 120}}>
                {hourBuckets.map((v, i) => (
                  <div key={i} style={{flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 4}}>
                    <div style={{width: "100%", height: `${v * 10}px`, background: i === 4 ? "var(--accent)" : "var(--accent-tint)", borderRadius: 3, border: "1px solid var(--accent-border)"}} />
                    <div style={{fontSize: 9, color: "var(--fg-subtle)", fontFamily: "var(--font-mono)"}}>{String(i*2).padStart(2,"0")}</div>
                  </div>
                ))}
              </div>
            </div>
            <div className="card">
              <div className="card-head">Status-Verteilung</div>
              <div className="card-body col" style={{gap: 8}}>
                {statusMix.map(s => (
                  <div key={s.key}>
                    <div className="row" style={{justifyContent: "space-between", fontSize: 12}}>
                      <span>{s.label}</span>
                      <span className="mono muted">{s.n}</span>
                    </div>
                    <div style={{height: 5, background: "var(--bg-sunken)", borderRadius: 3, overflow: "hidden", marginTop: 3}}>
                      <div style={{width: `${(s.n/total)*100}%`, height: "100%", background: statusColor(s.key)}} />
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>

        <div className="col" style={{gap: 16, minHeight: 0}}>
          <div className="card">
            <div className="card-head">Aktivität · Live</div>
            <div className="card-body">
              <div className="timeline">
                <TlItem t="ok"   head="Apixaban für Hr. Müller geliefert"      who="Adler-Apotheke" ts="vor 18 Min" />
                <TlItem t="info" head="Dr. Schneider: Rückfrage zu Tramadol"    who="A-2802" ts="vor 1 Std" />
                <TlItem t="ok"   head="Ibuprofen freigegeben"                   who="Dr. Schneider · A-2801" ts="vor 2 Std" />
                <TlItem t="warn" head="Visite morgen 09:00 — 4 Bewohner"        who="Dr. Schneider · V-104" ts="vor 3 Std" />
                <TlItem t="ok"   head="Melperon abgelehnt"                       who="Dr. Bauer · A-2795" ts="gestern" />
              </div>
            </div>
          </div>
          <div className="card">
            <div className="card-head">Diese Woche · Aufgaben</div>
            <div className="card-body col" style={{gap: 6, fontSize: 12}}>
              <TaskLine done label="Quartalsbericht abgegeben" />
              <TaskLine label="Visite Dr. Schneider vorbereiten" meta="Di. 09:00" />
              <TaskLine label="BtM-Dokumentation prüfen" meta="Fr." />
              <TaskLine label="Apotheken-Abrechnung KW 16" meta="Fr." />
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

const statusColor = (k) => ({
  offen: "var(--info)", bearbeitung: "var(--warning)",
  freigegeben: "var(--success)", geliefert: "var(--fg-muted)", abgelehnt: "var(--danger)"
}[k] || "var(--fg-muted)");

const TaskLine = ({ label, meta, done }) => (
  <div className="row" style={{gap: 8}}>
    <CheckBox checked={!!done} />
    <span style={{flex: 1, color: done ? "var(--fg-muted)" : "var(--fg)", textDecoration: done ? "line-through" : "none"}}>{label}</span>
    {meta && <span className="mono muted" style={{fontSize: 11}}>{meta}</span>}
  </div>
);

const TlItem = ({ t, head, who, ts }) => (
  <div className={`tl-item ${t}`}>
    <div className="tl-dot"><Icon name={t === "ok" ? "check" : t === "warn" ? "warning" : "activity"} size={10} /></div>
    <div className="tl-body">
      <div className="head">{head}</div>
      <div className="who">{who}</div>
      <div className="ts">{ts}</div>
    </div>
  </div>
);

// ---------- Anfragen ----------
const AnfragenView = ({ scoped, counts, tab, onTab, selected, onSelect, onNew }) => {
  const filtered = tab === "alle" ? scoped : scoped.filter(a => a.status === tab);
  const current = ANFRAGEN.find(a => a.id === selected) || filtered[0];
  return (
    <>
      <div className="content-head">
        <div><h1>Anfragen</h1><div className="sub">Medikationen · Verlängerungen · Anpassungen</div></div>
        <div className="right">
          <Btn icon="filter">Filter</Btn>
          <Btn icon="printer">Export</Btn>
          <Btn variant="primary" icon="plus" kbd="N" onClick={onNew} data-tour="heim-new">Neue Anfrage</Btn>
        </div>
      </div>
      <Tabs
        active={tab} onChange={onTab}
        items={[
          { id: "offen",       label: "Offen",          count: counts.offen, icon: "clock" },
          { id: "bearbeitung", label: "In Bearbeitung", count: counts.bearbeitung, icon: "activity" },
          { id: "freigegeben", label: "Freigegeben",    count: counts.freigegeben, icon: "check" },
          { id: "geliefert",   label: "Geliefert",      count: counts.geliefert, icon: "truck" },
          { id: "abgelehnt",   label: "Abgelehnt",      count: counts.abgelehnt, icon: "x" },
          { id: "alle",        label: "Alle",           count: counts.alle },
        ]}
      />
      <Toolbar>
        <div className="search-inp"><Icon name="search" size={12} /><input placeholder="Suche in Anfragen…" /></div>
        <span className="chip active"><Icon name="check" size={10} /> Heim: aktuell</span>
        <span className="chip"><Icon name="plus" size={10} /> Arzt</span>
        <span className="chip"><Icon name="plus" size={10} /> Priorität</span>
        <span className="chip"><Icon name="plus" size={10} /> Zeitraum</span>
        <div className="spacer" />
        <span className="muted" style={{fontSize: 12}}>{filtered.length} Anfragen</span>
      </Toolbar>
      <div className="split">
        <div className="master">
          <table className="table">
            <thead>
              <tr>
                <th style={{width: 28, paddingLeft: 16}}></th>
                <th style={{width: 32}}>P</th>
                <th style={{width: 90}}>#</th>
                <th>Bewohner</th>
                <th>Medikation</th>
                <th style={{width: 110}}>Typ</th>
                <th style={{width: 90}}>Dosis</th>
                <th style={{width: 140}}>Arzt</th>
                <th style={{width: 130}}>Status</th>
                <th style={{width: 90, textAlign: "right", paddingRight: 16}}>Erstellt</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(a => {
                const b = BEWOHNER.find(x => x.id === a.bewohner);
                const arzt = DOCTORS.find(d => d.id === a.arzt);
                return (
                  <tr key={a.id} className={selected === a.id ? "selected" : ""} onClick={() => onSelect(a.id)}>
                    <td style={{paddingLeft: 16}}><CheckBox /></td>
                    <td><Prio level={a.prio} /></td>
                    <td><span className="mono muted">{a.id}</span></td>
                    <td data-bewohner={b?.id}><div className="row" style={{gap: 6}}><Avatar name={b?.name} size={18} />{b?.name}</div></td>
                    <td className="mono">{a.med}</td>
                    <td><TypBadge typ={a.typ} /></td>
                    <td className="mono muted">{a.dosis}</td>
                    <td className="muted">{arzt?.name.replace("Dr. med. ", "")}</td>
                    <td><StatusBadge status={a.status} /></td>
                    <td className="muted" style={{textAlign: "right", paddingRight: 16, fontSize: 11}}>{a.erstellt}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {current ? <AnfrageDetail anfrage={current} /> : <div className="empty">Keine Anfrage ausgewählt</div>}
      </div>
    </>
  );
};

const AnfrageDetail = ({ anfrage }) => {
  const b = BEWOHNER.find(x => x.id === anfrage.bewohner);
  const arzt = DOCTORS.find(d => d.id === anfrage.arzt);
  const trail = TRAIL[anfrage.id] || [
    { t: "ok", who: `${anfrage.von} (Pflege)`, head: "Anfrage erstellt", ts: `heute · ${anfrage.erstellt}` },
    { t: "info", who: "System", head: `Zugestellt an ${arzt?.name}`, ts: `heute · ${anfrage.erstellt}` },
  ];
  return (
    <div className="detail">
      <div className="detail-head">
        <div className="eyebrow row" style={{justifyContent: "space-between"}}>
          <span className="mono">{anfrage.id}</span>
          <StatusBadge status={anfrage.status} />
        </div>
        <h2 className="mono">{anfrage.med}</h2>
        <div className="muted" style={{fontSize: 12}}>{anfrage.typ} · {anfrage.dauer}</div>
        <div className="meta">
          <span><Icon name="user" size={11} /> {b?.name}</span>
          <span><Icon name="home" size={11} /> {HEIMS.find(h => h.id === b?.heim)?.name} · {b?.zimmer}</span>
          <span><Icon name="stethoscope" size={11} /> {arzt?.name}</span>
        </div>
        <div style={{display: "flex", gap: 6, marginTop: 12}}>
          {anfrage.status === "offen" && (
            <>
              <Btn variant="success" icon="check">Freigabe (als Arzt)</Btn>
              <Btn variant="danger-outline" icon="x">Ablehnen</Btn>
            </>
          )}
          <Btn icon="mail">Antworten</Btn>
          <Btn icon="paperclip">Anhang</Btn>
          <div style={{marginLeft: "auto"}}><Btn icon="more" /></div>
        </div>
      </div>
      <div className="detail-section">
        <h3>Verordnung</h3>
        <dl className="kv">
          <dt>Medikament</dt><dd className="mono">{anfrage.med}</dd>
          <dt>Typ</dt><dd><TypBadge typ={anfrage.typ} /></dd>
          <dt>Dosis</dt><dd className="mono">{anfrage.dosis}</dd>
          <dt>Dauer</dt><dd>{anfrage.dauer}</dd>
          <dt>Priorität</dt><dd><Prio level={anfrage.prio} /> {anfrage.prio === "H" ? "Hoch" : anfrage.prio === "M" ? "Mittel" : "Normal"}</dd>
          <dt>Apotheke</dt><dd>Adler-Apotheke · München <span className="muted">(Standard)</span></dd>
          {anfrage.notiz && <><dt>Notiz</dt><dd>{anfrage.notiz}</dd></>}
        </dl>
      </div>
      <div className="detail-section">
        <h3>Bewohner-Kontext</h3>
        <dl className="kv">
          <dt>Diagnosen</dt><dd>{b?.diagnosen.map(d => <span key={d} className="badge-pill" style={{marginRight: 4, marginBottom: 4}}>{d}</span>)}</dd>
          <dt>Allergien</dt><dd>{b?.allergien.length ? b.allergien.map(a => <span key={a} className="badge-pill abgelehnt" style={{marginRight: 4}}>{a}</span>) : <span className="muted">keine dokumentiert</span>}</dd>
          <dt>Pflegegrad</dt><dd className="mono">{b?.pflegegrad}</dd>
          <dt>Aktuelle Meds</dt><dd className="muted">{(MEDPLAN[b?.id] || []).length} Dauermedikationen · <a href="#" style={{color: "var(--accent)"}}>vollständig anzeigen</a></dd>
        </dl>
      </div>
      <div className="detail-section">
        <h3>Verlauf · Audit-Log</h3>
        <div className="timeline">
          {trail.map((t, i) => (
            <div key={i} className={`tl-item ${t.t}`}>
              <div className="tl-dot"><Icon name={t.t === "ok" ? "check" : t.t === "warn" ? "warning" : "activity"} size={10} /></div>
              <div className="tl-body">
                <div className="head">{t.head}</div>
                <div className="who">{t.who}</div>
                <div className="ts">{t.ts}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
      <div className="detail-section" style={{background: "var(--bg-sunken)", borderBottom: 0}}>
        <div style={{display: "flex", gap: 8, alignItems: "center", fontSize: 12, color: "var(--fg-muted)"}}>
          <Icon name="shield" size={13} /> Alle Änderungen werden mit Zeitstempel & Nutzer DSGVO-konform protokolliert.
        </div>
      </div>
    </div>
  );
};

// ---------- Bewohner (with tabs inside detail) ----------
const BewohnerView = ({ bewohner, selected, onSelect, tab, onTab, onNewAnfrage }) => {
  const current = BEWOHNER.find(b => b.id === selected) || bewohner[0];
  return (
    <>
      <div className="content-head">
        <div><h1>Bewohner</h1><div className="sub">{bewohner.length} Personen · {bewohner.filter(b => b.offen > 0).length} mit offenen Anfragen</div></div>
        <div className="right">
          <Btn icon="filter">Filter</Btn>
          <Btn icon="plus">Bewohner anlegen</Btn>
        </div>
      </div>
      <Toolbar>
        <div className="search-inp"><Icon name="search" size={12} /><input placeholder="Name, Zimmer, Diagnose…" /></div>
        <span className="chip"><Icon name="plus" size={10} /> Pflegegrad</span>
        <span className="chip"><Icon name="plus" size={10} /> Hausarzt</span>
        <div className="spacer" />
        <span className="muted" style={{fontSize: 12}}>{bewohner.length} Bewohner</span>
      </Toolbar>
      <div className="split">
        <div className="master">
          <table className="table">
            <thead>
              <tr><th style={{paddingLeft: 16}}>Name</th><th>Zimmer</th><th>Alter</th><th>Pflegegrad</th><th>Hausarzt</th><th>Offen</th></tr>
            </thead>
            <tbody>
              {bewohner.map(b => {
                const arzt = DOCTORS.find(d => d.id === b.arzt);
                return (
                  <tr key={b.id} className={current?.id === b.id ? "selected" : ""} onClick={() => onSelect(b.id)}>
                    <td style={{paddingLeft: 16}}><div className="row" style={{gap: 8}}><Avatar name={b.name} size={22} />{b.name}</div></td>
                    <td className="mono muted">{b.zimmer}</td>
                    <td className="num">{b.alter}</td>
                    <td className="mono">PG {b.pflegegrad}</td>
                    <td className="muted">{arzt?.name.replace("Dr. med. ", "")}</td>
                    <td>{b.offen > 0 ? <span className="badge-pill offen">{b.offen}</span> : <span className="muted">—</span>}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {current && <BewohnerDetail b={current} tab={tab} onTab={onTab} onNewAnfrage={onNewAnfrage} />}
      </div>
    </>
  );
};

const BewohnerDetail = ({ b, tab, onTab, onNewAnfrage }) => {
  const arzt = DOCTORS.find(d => d.id === b.arzt);
  const plan = MEDPLAN[b.id] || [];
  const vitals = VITALS[b.id];
  const anfragen = ANFRAGEN.filter(a => a.bewohner === b.id);
  return (
    <div className="detail">
      <div className="detail-head">
        <div style={{display: "flex", gap: 14, alignItems: "flex-start"}}>
          <Avatar name={b.name} size={48} />
          <div style={{flex: 1}}>
            <div className="eyebrow">{b.zimmer} · {HEIMS.find(h => h.id === b.heim)?.name}</div>
            <h2>{b.name}</h2>
            <div className="muted" style={{fontSize: 12}}>geb. {b.geb} · {b.alter} Jahre · Pflegegrad {b.pflegegrad} · {b.kasse}</div>
          </div>
        </div>
        <div style={{display: "flex", gap: 6, marginTop: 12}}>
          <Btn variant="primary" icon="plus" onClick={() => onNewAnfrage(b.id)}>Neue Anfrage</Btn>
          <Btn icon="stethoscope">Visite planen</Btn>
          <Btn icon="clipboard">Akte öffnen</Btn>
        </div>
        <div style={{marginTop: 14, display: "flex", gap: 2, borderBottom: "1px solid var(--border)", marginLeft: -18, marginRight: -18, paddingLeft: 18}}>
          {[
            ["uebersicht","Übersicht","user"],
            ["meds","Medikationsplan","pill"],
            ["vitals","Vitalwerte","activity"],
            ["anfragen",`Anfragen (${anfragen.length})`,"inbox"],
          ].map(([id, label, icon]) => (
            <button key={id} onClick={() => onTab(id)} className={`tab ${tab === id ? "active" : ""}`} style={{background: "transparent"}}>
              <Icon name={icon} size={12} /> {label}
            </button>
          ))}
        </div>
      </div>

      {tab === "uebersicht" && (
        <>
          <div className="detail-section">
            <h3>Stammdaten</h3>
            <dl className="kv">
              <dt>Eingezogen</dt><dd>{b.eingezogen}</dd>
              <dt>Hausarzt</dt><dd>{arzt?.name} <span className="muted">· {arzt?.spec}</span></dd>
              <dt>Kontakt</dt><dd>{b.kontakt || <span className="muted">nicht hinterlegt</span>}</dd>
              <dt>Kasse</dt><dd>{b.kasse}</dd>
            </dl>
          </div>
          <div className="detail-section">
            <h3>Medizinisch</h3>
            <dl className="kv">
              <dt>Diagnosen</dt><dd>{b.diagnosen.map(d => <span key={d} className="badge-pill" style={{marginRight: 4, marginBottom: 4}}>{d}</span>)}</dd>
              <dt>Allergien</dt><dd>{b.allergien.length ? b.allergien.map(a => <span key={a} className="badge-pill abgelehnt" style={{marginRight: 4}}>{a}</span>) : <span className="muted">keine dokumentiert</span>}</dd>
            </dl>
          </div>
        </>
      )}

      {tab === "meds" && (
        <div className="detail-section">
          <h3>Aktiver Medikationsplan · {plan.length} Positionen</h3>
          {plan.length === 0 ? <div className="muted" style={{fontSize: 12}}>Keine aktiven Medikamente hinterlegt.</div> : (
            <table className="table" style={{fontSize: 12, marginTop: 4}}>
              <thead><tr><th style={{paddingLeft: 0}}>Medikament</th><th>Dosis</th><th>Seit</th><th>Grund</th><th>Verordner</th></tr></thead>
              <tbody>
                {plan.map((p, i) => {
                  const d = DOCTORS.find(x => x.id === p.arzt);
                  return (
                    <tr key={i}>
                      <td className="mono" style={{paddingLeft: 0}}>
                        {p.med}
                        {p.hinweis && <div style={{fontSize: 10, color: "var(--warning)", marginTop: 2, fontFamily: "var(--font-sans)"}}><Icon name="warning" size={10} /> {p.hinweis}</div>}
                      </td>
                      <td className="mono">{p.dosis}</td>
                      <td className="muted">{p.seit}</td>
                      <td>{p.grund}</td>
                      <td className="muted">{d?.name.replace("Dr. med. ", "")}</td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          )}
        </div>
      )}

      {tab === "vitals" && vitals && (
        <>
          <div className="detail-section">
            <h3>Blutdruck (letzte 14 Tage, morgens)</h3>
            <VitalChart data={vitals.bp.map(([s,d]) => s)} data2={vitals.bp.map(([s,d]) => d)} unit="mmHg" refMin={110} refMax={140} />
            <div className="row" style={{gap: 16, marginTop: 6, fontSize: 11, color: "var(--fg-muted)"}}>
              <span className="row" style={{gap: 4}}><span style={{width: 8, height: 2, background: "var(--accent)"}} /> Systolisch</span>
              <span className="row" style={{gap: 4}}><span style={{width: 8, height: 2, background: "var(--fg-muted)"}} /> Diastolisch</span>
              <span>Ziel: 110–140 / 70–90 mmHg</span>
            </div>
          </div>
          <div className="detail-section">
            <h3>Puls</h3>
            <VitalChart data={vitals.puls} unit="bpm" refMin={60} refMax={90} color="var(--info)" />
          </div>
          {vitals.glucose && (
            <div className="detail-section">
              <h3>Blutzucker (nüchtern)</h3>
              <VitalChart data={vitals.glucose} unit="mg/dL" refMin={80} refMax={140} color="var(--warning)" />
            </div>
          )}
          {vitals.nrs && (
            <div className="detail-section">
              <h3>Schmerz NRS</h3>
              <VitalChart data={vitals.nrs} unit="/10" refMin={0} refMax={5} color="var(--danger)" />
            </div>
          )}
        </>
      )}

      {tab === "anfragen" && (
        <div className="detail-section">
          <h3>Anfragen · Verlauf</h3>
          {anfragen.length === 0 ? <div className="muted" style={{fontSize: 12}}>Keine Anfragen.</div> : (
            <table className="table" style={{fontSize: 12}}>
              <thead><tr><th style={{paddingLeft: 0}}>#</th><th>Medikament</th><th>Typ</th><th>Status</th><th>Erstellt</th></tr></thead>
              <tbody>
                {anfragen.map(a => (
                  <tr key={a.id}>
                    <td className="mono muted" style={{paddingLeft: 0}}>{a.id}</td>
                    <td>{a.med}</td>
                    <td><TypBadge typ={a.typ} /></td>
                    <td><StatusBadge status={a.status} /></td>
                    <td className="muted" style={{fontSize: 11}}>{a.erstellt}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          )}
        </div>
      )}
    </div>
  );
};

// Mini time-series chart
const VitalChart = ({ data, data2, unit, refMin, refMax, color = "var(--accent)" }) => {
  const w = 420, h = 90, pad = 8;
  const all = data2 ? [...data, ...data2] : data;
  const min = Math.min(refMin ?? Infinity, ...all) - 2;
  const max = Math.max(refMax ?? -Infinity, ...all) + 2;
  const xStep = (w - pad*2) / (data.length - 1);
  const scale = v => h - pad - ((v - min) / (max - min)) * (h - pad*2);
  const path = arr => arr.map((v, i) => `${i === 0 ? "M" : "L"}${(pad + i*xStep).toFixed(1)} ${scale(v).toFixed(1)}`).join(" ");
  const refYmin = refMin != null ? scale(refMin) : null;
  const refYmax = refMax != null ? scale(refMax) : null;
  return (
    <div style={{position: "relative"}}>
      <svg width="100%" height={h} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" style={{display: "block"}}>
        {refYmin != null && refYmax != null && (
          <rect x={pad} y={Math.min(refYmin, refYmax)} width={w - pad*2} height={Math.abs(refYmax - refYmin)} fill="var(--success-tint)" opacity="0.6" />
        )}
        <path d={path(data)} fill="none" stroke={color} strokeWidth="1.6" />
        {data2 && <path d={path(data2)} fill="none" stroke="var(--fg-muted)" strokeWidth="1.2" strokeDasharray="3 3" />}
        {data.map((v, i) => (
          <circle key={i} cx={pad + i*xStep} cy={scale(v)} r="1.8" fill={color} />
        ))}
      </svg>
      <div style={{display: "flex", justifyContent: "space-between", fontSize: 10, color: "var(--fg-subtle)", fontFamily: "var(--font-mono)", marginTop: 4}}>
        <span>{data.length} d</span>
        <span>letzte: {data[data.length - 1]} {unit}{data2 ? ` / ${data2[data2.length-1]}` : ""}</span>
      </div>
    </div>
  );
};

// ---------- Specialty Chip — shared ----------
const SPEC_TONES = {
  Hausarzt:   { tone: "teal",   mark: "H" },
  Internist:  { tone: "amber",  mark: "I" },
  Geriater:   { tone: "teal",   mark: "G" },
  Nervenarzt: { tone: "violet", mark: "N" },
  Palliativ:  { tone: "rose",   mark: "P" },
  Urologe:    { tone: "indigo", mark: "U" },
};
const SpecChip = ({ spec, big }) => {
  const meta = SPEC_TONES[spec] || SPEC_TONES.Hausarzt;
  return (
    <span className={`spec-chip ${big ? "spec-chip-big" : ""}`} data-tone={meta.tone} title={spec}>
      <span className="spec-chip-mark">{meta.mark}</span>
      <span className="spec-chip-label">{spec}</span>
    </span>
  );
};

// ---------- Visiten (expanded) ----------
const VisitenView = ({ heim, selected, onSelect }) => {
  const scoped = heim === "alle" ? VISITEN : VISITEN.filter(v => v.heim === heim);
  const current = VISITEN.find(v => v.id === selected) || scoped[0];
  return (
    <>
      <div className="content-head">
        <div><h1>Visiten</h1><div className="sub">Geplante & dokumentierte Arztbesuche</div></div>
        <div className="right"><Btn icon="printer">Wochenplan</Btn><Btn variant="primary" icon="plus">Visite planen</Btn></div>
      </div>
      <div className="split">
        <div className="master">
          <table className="table">
            <thead><tr><th style={{paddingLeft: 16}}>#</th><th>Termin</th><th>Arzt</th><th>Fachrichtung</th><th>Heim</th><th>Bew.</th><th>Status</th></tr></thead>
            <tbody>
              {scoped.map(v => {
                const arzt = DOCTORS.find(d => d.id === v.arzt);
                const h = HEIMS.find(h => h.id === v.heim);
                const spec = arzt?.spec || "Hausarzt";
                return (
                  <tr key={v.id} className={current?.id === v.id ? "selected" : ""} onClick={() => onSelect(v.id)}>
                    <td style={{paddingLeft: 16}} className="mono muted">{v.id}</td>
                    <td className="mono">{v.datum} · {v.zeit}</td>
                    <td>{arzt?.name.replace("Dr. med. ", "Dr. ")}</td>
                    <td><SpecChip spec={spec} /></td>
                    <td className="muted">{h?.name}</td>
                    <td className="num">{v.bewohner.length}</td>
                    <td><StatusBadge status={v.status === "geplant" ? "offen" : "erledigt"} /></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        {current && <VisiteDetail v={current} />}
      </div>
    </>
  );
};

const VisiteDetail = ({ v }) => {
  const arzt = DOCTORS.find(d => d.id === v.arzt);
  const h = HEIMS.find(h => h.id === v.heim);
  const isPlanned = v.status === "geplant";
  const spec = arzt?.spec || "Hausarzt";
  const isKonsil = spec !== "Hausarzt";
  return (
    <div className="detail">
      <div className="detail-head">
        <div className="eyebrow row" style={{justifyContent: "space-between"}}>
          <span className="mono">{v.id} · {isKonsil ? "Konsil" : "Regelvisite"}</span>
          <StatusBadge status={isPlanned ? "offen" : "erledigt"} />
        </div>
        <div className="row" style={{gap: 10, alignItems: "center", flexWrap: "wrap"}}>
          <h2 style={{margin: 0}}>{arzt?.name}</h2>
          <SpecChip spec={spec} big />
        </div>
        <div className="muted" style={{fontSize: 12, marginTop: 4}}>{h?.name} · {h?.address}</div>
        {v.anlass && (
          <div style={{fontSize: 12.5, color: "var(--fg-muted)", marginTop: 8, fontStyle: "italic"}}>
            Anlass: {v.anlass}
          </div>
        )}
        <div className="meta"><span><Icon name="calendar" size={11} /> {v.datum} · {v.zeit}</span><span><Icon name="users" size={11} /> {v.bewohner.length} Bewohner</span>{arzt?.interval && <span><Icon name="repeat" size={11} /> {arzt.interval}</span>}</div>
        <div style={{marginTop: 12, display: "flex", gap: 6}}>
          {isPlanned ? (
            <>
              <Btn variant="primary" icon="stethoscope" onClick={() => window.dispatchEvent(new CustomEvent("medlink:startVisite", { detail: { visitId: v.id } }))}>Visite starten</Btn>
              <Btn icon="clipboard">Vorbereitung</Btn>
              <Btn icon="mail">Arzt erinnern</Btn>
            </>
          ) : (
            <>
              <Btn icon="eye">Protokoll</Btn>
              <Btn icon="printer">PDF</Btn>
            </>
          )}
        </div>
      </div>

      <div className="detail-section">
        <h3>Bewohner & Vorbereitung</h3>
        <table className="table" style={{fontSize: 12}}>
          <thead><tr><th style={{paddingLeft: 0}}>Bewohner</th><th>Zimmer</th><th>Fokus</th><th>Offene Anfragen</th><th style={{textAlign: "right"}}>Vorb.</th></tr></thead>
          <tbody>
            {v.bewohner.map(bid => {
              const b = BEWOHNER.find(x => x.id === bid);
              const fokus = b?.diagnosen[0];
              const offen = ANFRAGEN.filter(a => a.bewohner === bid && (a.status === "offen" || a.status === "bearbeitung")).length;
              return (
                <tr key={bid}>
                  <td style={{paddingLeft: 0}} data-bewohner={b?.id}><div className="row" style={{gap: 6}}><Avatar name={b?.name} size={18} />{b?.name}</div></td>
                  <td className="mono muted">{b?.zimmer}</td>
                  <td className="muted">{fokus}</td>
                  <td>{offen > 0 ? <span className="badge-pill offen">{offen} offen</span> : <span className="muted">—</span>}</td>
                  <td style={{textAlign: "right"}}><CheckBox checked={bid === "b1"} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {!isPlanned && v.protokoll && (
        <div className="detail-section">
          <h3>Protokoll</h3>
          <div style={{padding: 10, background: "var(--bg-raised)", border: "1px solid var(--border)", borderRadius: "var(--r-md)", fontSize: 12, lineHeight: 1.55}}>
            {v.protokoll}
            <div style={{fontSize: 11, color: "var(--fg-subtle)", marginTop: 6}}>— {arzt?.name}, elektronisch signiert</div>
          </div>
        </div>
      )}

      {isPlanned && (
        <div className="detail-section">
          <h3>Checkliste</h3>
          <div className="col" style={{gap: 6, fontSize: 12}}>
            <TaskLine done label="Medikationspläne ausgedruckt" />
            <TaskLine done label="Vitalwerte der letzten 7 Tage zusammengestellt" />
            <TaskLine label="Angehörigen-Rücksprachen dokumentiert (Hr. Müller)" />
            <TaskLine label="BtM-Nachweise bereitgelegt" meta="optional" />
          </div>
        </div>
      )}

      <div className="detail-section">
        <h3>Nachbesprechung / Chat</h3>
        <div style={{padding: 10, background: "var(--bg-raised)", border: "1px solid var(--border)", borderRadius: "var(--r-md)", fontSize: 12, lineHeight: 1.5}}>
          <div><strong>Dr. Schneider</strong> <span className="muted">· gestern 16:02</span></div>
          <div style={{marginTop: 2}}>Ich würde für Hr. Müller die Blutdruckwerte 3 Tage morgens + abends messen, bevor wir Ramipril anpassen.</div>
          <div className="hairline" style={{margin: "8px 0"}} />
          <div><strong>Maria Lehmann</strong> <span className="muted">· heute 07:45</span></div>
          <div style={{marginTop: 2}}>Verstanden, Messplan hinterlegt. Ergebnisse lade ich Freitag hoch.</div>
        </div>
      </div>
    </div>
  );
};

// ---------- Therapien / Rezepte (kept compact) ----------
const TherapienView = ({ heim }) => {
  const scoped = heim === "alle" ? THERAPIEN : THERAPIEN.filter(t => t.heim === heim);
  return (
    <>
      <div className="content-head"><div><h1>Therapien</h1><div className="sub">Physio · Ergo · Logo</div></div><div className="right"><Btn variant="primary" icon="plus">Einheit planen</Btn></div></div>
      <table className="table" style={{margin: "0 24px", width: "calc(100% - 48px)"}}>
        <thead><tr><th style={{paddingLeft: 0}}>#</th><th>Typ</th><th>Bewohner</th><th>Termin</th><th>Therapeut</th><th>Status</th></tr></thead>
        <tbody>
          {scoped.map(t => {
            const b = BEWOHNER.find(x => x.id === t.bewohner);
            return (
              <tr key={t.id}>
                <td className="mono muted" style={{paddingLeft: 0}}>{t.id}</td>
                <td><span className="badge-pill">{t.typ}</span></td>
                <td data-bewohner={b?.id}>{b?.name}</td>
                <td className="mono">{t.datum} · {t.zeit}</td>
                <td>{t.therapeut}</td>
                <td><StatusBadge status={t.status === "geplant" ? "offen" : "erledigt"} /></td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </>
  );
};

const RezepteView = ({ scoped }) => (
  <>
    <div className="content-head"><div><h1>Rezepte</h1><div className="sub">Laufende & gelieferte Verordnungen an die Apotheke</div></div></div>
    <table className="table" style={{margin: "0 24px", width: "calc(100% - 48px)"}}>
      <thead><tr><th style={{paddingLeft: 0}}>#</th><th>Bewohner</th><th>Medikament</th><th>Apotheke</th><th>Status</th><th>Erstellt</th></tr></thead>
      <tbody>
        {scoped.filter(a => a.status === "freigegeben" || a.status === "geliefert").map(a => {
          const b = BEWOHNER.find(x => x.id === a.bewohner);
          return (
            <tr key={a.id}>
              <td className="mono muted" style={{paddingLeft: 0}}>{a.id}</td>
              <td data-bewohner={b?.id}>{b?.name}</td>
              <td className="mono">{a.med}</td>
              <td>Adler-Apotheke</td>
              <td><StatusBadge status={a.status} /></td>
              <td className="muted" style={{fontSize: 11}}>{a.erstellt}</td>
            </tr>
          );
        })}
      </tbody>
    </table>
  </>
);

// ---------- Reports (new, rich) ----------
const ReportsView = ({ scoped, heim }) => {
  const weeklyMax = Math.max(...REPORT_WEEKLY.map(w => w.anfragen));
  return (
    <>
      <div className="content-head">
        <div><h1>Reports</h1><div className="sub">Auswertung · {heim.name} · Q2 2026</div></div>
        <div className="right">
          <div className="seg"><button className="active">Woche</button><button>Monat</button><button>Quartal</button></div>
          <Btn icon="printer">PDF exportieren</Btn>
        </div>
      </div>
      <div className="kpi-grid">
        <Kpi label="Anfragen gesamt · KW 16" value="49" icon="inbox" trend="vs. KW 15: +3" points={[42,38,46,52,49,55]} />
        <Kpi label="Freigabequote" value="96%" icon="check" trend="2 abgelehnt" points={[92,94,95,95,96,96]} />
        <Kpi label="Ø Zeit bis Freigabe" value="94 Min" icon="clock" trend="↓ 24 Min vs. KW 15" points={[148,134,128,112,118,94]} />
        <Kpi label="Aktive Bewohner" value={heim.residents} icon="users" trend={`${heim.occupancy}% Belegung`} points={[82,83,83,84,84,84]} />
      </div>
      <div style={{padding: "16px 24px", display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 16, flex: 1, minHeight: 0}}>
        <div className="card">
          <div className="card-head">Wöchentliche Anfragen · letzte 6 Wochen</div>
          <div className="card-body">
            <div style={{display: "flex", alignItems: "flex-end", gap: 12, height: 180, padding: "0 4px"}}>
              {REPORT_WEEKLY.map(w => (
                <div key={w.week} style={{flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 6}}>
                  <div style={{width: "100%", height: `${(w.anfragen/weeklyMax)*150}px`, display: "flex", flexDirection: "column", justifyContent: "flex-end", gap: 1}}>
                    <div style={{width: "100%", height: `${(w.abgelehnt/w.anfragen)*100}%`, background: "var(--danger-tint)", borderTop: "1px solid var(--danger-border)"}} />
                    <div style={{width: "100%", height: `${(w.freigegeben/w.anfragen)*100}%`, background: "var(--accent-tint)", borderTop: "1px solid var(--accent-border)"}} />
                  </div>
                  <div className="mono" style={{fontSize: 13, fontWeight: 500}}>{w.anfragen}</div>
                  <div style={{fontSize: 10, color: "var(--fg-subtle)", fontFamily: "var(--font-mono)"}}>{w.week}</div>
                </div>
              ))}
            </div>
            <div className="row" style={{gap: 16, marginTop: 10, fontSize: 11, color: "var(--fg-muted)"}}>
              <span className="row" style={{gap: 4}}><span style={{width: 10, height: 8, background: "var(--accent-tint)", border: "1px solid var(--accent-border)"}} /> Freigegeben</span>
              <span className="row" style={{gap: 4}}><span style={{width: 10, height: 8, background: "var(--danger-tint)", border: "1px solid var(--danger-border)"}} /> Abgelehnt</span>
            </div>
          </div>
        </div>
        <div className="card">
          <div className="card-head">Top Medikamente · 90 Tage</div>
          <div className="card-body col" style={{gap: 8}}>
            {TOP_MEDS.map(m => (
              <div key={m.med}>
                <div className="row" style={{justifyContent: "space-between", fontSize: 12}}>
                  <span className="mono">{m.med}</span>
                  <span className="muted num">{m.n}×</span>
                </div>
                <div style={{height: 5, background: "var(--bg-sunken)", borderRadius: 3, overflow: "hidden", marginTop: 3}}>
                  <div style={{width: `${(m.n/TOP_MEDS[0].n)*100}%`, height: "100%", background: "var(--accent)"}} />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
      <div style={{padding: "0 24px 24px", display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 16}}>
        <div className="card">
          <div className="card-head">Zeit bis Freigabe · nach Arzt</div>
          <div className="card-body col" style={{gap: 8, fontSize: 12}}>
            {DOCTORS.map(d => {
              const avg = d.id === "schn" ? 86 : d.id === "wag" ? 122 : 98;
              return (
                <div key={d.id}>
                  <div className="row" style={{justifyContent: "space-between"}}><span>{d.name}</span><span className="mono muted">{avg} Min</span></div>
                  <div style={{height: 5, background: "var(--bg-sunken)", borderRadius: 3, overflow: "hidden", marginTop: 3}}>
                    <div style={{width: `${(avg/150)*100}%`, height: "100%", background: avg < 100 ? "var(--success)" : "var(--warning)"}} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
        <div className="card">
          <div className="card-head">Anfragen nach Typ</div>
          <div className="card-body col" style={{gap: 8, fontSize: 12}}>
            <TypSlice label="Verlängerung" n={58} total={95} tone="var(--accent)" />
            <TypSlice label="Neu"           n={24} total={95} tone="var(--info)" />
            <TypSlice label="Anpassung"     n={13} total={95} tone="var(--warning)" />
          </div>
        </div>
        <div className="card">
          <div className="card-head">Apotheke · Lieferzeit</div>
          <div className="card-body col" style={{gap: 8, fontSize: 12}}>
            <div className="row" style={{justifyContent: "space-between"}}><span>Adler-Apotheke</span><span className="mono muted">Ø 2:08 h</span></div>
            <div className="row" style={{justifyContent: "space-between"}}><span>Sonnen-Apotheke</span><span className="mono muted">Ø 4:12 h</span></div>
            <div className="row" style={{justifyContent: "space-between"}}><span>Bahnhof-Apotheke</span><span className="mono muted">Ø 18:30 h</span></div>
            <div className="hairline" style={{margin: "4px 0"}} />
            <div className="muted">Ziel: ≤ 4h für freigegebene Nicht-BtM-Rezepte.</div>
          </div>
        </div>
      </div>
    </>
  );
};

const TypSlice = ({ label, n, total, tone }) => (
  <div>
    <div className="row" style={{justifyContent: "space-between"}}><span>{label}</span><span className="mono muted">{n} ({Math.round(n/total*100)}%)</span></div>
    <div style={{height: 5, background: "var(--bg-sunken)", borderRadius: 3, overflow: "hidden", marginTop: 3}}>
      <div style={{width: `${(n/total)*100}%`, height: "100%", background: tone}} />
    </div>
  </div>
);

// ---------- Audit-Log ----------
const AuditView = () => (
  <>
    <div className="content-head">
      <div><h1>Audit-Log</h1><div className="sub">Lückenlos protokolliert · DSGVO Art. 30 · manipulationssicher</div></div>
      <div className="right"><Btn icon="filter">Filter</Btn><Btn icon="printer">Export (CSV)</Btn></div>
    </div>
    <Toolbar>
      <div className="search-inp"><Icon name="search" size={12} /><input placeholder="Nutzer, Aktion, Ziel…" /></div>
      <span className="chip"><Icon name="plus" size={10} /> Heute</span>
      <span className="chip"><Icon name="plus" size={10} /> Rolle</span>
      <span className="chip"><Icon name="plus" size={10} /> Aktion</span>
      <div className="spacer" />
      <span className="muted" style={{fontSize: 12}}>{AUDIT.length} Einträge · letzte 24h</span>
    </Toolbar>
    <table className="table" style={{margin: "0 24px", width: "calc(100% - 48px)"}}>
      <thead>
        <tr>
          <th style={{paddingLeft: 0, width: 170}}>Zeit</th>
          <th style={{width: 160}}>Nutzer</th>
          <th style={{width: 140}}>Aktion</th>
          <th>Ziel</th>
          <th style={{width: 80}}>Heim</th>
          <th style={{width: 120, textAlign: "right"}}>IP</th>
        </tr>
      </thead>
      <tbody>
        {AUDIT.map((e, i) => (
          <tr key={i}>
            <td className="mono muted" style={{paddingLeft: 0, fontSize: 11}}>{e.ts}</td>
            <td><div className="row" style={{gap: 6}}><Avatar name={e.who} size={18} /><span>{e.who}</span></div></td>
            <td><span className={`badge-pill ${e.action === "abgelehnt" ? "abgelehnt" : e.action === "freigegeben" ? "freigegeben" : e.action === "geliefert" ? "geliefert" : ""}`}>{e.action}</span></td>
            <td className="muted">{e.target}</td>
            <td><span className="mono">{HEIMS.find(h => h.id === e.heim)?.mark || "—"}</span></td>
            <td className="mono muted" style={{textAlign: "right", fontSize: 11}}>{e.ip}</td>
          </tr>
        ))}
      </tbody>
    </table>
  </>
);

const BenutzerView = () => (
  <>
    <div className="content-head">
      <div><h1>Benutzer & Rollen</h1><div className="sub">Pflege · Pflegeleitung · Administrator</div></div>
      <div className="right"><Btn variant="primary" icon="plus">Benutzer einladen</Btn></div>
    </div>
    <table className="table" style={{margin: "0 24px", width: "calc(100% - 48px)"}}>
      <thead><tr><th style={{paddingLeft: 0}}>Name</th><th>Rolle</th><th>Heim</th><th>2FA</th><th>Letzter Login</th><th>Status</th></tr></thead>
      <tbody>
        {[
          ["Maria Lehmann","Pflegeleitung","Rosenhof","TOTP","heute · 07:55","aktiv"],
          ["Jonas Richter","Pflege","Rosenhof","TOTP","heute · 08:12","aktiv"],
          ["Peter Groß","Pflege","Linde","TOTP","heute · 06:40","aktiv"],
          ["Birgit Kleine","Pflege","Marienblick","TOTP","heute · 09:01","aktiv"],
          ["Sabine Voß","Pflegeleitung","Sonnenwiese","TOTP","gestern · 19:30","aktiv"],
          ["Hans Mayer","Administrator","—","Hardware-Token","vor 3 Tagen","inaktiv"],
        ].map(([n,r,h,t,l,s]) => (
          <tr key={n}>
            <td style={{paddingLeft: 0}}><div className="row" style={{gap: 8}}><Avatar name={n} size={22} />{n}</div></td>
            <td>{r}</td>
            <td className="muted">{h}</td>
            <td className="mono">{t}</td>
            <td className="muted" style={{fontSize: 11}}>{l}</td>
            <td><StatusBadge status={s === "aktiv" ? "freigegeben" : "abgelehnt"} /></td>
          </tr>
        ))}
      </tbody>
    </table>
  </>
);

const Toggle = ({ on, onChange, label }) => (
  <button
    type="button"
    onClick={() => { onChange(!on); window.dispatchEvent(new CustomEvent("medlink:toast", { detail: `${label}: ${!on ? "aktiviert" : "deaktiviert"}` })); }}
    aria-pressed={on}
    style={{
      width: 34, height: 20, borderRadius: 999, padding: 2,
      background: on ? "var(--accent)" : "var(--border-strong)",
      border: "none", cursor: "pointer", position: "relative", transition: "background 160ms",
    }}
  >
    <span style={{
      display: "block", width: 16, height: 16, borderRadius: "50%",
      background: "#fff", transform: on ? "translateX(14px)" : "translateX(0)",
      transition: "transform 160ms", boxShadow: "0 1px 3px rgba(0,0,0,0.2)",
    }} />
  </button>
);

const SettingsView = () => {
  const [notifPush, setNotifPush] = React.useState(true);
  const [notifEmail, setNotifEmail] = React.useState(true);
  const [notifSms, setNotifSms] = React.useState(false);
  const [force2fa, setForce2fa] = React.useState(true);
  const [sessionMin, setSessionMin] = React.useState(30);
  const [pharmacies, setPharmacies] = React.useState(() => PHARMACIES.map(p => ({ ...p })));
  const togglePharmacy = (id) => setPharmacies(xs => xs.map(p => {
    if (p.id !== id) return p;
    const next = { ...p, open: !p.open };
    window.dispatchEvent(new CustomEvent("medlink:toast", { detail: `${p.name}: ${next.open ? "verbunden" : "getrennt"}` }));
    return next;
  }));
  return (
    <>
      <div className="content-head">
        <div><h1>Einstellungen</h1><div className="sub">Mandant · Apotheken · Sicherheit · Benachrichtigungen</div></div>
        <div className="right">
          <Btn icon="printer">Audit-Bericht</Btn>
          <Btn variant="primary" icon="check" onClick={() => window.dispatchEvent(new CustomEvent("medlink:toast", { detail: "Einstellungen gespeichert · an alle Rollen propagiert" }))}>Speichern</Btn>
        </div>
      </div>
      <div style={{padding: 24, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16}}>
        <div className="card">
          <div className="card-head">Mandant</div>
          <div className="card-body col" style={{gap: 10, fontSize: 12}}>
            <dl className="kv">
              <dt>Name</dt><dd>Haus Rosenhof gGmbH</dd>
              <dt>Träger</dt><dd>Diakonie Bayern · KdöR</dd>
              <dt>HRB</dt><dd className="mono">HRB 184 293 · AG München</dd>
              <dt>Hosting</dt><dd>Hetzner · Rechenzentrum Nürnberg (DE)</dd>
              <dt>Backup</dt><dd>täglich · 30 Tage Aufbewahrung · verschlüsselt</dd>
              <dt>AVV</dt><dd><span className="badge-pill freigegeben"><Icon name="check" size={10} /> unterzeichnet · 12.01.2026</span></dd>
              <dt>Aufsicht</dt><dd>Regierung von Oberbayern (Heim-Aufsicht)</dd>
            </dl>
          </div>
        </div>
        <div className="card">
          <div className="card-head">Sicherheit</div>
          <div className="card-body col" style={{gap: 10, fontSize: 12}}>
            <div className="row" style={{justifyContent: "space-between"}}>
              <span>2FA für alle Rollen erzwingen</span>
              <Toggle on={force2fa} onChange={setForce2fa} label="2FA-Pflicht" />
            </div>
            <div className="row" style={{justifyContent: "space-between"}}>
              <span>Session-Timeout</span>
              <div className="seg">
                {[15, 30, 60].map(m => (
                  <button key={m} className={sessionMin === m ? "active" : ""} onClick={() => { setSessionMin(m); window.dispatchEvent(new CustomEvent("medlink:toast", { detail: `Session-Timeout: ${m} Min` })); }}>{m} Min</button>
                ))}
              </div>
            </div>
            <div className="row" style={{justifyContent: "space-between"}}><span>TLS-Version</span><span className="mono">1.3 · HSTS preload</span></div>
            <div className="row" style={{justifyContent: "space-between"}}><span>Verschlüsselung at rest</span><span className="mono">AES-256-GCM</span></div>
            <div className="row" style={{justifyContent: "space-between"}}><span>Letzter Pentest</span><span>02.2026 · 0 Critical · 2 Low</span></div>
            <div className="row" style={{justifyContent: "space-between"}}><span>BSI-Grundschutz</span><span className="badge-pill freigegeben"><Icon name="check" size={10} /> testiert</span></div>
          </div>
        </div>
        <div className="card">
          <div className="card-head">
            Verbundene Apotheken
            <div className="right"><Btn icon="plus" onClick={() => window.dispatchEvent(new CustomEvent("medlink:toast", { detail: "Apotheken-Einladung generiert · KIM-Link kopiert" }))}>Apotheke anbinden</Btn></div>
          </div>
          <div className="card-body col" style={{gap: 8, fontSize: 12}}>
            {pharmacies.map(p => (
              <div key={p.id} className="row" style={{justifyContent: "space-between"}}>
                <span>{p.name} <span className="muted">· {p.city}</span></span>
                <div className="row" style={{gap: 8}}>
                  <span className={`badge-pill ${p.open ? "freigegeben" : "abgelehnt"}`}><Icon name={p.open ? "check" : "x"} size={10} /> {p.open ? "verbunden" : "offline"}</span>
                  <Toggle on={p.open} onChange={() => togglePharmacy(p.id)} label={p.name} />
                </div>
              </div>
            ))}
          </div>
        </div>
        <div className="card">
          <div className="card-head">Benachrichtigungen</div>
          <div className="card-body col" style={{gap: 10, fontSize: 12}}>
            <div className="row" style={{justifyContent: "space-between"}}>
              <span>Push · neue Anfrage freigegeben</span>
              <Toggle on={notifPush} onChange={setNotifPush} label="Push-Benachrichtigungen" />
            </div>
            <div className="row" style={{justifyContent: "space-between"}}>
              <span>E-Mail · tägliche Zusammenfassung</span>
              <Toggle on={notifEmail} onChange={setNotifEmail} label="E-Mail-Zusammenfassung" />
            </div>
            <div className="row" style={{justifyContent: "space-between"}}>
              <span>SMS · kritische Ablehnungen</span>
              <Toggle on={notifSms} onChange={setNotifSms} label="SMS-Benachrichtigungen" />
            </div>
            <div className="row" style={{justifyContent: "space-between"}}>
              <span>Ruhezeiten (kein Push)</span>
              <span className="mono">22:00 – 06:00</span>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

window.HeimPortal = HeimPortal;
