import React, { useEffect, useMemo, useState, useRef } from "react";
import {
  listUsers,
  getUserById,
  createUser,
  updateUser,
  deleteUser,
  setUserPin,
  setUserPassword,
  adjustUserBalance,
  listBookings,
  getProducts 
} from "../../api";
import { FiEdit2 } from "react-icons/fi";

function cx(...arr) {
  return arr.filter(Boolean).join(" ");
}

function euro(cents) {
  if (typeof cents !== "number") return "—";
  return (cents / 100).toFixed(2) + " €";
}

const defaultParams = {
  q: "",
  role: "",
  active: "",
  balance_lt: "",
  limit: 25,
  offset: 0,
  sort: "name",
  order: "asc",
};

function NiceDropdown({
  value,
  onChange,
  options,
  placeholder = "Auswählen…",
  className = "",
  buttonClassName = "",
  minWidth = 160,
}) {
  const [open, setOpen] = useState(false);
  const btnRef = useRef(null);
  const popRef = useRef(null);

  const current = useMemo(
    () => options?.find((o) => String(o.value) === String(value)) ?? null,
    [options, value]
  );

  useEffect(() => {
    function onDoc(e) {
      if (!open) return;
      if (popRef.current?.contains(e.target)) return;
      if (btnRef.current?.contains(e.target)) return;
      setOpen(false);
    }
    document.addEventListener("mousedown", onDoc);
    return () => document.removeEventListener("mousedown", onDoc);
  }, [open]);

  return (
    <div className={`relative ${className}`} style={{ minWidth }}>
      <button
        type="button"
        ref={btnRef}
        onClick={() => setOpen((o) => !o)}
        className={
          "w-full bg-black/40 text-white rounded-xl border border-white/20 px-3 py-2 " +
          "text-left flex items-center justify-between hover:bg-white/10 " +
          buttonClassName
        }
        aria-haspopup="listbox"
        aria-expanded={open}
      >
        <span className={current ? "" : "text-white/60"}>
          {current?.label ?? placeholder}
        </span>
        <span className="text-white/60">▾</span>
      </button>

      {open && (
        <div
          ref={popRef}
          className="absolute z-20 mt-2 w-full rounded-xl border border-white/15 bg-black/80 backdrop-blur p-1 shadow-2xl"
          role="listbox"
        >
          {options.map((opt) => {
            const active = String(opt.value) === String(value);
            return (
              <button
                key={String(opt.value)}
                type="button"
                onClick={() => {
                  onChange(opt.value);
                  setOpen(false);
                }}
                className={
                  "w-full text-left px-3 py-2 rounded-lg transition " +
                  (active ? "bg-white/15 text-white" : "text-white/80 hover:bg-white/10")
                }
                role="option"
                aria-selected={active}
              >
                {opt.label}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

export default function UsersPage() {
  // Query-State
  const [params, setParams] = useState(defaultParams);
  const [rows, setRows] = useState([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState(null);

  // Drawer-State 
  const [open, setOpen] = useState(false);
  const [selectedId, setSelectedId] = useState(null);
  const [detail, setDetail] = useState(null);
  const [detailLoading, setDetailLoading] = useState(false);
  const [detailErr, setDetailErr] = useState(null);
  const [dirty, setDirty] = useState(false);

  // Viewer-State 
  const [viewerOpen, setViewerOpen] = useState(false);
  const [viewerUser, setViewerUser] = useState(null);
  const [viewerBookings, setViewerBookings] = useState([]);
  const [viewerLoading, setViewerLoading] = useState(false);
  const [viewerErr, setViewerErr] = useState(null);

  // Forms
  const [formBase, setFormBase] = useState({
    name: "", email: "", alias: "", paypal_email: "",
    role: "user", is_active: true,
  });
  const [formSec, setFormSec] = useState({ pin: "", password: "" });
  const [formAdj, setFormAdj] = useState({ amount_eur: "", reason: "" });

  // Create modal
  const [creating, setCreating] = useState(false);
  const [createForm, setCreateForm] = useState({
    name: "", email: "", alias: "", paypal_email: "",
    role: "user", password: "", pin: "",
  });
  const [createErr, setCreateErr] = useState(null);
  const [busy, setBusy] = useState(false);

  // --- Daten laden: Liste ---
  useEffect(() => {
    let alive = true;
    setLoading(true); setErr(null);
    (async () => {
      try {
        const data = await listUsers(cleanParams(params));
        if (!alive) return;
        setRows(Array.isArray(data) ? data : []);
      } catch (e) {
        if (alive) setErr(e);
      } finally {
        if (alive) setLoading(false);
      }
    })();
    return () => { alive = false; };
  }, [params.q, params.role, params.active, params.balance_lt, params.limit, params.offset, params.sort, params.order]);

  // --- Daten laden: Bearbeiten ---
  useEffect(() => {
    if (!open || !selectedId) return;
    let alive = true;
    setDetailLoading(true); setDetailErr(null);
    (async () => {
      try {
        const data = await getUserById(selectedId);
        if (!alive) return;
        setDetail(data);
        setFormBase({
          name: data.name ?? "",
          email: data.email ?? "",
          alias: data.alias ?? "",
          paypal_email: data.paypal_email ?? "",
          role: data.role ?? "user",
          is_active: Boolean(data.is_active),
        });
        setFormSec({ pin: "", password: "" });
        setFormAdj({ amount_eur: "", reason: "" });
        setDirty(false);
      } catch (e) {
        if (alive) setDetailErr(e);
      } finally {
        if (alive) setDetailLoading(false);
      }
    })();
    return () => { alive = false; };
  }, [open, selectedId]);

  const totalShown = rows.length;

  // --- Helpers ---
  function setParam(k, v) {
    setParams((p) => ({ ...p, [k]: v, ...(k !== "offset" ? { offset: 0 } : null) }));
  }
  function cleanParams(p) {
    const out = {};
    for (const [k, v] of Object.entries(p)) if (v !== "" && v != null) out[k] = v;
    return out;
  }
  function onSort(key) {
    setParams((p) => {
      const order = p.sort === key ? (p.order === "asc" ? "desc" : "asc") : "asc";
      return { ...p, sort: key, order, offset: 0 };
    });
  }
  function openDetail(id) { setSelectedId(id); setOpen(true); }
  function closeDetail(force=false) {
    if (!force && dirty && !confirm("Nicht gespeicherte Änderungen verwerfen?")) return;
    setOpen(false); setSelectedId(null); setDetail(null); setDetailErr(null); setDirty(false);
  }


// --- Viewer ---
async function openViewer(id) {
  setViewerOpen(true);
  setViewerLoading(true);
  setViewerErr(null);
  setViewerUser(null);
  setViewerBookings([]);

  try {
    const user = await getUserById(id);
    setViewerUser(user);

    const data = await listBookings({ user_id: id, limit: 10, offset: 0 });
    let list = Array.isArray(data) ? data : (data.items || data.results || data.data || []);

    list = list.filter(b => (b.user_id === id) || (b.user?.id === id));

    const mapped = list.map(b => {
      const total =
        (typeof b.total_cents === "number" && b.total_cents) ??
        ((typeof b.price_cents === "number" ? b.price_cents : (b.product?.price_cents ?? 0)) *
          (typeof b.amount === "number" ? b.amount : 1));

      return {
        id: b.id,
        created_at: b.created_at || b.timestamp || null,               // Zeitfeld ist optional
        type: b.type || b.kind || "booking",
        product_name: b.product_name || b.product?.name || `#${b.product_id ?? "?"}`,
        amount_cents: total != null ? -Math.abs(Number(total)) : null, // Ausgaben negativ
      };
    });

    // Neueste zuerst; Fallback über ID
    mapped.sort((a, b) =>
      (new Date(b.created_at || 0) - new Date(a.created_at || 0)) ||
      ((b.id ?? 0) - (a.id ?? 0))
    );

    setViewerBookings(mapped.slice(0, 10));
  } catch (e) {
    setViewerErr(e);
  } finally {
    setViewerLoading(false);
  }
}



  
  function closeViewer() {
    setViewerOpen(false);
    setViewerUser(null);
    setViewerBookings([]);
    setViewerErr(null);
  }

  // --- Aktionen ---
  async function saveBase() {
    if (!selectedId) return;
    setBusy(true);
    try {
      const payload = {
        name: formBase.name,
        email: formBase.email,
        alias: formBase.alias,
        paypal_email: formBase.paypal_email || null,
        role: formBase.role,
        is_active: formBase.is_active,
      };
      const updated = await updateUser(selectedId, payload);
      setDetail(updated);
      setDirty(false);
      setParams((p) => ({ ...p }));
    } catch (e) {
      alert(e.status === 403 ? "Aktion verweigert: Management-Login erforderlich." : `Fehler beim Speichern: ${e.message || e}`);
    } finally { setBusy(false); }
  }

  async function saveSecurity() {
    if (!selectedId) return;
    setBusy(true);
    try {
      if (formSec.pin && formSec.pin.length === 6) await setUserPin(selectedId, formSec.pin);
      if (formSec.password && formSec.password.length >= 8) await setUserPassword(selectedId, formSec.password);
      setFormSec({ pin: "", password: "" });
      alert("Sicherheitsdaten aktualisiert.");
    } catch (e) {
      alert(e.status === 403 ? "Aktion verweigert: Management-Login erforderlich." : `Fehler Sicherheit: ${e.message || e}`);
    } finally { setBusy(false); }
  }

  async function runAdjustment() {
    if (!selectedId) return;
    const cents = Math.round(parseFloat((formAdj.amount_eur || "").replace(",", ".")) * 100);
    if (!Number.isFinite(cents) || cents === 0) { alert("Betrag ungültig oder 0."); return; }
    if (!formAdj.reason || formAdj.reason.trim().length < 1) { alert("Bitte Grund angeben."); return; }
    setBusy(true);
    try {
      await adjustUserBalance(selectedId, cents, formAdj.reason.trim());
      const data = await getUserById(selectedId);
      setDetail(data);
      setFormAdj({ amount_eur: "", reason: "" });
      setDirty(false);
      setParams((p) => ({ ...p }));
    } catch (e) {
      alert(e.status === 403 ? "Aktion verweigert: Management-Login erforderlich." : `Fehler Kontokorrektur: ${e.message || e}`);
    } finally { setBusy(false); }
  }

  async function removeUser() {
    if (!selectedId) return;
    if (!confirm("Diesen Nutzer wirklich löschen?")) return;
    setBusy(true);
    try {
      await deleteUser(selectedId);
      closeDetail(true);
      setParams((p) => ({ ...p }));
    } catch (e) {
      alert(e.status === 403 ? "Aktion verweigert: Management-Login erforderlich." : `Löschen fehlgeschlagen: ${e.message || e}`);
    } finally { setBusy(false); }
  }

  async function createNewUser() {
    const f = createForm;
    if (!f.name || !f.email || !f.password || !f.pin) { setCreateErr("Name, E-Mail, Passwort und PIN sind Pflicht."); return; }
    if (f.pin.length !== 6) { setCreateErr("PIN muss genau 6 Zeichen haben."); return; }
    if (f.password.length < 8) { setCreateErr("Passwort mindestens 8 Zeichen."); return; }
    setCreateErr(null);
    setBusy(true);
    try {
      await createUser({
        name: f.name, email: f.email,
        alias: f.alias || null,
        paypal_email: f.paypal_email || null,
        role: f.role || "user",
        password: f.password, pin: f.pin,
      });
      setCreating(false);
      setCreateForm({ name:"", email:"", alias:"", paypal_email:"", role:"user", password:"", pin:"" });
      setParams((p) => ({ ...p }));
    } catch (e) {
      setCreateErr(e.status === 403 ? "Management-Login erforderlich." : (e.message || String(e)));
    } finally { setBusy(false); }
  }

  const sortIcon = useMemo(() => {
    return (key) => params.sort === key ? (
      <span className="ml-1 text-white/50">{params.order === "asc" ? "▲" : "▼"}</span>
    ) : null;
  }, [params.sort, params.order]);

  return (
    <div className="space-y-4">
      {/* Gesamtkasten mit integrierter Toolbar + Tabelle + Pagination */}
      <div className="rounded-2xl bg-white/5 border border-cyan-400/20">
        {/* Toolbar oben im Kasten */}
        <div className="px-4 py-3 border-b border-white/10 flex flex-col gap-3 md:flex-row md:items-center md:justify-between">
          <h2 className="text-white/90 font-semibold">Nutzerverwaltung</h2>

          <div className="flex flex-wrap gap-2">
            {/* Suche */}
            <div className="relative">
              <input
                className="px-3 py-2 rounded-xl bg-white/5 border border-white/10 text-white/90 placeholder-white/40 focus:outline-none focus:border-cyan-400/40"
                placeholder="Suche (Name, E-Mail, Alias)"
                value={params.q}
                onChange={(e) => setParam("q", e.target.value)}
              />
            </div>

            

            {/* Rollen-Filter */}
            <NiceDropdown
              value={params.role}
              onChange={(v) => setParam("role", v)}
              placeholder="Alle Rollen"
              options={[
                { value: "", label: "Alle Rollen" },
                { value: "user", label: "User" },
                { value: "manager", label: "Manager" },
                { value: "admin", label: "Admin" },
              ]}
            />
            
            {/* Aktiv-Filter */}
            <NiceDropdown
              value={params.active}
              onChange={(v) => setParam("active", v)}
              placeholder="Aktiv/Inaktiv"
              options={[
                { value: "", label: "Alle" },
                { value: "true", label: "Aktiv" },
                { value: "false", label: "Inaktiv" },
              ]}
            />
            


            {/* Quickfilter: Kontostand < 0 */}
            <button
              className={cx(
                "px-3 py-2 rounded-xl border",
                params.balance_lt === "0"
                  ? "bg-amber-500/20 border-amber-400/40 text-amber-100"
                  : "bg-white/5 border-white/10 text-white/80 hover:bg-white/10"
              )}
              onClick={() => setParam("balance_lt", params.balance_lt === "0" ? "" : "0")}
              title="Kontostand < 0"
            >
              &lt; 0 €
            </button>

            {/* Nutzer anlegen */}
            <button
              className="px-3 py-2 rounded-xl bg-emerald-500/20 text-emerald-100 border border-emerald-400/30 hover:bg-emerald-500/30"
              onClick={() => setCreating(true)}
            >
               Nutzer anlegen
            </button>
          </div>
        </div>

        {/* Tabelle */}
        <div className="overflow-x-auto">
          <table className="min-w-full text-sm">
            <thead className="text-white/60">
              <tr>
                <Th onClick={() => onSort("name")} active={params.sort === "name"} order={params.order}>Name</Th>
                <Th onClick={() => onSort("email")} active={params.sort === "email"} order={params.order}>E-Mail</Th>
                <Th>Alias</Th>
                <Th onClick={() => onSort("role")} active={params.sort === "role"} order={params.order}>Rolle</Th>
                <Th onClick={() => onSort("balance_cents")} active={params.sort === "balance_cents"} order={params.order}>Kontostand</Th>
                <Th onClick={() => onSort("is_active")} active={params.sort === "is_active"} order={params.order}>Status</Th>
                <Th>Aktionen</Th>
              </tr>
            </thead>
            <tbody className="text-white/85">
              {loading ? (
                <tr><td className="p-4 text-white" colSpan={7}>Lade…</td></tr>
              ) : err ? (
                <tr><td className="p-4 text-red-300" colSpan={7}>Fehler: {String(err.message || err)}</td></tr>
              ) : rows.length === 0 ? (
                <tr><td className="p-4 text-white/70" colSpan={7}>Keine Nutzer gefunden.</td></tr>
              ) : (
                rows.map((u) => (
                  <tr key={u.id} className="border-t border-white/10">
                    <td className="py-2 px-3">{u.name}</td>
                    <td className="py-2 px-3">{u.email}</td>
                    <td className="py-2 px-3">{u.alias || "—"}</td>
                    <td className="py-2 px-3">{u.role}</td>
                    <td className={cx(
                      "py-2 px-3 font-mono",
                      typeof u.balance_cents === "number" && u.balance_cents < 0
                        ? "text-red-300"
                        : u.balance_cents < 500
                        ? "text-amber-200"
                        : "text-white/90"
                    )}>
                      {euro(u.balance_cents)}
                    </td>
                    <td className="py-2 px-3">{u.is_active ? "aktiv" : "inaktiv"}</td>
                    <td className="py-2 px-3">
                      <div className="flex items-center gap-2">
                        {/* Anzeigen (Auge) */}
                        <button
                          className="p-1.5 rounded-lg bg-white/10 hover:bg-white/15 border border-white/10 text-white/80"
                          title="Details & Buchungen ansehen"
                          onClick={() => openViewer(u.id)}
                        >
                          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" className="pointer-events-none">
                            <path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z" stroke="currentColor" strokeWidth="1.8"/>
                            <circle cx="12" cy="12" r="3" stroke="currentColor" strokeWidth="1.8"/>
                          </svg>
                        </button>

                        {/* Bearbeiten (Stift / FiEdit2) */}
                        <button
                          className="p-1.5 rounded-lg bg-white/10 hover:bg-white/15 border border-white/10 text-white/80"
                          title="Bearbeiten"
                          onClick={() => openDetail(u.id)}
                        >
                          <FiEdit2 size={18} />
                        </button>
                      </div>
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </table>
        </div>

        {/* Pagination im Kasten */}
        <div className="flex items-center justify-between px-4 py-3 text-white/70 border-t border-white/10">
          <div>Zeige {totalShown} Einträge</div>
          <div className="flex gap-2">
            <button
              className="px-3 py-1 rounded-lg bg-white/10 border border-white/10 disabled:opacity-40"
              disabled={params.offset <= 0}
              onClick={() => setParam("offset", Math.max(0, params.offset - params.limit))}
            >
              ← Zurück
            </button>
            <button
              className="px-3 py-1 rounded-lg bg-white/10 border border-white/10 disabled:opacity-40"
              disabled={rows.length < params.limit}
              onClick={() => setParam("offset", params.offset + params.limit)}
            >
              Weiter →
            </button>
          </div>
        </div>
      </div>

      

        {/* Drawer (Bearbeiten) – fixed */}
        {open && (
          <div className="fixed inset-0 z-40">
            {/* 60% transparenter Hintergrund */}
            <div className="fixed inset-0 bg-black/60" onClick={() => closeDetail(false)} />
        
            {/* Panel */}
            <div className="fixed right-0 top-0 h-full w-full sm:w-[560px] bg-black border-l border-white/10 shadow-xl overflow-y-auto z-50">
              {/* Header */}
              <div className="p-5 border-b border-white/10 flex items-center justify-between">
                <h3 className="text-white/90 font-semibold">Nutzer bearbeiten</h3>
                <button
                  className="px-3 py-1 rounded-lg bg-gray-800 hover:bg-gray-700 border border-gray-600 text-gray-100"
                  onClick={() => closeDetail(false)}
                >
                  Schließen
                </button>
              </div>
        
              {/* Inhalt */}
              <div className="p-5 space-y-6">
                {detailLoading ? (
                  <div className="text-white">Lade Details…</div>
                ) : detailErr ? (
                  <div className="text-red-300">Fehler: {String(detailErr.message || detailErr)}</div>
                ) : !detail ? (
                  <div className="text-white/70">Keine Daten.</div>
                ) : (
                  <>
                    {/* Stammdaten */}
                    <section className="space-y-3">
                      <h4 className="text-white/85 font-semibold">Daten</h4>
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <TextField
                          label="Name"
                          value={formBase.name}
                          onChange={(v) => { setFormBase(f => ({ ...f, name: v })); setDirty(true); }}
                          inputClassName="bg-gray-800 text-gray-100 border-gray-600 placeholder:text-gray-400 focus:ring-2 focus:ring-gray-400/40"
                        />
                        <TextField
                          label="E-Mail"
                          value={formBase.email}
                          onChange={(v) => { setFormBase(f => ({ ...f, email: v })); setDirty(true); }}
                          inputClassName="bg-gray-800 text-gray-100 border-gray-600 placeholder:text-gray-400 focus:ring-2 focus:ring-gray-400/40"
                        />
                        <TextField
                          label="Alias"
                          value={formBase.alias}
                          onChange={(v) => { setFormBase(f => ({ ...f, alias: v })); setDirty(true); }}
                          inputClassName="bg-gray-800 text-gray-100 border-gray-600 placeholder:text-gray-400 focus:ring-2 focus:ring-gray-400/40"
                        />
                        <TextField
                          label="PayPal"
                          value={formBase.paypal_email}
                          onChange={(v) => { setFormBase(f => ({ ...f, paypal_email: v })); setDirty(true); }}
                          inputClassName="bg-gray-800 text-gray-100 border-gray-600 placeholder:text-gray-400 focus:ring-2 focus:ring-gray-400/40"
                        />

                        {/* Rolle */}
                        <div className="space-y-1">
                          <div className="text-xs text-white/60">Rolle</div>
                          <NiceDropdown
                            value={formBase.role}
                            onChange={(v) => { setFormBase(f => ({ ...f, role: v })); setDirty(true); }}
                            placeholder="Rolle wählen"
                            options={[
                              { value: "user",    label: "User" },
                              { value: "manager", label: "Manager" },
                              { value: "admin",   label: "Admin" },
                            ]}
                            minWidth={200}
                            buttonClassName="bg-gray-800 text-gray-100 border-gray-600 hover:bg-gray-700"
                          />
                        </div>
                          
                        {/* Status */}
                        <div className="space-y-1">
                          <div className="text-xs text-white/60">Status</div>
                          <NiceDropdown
                            value={formBase.is_active ? "true" : "false"}
                            onChange={(v) => { setFormBase(f => ({ ...f, is_active: v === "true" })); setDirty(true); }}
                            placeholder="Status wählen"
                            options={[
                              { value: "true",  label: "Aktiv" },
                              { value: "false", label: "Inaktiv" },
                            ]}
                            minWidth={200}
                            buttonClassName="bg-gray-800 text-gray-100 border-gray-600 hover:bg-gray-700"
                          />
                        </div>
                      </div>
                          
                      <div className="flex gap-2">
                        <button
                          className="px-4 py-2 rounded-xl bg-emerald-500/20 text-emerald-100 border border-emerald-400/30 hover:bg-emerald-500/30 disabled:opacity-50"
                          onClick={saveBase}
                          disabled={busy || !dirty}
                        >
                          Speichern
                        </button>
                        <button
                          className="px-4 py-2 rounded-xl bg-gray-800 border border-gray-600 hover:bg-gray-700 text-gray-100 disabled:opacity-50"
                          onClick={() => {
                            setFormBase({
                              name: detail.name ?? "",
                              email: detail.email ?? "",
                              alias: detail.alias ?? "",
                              paypal_email: detail.paypal_email ?? "",
                              role: detail.role ?? "user",
                              is_active: Boolean(detail.is_active),
                            });
                            setDirty(false);
                          }}
                          disabled={busy || !dirty}
                        >
                          Zurücksetzen
                        </button>
                      </div>
                    </section>
                        
                    {/* Sicherheit */}
                    <section className="space-y-3">
                      <h4 className="text-white/85 font-semibold">Sicherheit</h4>
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <TextField
                          label="Neue PIN (6)"
                          value={formSec.pin}
                          onChange={(v) => setFormSec(s => ({ ...s, pin: v }))}
                          maxLength={6}
                          inputClassName="bg-gray-800 text-gray-100 border-gray-600 placeholder:text-gray-400 focus:ring-2 focus:ring-gray-400/40"
                        />
                        <TextField
                          label="Neues Passwort (≥8)"
                          value={formSec.password}
                          onChange={(v) => setFormSec(s => ({ ...s, password: v }))}
                          type="password"
                          inputClassName="bg-gray-800 text-gray-100 border-gray-600 placeholder:text-gray-400 focus:ring-2 focus:ring-gray-400/40"
                        />
                      </div>
                      <button
                        className="px-4 py-2 rounded-xl bg-cyan-500/20 text-cyan-100 border border-cyan-400/30 hover:bg-cyan-500/30 disabled:opacity-50"
                        onClick={saveSecurity}
                        disabled={busy || (!formSec.pin && !formSec.password)}
                      >
                        Anwenden
                      </button>
                    </section>
                        
                    {/* Konto */}
                    <section className="space-y-3">
                      <h4 className="text-white/85 font-semibold">Konto</h4>
                      <div className="text-white/70">
                        Aktueller Kontostand: <span className="font-mono">{euro(detail.balance_cents)}</span>
                      </div>
                      <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                        <TextField
                          label="Betrag (€, +/-)"
                          value={formAdj.amount_eur}
                          onChange={(v) => setFormAdj(a => ({ ...a, amount_eur: v }))}
                          placeholder="+10.00"
                          inputClassName="bg-gray-800 text-gray-100 border-gray-600 placeholder:text-gray-400 focus:ring-2 focus:ring-gray-400/40"
                        />
                        <TextField
                          label="Grund"
                          value={formAdj.reason}
                          onChange={(v) => setFormAdj(a => ({ ...a, reason: v }))}
                          inputClassName="bg-gray-800 text-gray-100 border-gray-600 placeholder:text-gray-400 focus:ring-2 focus:ring-gray-400/40"
                        />
                      </div>
                      <button
                        className="px-4 py-2 rounded-xl bg-amber-500/20 text-amber-100 border border-amber-400/30 hover:bg-amber-500/30 disabled:opacity-50"
                        onClick={runAdjustment}
                        disabled={busy}
                      >
                        Korrektur verbuchen
                      </button>
                    </section>
                        
                    {/* Gefahrzone */}
                    <section className="space-y-3">
                      <h4 className="text-red-300 font-semibold"></h4>
                      <button
                        className="px-4 py-2 rounded-xl bg-red-500/20 text-red-100 border border-red-400/30 hover:bg-red-500/30 disabled:opacity-50"
                        onClick={removeUser}
                        disabled={busy}
                      >
                        Nutzer löschen
                      </button>
                    </section>
                  </>
                )}
              </div>
            </div>
          </div>
        )}

      {/* Viewer Modal (Read-Only) */}
      {viewerOpen && (
        <div className="fixed inset-0 z-50">
          <div className="fixed inset-0 bg-black/60" onClick={closeViewer} />
          <div className="fixed left-1/2 top-10 -translate-x-1/2 w-full max-w-4xl bg-slate-900 border border-white/10 rounded-2xl shadow-2xl p-5">
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-white/90 font-semibold">Nutzerdaten & Buchungen</h3>
              <button
                className="px-3 py-1 rounded-lg bg-white/10 hover:bg-white/15 border border-white/10 text-white/80"
                onClick={closeViewer}
              >
                Schließen
              </button>
            </div>

            {viewerLoading ? (
              <div className="text-white">Lade…</div>
            ) : viewerErr ? (
              <div className="text-red-300">Fehler: {String(viewerErr.message || viewerErr)}</div>
            ) : !viewerUser ? (
              <div className="text-white/70">Keine Daten.</div>
            ) : (
              <div className="space-y-6">
                {/* Stammdaten */}
                <section className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <ReadField label="Name" value={viewerUser.name} />
                  <ReadField label="E-Mail" value={viewerUser.email} />
                  <ReadField label="Alias" value={viewerUser.alias || "—"} />
                  <ReadField label="PayPal" value={viewerUser.paypal_email || "—"} />
                  <ReadField label="Rolle" value={viewerUser.role} />
                  <ReadField label="Status" value={viewerUser.is_active ? "aktiv" : "inaktiv"} />
                  <ReadField label="Kontostand" value={euro(viewerUser.balance_cents)} />
                  <ReadField label="Erstellt" value={formatDate(viewerUser.created_at)} />
                </section>

                {/* Buchungen */}
                <section>
                  <div className="text-white/85 font-semibold mb-2">Letzte Buchungen</div>
                  <div className="rounded-xl bg-white/5 border border-white/10 overflow-x-auto">
                    <table className="min-w-full text-sm">
                      <thead className="text-white/60">
                        <tr>
                          <th className="text-left py-2 px-3">Zeit</th>
                          <th className="text-left py-2 px-3">Typ</th>
                          <th className="text-left py-2 px-3">Produkt</th>
                          <th className="text-right py-2 px-3">Betrag</th>
                        </tr>
                      </thead>
                      <tbody className="text-white/85">
                        {Array.isArray(viewerBookings) && viewerBookings.length > 0 ? viewerBookings.map((b) => (
                          <tr key={b.id} className="border-t border-white/10">
                            <td className="py-2 px-3">{formatDate(b.created_at)}</td>
                            <td className="py-2 px-3">{b.type || b.kind || "—"}</td>
                            <td className="py-2 px-3">{b.product_name || (b.product_id != null ? `#${b.product_id}` : "—")}</td>
                            <td className={cx("py-2 px-3 text-right font-mono", (b.amount_cents ?? 0) < 0 ? "text-red-300" : "text-white/90")}>
                              {typeof b.amount_cents === "number" ? euro(b.amount_cents) : "—"}
                            </td>
                          </tr>
                        )) : (
                          <tr><td className="py-3 px-3 text-white/70" colSpan={4}>Keine Buchungen gefunden.</td></tr>
                        )}
                      </tbody>
                    </table>
                  </div>
                </section>
              </div>
            )}
          </div>
        </div>
      )}

      {/* Create Modal */}
      {creating && (
        <div className="fixed inset-0 z-40">
          <div className="fixed inset-0 bg-black/60" onClick={() => setCreating(false)} />
          <div className="fixed left-1/2 top-24 -translate-x-1/2 w-full max-w-xl bg-slate-900 border border-white/10 rounded-2xl shadow-xl p-5">
            <div className="flex items-center justify-between mb-3">
              <h3 className="text-white/90 font-semibold">Nutzer anlegen</h3>
              <button
                className="px-3 py-1 rounded-lg bg-white/10 hover:bg-white/15 border border-white/10 text-white/80"
                onClick={() => setCreating(false)}
              >
                Schließen
              </button>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <TextField label="Name" value={createForm.name} onChange={(v) => setCreateForm(f => ({ ...f, name: v }))} />
              <TextField label="E-Mail" value={createForm.email} onChange={(v) => setCreateForm(f => ({ ...f, email: v }))} />
              <TextField label="Alias" value={createForm.alias} onChange={(v) => setCreateForm(f => ({ ...f, alias: v }))} />
              <TextField label="PayPal" value={createForm.paypal_email} onChange={(v) => setCreateForm(f => ({ ...f, paypal_email: v }))} />
              <SelectField
                label="Rolle"
                value={createForm.role}
                onChange={(v) => setCreateForm(f => ({ ...f, role: v }))}
                options={[
                  { value: "user", label: "user" },
                  { value: "manager", label: "manager" },
                  { value: "admin", label: "admin" },
                ]}
              />
              <TextField label="Passwort (≥8)" type="password" value={createForm.password} onChange={(v) => setCreateForm(f => ({ ...f, password: v }))} />
              <TextField label="PIN (6)" value={createForm.pin} onChange={(v) => setCreateForm(f => ({ ...f, pin: v }))} maxLength={6} />
            </div>
            {createErr && <div className="text-red-300 text-sm mt-2">{createErr}</div>}
            <div className="mt-4 flex justify-end gap-2">
              <button
                className="px-4 py-2 rounded-xl bg-white/10 border border-white/10 hover:bg-white/15 text-white/80"
                onClick={() => setCreating(false)}
              >
                Abbrechen
              </button>
              <button
                className="px-4 py-2 rounded-xl bg-emerald-500/20 text-emerald-100 border border-emerald-400/30 hover:bg-emerald-500/30 disabled:opacity-50"
                onClick={createNewUser}
                disabled={busy}
              >
                Anlegen
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/* ---------- kleine UI-Bausteine ---------- */

function Th({ children, onClick, active, order }) {
  return (
    <th
      className={cx("text-left py-2 px-3 select-none", onClick ? "cursor-pointer hover:text-white/80" : "")}
      onClick={onClick}
    >
      <span className="inline-flex items-center">
        {children}
        {active ? <span className="ml-1 text-white/50">{order === "asc" ? "▲" : "▼"}</span> : null}
      </span>
    </th>
  );
}

function TextField({
  label,
  value,
  onChange,
  type = "text",
  maxLength,
  placeholder,
  inputClassName = "",
}) {
  return (
    <label className="block">
      <div className="text-white/60 text-xs mb-1">{label}</div>
      <input
        type={type}
        value={value ?? ""}
        onChange={(e) => onChange(e.target.value)}
        maxLength={maxLength}
        placeholder={placeholder}
        className={cx(
          "w-full px-3 py-2 rounded-xl border bg-gray-800 text-gray-100",
          "border-gray-600 placeholder:text-gray-400",
          "focus:outline-none focus:ring-2 focus:ring-gray-400/40",
          inputClassName
        )}
      />
    </label>
  );
}


function SelectField({ label, value, onChange, options }) {
  return (
    <label className="block">
      <div className="text-white/60 text-xs mb-1">{label}</div>
      <select
        style={{ colorScheme: "white" }}
        className="w-full px-3 py-2 rounded-xl bg-slate-800 text-slate-100 border border-white/10 focus:outline-none border-3 focus:border-cyan-200/40"
        value={value}
        onChange={(e) => onChange(e.target.value)}
      >
        {options.map((o) => (
          <option key={o.value} value={o.value}>
            {o.label}
          </option>
        ))}
      </select>
    </label>
  );
}

function ReadField({ label, value }) {
  return (
    <div className="min-w-0">
      <div className="text-white/60 text-xs mb-1">{label}</div>
      <div className="px-3 py-2 rounded-xl bg-white/5 border border-white/10 text-white/90">{value ?? "—"}</div>
    </div>
  );
}

function formatDate(s) {
  if (!s) return "—";
  try {
    const d = new Date(s);
    return d.toLocaleString();
  } catch { return String(s); }
}

function SimpleDropdown({ value, onChange, options, placeholder }) {
  const [open, setOpen] = React.useState(false);

  return (
    <div className="relative">
      <button
        type="button"
        onClick={() => setOpen(o => !o)}
        className="w-40 flex items-center justify-between px-3 py-2 rounded-lg 
                   bg-white/10 border border-white/20 text-white"
      >
        <span>{options.find(o => o.value === value)?.label || placeholder}</span>
        <span className={`transition-transform ${open ? "rotate-180" : ""}`}>▼</span>
      </button>

      {open && (
        <div className="absolute z-50 mt-2 w-40 rounded-lg bg-slate-900 border border-white/15 shadow-lg">
          <ul className="max-h-60 overflow-auto">
            {options.map(opt => (
              <li key={opt.value}>
                <button
                  type="button"
                  onClick={() => {
                    onChange(opt.value);
                    setOpen(false);
                  }}
                  className={`w-full text-left px-3 py-2 hover:bg-white/10 ${
                    value === opt.value ? "bg-cyan-600/30" : ""
                  }`}
                >
                  {opt.label}
                </button>
              </li>
            ))}
          </ul>
        </div>
      )}
    </div>
  );
}
