// ============================================================
// LSMD — Aktensystem (MedicNet-Stil) · Pflicht-Parameter
// ============================================================

function PatientStatusBadge({ status, className = '' }) {
  const s = PATIENT_STATUS[status] || { label: status, color: '#8899AA' };
  return (
    <span className={`inline-flex items-center gap-1.5 whitespace-nowrap rounded px-2 py-0.5 text-[11px] font-bold uppercase tracking-wide ${className}`}
      style={{ color: s.color, background: `${s.color}1f`, border: `1px solid ${s.color}40` }}>
      <span className="h-1.5 w-1.5 rounded-full" style={{ background: s.color }} />{s.label}
    </span>
  );
}

function ageFrom(gebdatum) {
  const [d, m, y] = (gebdatum || '01.01.2000').split('.').map(Number);
  const today = new Date(2026, 5, 2);
  let a = today.getFullYear() - y;
  if (today.getMonth() + 1 < m || (today.getMonth() + 1 === m && today.getDate() < d)) a--;
  return a;
}

// kleine Flag-Badges (Patientenhinweise)
function FlagBadges({ flags, size = 'sm' }) {
  const active = PATIENT_FLAGS.filter(f => flags && flags[f.id]);
  if (active.length === 0) return null;
  return (
    <div className="flex flex-wrap gap-1.5">
      {active.map(f => (
        <span key={f.id} className="inline-flex items-center gap-1 whitespace-nowrap rounded px-2 py-0.5 text-[11px] font-bold uppercase tracking-wide"
          style={{ color: f.color, background: `${f.color}1f`, border: `1px solid ${f.color}40` }}>
          <Icon name={f.icon} size={12} /> {f.label}
        </span>
      ))}
    </div>
  );
}

// Sektions-Block (Label-Header + Inhalt) — wie MedicNet-Panels
function Section({ title, icon, children, action }) {
  return (
    <div className="rounded-lg border border-line bg-card overflow-hidden">
      <div className="flex items-center justify-between gap-2 px-4 h-11 border-b border-line bg-bg2">
        <div className="flex items-center gap-2 uplabel text-[11px]">
          {icon && <Icon name={icon} size={13} />} {title}
        </div>
        {action}
      </div>
      <div className="p-4">{children}</div>
    </div>
  );
}

// Patientenfoto per Strg+V einfügen
function PatientPhotoBox({ dbId, photoUrl, onChange, onUploaded, disabled }) {
  const boxRef = React.useRef(null);
  const [preview, setPreview] = useState(photoUrl || '');
  const [uploading, setUploading] = useState(false);
  const [hint, setHint] = useState('');

  useEffect(() => { setPreview(photoUrl || ''); }, [photoUrl]);

  const handlePaste = (e) => {
    if (disabled) return;
    e.preventDefault();
    e.stopPropagation();
    const items = e.clipboardData?.items;
    if (!items) return;
    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      if (!item.type.startsWith('image/')) continue;
      const blob = item.getAsFile();
      const reader = new FileReader();
      reader.onload = async () => {
        const dataUrl = reader.result;
        setPreview(dataUrl);
        onChange?.(dataUrl);
        if (dbId) {
          setUploading(true);
          setHint('');
          try {
            const res = await window.LSMD.uploadPatientPhoto(dbId, dataUrl);
            setPreview(res.photoUrl);
            onUploaded?.(res.patient);
            setHint('Gespeichert');
          } catch (err) {
            setHint(err.message || 'Speichern fehlgeschlagen');
          } finally {
            setUploading(false);
          }
        } else {
          setHint('Mit „Speichern“ wird das Bild übernommen');
        }
      };
      reader.readAsDataURL(blob);
      return;
    }
  };

  return (
    <div>
      <div
        ref={boxRef}
        tabIndex={0}
        role="button"
        onPaste={handlePaste}
        onClick={() => boxRef.current?.focus()}
        className="relative aspect-[4/3] w-full rounded-lg border-2 border-dashed border-line overflow-hidden outline-none focus:border-accent cursor-pointer bg-bg/30 transition-colors hover:border-accent/50"
      >
        {preview ? (
          <img src={preview} alt="Patientenfoto" className="w-full h-full object-cover" />
        ) : (
          <div className="absolute inset-0 grid place-items-center p-6 text-center">
            <Icon name="ImagePlus" size={36} className="text-muted mb-2" />
            <p className="text-sm font-bold">Patientenfoto</p>
            <p className="text-xs text-muted mt-1">Feld anklicken · Strg+V zum Einfügen</p>
          </div>
        )}
        {uploading && (
          <div className="absolute inset-0 bg-black/60 grid place-items-center text-white text-sm font-semibold">
            Speichert …
          </div>
        )}
      </div>
      {hint && <p className={`mt-2 text-xs font-semibold ${hint === 'Gespeichert' ? 'text-success' : 'text-muted'}`}>{hint}</p>}
    </div>
  );
}

