/* global React, Icon, DEFAULT_INVENTORY */
const { useState: useStateAdmin } = React;

// ============ Reusable inventory editor ============
function InventoryEditor({ items, onChange, readOnly }) {
  const [newName, setNewName] = useStateAdmin("");
  const [pendingDel, setPendingDel] = useStateAdmin(null);
  const [dragId, setDragId] = useStateAdmin(null);
  const [overId, setOverId] = useStateAdmin(null);

  const setCount = (id, count) => onChange(items.map(it => it.id === id ? { ...it, count: Math.max(0, count) } : it));
  const setName = (id, name) => onChange(items.map(it => it.id === id ? { ...it, name } : it));
  const remove = (id) => onChange(items.filter(it => it.id !== id));
  const add = () => {
    const n = newName.trim();
    if (!n) return;
    onChange([...items, { id: "i_" + Date.now(), name: n, count: 0 }]);
    setNewName("");
  };
  const move = (id, dir) => {
    const i = items.findIndex(it => it.id === id);
    const j = i + dir;
    if (i < 0 || j < 0 || j >= items.length) return;
    const next = items.slice();
    [next[i], next[j]] = [next[j], next[i]];
    onChange(next);
  };
  const reorder = (fromId, toId) => {
    if (fromId === toId) return;
    const from = items.findIndex(it => it.id === fromId);
    const to = items.findIndex(it => it.id === toId);
    if (from < 0 || to < 0) return;
    const next = items.slice();
    const [moved] = next.splice(from, 1);
    next.splice(to, 0, moved);
    onChange(next);
  };

  return (
    <div>
      <div style={{ display: "grid", gap: 8 }}>
        {items.length === 0 && <div className="muted text-sm" style={{ padding: 8 }}>Noch keine Utensilien hinterlegt.</div>}
        {items.map((it, idx) => (
          <div
            key={it.id}
            className={"inv-row" + (overId === it.id && dragId && dragId !== it.id ? " drop-target" : "") + (dragId === it.id ? " dragging" : "")}
            onDragOver={(e) => { if (dragId) { e.preventDefault(); setOverId(it.id); } }}
            onDrop={(e) => { e.preventDefault(); if (dragId) reorder(dragId, it.id); setDragId(null); setOverId(null); }}
          >
            {!readOnly && (
              <div className="inv-reorder">
                <button className="inv-move" onClick={() => move(it.id, -1)} disabled={idx === 0} title="Nach oben" aria-label="Nach oben">
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="18 15 12 9 6 15"/></svg>
                </button>
                <button className="inv-move" onClick={() => move(it.id, 1)} disabled={idx === items.length - 1} title="Nach unten" aria-label="Nach unten">
                  <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
                </button>
              </div>
            )}
            <div
              className={"inv-icon" + (readOnly ? "" : " inv-handle")}
              draggable={!readOnly}
              onDragStart={() => !readOnly && setDragId(it.id)}
              onDragEnd={() => { setDragId(null); setOverId(null); }}
              title={readOnly ? "" : "Ziehen zum Umsortieren"}
            >
              <Icon.Box />
            </div>
            {readOnly ? (
              <div className="flex-1 fw-600">{it.name}</div>
            ) : (
              <input className="input input-sm flex-1" value={it.name} onChange={(e) => setName(it.id, e.target.value)} />
            )}
            {readOnly ? (
              <div className="inv-count-ro">{it.count}</div>
            ) : (
              <div className="stepper">
                <button onClick={() => setCount(it.id, it.count - 1)}>−</button>
                <input
                  value={it.count}
                  onChange={(e) => { const n = parseInt(e.target.value); if (!isNaN(n)) setCount(it.id, n); }}
                />
                <button onClick={() => setCount(it.id, it.count + 1)}>+</button>
              </div>
            )}
            {!readOnly && (
              <button className="btn btn-icon btn-danger" onClick={() => setPendingDel(it)} title="Artikel entfernen">
                <Icon.Trash />
              </button>
            )}
          </div>
        ))}
      </div>
      {!readOnly && (
        <div className="row gap-2 mt-3" style={{ flexWrap: "wrap" }}>
          <input
            className="input"
            style={{ maxWidth: 260 }}
            placeholder="Neuer Artikel (z.B. Markierungsstangen)"
            value={newName}
            onChange={(e) => setNewName(e.target.value)}
            onKeyDown={(e) => e.key === "Enter" && add()}
          />
          <button className="btn btn-secondary" onClick={add}><Icon.Plus /> Artikel hinzufügen</button>
        </div>
      )}

      {pendingDel && (
        <div className="modal-backdrop" onClick={() => setPendingDel(null)}>
          <div className="modal" style={{ maxWidth: 400 }} onClick={(e) => e.stopPropagation()}>
            <div className="modal-head"><h3>Artikel löschen?</h3></div>
            <div className="modal-body">
              <p style={{ margin: 0, fontSize: 14, lineHeight: 1.5 }}>
                Soll der Lagerartikel <strong>{pendingDel.name}</strong> wirklich gelöscht werden?
              </p>
            </div>
            <div className="modal-foot">
              <button className="btn btn-secondary" onClick={() => setPendingDel(null)}>Abbrechen</button>
              <button className="btn" style={{ background: "var(--danger)" }} onClick={() => { remove(pendingDel.id); setPendingDel(null); }}>
                Löschen
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ============ Inventur history (audit trail) ============
function fmtInventurDate(iso) {
  const d = new Date(iso);
  if (isNaN(d)) return iso;
  const date = (window.formatDateDE ? window.formatDateDE(iso.slice(0, 10)) : d.toLocaleDateString("de-AT"));
  const time = d.toLocaleTimeString("de-AT", { hour: "2-digit", minute: "2-digit" });
  return date + " · " + time + " Uhr";
}

function diffInventur(curr, prev) {
  const prevMap = new Map(((prev && prev.items) || []).map(it => [it.name, it.count]));
  const currMap = new Map((curr.items || []).map(it => [it.name, it.count]));
  const changes = [];
  (curr.items || []).forEach(it => {
    if (!prevMap.has(it.name)) changes.push({ type: "added", name: it.name, to: it.count });
    else if (prevMap.get(it.name) !== it.count) changes.push({ type: "changed", name: it.name, from: prevMap.get(it.name), to: it.count });
  });
  (((prev && prev.items) || [])).forEach(it => {
    if (!currMap.has(it.name)) changes.push({ type: "removed", name: it.name, from: it.count });
  });
  return changes;
}

function InventurVerlauf({ history }) {
  const [openId, setOpenId] = useStateAdmin(null);
  const ordered = (history || []).slice().reverse(); // newest first
  return (
    <div>
      <div className="section-h" style={{ margin: "28px 0 12px" }}>
        <h3>Inventur-Verlauf</h3>
        <span className="section-meta">{ordered.length} {ordered.length === 1 ? "Inventur" : "Inventuren"} · nachvollziehbar, was sich geändert hat</span>
      </div>
      {ordered.length === 0 ? (
        <div className="card card-pad-lg"><div className="empty-state">
          <h3>Noch keine Inventur erfasst</h3>
          <p>Sobald du eine Inventur abschließt, wird der Bestand hier mit Datum festgehalten – inklusive aller Änderungen seit der letzten Inventur.</p>
        </div></div>
      ) : ordered.map((entry, idx) => {
        const prev = ordered[idx + 1]; // next-older
        const changes = diffInventur(entry, prev);
        const open = openId === entry.id;
        return (
          <div key={entry.id} className="card card-pad mb-2">
            <div className="row" style={{ alignItems: "flex-start", gap: 12 }}>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div className="fw-700 text-sm">{fmtInventurDate(entry.date)}</div>
                <div className="text-xs muted" style={{ marginTop: 2 }}>
                  {entry.by ? "von " + entry.by + " · " : ""}{entry.total} Stück · {(entry.items || []).length} Artikel
                </div>
              </div>
              <button className="btn btn-secondary btn-sm" onClick={() => setOpenId(open ? null : entry.id)}>
                {open ? "Bestand ausblenden" : "Vollständiger Bestand"}
              </button>
            </div>

            <div style={{ marginTop: 10 }}>
              {!prev ? (
                <div className="inv-change inv-change-base">Erste Inventur – Ausgangsbestand erfasst.</div>
              ) : changes.length === 0 ? (
                <div className="inv-change inv-change-base">Keine Änderungen seit der letzten Inventur.</div>
              ) : (
                <div className="inv-change-list">
                  {changes.map((c, i) => {
                    if (c.type === "added") return (
                      <div key={i} className="inv-change"><span className="inv-tag inv-tag-add">Neu</span><span className="flex-1">{c.name}</span><span className="inv-delta inv-delta-up">+{c.to}</span></div>
                    );
                    if (c.type === "removed") return (
                      <div key={i} className="inv-change"><span className="inv-tag inv-tag-del">Entfernt</span><span className="flex-1">{c.name}</span><span className="inv-delta inv-delta-down">−{c.from}</span></div>
                    );
                    const delta = c.to - c.from;
                    return (
                      <div key={i} className="inv-change"><span className="inv-tag inv-tag-chg">Menge</span><span className="flex-1">{c.name}</span><span className="inv-change-nums">{c.from} → {c.to}</span><span className={"inv-delta " + (delta > 0 ? "inv-delta-up" : "inv-delta-down")}>{delta > 0 ? "+" : "−"}{Math.abs(delta)}</span></div>
                    );
                  })}
                </div>
              )}
            </div>

            {open && (
              <div className="inv-snapshot">
                {(entry.items || []).length === 0 ? (
                  <div className="muted text-sm">Keine Artikel erfasst.</div>
                ) : (entry.items || []).map((it, i) => (
                  <div key={i} className="inv-snapshot-row"><span className="flex-1">{it.name}</span><span className="inv-snapshot-count">{it.count}</span></div>
                ))}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

// ============ Trainer-facing Lager page ============
function LagerPage({ className, items, onChange, isAdmin, lastInventory, onInventur, history }) {
  const [editing, setEditing] = useStateAdmin(false);
  const total = items.reduce((s, it) => s + (it.count || 0), 0);
  const fmt = (window.formatDateDE) || ((x) => x);
  const canEdit = isAdmin && editing;

  const finish = () => { onInventur(items); setEditing(false); };

  return (
    <div>
      <div className="page-header">
        <div>
          <h1 className="page-title">Trainingsutensilien</h1>
          <p className="page-subtitle">
            Material-Bestand der Spielklasse {className}.{" "}
            {editing
              ? "Inventur läuft – Mengen und Artikel können jetzt bearbeitet werden."
              : isAdmin
                ? "Schreibgeschützt. Starte eine Inventur, um Änderungen vorzunehmen."
                : "Schreibgeschützt – nur ein Admin dieser Spielklasse kann eine Inventur durchführen."}
          </p>
        </div>
        {isAdmin && (
          editing ? (
            <div className="row gap-2">
              <button className="btn btn-secondary" onClick={() => setEditing(false)}>Abbrechen</button>
              <button className="btn" onClick={finish}><Icon.Check /> Inventur abschließen</button>
            </div>
          ) : (
            <button className="btn" onClick={() => setEditing(true)}><Icon.Box /> Inventur starten</button>
          )
        )}
      </div>
      {editing && (
        <div className="card card-pad mb-3" style={{ borderColor: "var(--warn)", background: "rgba(217,119,6,0.08)" }}>
          <div className="row gap-2 text-sm fw-600" style={{ color: "var(--warn)" }}>
            <Icon.Box /> Inventur-Modus aktiv – Änderungen werden mit „Inventur abschließen" als aktueller Stand bestätigt.
          </div>
        </div>
      )}
      <div className="stat-grid">
        <div className="stat">
          <div className="stat-label">Artikel</div>
          <div className="stat-value">{items.length}</div>
          <div className="stat-meta">verschiedene Materialien</div>
        </div>
        <div className="stat">
          <div className="stat-label">Stück gesamt</div>
          <div className="stat-value">{total}</div>
          <div className="stat-meta">über alle Artikel</div>
        </div>
        <div className="stat" style={lastInventory ? { borderColor: "var(--primary)", background: "var(--primary-pale)" } : null}>
          <div className="stat-label">Letzte Inventur</div>
          <div className="stat-value" style={{ fontSize: 22, color: lastInventory ? "var(--primary)" : "var(--text-soft)" }}>{lastInventory ? fmt(lastInventory) : "—"}</div>
          <div className="stat-meta">{lastInventory ? "aktueller Stand bestätigt" : "noch keine Inventur"}</div>
        </div>
      </div>
      <div className="card card-pad-lg">
        <InventoryEditor items={items} onChange={onChange} readOnly={!canEdit} />
      </div>
      <InventurVerlauf history={history} />
    </div>
  );
}

// ============ Admin area ============
function AdminArea({
  classes, trainers, classData,
  onAddClass, onRenameClass, onDeleteClass,
  onAddTrainer, onUpdateTrainer, onDeleteTrainer,
  onInventoryChange, onToggleFeature, onSetPoolMode,
}) {
  const [tab, setTab] = useStateAdmin("classes");
  const [newClass, setNewClass] = useStateAdmin("");
  const [invClassId, setInvClassId] = useStateAdmin(classes[0]?.id || null);
  const [pendingClass, setPendingClass] = useStateAdmin(null);
  const [pendingTrainer, setPendingTrainer] = useStateAdmin(null);

  // new-trainer form
  const blankTrainer = { name: "", email: "", password: "", admin: false, inventoryAdmin: false, classIds: [] };
  const [draft, setDraft] = useStateAdmin(blankTrainer);

  const addClass = () => {
    const n = newClass.trim();
    if (!n) return;
    onAddClass(n);
    setNewClass("");
  };

  const toggleDraftClass = (cid) => {
    setDraft(d => ({
      ...d,
      classIds: d.classIds.includes(cid) ? d.classIds.filter(x => x !== cid) : [...d.classIds, cid],
    }));
  };

  const saveDraft = () => {
    if (!draft.name.trim() || !draft.email.trim() || !draft.password.trim()) return;
    onAddTrainer({ ...draft, name: draft.name.trim(), email: draft.email.trim() });
    setDraft(blankTrainer);
  };

  const invItems = (invClassId && classData[invClassId]?.inventory) || [];
  const invClass = classes.find(c => c.id === invClassId);

  return (
    <div>
      <div className="page-header">
        <div>
          <h1 className="page-title">Administration</h1>
          <p className="page-subtitle">Spielklassen, Trainer-Logins und Trainingsutensilien verwalten.</p>
        </div>
        <div className="view-tabs">
          <button className={"view-tab" + (tab === "classes" ? " active" : "")} onClick={() => setTab("classes")}>Spielklassen</button>
          <button className={"view-tab" + (tab === "trainers" ? " active" : "")} onClick={() => setTab("trainers")}>Trainer</button>
          <button className={"view-tab" + (tab === "inventory" ? " active" : "")} onClick={() => setTab("inventory")}>Trainingsutensilien</button>
        </div>
      </div>

      {/* ===== Spielklassen ===== */}
      {tab === "classes" && (
        <div>
          <div className="card card-pad mb-3">
            <div className="row gap-2" style={{ flexWrap: "wrap" }}>
              <input
                className="input"
                style={{ maxWidth: 240 }}
                placeholder="Neue Spielklasse (z.B. U11)"
                value={newClass}
                onChange={(e) => setNewClass(e.target.value)}
                onKeyDown={(e) => e.key === "Enter" && addClass()}
              />
              <button className="btn" onClick={addClass}><Icon.Plus /> Spielklasse anlegen</button>
            </div>
          </div>
          <div style={{ display: "grid", gap: 8 }}>
            {classes.map(c => {
              const cd = classData[c.id];
              const playerCount = cd?.players?.length || 0;
              const trainerCount = trainers.filter(t => (t.classIds || []).includes(c.id)).length;
              const feats = (cd && cd.features) || { matrix: true, history: true, jahresplan: true, lager: true };
              const poolMode = (cd && cd.poolMode) || "erweitert";
              const FEATURE_DEFS = [
                { key: "matrix", label: "Matrixplan" },
                { key: "history", label: "Historie" },
                { key: "jahresplan", label: "Jahresplan" },
                { key: "lager", label: "Trainingsutensilien" },
              ];
              return (
                <div key={c.id} className="card card-pad" style={{ display: "grid", gap: 12 }}>
                  <div className="row gap-3" style={{ flexWrap: "wrap" }}>
                    <div className="class-badge">{c.name}</div>
                    <input className="input input-sm" style={{ maxWidth: 160 }} value={c.name} onChange={(e) => onRenameClass(c.id, e.target.value)} />
                    <span className="text-sm muted flex-1">{playerCount} Spieler · {trainerCount} Trainer</span>
                    <button className="btn btn-icon btn-danger" onClick={() => setPendingClass(c)} title="Spielklasse löschen"><Icon.Trash /></button>
                  </div>
                  <div>
                    <div className="text-xs muted" style={{ marginBottom: 6, fontWeight: 600 }}>Spielerpool-Ansicht</div>
                    <div className="seg-control">
                      <button className={"seg-btn" + (poolMode !== "erweitert" ? " active" : "")} onClick={() => onSetPoolMode(c.id, "standard")}>Standard</button>
                      <button className={"seg-btn" + (poolMode === "erweitert" ? " active" : "")} onClick={() => onSetPoolMode(c.id, "erweitert")}>Erweitert</button>
                    </div>
                    <div className="text-xs muted" style={{ marginTop: 6 }}>
                      {poolMode === "erweitert"
                        ? "Sterne-Bewertung und Mannschafts-Zuteilung im Spielerpool sichtbar."
                        : "Ohne Bewertung – Sterne und Mannschafts-Zuteilung sind im Spielerpool ausgeblendet."}
                    </div>
                  </div>
                  <div>
                    <div className="text-xs muted" style={{ marginBottom: 6, fontWeight: 600 }}>Sichtbare Bereiche für Trainer</div>
                    <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                      {FEATURE_DEFS.map(f => (
                        <button key={f.key} className={"chip-toggle" + (feats[f.key] !== false ? " on" : "")} onClick={() => onToggleFeature(c.id, f.key)} style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
                          {feats[f.key] !== false ? <Icon.Check /> : null} {f.label}
                        </button>
                      ))}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      )}

      {/* ===== Trainer ===== */}
      {tab === "trainers" && (
        <div>
          <div className="card card-pad-lg mb-3">
            <div className="section-h" style={{ margin: "0 0 12px" }}><h3>Neuen Trainer anlegen</h3></div>
            <div className="settings-grid" style={{ gap: 16 }}>
              <div style={{ display: "grid", gap: 10 }}>
                <div><label className="label">Name</label><input className="input" value={draft.name} onChange={(e) => setDraft({ ...draft, name: e.target.value })} placeholder="Vor- und Nachname" /></div>
                <div><label className="label">E-Mail (Login)</label><input className="input" value={draft.email} onChange={(e) => setDraft({ ...draft, email: e.target.value })} placeholder="vorname@admiradornbirn.at" /></div>
                <div><label className="label">Passwort</label><input className="input" value={draft.password} onChange={(e) => setDraft({ ...draft, password: e.target.value })} placeholder="Passwort" /></div>
              </div>
              <div>
                <label className="label">Spielklassen</label>
                <div style={{ display: "flex", flexWrap: "wrap", gap: 8, marginBottom: 14 }}>
                  {classes.map(c => (
                    <button key={c.id} className={"chip-toggle" + (draft.classIds.includes(c.id) ? " on" : "")} onClick={() => toggleDraftClass(c.id)}>
                      {c.name}
                    </button>
                  ))}
                </div>
                <label className="row gap-2" style={{ cursor: "pointer", userSelect: "none" }}>
                  <span className={"checkbox" + (draft.admin ? " checked" : "")} onClick={() => setDraft({ ...draft, admin: !draft.admin })}>
                    {draft.admin && <Icon.Check />}
                  </span>
                  <span className="text-sm fw-600">Admin-Rechte (darf diesen Bereich verwalten)</span>
                </label>
                <label className="row gap-2 mt-2" style={{ cursor: "pointer", userSelect: "none" }}>
                  <span className={"checkbox" + (draft.inventoryAdmin ? " checked" : "")} onClick={() => setDraft({ ...draft, inventoryAdmin: !draft.inventoryAdmin })}>
                    {draft.inventoryAdmin && <Icon.Check />}
                  </span>
                  <span className="text-sm fw-600">Trainingsutensilien Verwaltung (darf Inventur durchführen)</span>
                </label>
                <button className="btn mt-4" onClick={saveDraft} disabled={!draft.name.trim() || !draft.email.trim() || !draft.password.trim()}>
                  <Icon.Plus /> Trainer anlegen
                </button>
              </div>
            </div>
          </div>

          <div style={{ display: "grid", gap: 10 }}>
            {trainers.map(t => (
              <div key={t.id} className="card card-pad">
                <div className="row gap-3" style={{ flexWrap: "wrap", alignItems: "flex-start" }}>
                  <div className="profile-avatar" style={{ width: 38, height: 38, fontSize: 13 }}>
                    {t.name.split(" ").map(s => s[0]).slice(0, 2).join("")}
                  </div>
                  <div style={{ flex: 1, minWidth: 220, display: "grid", gap: 8 }}>
                    <input className="input input-sm" value={t.name} onChange={(e) => onUpdateTrainer(t.id, { name: e.target.value })} />
                    <div className="row gap-2" style={{ flexWrap: "wrap" }}>
                      <input className="input input-sm" style={{ flex: 1, minWidth: 180 }} value={t.email} onChange={(e) => onUpdateTrainer(t.id, { email: e.target.value })} />
                      <input className="input input-sm" style={{ width: 130 }} value={t.password} onChange={(e) => onUpdateTrainer(t.id, { password: e.target.value })} />
                    </div>
                    <div style={{ display: "flex", flexWrap: "wrap", gap: 6 }}>
                      {classes.map(c => {
                        const on = (t.classIds || []).includes(c.id);
                        return (
                          <button key={c.id} className={"chip-toggle" + (on ? " on" : "")} onClick={() => {
                            const next = on ? t.classIds.filter(x => x !== c.id) : [...(t.classIds || []), c.id];
                            onUpdateTrainer(t.id, { classIds: next });
                          }}>{c.name}</button>
                        );
                      })}
                    </div>
                    <label className="row gap-2" style={{ cursor: "pointer", userSelect: "none" }}>
                      <span className={"checkbox" + (t.admin ? " checked" : "")} onClick={() => onUpdateTrainer(t.id, { admin: !t.admin })}>
                        {t.admin && <Icon.Check />}
                      </span>
                      <span className="text-sm">Admin-Rechte</span>
                    </label>
                    <label className="row gap-2" style={{ cursor: "pointer", userSelect: "none" }}>
                      <span className={"checkbox" + (t.inventoryAdmin ? " checked" : "")} onClick={() => onUpdateTrainer(t.id, { inventoryAdmin: !t.inventoryAdmin })}>
                        {t.inventoryAdmin && <Icon.Check />}
                      </span>
                      <span className="text-sm">Trainingsutensilien Verwaltung</span>
                    </label>
                  </div>
                  <button className="btn btn-icon btn-danger" onClick={() => setPendingTrainer(t)} title="Trainer löschen"><Icon.Trash /></button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* ===== Lager ===== */}
      {tab === "inventory" && (
        <div>
          <div className="card card-pad mb-3">
            <label className="label">Spielklasse</label>
            <select className="select" style={{ maxWidth: 240 }} value={invClassId || ""} onChange={(e) => setInvClassId(e.target.value)}>
              {classes.map(c => <option key={c.id} value={c.id}>{c.name}</option>)}
            </select>
          </div>
          {invClass ? (
            <div className="card card-pad-lg">
              <div className="section-h" style={{ margin: "0 0 12px" }}>
                <h3>Trainingsutensilien — Spielklasse {invClass.name}</h3>
                <span className="section-meta">Standard-Artikel + eigene</span>
              </div>
              <InventoryEditor items={invItems} onChange={(items) => onInventoryChange(invClassId, items)} />
            </div>
          ) : (
            <div className="card card-pad-lg"><div className="empty-state"><h3>Keine Spielklasse</h3><p>Lege zuerst eine Spielklasse an.</p></div></div>
          )}
        </div>
      )}

      {pendingClass && (
        <div className="modal-backdrop" onClick={() => setPendingClass(null)}>
          <div className="modal" style={{ maxWidth: 420 }} onClick={(e) => e.stopPropagation()}>
            <div className="modal-head"><h3>Spielklasse löschen?</h3></div>
            <div className="modal-body">
              <p style={{ margin: 0, fontSize: 14, lineHeight: 1.5 }}>
                Soll die Spielklasse <strong>{pendingClass.name}</strong> wirklich gelöscht werden?
                Spielerpool, Pläne und Trainingsutensilien dieser Klasse gehen dabei verloren. Das kann nicht rückgängig gemacht werden.
              </p>
            </div>
            <div className="modal-foot">
              <button className="btn btn-secondary" onClick={() => setPendingClass(null)}>Abbrechen</button>
              <button className="btn" style={{ background: "var(--danger)" }} onClick={() => { onDeleteClass(pendingClass.id); setPendingClass(null); }}>
                Endgültig löschen
              </button>
            </div>
          </div>
        </div>
      )}

      {pendingTrainer && (
        <div className="modal-backdrop" onClick={() => setPendingTrainer(null)}>
          <div className="modal" style={{ maxWidth: 420 }} onClick={(e) => e.stopPropagation()}>
            <div className="modal-head"><h3>Trainer löschen?</h3></div>
            <div className="modal-body">
              <p style={{ margin: 0, fontSize: 14, lineHeight: 1.5 }}>
                Soll der Trainer <strong>{pendingTrainer.name}</strong> wirklich gelöscht werden?
                Der Login ({pendingTrainer.email}) wird dabei entfernt.
              </p>
            </div>
            <div className="modal-foot">
              <button className="btn btn-secondary" onClick={() => setPendingTrainer(null)}>Abbrechen</button>
              <button className="btn" style={{ background: "var(--danger)" }} onClick={() => { onDeleteTrainer(pendingTrainer.id); setPendingTrainer(null); }}>
                Endgültig löschen
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

window.AdminArea = AdminArea;
window.LagerPage = LagerPage;
window.InventoryEditor = InventoryEditor;
