// Therapeuten-Portal — multi-view: Termine · Dokumentation · Empfehlungen
const TherapeutPortal = ({ ctx }) => {
  if (window.useStoreVersion) window.useStoreVersion();
  const [view, setView] = React.useState("termine");
  const [cmdOpen, setCmdOpen] = React.useState(false);
  const [selected, setSelected] = React.useState("T-504");
  const [dokuOpen, setDokuOpen] = React.useState(null);
  const [empfOpen, setEmpfOpen] = React.useState(false);

  React.useEffect(() => {
    const h = (e) => { if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { e.preventDefault(); setCmdOpen(true); } };
    window.addEventListener("keydown", h);
    return () => window.removeEventListener("keydown", h);
  }, []);

  const current = THERAPIEN.find(t => t.id === selected) || THERAPIEN[0];
  const bew = BEWOHNER.find(b => b.id === current?.bewohner);

  const plansCount = React.useMemo(() => {
    try { return Object.keys(JSON.parse(localStorage.getItem("medlink.therapy.plans") || "{}")).length; }
    catch { return 0; }
  }, [view]);

  const sections = [
    { label: "", items: [
      { id: "termine",       label: "Meine Termine",  icon: "calendar",  badge: THERAPIEN.filter(t => t.status === "geplant").length },
      { id: "doku",          label: "Dokumentation",  icon: "clipboard", badge: THERAPIEN.filter(t => t.status === "abgeschlossen").length },
      { id: "plaene",        label: "Therapiepläne",  icon: "activity",  badge: plansCount || null },
      { id: "empfehlungen",  label: "Empfehlungen",   icon: "stars",     badge: 3 },
    ]},
  ];

  const [planOpen, setPlanOpen] = React.useState(null); // Bewohner-ID oder null
  const crumbLabel = { termine: "Meine Termine", doku: "Dokumentation", plaene: "Therapiepläne", empfehlungen: "Empfehlungen" }[view];

  return (
    <>
      <Topbar
        portal="Therapeut"
        portalIcon="activity"
        onBrand={ctx.onBrandClick}
        onToggleSidebar={ctx.onPortalSwitch}
        crumbs={["Lena Vogt", crumbLabel]}
        heim={ctx.heim}
        onSearchClick={() => setCmdOpen(true)}
        userName="Lena Vogt"
        userRole="Physiotherapeutin"
        userEmail="vogt@physio-mobil.de"
        onLogout={ctx.onLogout}
        onAdmin={ctx.onAdmin}
      />
      <Sidebar
        scopeMark="T"
        scopeTitle="Therapie-Team Süd"
        scopeSub="Physio · Ergo · Logo"
        sections={sections}
        active={view}
        onNav={setView}
        compliance="DSGVO · Extra-Schutz aktiv"
      />
      <main className="content">
        {view === "termine" && (
          <TherTermine
            current={current} bew={bew} selected={selected} onSelect={setSelected}
            onDoku={(t) => { setSelected(t.id); setDokuOpen(t); }}
            onEmpfehlen={() => setEmpfOpen(true)}
            onNew={() => ctx.toast("Termin-Editor geöffnet")}
            onPrint={() => ctx.toast("Wochenplan als PDF generiert")}
          />
        )}
        {view === "doku"          && <TherDoku onOpenDoku={(t) => { setSelected(t.id); setDokuOpen(t); }} onJump={() => setView("termine")} actions={ctx} />}
        {view === "plaene"        && <TherPlaene onOpen={(bid) => setPlanOpen(bid || "__new")} actions={ctx} />}
        {view === "empfehlungen"  && <TherEmpfehlungen onNew={() => setEmpfOpen(true)} actions={ctx} />}
      </main>

      {planOpen && (
        <TherapiePlanEditor
          bewohnerId={planOpen === "__new" ? null : planOpen}
          onClose={() => setPlanOpen(null)}
          onSaved={(bid) => { setPlanOpen(null); ctx.toast(`Therapieplan für ${BEWOHNER.find(b => b.id === bid)?.name.split(",")[0]} gespeichert`); }}
        />
      )}

      {dokuOpen && (
        <DokuSheet
          einheit={dokuOpen}
          onClose={() => setDokuOpen(null)}
          onSave={() => { setDokuOpen(null); ctx.toast(`Einheit ${dokuOpen.id} dokumentiert · Pflege benachrichtigt`); }}
        />
      )}
      {empfOpen && (
        <EmpfehlungSheet
          defaultBewohner={bew}
          onClose={() => setEmpfOpen(false)}
          onSave={() => { setEmpfOpen(false); ctx.toast("Empfehlung an Pflege + Hausarzt gesendet"); }}
        />
      )}

      <CmdK open={cmdOpen} onClose={() => setCmdOpen(false)} onRun={(id) => {
        if (id.startsWith("portal:")) ctx.setPortal(id.slice(7));
        if (id.startsWith("nav:")) setView(id.slice(4));
      }} />
    </>
  );
};