// Feld-Zeile mit Icon (read-only Anzeige)
function DataRow({ icon, value, muted }) {
  return (
    <div className="flex items-center gap-2.5 rounded-md border border-line bg-bg/40 px-3 h-10">
      {icon && <Icon name={icon} size={15} className="text-muted shrink-0" />}
      <span className={`text-sm truncate ${muted ? 'text-muted italic' : 'font-medium'}`}>{value}</span>
    </div>
  );
}

// ---- Behandlungseintrag (aufklappbar) ----
function BehandlungEntry({ b, onDelete }) {
  const [open, setOpen] = useState(true);
  const teile = (regionObj) => Object.entries(regionObj);
  const Region = ({ title, region, defs }) => (
    <div>
      <div className="text-sm font-bold mb-2">{title}</div>
      <div className="flex flex-col">
        {defs.map(([key, label]) => {
          const val = region[key];
          return (
            <div key={key} className="flex items-baseline gap-2 py-1.5 border-b border-line/40 last:border-0">
              <span className="text-[13px] font-semibold w-28 shrink-0" style={{ color: val ? 'var(--c-signal)' : 'var(--c-muted)' }}>{label}:</span>
              <span className={`text-[13px] ${val ? 'text-ink' : 'text-muted/50'}`}>{val || '—'}</span>
            </div>
          );
        })}
      </div>
    </div>
  );
  return (
    <div className="rounded-lg border border-line overflow-hidden">
      <button onClick={() => setOpen(o => !o)} className="w-full flex items-center gap-2 px-4 h-12 bg-bg2 hover:bg-white/[.03] transition-colors text-left">
        <Icon name="ChevronDown" size={16} className={`text-muted transition-transform ${open ? '' : '-rotate-90'}`} />
        <span className="text-[13px] font-semibold">Behandlung · {b.id}</span>
        <span className="text-[12px] text-muted hidden sm:inline">→ {b.ersteller}</span>
        <span className="text-[12px] text-muted ml-auto hidden md:inline">Erstellt am {b.erstellt}</span>
        <span className="rounded px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide shrink-0"
          style={b.abgeschlossen ? { color: '#22C55E', background: '#22C55E1f', border: '1px solid #22C55E40' } : { color: '#F59E0B', background: '#F59E0B1f', border: '1px solid #F59E0B40' }}>
          {b.abgeschlossen ? 'Abgeschlossen' : 'Laufend'}
        </span>
      </button>
      {open && (
        <div className="p-4 flex flex-col gap-4">
          <div className="flex gap-2">
            <Btn variant="outline" size="sm" icon="Pencil">Eintrag bearbeiten</Btn>
            <Btn variant="ghost" size="sm" icon="Trash2" className="!text-accent" onClick={onDelete}>Eintrag löschen</Btn>
          </div>
          <Section title="Verlauf" icon="ScrollText">
            <p className="text-sm leading-relaxed whitespace-pre-line">{b.verlauf || '—'}</p>
            {b.datum && <div className="mt-2 text-[12px] text-muted"><span className="text-[#3B82F6] font-semibold">Datum:</span> {b.datum}</div>}
          </Section>
          <Section title="Verletzungsarten" icon="Activity">
            <div className="grid sm:grid-cols-2 gap-3">
              <div className="flex items-baseline gap-2"><span className="text-[13px] font-semibold text-signal">Intensität der Wunden:</span><span className="text-sm">{b.intensitaet || '—'}</span></div>
              <div className="flex items-baseline gap-2"><span className="text-[13px] font-semibold text-signal">Art der Blutung:</span><span className="text-sm">{b.blutung || '—'}</span></div>
            </div>
          </Section>
          <Section title="Vorgenommene Behandlungen" icon="Stethoscope">
            <p className="text-sm leading-relaxed">{b.vorgenommen || '—'}</p>
          </Section>
          <Section title="Vorliegende Verletzungen" icon="Bone">
            <div className="grid md:grid-cols-2 gap-6">
              <Region title="Oberkörper" region={b.verletzungen.oberkoerper} defs={KOERPER_TEILE.oberkoerper} />
              <Region title="Unterkörper" region={b.verletzungen.unterkoerper} defs={KOERPER_TEILE.unterkoerper} />
            </div>
          </Section>
        </div>
      )}
    </div>
  );
}

// ---- Detailansicht einer Akte ----
function PatientDetail({ patient, onBack, onDelete, onUpdated }) {
  const [behandlungen, setBehandlungen] = useState(patient.behandlungen || []);
  const [addOpen, setAddOpen] = useState(false);
  const [editOpen, setEditOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const [err, setErr] = useState('');
  const [photoUrl, setPhotoUrl] = useState(patient.photoUrl || '');
  const p = patient;

  useEffect(() => { setPhotoUrl(patient.photoUrl || ''); }, [patient.photoUrl]);

  useEffect(() => {
    setBehandlungen(patient.behandlungen || []);
  }, [patient]);

  const addEntry = async (entry) => {
    if (!p.dbId) return;
    setBusy(true);
    setErr('');
    try {
      const res = await window.LSMD.addPatientEntry(p.dbId, entry);
      setBehandlungen(res.patient.behandlungen || []);
      onUpdated?.(res.patient);
      setAddOpen(false);
    } catch (e) {
      setErr(e.message || 'Eintrag konnte nicht gespeichert werden');
    } finally {
      setBusy(false);
    }
  };

  const delEntry = async (id) => {
    if (!p.dbId || !window.confirm('Akteneintrag wirklich löschen?')) return;
    setBusy(true);
    setErr('');
    try {
      const res = await window.LSMD.deletePatientEntry(p.dbId, id);
      setBehandlungen(res.patient.behandlungen || []);
      onUpdated?.(res.patient);
    } catch (e) {
      setErr(e.message || 'Löschen fehlgeschlagen');
    } finally {
      setBusy(false);
    }
  };

  const saveEdit = async (form) => {
    if (!p.dbId) return;
    setBusy(true);
    setErr('');
    try {
      const res = await window.LSMD.updatePatient(p.dbId, form);
      onUpdated?.(res.patient);
      if (res.patient?.photoUrl) setPhotoUrl(res.patient.photoUrl);
      setEditOpen(false);
    } catch (e) {
      setErr(e.message || 'Speichern fehlgeschlagen');
    } finally {
      setBusy(false);
    }
  };

  return (
    <div>
      <button onClick={onBack} className="text-sm text-muted hover:text-ink flex items-center gap-1.5 mb-4"><Icon name="ArrowLeft" size={16} /> Zurück zur Aktenübersicht</button>

      {/* Kopf */}
      <Card className="p-5 mb-5">
        <div className="flex flex-wrap items-center justify-between gap-4">
          <div className="flex items-center gap-4 min-w-0">
            <div className="grid place-items-center h-16 w-16 rounded-lg shrink-0 overflow-hidden" style={!photoUrl ? { background: `${PATIENT_STATUS[p.status].color}1f`, color: PATIENT_STATUS[p.status].color } : {}}>
              {photoUrl ? <img src={photoUrl} alt="" className="w-full h-full object-cover" /> : <Icon name="UserRound" size={30} />}
            </div>
            <div className="min-w-0 flex flex-col gap-1.5">
              <div className="flex items-center gap-2.5 flex-wrap">
                <h1 className="text-2xl font-extrabold tracking-tight">{p.name}</h1>
                <PatientStatusBadge status={p.status} />
              </div>
              <div className="text-sm text-muted font-mono">{p.id} · {p.geschlecht} · {ageFrom(p.gebdatum)} Jahre</div>
              <FlagBadges flags={p.flags} />
            </div>
          </div>
          <div className="flex flex-wrap gap-2">
            <Btn variant="outline" icon="Pencil" size="sm" className="!border-warning/60 !text-warning" onClick={() => setEditOpen(true)} disabled={busy || !p.dbId}>Bearbeiten</Btn>
            <Btn variant="outline" icon="Trash2" size="sm" className="!border-accent/60 !text-accent" onClick={onDelete} disabled={busy}>Löschen</Btn>
            <Btn variant="outline" icon="FilePlus2" size="sm" className="!border-discord/60 !text-[#7C8CFF]" onClick={() => setAddOpen(true)} disabled={busy}>Akteneintrag hinzufügen</Btn>
            <Btn variant="outline" icon="Share2" size="sm" className="!border-success/60 !text-success" disabled title="Freigabe folgt">Akte freigeben</Btn>
          </div>
        </div>
        {err && <p className="mt-3 text-sm text-signal">{err}</p>}
      </Card>

      {/* Stammdaten zweispaltig */}
      <div className="grid lg:grid-cols-2 gap-5">
        {/* Links */}
        <div className="flex flex-col gap-5">
          <Section title="Vor- und Nachname" icon="User"><DataRow icon="User" value={p.name} /></Section>
          <Section title="Geschlecht" icon="Venus"><DataRow icon="VenusAndMars" value={p.geschlecht === 'M' ? 'Männlich (M)' : p.geschlecht === 'W' ? 'Weiblich (W)' : p.geschlecht} /></Section>
          <Section title="Geburtsdatum" icon="Calendar"><DataRow icon="Calendar" value={`${p.gebdatum}  ·  ${ageFrom(p.gebdatum)} Jahre`} /></Section>
          <Section title="Kontakt" icon="Phone">
            <div className="flex flex-col gap-2">
              <DataRow icon="Phone" value={p.tel} />
              <DataRow icon="Home" value={p.adresse} />
            </div>
          </Section>
          <Section title="Notfallkontakte" icon="Contact">
            <div className="flex flex-col gap-2">
              {p.notfallkontakte.length === 0 && <DataRow icon="UserX" value="Keine hinterlegt" muted />}
              {p.notfallkontakte.map((k, i) => <DataRow key={i} icon="UserRound" value={`${k.name}  |  ${k.nr}`} />)}
            </div>
          </Section>
          <Section title="Sonstiges" icon="StickyNote">
            <p className={`text-sm ${p.sonstiges ? '' : 'text-muted italic'}`}>{p.sonstiges || 'Keine Angaben'}</p>
          </Section>
          <Section title="Patientenhinweise" icon="ShieldAlert">
            <div className="flex flex-col gap-2.5">
              {PATIENT_FLAGS.map(f => {
                const on = p.flags && p.flags[f.id];
                return (
                  <div key={f.id} className="flex items-center gap-2.5">
                    <span className="grid place-items-center h-5 w-5 rounded-sm border" style={{ borderColor: on ? f.color : 'var(--c-border)', background: on ? f.color : 'transparent' }}>
                      {on && <Icon name="Check" size={13} className="text-white" strokeWidth={3} />}
                    </span>
                    <span className={`text-sm font-semibold ${on ? '' : 'text-muted'}`} style={on ? { color: f.color } : {}}>{f.label}</span>
                  </div>
                );
              })}
            </div>
          </Section>
        </div>

        {/* Rechts */}
        <div className="flex flex-col gap-5">
          <Section title="Bild" icon="Image">
            <PatientPhotoBox
              dbId={p.dbId}
              photoUrl={photoUrl}
              disabled={busy}
              onUploaded={(pat) => { setPhotoUrl(pat.photoUrl); onUpdated?.(pat); }}
            />
          </Section>
          <Section title="Blutgruppe" icon="Droplet"><DataRow icon="HeartPulse" value={p.blutgruppe || '—'} /></Section>
          <Section title="Allergien" icon="TriangleAlert">
            <p className={`text-sm ${p.allergien ? '' : 'text-muted italic'}`}>{p.allergien || 'Keine erfasst'}</p>
          </Section>
          <Section title="Vorerkrankungen" icon="Activity">
            <p className={`text-sm ${p.vorerkrankungen ? '' : 'text-muted italic'}`}>{p.vorerkrankungen || 'Keine erfasst'}</p>
          </Section>
          <Section title="Größe" icon="Ruler"><DataRow icon="MoveVertical" value={`${p.groesse} cm`} /></Section>
          <Section title="Gewicht" icon="Weight"><DataRow icon="Scale" value={`${p.gewicht} kg`} /></Section>
        </div>
      </div>

      {/* Akteneinträge / Behandlungen */}
      <div className="mt-8">
        <div className="flex items-center justify-between mb-4">
          <div>
            <h2 className="text-lg font-bold">Akteneinträge</h2>
            <p className="text-sm text-muted mt-0.5">{behandlungen.length} Behandlung(en) dokumentiert</p>
          </div>
          <Btn icon="FilePlus2" size="sm" onClick={() => setAddOpen(true)}>Akteneintrag hinzufügen</Btn>
        </div>
        <div className="flex flex-col gap-3">
          {behandlungen.map(b => <BehandlungEntry key={b.id} b={b} onDelete={() => delEntry(b.id)} />)}
          {behandlungen.length === 0 && <div className="rounded-lg border border-dashed border-line p-8 text-center text-sm text-muted">Noch keine Behandlungen dokumentiert.</div>}
        </div>
      </div>

      <AkteneintragModal open={addOpen} onClose={() => setAddOpen(false)} onSave={addEntry} saving={busy} />
      <PatientModal open={editOpen} onClose={() => setEditOpen(false)} onSave={saveEdit} initial={p} title="Akte bearbeiten" saving={busy} />
    </div>
  );
}

// ---- Akteneintrag-Formular (Behandlung dokumentieren) ----
function AkteneintragModal({ open, onClose, onSave, saving }) {
  const [f, setF] = useState(ENTRY_DEFAULT());
  useEffect(() => { if (open) setF(ENTRY_DEFAULT()); }, [open]);
  const setV = (k, v) => setF(s => ({ ...s, [k]: v }));
  const setTeil = (region, key, v) => setF(s => ({ ...s, verletzungen: { ...s.verletzungen, [region]: { ...s.verletzungen[region], [key]: v } } }));

  const save = () => {
    if (!f.verlauf?.trim()) return;
    onSave({ ...f, titel: 'Behandlung' });
  };

  const teilInput = (region, key, label) => (
    <div key={key} className="flex items-center gap-2">
      <label className="text-[12px] font-semibold w-28 shrink-0 text-signal">{label}:</label>
      <input value={f.verletzungen[region][key]} onChange={e => setTeil(region, key, e.target.value)} placeholder="—"
        className="flex-1 h-9 rounded-md bg-bg/60 border border-line px-2.5 text-[13px] outline-none focus:border-accent" />
    </div>
  );

  return (
    <Modal open={open} onClose={onClose} title="Akteneintrag hinzufügen" width="max-w-3xl"
      footer={<><Btn variant="ghost" onClick={onClose}>Abbrechen</Btn><Btn icon="Check" onClick={save} disabled={saving}>{saving ? 'Speichert …' : 'Speichern'}</Btn></>}>
      <div className="flex flex-col gap-5 max-h-[70vh] overflow-y-auto pr-1">
        <Field label="Verlauf" required hint="Hergang, Diagnose, Medikamente …">
          <TextArea rows={4} value={f.verlauf} onChange={e => setV('verlauf', e.target.value)} placeholder={'z. B. Verkehrsunfall\nQuetschung am Fuß (links)\nMedikamente: 2× Ibu (400)'} />
        </Field>
        <div className="grid sm:grid-cols-2 gap-4">
          <Field label="Intensität der Wunden">
            <Select value={f.intensitaet} onChange={e => setV('intensitaet', e.target.value)}>{INTENSITAET_OPT.map(o => <option key={o} value={o}>{o || 'Bitte wählen …'}</option>)}</Select>
          </Field>
          <Field label="Art der Blutung">
            <Select value={f.blutung} onChange={e => setV('blutung', e.target.value)}>{BLUTUNG_OPT.map(o => <option key={o} value={o}>{o || 'Bitte wählen …'}</option>)}</Select>
          </Field>
        </div>
        <Field label="Vorgenommene Behandlungen">
          <TextArea rows={2} value={f.vorgenommen} onChange={e => setV('vorgenommen', e.target.value)} placeholder="Durchgeführte Maßnahmen …" />
        </Field>
        <div>
          <Label className="mb-2">Vorliegende Verletzungen</Label>
          <div className="grid md:grid-cols-2 gap-5">
            <div className="rounded-md border border-line p-3">
              <div className="text-sm font-bold mb-2">Oberkörper</div>
              <div className="flex flex-col gap-2">{KOERPER_TEILE.oberkoerper.map(([k, l]) => teilInput('oberkoerper', k, l))}</div>
            </div>
            <div className="rounded-md border border-line p-3">
              <div className="text-sm font-bold mb-2">Unterkörper</div>
              <div className="flex flex-col gap-2">{KOERPER_TEILE.unterkoerper.map(([k, l]) => teilInput('unterkoerper', k, l))}</div>
            </div>
          </div>
        </div>
        <label className="flex items-center gap-2.5 cursor-pointer">
          <span className="grid place-items-center h-5 w-5 rounded-sm border" style={{ borderColor: f.abgeschlossen ? '#22C55E' : 'var(--c-border)', background: f.abgeschlossen ? '#22C55E' : 'transparent' }} onClick={() => setV('abgeschlossen', !f.abgeschlossen)}>
            {f.abgeschlossen && <Icon name="Check" size={13} className="text-white" strokeWidth={3} />}
          </span>
          <span className="text-sm font-semibold" onClick={() => setV('abgeschlossen', !f.abgeschlossen)}>Behandlung abgeschlossen</span>
        </label>
      </div>
    </Modal>
  );
}

// ---- Patient hinzufügen (alle Pflicht-Parameter) ----
function patientToForm(p) {
  const notfall = (p.notfallkontakte || []).map(k => `${k.name} | ${k.nr}`).join('\n');
  return {
    name: p.name || '',
    geschlecht: p.geschlecht || 'M',
    gebdatum: p.gebdatum || '',
    tel: p.tel === '—' ? '' : (p.tel || ''),
    adresse: p.adresse === '—' ? '' : (p.adresse || ''),
    notfall,
    blutgruppe: p.blutgruppe || '',
    allergien: p.allergien || '',
    vorerkrankungen: p.vorerkrankungen || '',
    groesse: p.groesse ? String(p.groesse) : '',
    gewicht: p.gewicht ? String(p.gewicht) : '',
    sonstiges: p.sonstiges || '',
    flags: { gewalt: false, gang: false, verstorben: false, ...(p.flags || {}) },
    status: p.status || 'STABIL',
    photo_preview: p.photoUrl || '',
  };
}

function formToPatientPayload(f) {
  const notfallkontakte = f.notfall.split('\n').map(l => l.trim()).filter(Boolean).map(l => {
    const [name, nr] = l.split('|').map(x => x && x.trim());
    return { name: name || l, nr: nr || '—' };
  });
  return {
    name: f.name,
    geschlecht: f.geschlecht,
    gebdatum: f.gebdatum,
    tel: f.tel,
    adresse: f.adresse,
    notfallkontakte,
    blutgruppe: f.blutgruppe,
    allergien: f.allergien,
    vorerkrankungen: f.vorerkrankungen,
    groesse: f.groesse,
    gewicht: f.gewicht,
    sonstiges: f.sonstiges,
    flags: f.flags,
    status: f.flags.verstorben ? 'VERSTORBEN' : (f.status || 'STABIL'),
    photo_base64: (f.photo_preview && String(f.photo_preview).startsWith('data:image/')) ? f.photo_preview : null,
  };
}

function PatientModal({ open, onClose, onSave, initial, title = 'Patient hinzufügen', saving }) {
  const empty = patientToForm({});
  const [f, setF] = useState(empty);
  useEffect(() => {
    if (open) setF(initial ? patientToForm(initial) : empty);
  }, [open, initial]);
  const setV = (k, v) => setF(s => ({ ...s, [k]: v }));
  const toggleFlag = (id) => setF(s => ({ ...s, flags: { ...s.flags, [id]: !s.flags[id] } }));

  const save = () => {
    if (!f.name.trim()) return;
    onSave(formToPatientPayload(f));
  };

  return (
    <Modal open={open} onClose={onClose} title={title} width="max-w-3xl"
      footer={<><Btn variant="ghost" onClick={onClose}>Abbrechen</Btn><Btn icon="Check" onClick={save} disabled={saving}>{saving ? 'Speichert …' : 'Speichern'}</Btn></>}>
      <div className="max-h-[70vh] overflow-y-auto pr-1 flex flex-col gap-4">
        <Field label="Patientenfoto">
          <PatientPhotoBox
            dbId={initial?.dbId}
            photoUrl={f.photo_preview}
            onChange={(dataUrl) => { setV('photo_preview', dataUrl); }}
          />
        </Field>
      <div className="grid md:grid-cols-2 gap-x-5 gap-y-4">
        <Field label="Vor- und Nachname" required><TextInput value={f.name} onChange={e => setV('name', e.target.value)} placeholder="Vorname Nachname" /></Field>
        <Field label="Blutgruppe"><Select value={f.blutgruppe} onChange={e => setV('blutgruppe', e.target.value)}>{BLOOD_TYPES.map(b => <option key={b} value={b}>{b || 'Bitte wählen …'}</option>)}</Select></Field>

        <Field label="Status"><Select value={f.status} onChange={e => setV('status', e.target.value)}>{Object.keys(PATIENT_STATUS).map(k => <option key={k} value={k}>{PATIENT_STATUS[k].label}</option>)}</Select></Field>
        <Field label="Geschlecht"><Select value={f.geschlecht} onChange={e => setV('geschlecht', e.target.value)}><option value="M">Männlich (M)</option><option value="W">Weiblich (W)</option><option value="D">Divers (D)</option></Select></Field>
        <Field label="Allergien" hint="z. B. Heuschnupfen, Meeresfrüchte, Nüsse"><TextInput value={f.allergien} onChange={e => setV('allergien', e.target.value)} placeholder="Heuschnupfen, Meeresfrüchte oder Nüsse" /></Field>

        <Field label="Geburtsdatum"><TextInput value={f.gebdatum} onChange={e => setV('gebdatum', e.target.value)} placeholder="02.02.1970" /></Field>
        <Field label="Vorerkrankungen"><TextInput value={f.vorerkrankungen} onChange={e => setV('vorerkrankungen', e.target.value)} placeholder="z. B. Asthma" /></Field>

        <Field label="Telefonnummer"><TextInput value={f.tel} onChange={e => setV('tel', e.target.value)} placeholder="123-555-678" /></Field>
        <Field label="Größe (cm)"><TextInput value={f.groesse} onChange={e => setV('groesse', e.target.value)} placeholder="185" /></Field>

        <Field label="Adresse"><TextInput value={f.adresse} onChange={e => setV('adresse', e.target.value)} placeholder="Millow Street 20, Los Santos" /></Field>
        <Field label="Gewicht (kg)"><TextInput value={f.gewicht} onChange={e => setV('gewicht', e.target.value)} placeholder="120" /></Field>

        <Field label="Notfallkontakte" hint="Eine Person pro Zeile · Format: Name | Nummer">
          <TextArea rows={3} value={f.notfall} onChange={e => setV('notfall', e.target.value)} placeholder={'Maria Mustermann | 1234-555-678\nGeorg Mustermann | 1234-555-678'} />
        </Field>
        <Field label="Sonstiges"><TextArea rows={3} value={f.sonstiges} onChange={e => setV('sonstiges', e.target.value)} placeholder="Gib hier irgendwelche Notizen oder Hinweise ein" /></Field>

        <div className="md:col-span-2">
          <Label className="mb-2">Patientenhinweise</Label>
          <div className="flex flex-wrap gap-3">
            {PATIENT_FLAGS.map(fl => {
              const on = f.flags[fl.id];
              return (
                <button key={fl.id} onClick={() => toggleFlag(fl.id)} className="flex items-center gap-2.5 rounded-md border px-3 h-10 transition-all" style={{ borderColor: on ? fl.color : 'var(--c-border)', background: on ? `${fl.color}1a` : 'transparent' }}>
                  <span className="grid place-items-center h-5 w-5 rounded-sm border" style={{ borderColor: on ? fl.color : 'var(--c-border)', background: on ? fl.color : 'transparent' }}>
                    {on && <Icon name="Check" size={13} className="text-white" strokeWidth={3} />}
                  </span>
                  <span className="text-sm font-semibold" style={on ? { color: fl.color } : {}}>{fl.label}</span>
                </button>
              );
            })}
          </div>
        </div>
      </div>
      </div>
    </Modal>
  );
}

// ---- Übersicht / Liste ----
function Aktensystem() {
  const [sel, setSel] = useState(null);
  const [q, setQ] = useState('');
  const [filter, setFilter] = useState('ALLE');
  const [createOpen, setCreateOpen] = useState(false);
  const [list, setList] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      setLoading(true);
      try {
        const data = await window.LSMD.loadPatients(q);
        if (!cancelled) setList(data.patients || []);
      } catch (e) {
        console.error(e);
        if (!cancelled) setList([]);
      } finally {
        if (!cancelled) setLoading(false);
      }
    };
    const t = setTimeout(load, q ? 250 : 0);
    return () => { cancelled = true; clearTimeout(t); };
  }, [q]);

  const filters = ['ALLE', ...Object.keys(PATIENT_STATUS)];
  const rows = list.filter(p => (filter === 'ALLE' || p.status === filter) && (q === '' || p.name.toLowerCase().includes(q.toLowerCase()) || p.id.toLowerCase().includes(q.toLowerCase())));

  const [createBusy, setCreateBusy] = useState(false);

  const refreshInList = (patient) => {
    setList(prev => {
      const i = prev.findIndex(x => x.dbId === patient.dbId || x.id === patient.id);
      if (i < 0) return [patient, ...prev];
      const next = [...prev];
      next[i] = { ...next[i], ...patient };
      return next;
    });
    setSel(patient);
  };

  const createPatient = async (form) => {
    setCreateBusy(true);
    try {
      const res = await window.LSMD.createPatient(form);
      setList([res.patient, ...list]);
      setCreateOpen(false);
    } catch (e) {
      alert(e.message || 'Patient konnte nicht angelegt werden');
    } finally {
      setCreateBusy(false);
    }
  };

  const deletePatient = async (p) => {
    if (!p.dbId || !window.confirm(`Akte ${p.id} wirklich löschen?`)) return;
    try {
      await window.LSMD.deletePatient(p.dbId);
      setList(list.filter(x => x.dbId !== p.dbId && x.id !== p.id));
      setSel(null);
    } catch (e) {
      alert(e.message || 'Löschen fehlgeschlagen');
    }
  };

  const openPatient = async (p) => {
    if (!p.dbId) { setSel(p); return; }
    try {
      const { patient } = await window.LSMD.loadPatient(p.dbId);
      setSel(patient);
    } catch (e) {
      console.error(e);
      setSel(p);
    }
  };

  if (sel) {
    return (
      <PatientDetail
        patient={sel}
        onBack={() => setSel(null)}
        onDelete={() => deletePatient(sel)}
        onUpdated={refreshInList}
      />
    );
  }

  return (
    <div>
      <PageHead title="Aktensystem" sub="MedicNet · Patientenakten & Behandlungsverläufe">
        <Btn icon="FilePlus" onClick={() => setCreateOpen(true)}>Patient hinzufügen</Btn>
      </PageHead>

      {/* Quick-Stats */}
      <div className="grid grid-cols-2 md:grid-cols-4 gap-3 mb-5">
        {[['Akten gesamt', list.length, 'Files', 'ink'], ['In Behandlung', list.filter(p => p.status === 'BEHANDLUNG').length, 'Activity', 'warning'], ['Kritisch', list.filter(p => p.status === 'KRITISCH').length, 'TriangleAlert', 'accent'], ['Stabil', list.filter(p => p.status === 'STABIL').length, 'HeartPulse', 'success']].map(([l, v, ic, tone]) => (
        <StatCard key={l} label={l} value={v} sub="aktuell" icon={ic} tone={tone} />
        ))}
      </div>

      <div className="flex flex-wrap items-center gap-2 mb-4">
        {filters.map(fl => (
          <button key={fl} onClick={() => setFilter(fl)} className={`inline-flex items-center gap-1.5 rounded-md border px-2.5 h-8 text-[12px] font-bold uppercase tracking-wide transition-all ${filter === fl ? 'border-accent text-accent bg-[var(--c-accent-soft)]' : 'border-line text-muted hover:text-ink'}`}>
            {fl !== 'ALLE' && <span className="h-1.5 w-1.5 rounded-full" style={{ background: PATIENT_STATUS[fl].color }} />}
            {fl === 'ALLE' ? 'Alle' : PATIENT_STATUS[fl].label}
          </button>
        ))}
      </div>

      <div className="relative mb-4">
        <Icon name="Search" size={16} className="absolute left-3 top-1/2 -translate-y-1/2 text-muted" />
        <input value={q} onChange={e => setQ(e.target.value)} placeholder="Patient oder Aktennummer suchen …" className="w-full h-11 rounded-md bg-card border border-line pl-9 pr-3 text-sm outline-none focus:border-accent" />
      </div>

      {loading && <div className="rounded-lg border border-line p-10 text-center text-sm text-muted">Patientenakten werden geladen …</div>}

      <div className="grid md:grid-cols-2 xl:grid-cols-3 gap-3">
        {!loading && rows.map(p => (
          <button key={p.dbId || p.id} onClick={() => openPatient(p)} className="text-left rounded-lg border border-line bg-card p-4 hover:border-accent/50 transition-colors group">
            <div className="flex items-start justify-between gap-2">
              <div className="flex items-center gap-3 min-w-0">
                <div className="grid place-items-center h-11 w-11 rounded-md shrink-0" style={{ background: `${PATIENT_STATUS[p.status].color}1f`, color: PATIENT_STATUS[p.status].color }}><Icon name="UserRound" size={22} /></div>
                <div className="min-w-0">
                  <div className="font-bold truncate">{p.name}</div>
                  <div className="font-mono text-[11px] text-muted">{p.id}</div>
                </div>
              </div>
              <Icon name="ChevronRight" size={16} className="text-muted group-hover:text-accent transition-colors shrink-0" />
            </div>
            <div className="mt-3 flex items-center justify-between">
              <PatientStatusBadge status={p.status} />
              <span className="text-[11px] text-muted">{ageFrom(p.gebdatum)} J. · {p.geschlecht} · {p.blutgruppe || '—'}</span>
            </div>
            <div className="mt-3 pt-3 border-t border-line/60 flex items-center gap-1.5 text-[12px] text-muted min-h-[20px]">
              {(p.flags && (p.flags.gewalt || p.flags.gang || p.flags.verstorben))
                ? <FlagBadges flags={p.flags} />
                : <><Icon name="FileText" size={13} /><span className="truncate">{p.entry_count ?? (p.behandlungen || []).length} Akteneintrag(e)</span></>}
            </div>
          </button>
        ))}
      </div>
      {!loading && rows.length === 0 && <div className="rounded-lg border border-dashed border-line p-10 text-center text-sm text-muted">Keine Akten in der Datenbank. Lege die erste Akte an.</div>}

      <PatientModal open={createOpen} onClose={() => setCreateOpen(false)} onSave={createPatient} saving={createBusy} />
    </div>
  );
}

Object.assign(window, { Aktensystem, PatientStatusBadge, FlagBadges });