// --- View: Termine (master/detail) ---
const TherTermine = ({ current, bew, selected, onSelect, onDoku, onEmpfehlen, onNew, onPrint }) => (
  <>
    <div className="content-head">
      <div><h1>Meine Termine</h1><div className="sub">Zugewiesene Einheiten · diese & nächste Woche</div></div>
      <div className="right">
        <Btn icon="printer" onClick={onPrint}>Wochen-Ausdruck</Btn>
        <Btn variant="primary" icon="plus" onClick={onNew}>Termin anlegen</Btn>
      </div>
    </div>
    <div className="split">
      <div className="master">
        <table className="table">
          <thead><tr><th style={{paddingLeft: 16}}>#</th><th>Typ</th><th>Bewohner</th><th>Heim</th><th>Termin</th><th>Status</th></tr></thead>
          <tbody>
            {THERAPIEN.map(t => {
              const b = BEWOHNER.find(x => x.id === t.bewohner);
              const h = HEIMS.find(h => h.id === t.heim);
              return (
                <tr key={t.id} className={current?.id === t.id ? "selected" : ""} onClick={() => onSelect(t.id)}>
                  <td className="mono muted" style={{paddingLeft: 16}}>{t.id}</td>
                  <td><span className="badge-pill"><Icon name={t.typ === "Physio" ? "activity" : t.typ === "Ergo" ? "heart" : "mail"} size={11} />{t.typ}</span></td>
                  <td>{b?.name}</td>
                  <td className="muted">{h?.name.replace("Haus ", "").replace("Seniorenzentrum ", "").replace("Pflegeheim ", "")}</td>
                  <td className="mono">{t.datum} · {t.zeit}</td>
                  <td><StatusBadge status={t.status === "geplant" ? "offen" : "erledigt"} /></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
      {current && bew && (
        <div className="detail">
          <div className="detail-head">
            <div className="eyebrow row" style={{justifyContent: "space-between"}}>
              <span className="mono">{current.id} · {current.typ}</span>
              <StatusBadge status={current.status === "geplant" ? "offen" : "erledigt"} />
            </div>
            <h2>{bew.name}</h2>
            <div className="muted" style={{fontSize: 12}}>{bew.zimmer} · {HEIMS.find(h => h.id === current.heim)?.name}</div>
            <div className="meta">
              <span><Icon name="calendar" size={11} /> {current.datum} · {current.zeit}</span>
              <span><Icon name="user" size={11} /> {current.therapeut}</span>
            </div>
            <div style={{marginTop: 14, display: "flex", gap: 6, flexWrap: "wrap"}}>
              <Btn variant="primary" icon="check" onClick={() => onDoku(current)}>Behandlung dokumentieren</Btn>
              <Btn icon="activity" onClick={onEmpfehlen}>Empfehlung an Pflege</Btn>
            </div>
          </div>
          <div className="detail-section">
            <h3>Kurzdokumentation (letzte Einheit)</h3>
            <div style={{padding: 10, background: "var(--bg-raised)", border: "1px solid var(--border)", borderRadius: "var(--r-md)", fontSize: 12, lineHeight: 1.55}}>
              Mobilisation am Rollator · 2×15 Min · Schmerzangabe NRS 3/10 vor, 2/10 nach Einheit. Tagesform besser als Vorwoche. Empfehlung: Fortsetzung 3×/Woche.
              <div style={{fontSize: 11, color: "var(--fg-subtle)", marginTop: 6}}>— L. Vogt · 15.04.2026 · 14:30</div>
            </div>
          </div>
          <div className="detail-section">
            <h3>Diagnosen</h3>
            <div>{bew.diagnosen.map(d => <span key={d} className="badge-pill" style={{marginRight: 4, marginBottom: 4}}>{d}</span>)}</div>
          </div>
          <div className="detail-section">
            <h3>Verordnung</h3>
            <dl className="kv">
              <dt>Typ</dt><dd>{current.typ}</dd>
              <dt>Frequenz</dt><dd>3×/Woche</dd>
              <dt>Gesamtumfang</dt><dd>20 Einheiten · 14 verbleibend</dd>
              <dt>Verordnet von</dt><dd>Dr. Bauer (Geriater)</dd>
            </dl>
          </div>
        </div>
      )}
    </div>
  </>
);

// --- View: Dokumentation (history of past sessions) ---
const TherDoku = ({ onOpenDoku, onJump, actions }) => {
  const done = THERAPIEN.filter(t => t.status === "abgeschlossen");
  const planned = THERAPIEN.filter(t => t.status === "geplant");
  return (
    <>
      <div className="content-head">
        <div><h1>Dokumentation</h1><div className="sub">Vergangene Einheiten · {done.length} dokumentiert · {planned.length} ausstehend</div></div>
        <div className="right">
          <Btn icon="download" onClick={() => actions.toast("Doku-Export als CSV gestartet")}>Export</Btn>
          <Btn icon="printer" onClick={() => actions.toast("PDF-Zusammenfassung generiert")}>PDF</Btn>
          <Btn variant="primary" icon="plus" onClick={onJump}>Neue Einheit</Btn>
        </div>
      </div>
      <div className="kpi-grid" style={{gridTemplateColumns: "repeat(4, 1fr)"}}>
        <Kpi label="Einheiten (diese Woche)" value="14" icon="activity" trend="+2 zur Vorwoche" points={[6,8,7,9,11,10,12,14]} />
        <Kpi label="Dokumentationsquote" value="96%" icon="check" trend="Ziel: 100%" points={[88,90,92,94,95,96,96,96]} />
        <Kpi label="Ø Einheit-Dauer" value="22 Min" icon="clock" trend="Physio · Ergo · Logo" points={[20,22,21,23,22,22,21,22]} />
        <Kpi label="Rückmeldung an Arzt" value="3" icon="mail" trend="offen zu beantworten" points={[1,2,1,3,2,3,3,3]} />
      </div>
      <div style={{padding: "16px 24px"}}>
        <h3 style={{margin: "0 0 10px", fontSize: 12, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--fg-subtle)"}}>Dokumentiert</h3>
        <table className="table">
          <thead><tr><th style={{paddingLeft: 0}}>#</th><th>Bewohner</th><th>Typ</th><th>Termin</th><th>NRS vorher → nachher</th><th>Aktion</th></tr></thead>
          <tbody>
            {done.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>{b?.name}</td>
                  <td><span className="badge-pill">{t.typ}</span></td>
                  <td className="mono">{t.datum} · {t.zeit}</td>
                  <td className="mono">{Math.floor(Math.random() * 3) + 3} → {Math.floor(Math.random() * 3) + 1}</td>
                  <td>
                    <div style={{display: "flex", gap: 4}}>
                      <Btn icon="eye" onClick={() => onOpenDoku(t)}>Öffnen</Btn>
                      <Btn icon="printer" onClick={() => actions.toast(`Dokumentation ${t.id} gedruckt`)}>PDF</Btn>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
        <h3 style={{margin: "18px 0 10px", fontSize: 12, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--fg-subtle)"}}>Noch zu dokumentieren</h3>
        <table className="table">
          <thead><tr><th style={{paddingLeft: 0}}>#</th><th>Bewohner</th><th>Typ</th><th>Termin</th><th>Aktion</th></tr></thead>
          <tbody>
            {planned.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>{b?.name}</td>
                  <td><span className="badge-pill">{t.typ}</span></td>
                  <td className="mono">{t.datum} · {t.zeit}</td>
                  <td><Btn variant="primary" icon="check" onClick={() => onOpenDoku(t)}>Dokumentieren</Btn></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </>
  );
};

// --- View: Empfehlungen (recommendations to doctors/nursing) ---
const TherEmpfehlungen = ({ onNew, actions }) => {
  const recs = [
    { id: "E-042", datum: "18.04.2026", bewohner: "Müller, Heinrich", an: "Dr. Schneider", titel: "Rollator-Mobilisation 3×/Woche fortsetzen", status: "beantwortet", antwort: "Einverstanden. Fortsetzung für weitere 4 Wochen genehmigt." },
    { id: "E-041", datum: "17.04.2026", bewohner: "Becker, Wilhelm",  an: "Dr. Schneider", titel: "Schmerzspitzen NRS >6 — Tramadol-Bedarfsmedikation prüfen", status: "beantwortet", antwort: "Tramadol 50 mg b.B. freigegeben (A-2802)." },
    { id: "E-040", datum: "16.04.2026", bewohner: "Krüger, Friedrich",an: "Pflege Linde",  titel: "Fallrisiko erhöht — Nachtkontrollen intensivieren", status: "offen" },
    { id: "E-039", datum: "15.04.2026", bewohner: "Weber, Klaus-Dieter", an: "Dr. Bauer",  titel: "Ergotherapie-Frequenz auf 2×/Woche reduzieren", status: "offen" },
    { id: "E-038", datum: "12.04.2026", bewohner: "Fischer, Anna",    an: "Pflege Marienblick", titel: "Balance-Training im Alltag integrieren", status: "beantwortet", antwort: "Umgesetzt im Wochenplan. Fr. Fischer macht gut mit." },
  ];
  return (
    <>
      <div className="content-head">
        <div><h1>Empfehlungen</h1><div className="sub">An Ärzte & Pflegeteams · Rückmeldungen & offene Anliegen</div></div>
        <div className="right">
          <Btn icon="download" onClick={() => actions.toast("Export: empfehlungen-2026-04.csv")}>Export</Btn>
          <Btn variant="primary" icon="plus" onClick={onNew}>Neue Empfehlung</Btn>
        </div>
      </div>
      <div style={{padding: "16px 24px", display: "flex", flexDirection: "column", gap: 10}}>
        {recs.map(r => (
          <div key={r.id} className="card">
            <div className="card-head row" style={{justifyContent: "space-between"}}>
              <div className="row" style={{gap: 8}}>
                <span className="mono muted" style={{fontSize: 11}}>{r.id}</span>
                <span style={{fontWeight: 600}}>{r.titel}</span>
              </div>
              <StatusBadge status={r.status === "beantwortet" ? "freigegeben" : "offen"} />
            </div>
            <div className="card-body col" style={{gap: 8, fontSize: 12}}>
              <div className="row" style={{gap: 14, color: "var(--fg-muted)"}}>
                <span><Icon name="user" size={11} /> {r.bewohner}</span>
                <span><Icon name="mail" size={11} /> an {r.an}</span>
                <span><Icon name="calendar" size={11} /> {r.datum}</span>
              </div>
              {r.antwort && (
                <div style={{padding: 10, background: "var(--accent-tint)", border: "1px solid var(--accent-border)", borderRadius: "var(--r-md)", fontSize: 12, lineHeight: 1.55}}>
                  <div style={{fontSize: 10, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--accent)", marginBottom: 4}}>Antwort</div>
                  „{r.antwort}"
                </div>
              )}
              <div style={{display: "flex", gap: 4, marginTop: 4}}>
                <Btn icon="eye" onClick={() => actions.toast(`Empfehlung ${r.id} geöffnet`)}>Detail</Btn>
                {r.status === "offen" ? <Btn icon="mail" onClick={() => actions.toast("Erinnerung gesendet")}>Erinnern</Btn> : <Btn icon="check" onClick={() => actions.toast("Als gelesen markiert")}>Gelesen</Btn>}
                <Btn icon="copy" onClick={() => actions.toast("In Zwischenablage kopiert")}>Kopieren</Btn>
              </div>
            </div>
          </div>
        ))}
      </div>
    </>
  );
};

// --- Documentation sheet ---
const DokuSheet = ({ einheit, onClose, onSave }) => {
  const b = BEWOHNER.find(x => x.id === einheit.bewohner);
  const [nrsVor, setNrsVor] = React.useState(5);
  const [nrsNach, setNrsNach] = React.useState(3);
  const [note, setNote] = React.useState("");
  return (
    <div className="na-backdrop" onClick={onClose}>
      <div className="modal" style={{width: 560, maxWidth: "96vw", background: "var(--bg-raised)", border: "1px solid var(--border)", borderRadius: "var(--r-lg)", boxShadow: "0 24px 60px oklch(0% 0 0 / 0.25)"}} onClick={(e) => e.stopPropagation()}>
        <div style={{padding: "16px 20px", borderBottom: "1px solid var(--border)"}}>
          <div style={{fontSize: 11, color: "var(--fg-subtle)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 4}}>Behandlung dokumentieren · {einheit.id}</div>
          <h3 style={{margin: 0, fontSize: 16}}>{b?.name} <span className="muted" style={{fontWeight: 400}}>· {einheit.typ} · {einheit.datum} {einheit.zeit}</span></h3>
        </div>
        <div style={{padding: 18, display: "flex", flexDirection: "column", gap: 12}}>
          <div>
            <label style={{fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--fg-subtle)"}}>Schmerz-NRS (0–10)</label>
            <div className="row" style={{gap: 14, marginTop: 6}}>
              <div style={{flex: 1}}>
                <div style={{fontSize: 11, color: "var(--fg-muted)", marginBottom: 4}}>Vor Einheit: <span className="mono" style={{fontWeight: 600}}>{nrsVor}</span></div>
                <input type="range" min="0" max="10" value={nrsVor} onChange={(e) => setNrsVor(+e.target.value)} style={{width: "100%"}} />
              </div>
              <div style={{flex: 1}}>
                <div style={{fontSize: 11, color: "var(--fg-muted)", marginBottom: 4}}>Nach Einheit: <span className="mono" style={{fontWeight: 600}}>{nrsNach}</span></div>
                <input type="range" min="0" max="10" value={nrsNach} onChange={(e) => setNrsNach(+e.target.value)} style={{width: "100%"}} />
              </div>
            </div>
          </div>
          <div>
            <label style={{fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--fg-subtle)"}}>Notiz</label>
            <textarea value={note} onChange={(e) => setNote(e.target.value)} placeholder="Übungen, Auffälligkeiten, Empfehlung …" rows={5} style={{width: "100%", marginTop: 4, padding: 10, background: "var(--bg)", border: "1px solid var(--border)", borderRadius: "var(--r-md)", fontSize: 12, lineHeight: 1.55, resize: "vertical"}} />
          </div>
          <div className="row" style={{gap: 6, flexWrap: "wrap"}}>
            {["Mobilisation Rollator", "Balance", "Gelenkmobilisation", "Atemtherapie", "Kognitives Training"].map(tag => (
              <span key={tag} className="badge-pill" style={{cursor: "pointer"}} onClick={() => setNote(n => (n ? n + " · " : "") + tag)}>+ {tag}</span>
            ))}
          </div>
        </div>
        <div style={{padding: "12px 20px", borderTop: "1px solid var(--border)", display: "flex", justifyContent: "space-between", alignItems: "center", background: "var(--bg-sunken)"}}>
          <div style={{fontSize: 11, color: "var(--fg-subtle)"}}><Icon name="shield" size={11} /> Signatur: L. Vogt · wird im Audit-Log erfasst</div>
          <div style={{display: "flex", gap: 6}}>
            <Btn onClick={onClose}>Abbrechen</Btn>
            <Btn variant="primary" icon="check" onClick={onSave}>Speichern & an Pflege</Btn>
          </div>
        </div>
      </div>
    </div>
  );
};

// --- Empfehlung sheet ---
const EmpfehlungSheet = ({ defaultBewohner, onClose, onSave }) => {
  const [bewohner, setBewohner] = React.useState(defaultBewohner?.id || BEWOHNER[0].id);
  const [an, setAn] = React.useState("hausarzt");
  const [titel, setTitel] = React.useState("");
  const [text, setText] = React.useState("");
  return (
    <div className="na-backdrop" onClick={onClose}>
      <div className="modal" style={{width: 560, maxWidth: "96vw", background: "var(--bg-raised)", border: "1px solid var(--border)", borderRadius: "var(--r-lg)", boxShadow: "0 24px 60px oklch(0% 0 0 / 0.25)"}} onClick={(e) => e.stopPropagation()}>
        <div style={{padding: "16px 20px", borderBottom: "1px solid var(--border)"}}>
          <h3 style={{margin: 0, fontSize: 16}}>Neue Empfehlung</h3>
          <div style={{fontSize: 12, color: "var(--fg-subtle)", marginTop: 2}}>An Hausarzt oder Pflegeteam · wird im Audit-Log erfasst</div>
        </div>
        <div style={{padding: 18, display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12}}>
          <div style={{gridColumn: "1 / -1"}}>
            <label style={{fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--fg-subtle)"}}>Bewohner</label>
            <select className="select" value={bewohner} onChange={(e) => setBewohner(e.target.value)} style={{width: "100%", marginTop: 4}}>
              {BEWOHNER.map(b => <option key={b.id} value={b.id}>{b.name} · {b.zimmer}</option>)}
            </select>
          </div>
          <div>
            <label style={{fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--fg-subtle)"}}>Empfänger</label>
            <select className="select" value={an} onChange={(e) => setAn(e.target.value)} style={{width: "100%", marginTop: 4}}>
              <option value="hausarzt">Hausarzt</option>
              <option value="pflege">Pflegeteam</option>
              <option value="beide">Beide</option>
            </select>
          </div>
          <div>
            <label style={{fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--fg-subtle)"}}>Priorität</label>
            <select className="select" defaultValue="normal" style={{width: "100%", marginTop: 4}}>
              <option value="normal">Normal</option>
              <option value="hoch">Hoch</option>
            </select>
          </div>
          <div style={{gridColumn: "1 / -1"}}>
            <label style={{fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--fg-subtle)"}}>Titel</label>
            <input value={titel} onChange={(e) => setTitel(e.target.value)} placeholder="z. B. Rollator-Mobilisation fortsetzen" style={{width: "100%", marginTop: 4, padding: "8px 10px", background: "var(--bg)", border: "1px solid var(--border)", borderRadius: "var(--r-md)", fontSize: 13}} />
          </div>
          <div style={{gridColumn: "1 / -1"}}>
            <label style={{fontSize: 11, textTransform: "uppercase", letterSpacing: "0.06em", color: "var(--fg-subtle)"}}>Beschreibung</label>
            <textarea value={text} onChange={(e) => setText(e.target.value)} rows={5} placeholder="Beobachtung, Empfehlung, begründende Werte …" style={{width: "100%", marginTop: 4, padding: 10, background: "var(--bg)", border: "1px solid var(--border)", borderRadius: "var(--r-md)", fontSize: 12, lineHeight: 1.55, resize: "vertical"}} />
          </div>
        </div>
        <div style={{padding: "12px 20px", borderTop: "1px solid var(--border)", display: "flex", justifyContent: "flex-end", gap: 6, background: "var(--bg-sunken)"}}>
          <Btn onClick={onClose}>Abbrechen</Btn>
          <Btn variant="primary" icon="mail" onClick={onSave}>Senden</Btn>
        </div>
      </div>
    </div>
  );
};

// ================================================================
// Therapiepläne · Liste + Editor
// ================================================================
const THERAPY_PLANS_KEY = "medlink.therapy.plans";
const loadPlans = () => {
  try { return JSON.parse(localStorage.getItem(THERAPY_PLANS_KEY) || "{}"); }
  catch { return {}; }
};
const savePlans = (plans) => {
  try { localStorage.setItem(THERAPY_PLANS_KEY, JSON.stringify(plans)); } catch {}
};

const TherPlaene = ({ onOpen, actions }) => {
  const [plans, setPlans] = React.useState(() => loadPlans());
  const refresh = () => setPlans(loadPlans());
  React.useEffect(() => {
    const onFocus = () => refresh();
    window.addEventListener("focus", onFocus);
    return () => window.removeEventListener("focus", onFocus);
  }, []);
  const entries = Object.values(plans).sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));

  return (
    <>
      <div className="content-head">
        <div>
          <h1>Therapiepläne</h1>
          <div className="sub">Individuelle Pläne mit Zielen und wöchentlichem Sessions-Rahmen</div>
        </div>
        <div className="right">
          <Btn variant="primary" icon="plus" onClick={() => onOpen(null)}>Neuer Plan</Btn>
        </div>
      </div>

      {entries.length === 0 && (
        <div style={{ padding: 48, textAlign: "center", color: "var(--fg-subtle)" }}>
          <div style={{ fontSize: 28, fontFamily: "var(--font-serif)", fontWeight: 500, fontStyle: "italic", color: "var(--fg)", letterSpacing: "-0.02em", marginBottom: 8 }}>
            Noch kein Plan erstellt.
          </div>
          <div style={{ fontSize: 13, marginBottom: 22 }}>
            Legen Sie den ersten Therapieplan an: Ziele, Sessions-Rhythmus, Messgrößen.
          </div>
          <Btn variant="primary" icon="plus" onClick={() => onOpen(null)}>Ersten Plan erstellen</Btn>
        </div>
      )}

      {entries.length > 0 && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(320px, 1fr))", gap: 14, marginTop: 12 }}>
          {entries.map((p) => {
            const b = BEWOHNER.find((x) => x.id === p.bewohner);
            if (!b) return null;
            return (
              <div key={p.bewohner} className="plan-card" onClick={() => onOpen(p.bewohner)} role="button">
                <div className="plan-card-head">
                  <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                    <Avatar name={b.name} size={36} />
                    <div>
                      <div style={{ fontSize: 14, fontWeight: 600, letterSpacing: "-0.01em" }}>{b.name}</div>
                      <div style={{ fontSize: 11.5, color: "var(--fg-subtle)" }}>{b.zimmer} · PG {b.pflegegrad}</div>
                    </div>
                  </div>
                  <span className="plan-type">{p.type || "Physio"}</span>
                </div>
                <div className="plan-card-body">
                  <div className="plan-card-label">Ziele</div>
                  <div className="plan-card-list">
                    {(p.goals || []).slice(0, 3).map((g, i) => (
                      <div key={i} className="plan-goal"><Icon name="check" size={10} /> {g}</div>
                    ))}
                    {(p.goals || []).length > 3 && (
                      <div className="plan-goal-more">+ {p.goals.length - 3} weitere</div>
                    )}
                  </div>
                  <div className="plan-card-label" style={{ marginTop: 10 }}>Wochenplan</div>
                  <div className="plan-card-schedule">
                    {(p.sessions || []).map((s, i) => (
                      <div key={i} className="plan-slot">
                        <strong>{s.day}</strong> {s.time}
                        <span>{s.duration}′</span>
                      </div>
                    ))}
                  </div>
                </div>
                <div className="plan-card-foot">
                  Aktualisiert {new Date(p.updatedAt).toLocaleDateString("de-DE", { day: "2-digit", month: "2-digit", year: "2-digit" })}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </>
  );
};

const DAYS = [
  { k: "mo", l: "Mo" }, { k: "di", l: "Di" }, { k: "mi", l: "Mi" },
  { k: "do", l: "Do" }, { k: "fr", l: "Fr" }, { k: "sa", l: "Sa" }, { k: "so", l: "So" },
];
const THERAPY_TYPES = ["Physio", "Ergo", "Logo", "Manuelle Therapie", "Krankengymnastik"];
const DEFAULT_GOALS = [
  "Gangbild verbessern",
  "Sturzrisiko reduzieren",
  "Schmerzreduktion im LWS-Bereich",
  "Feinmotorik Hand re.",
  "Alltags-Mobilität steigern",
  "Atemtherapie COPD",
];

const TherapiePlanEditor = ({ bewohnerId, onClose, onSaved }) => {
  const existing = bewohnerId ? loadPlans()[bewohnerId] : null;
  const [selectedBid, setSelectedBid] = React.useState(bewohnerId || BEWOHNER[0]?.id);
  const [type, setType] = React.useState(existing?.type || "Physio");
  const [goals, setGoals] = React.useState(existing?.goals || ["Gangbild verbessern"]);
  const [goalInput, setGoalInput] = React.useState("");
  const [sessions, setSessions] = React.useState(existing?.sessions || [
    { day: "Mo", time: "09:00", duration: 30 },
    { day: "Do", time: "14:00", duration: 30 },
  ]);
  const [notes, setNotes] = React.useState(existing?.notes || "");

  const b = BEWOHNER.find((x) => x.id === selectedBid);

  const addGoal = () => {
    if (!goalInput.trim()) return;
    setGoals((gs) => [...gs, goalInput.trim()]);
    setGoalInput("");
  };
  const removeGoal = (i) => setGoals((gs) => gs.filter((_, k) => k !== i));
  const addSession = () => setSessions((s) => [...s, { day: "Mi", time: "10:00", duration: 30 }]);
  const updateSession = (i, patch) => setSessions((s) => s.map((x, k) => k === i ? { ...x, ...patch } : x));
  const removeSession = (i) => setSessions((s) => s.filter((_, k) => k !== i));

  const save = () => {
    const plans = loadPlans();
    plans[selectedBid] = {
      bewohner: selectedBid,
      type, goals, sessions, notes,
      createdAt: existing?.createdAt || Date.now(),
      updatedAt: Date.now(),
    };
    savePlans(plans);
    onSaved?.(selectedBid);
  };

  return (
    <>
      <div className="bw-backdrop" onClick={onClose} />
      <aside className="bw-sheet plan-editor" role="dialog" aria-label="Therapieplan" onClick={(e) => e.stopPropagation()}>
        <div className="bw-head">
          <div className="bw-avatar"><Avatar name={b?.name || "?"} size={42} /></div>
          <div className="bw-id">
            <div className="bw-name">
              {existing ? "Plan bearbeiten" : "Neuer Therapieplan"}
            </div>
            <div className="bw-sub">{b?.name || "Bewohner:in wählen"} {b && <>· Zi. <span className="mono">{b.zimmer}</span> · PG {b.pflegegrad}</>}</div>
          </div>
          <button className="bw-close" onClick={onClose} aria-label="Schließen"><Icon name="x" size={14} /></button>
        </div>

        <div style={{ padding: "14px 18px 110px" }}>
          {!bewohnerId && (
            <div className="plan-field">
              <label>Bewohner:in</label>
              <select className="plan-select" value={selectedBid} onChange={(e) => setSelectedBid(e.target.value)}>
                {BEWOHNER.map((x) => (
                  <option key={x.id} value={x.id}>{x.name} · Zi. {x.zimmer}</option>
                ))}
              </select>
            </div>
          )}

          <div className="plan-field">
            <label>Therapietyp</label>
            <div className="plan-chips">
              {THERAPY_TYPES.map((t) => (
                <button key={t} className="plan-chip" data-active={type === t} onClick={() => setType(t)}>
                  {t}
                </button>
              ))}
            </div>
          </div>

          <div className="plan-field">
            <label>Therapieziele</label>
            <div className="plan-goals">
              {goals.map((g, i) => (
                <div key={i} className="plan-goal-row">
                  <Icon name="check" size={11} />
                  <span>{g}</span>
                  <button className="plan-goal-x" onClick={() => removeGoal(i)} aria-label="Entfernen"><Icon name="x" size={11} /></button>
                </div>
              ))}
            </div>
            <div className="plan-goal-input">
              <input
                placeholder="Neues Ziel hinzufügen …"
                value={goalInput}
                onChange={(e) => setGoalInput(e.target.value)}
                onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addGoal(); } }}
              />
              <button onClick={addGoal} disabled={!goalInput.trim()}><Icon name="plus" size={12} /></button>
            </div>
            <div className="plan-goal-suggest">
              {DEFAULT_GOALS.filter((g) => !goals.includes(g)).slice(0, 4).map((g) => (
                <button key={g} onClick={() => setGoals((gs) => [...gs, g])}>+ {g}</button>
              ))}
            </div>
          </div>

          <div className="plan-field">
            <label>Wöchentlicher Sessions-Rahmen</label>
            <div className="plan-sessions">
              {sessions.map((s, i) => (
                <div key={i} className="plan-session-row">
                  <select value={s.day} onChange={(e) => updateSession(i, { day: e.target.value })}>
                    {DAYS.map((d) => <option key={d.k} value={d.l}>{d.l}</option>)}
                  </select>
                  <input type="time" value={s.time} onChange={(e) => updateSession(i, { time: e.target.value })} />
                  <div className="plan-session-dur">
                    <input type="number" min="15" max="90" step="15" value={s.duration} onChange={(e) => updateSession(i, { duration: parseInt(e.target.value) || 30 })} />
                    <span>Min</span>
                  </div>
                  <button className="plan-goal-x" onClick={() => removeSession(i)}><Icon name="x" size={11} /></button>
                </div>
              ))}
            </div>
            <button className="plan-add-session" onClick={addSession}>
              <Icon name="plus" size={12} /> Weitere Session hinzufügen
            </button>
          </div>

          <div className="plan-field">
            <label>Notizen</label>
            <textarea
              className="plan-textarea"
              placeholder="Besondere Hinweise, Kontraindikationen, Angehörigen-Absprachen …"
              value={notes}
              onChange={(e) => setNotes(e.target.value)}
            />
          </div>
        </div>

        <div className="plan-foot">
          <Btn onClick={onClose}>Abbrechen</Btn>
          <Btn variant="primary" icon="check" onClick={save} disabled={goals.length === 0 || sessions.length === 0}>
            {existing ? "Plan aktualisieren" : "Plan speichern"}
          </Btn>
        </div>
      </aside>
    </>
  );
};

window.TherapeutPortal = TherapeutPortal;
