/* Hallmark · pre-emit critique: P5 H5 E5 S5 R5 V5 */
/* Hallmark · component: AdminPage · genre: editorial · theme: Atelier (Dark & Light) · studied-DNA: https://inihaus.de */
import React, { useState, useEffect } from 'react';
import {
  Shield, Settings, Users, Calendar, Layers, Palette, Plus, Trash2, Edit3,
  UserCheck, UserX, Clock, CheckCircle2, AlertCircle, Layout, Search, Eye, EyeOff,
  Mail, Send, Lock, Activity
} from 'lucide-react';
import { apiFetch } from '../api/client';
import { getRandomSkillColor } from '../utils/colors';

export default function AdminPage({ branding, onRefreshBranding, onRefreshEvents, skills, onRefreshSkills }) {
  const [activeAdminTab, setActiveAdminTab] = useState('users'); // 'users' | 'events' | 'templates' | 'branding' | 'smtp' | 'sessions'

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [success, setSuccess] = useState('');

  // 1. Users & Security State
  const [usersList, setUsersList] = useState([]);
  const [userSearchQuery, setUserSearchQuery] = useState('');
  const [pendingUsers, setPendingUsers] = useState([]);
  const [restrictionEnabled, setRestrictionEnabled] = useState(false);
  const [requireApproval, setRequireApproval] = useState(false);
  const [requireEmailVerification, setRequireEmailVerification] = useState(true);
  const [domainRules, setDomainRules] = useState([]);
  const [newDomain, setNewDomain] = useState('');

  // 2. Events & Shifts State
  const [eventsList, setEventsList] = useState([]);

  // 3. Templates & Skills State
  const [templatesList, setTemplatesList] = useState([]);
  const [newSkillName, setNewSkillName] = useState('');
  const [newSkillDesc, setNewSkillDesc] = useState('');
  const [newSkillColor, setNewSkillColor] = useState(getRandomSkillColor());

  // 4. Branding & Layout State
  const [appName, setAppName] = useState(branding?.app_name || 'Veranstaltungsschichtplaner');
  const [logoUrl, setLogoUrl] = useState(branding?.logo_url || '');
  const [primaryColor, setPrimaryColor] = useState(branding?.primary_color || '#E05A47');
  const [bannerText, setBannerText] = useState(branding?.custom_banner_text || '');

  const [showCommunityInfoBox, setShowCommunityInfoBox] = useState(branding?.show_community_info_box ?? true);
  const [communityInfoTitle, setCommunityInfoTitle] = useState(branding?.community_info_title || '📌 Verein & Infos');
  const [communityInfoText, setCommunityInfoText] = useState(branding?.community_info_text || 'Initiative e.V. Hausverein\nOffene Angebote, DIY-Kultur & engagierte Schichten.');

  const [showSupportBox, setShowSupportBox] = useState(branding?.show_support_box ?? true);
  const [supportBoxTitle, setSupportBoxTitle] = useState(branding?.support_box_title || '❤️ Unterstützen');
  const [supportBoxText, setSupportBoxText] = useState(branding?.support_box_text || 'Hilf mit als Helfer*in an der Bar, beim Essen kochen oder beim Auf- & Abbau.');

  const [savingBranding, setSavingBranding] = useState(false);

  // 5. SMTP State
  const [smtpActive, setSmtpActive] = useState(false);
  const [smtpHost, setSmtpHost] = useState('smtp.beispiel.de');
  const [smtpPort, setSmtpPort] = useState(587);
  const [smtpUsername, setSmtpUsername] = useState('');
  const [smtpPassword, setSmtpPassword] = useState('');
  const [smtpUseTls, setSmtpUseTls] = useState(true);
  const [smtpUseSsl, setSmtpUseSsl] = useState(false);
  const [smtpFromEmail, setSmtpFromEmail] = useState('noreply@schichtplaner.de');
  const [smtpTestEmail, setSmtpTestEmail] = useState('');
  const [showSmtpPassword, setShowSmtpPassword] = useState(false);
  const [savingSmtp, setSavingSmtp] = useState(false);
  const [testingSmtp, setTestingSmtp] = useState(false);

  // 6. Active Sessions & IP Monitoring State (Restricted to Session Monitor Django Group or Superuser)
  const [activeSessions, setActiveSessions] = useState([]);
  const [isSessionMonitorAuthorized, setIsSessionMonitorAuthorized] = useState(false);
  const [sessionMonitorGroupName, setSessionMonitorGroupName] = useState('Session Monitor');

  useEffect(() => {
    fetchAdminData();
  }, []);

  const fetchAdminData = async () => {
    setLoading(true);
    try {
      try {
        const users = await apiFetch('/users/manage-users/');
        setUsersList(users.results || users);
      } catch (e) {}

      try {
        const pUsers = await apiFetch('/users/pending/');
        setPendingUsers(pUsers.results || pUsers);
      } catch (e) {}

      try {
        const setting = await apiFetch('/users/restriction-setting/');
        setRestrictionEnabled(setting.is_restriction_enabled);
        setRequireApproval(setting.require_admin_approval);
        setRequireEmailVerification(setting.require_email_verification ?? true);
      } catch (e) {}

      try {
        const rules = await apiFetch('/users/domain-rules/');
        setDomainRules(rules.results || rules);
      } catch (e) {}

      try {
        const evts = await apiFetch('/events/');
        setEventsList(evts.results || evts);
      } catch (e) {}

      try {
        const tmpls = await apiFetch('/templates/');
        setTemplatesList(tmpls.results || tmpls);
      } catch (e) {}

      try {
        const smtpData = await apiFetch('/users/smtp-setting/');
        if (smtpData) {
          setSmtpActive(smtpData.is_active ?? false);
          setSmtpHost(smtpData.host || '');
          setSmtpPort(smtpData.port || 587);
          setSmtpUsername(smtpData.username || '');
          setSmtpPassword(smtpData.password || '');
          setSmtpUseTls(smtpData.use_tls ?? true);
          setSmtpUseSsl(smtpData.use_ssl ?? false);
          setSmtpFromEmail(smtpData.from_email || '');
        }
      } catch (e) {}

      try {
        const sessionData = await apiFetch('/users/active-sessions/');
        setActiveSessions(sessionData.sessions || []);
        setIsSessionMonitorAuthorized(true);
        setSessionMonitorGroupName(sessionData.group_name || 'Session Monitor');
      } catch (e) {
        setIsSessionMonitorAuthorized(false);
      }

    } catch (err) {
      setError(err.message || 'Laden der Admin-Daten fehlgeschlagen.');
    } finally {
      setLoading(false);
    }
  };

  const showNotif = (msg) => {
    setSuccess(msg);
    setTimeout(() => setSuccess(''), 4000);
  };

  // --- USER ACTIONS ---
  const handleToggleUserAdmin = async (user) => {
    try {
      const updated = await apiFetch(`/users/manage-users/${user.id}/`, {
        method: 'PATCH',
        body: JSON.stringify({ is_admin_user: !user.is_admin_user })
      });
      setUsersList(usersList.map(u => u.id === user.id ? updated : u));
      showNotif(`Admin-Rechte für ${user.username} aktualisiert.`);
    } catch (e) {
      setError(e.message || 'Fehler beim Aktualisieren.');
    }
  };

  const handleToggleUserApproved = async (user) => {
    try {
      const updated = await apiFetch(`/users/manage-users/${user.id}/`, {
        method: 'PATCH',
        body: JSON.stringify({ is_approved: !user.is_approved })
      });
      setUsersList(usersList.map(u => u.id === user.id ? updated : u));
      showNotif(`Freischalt-Status für ${user.username} aktualisiert.`);
    } catch (e) {
      setError(e.message || 'Fehler beim Aktualisieren.');
    }
  };

  const handleConfirmUserEmail = async (userId) => {
    try {
      const res = await apiFetch(`/users/manage-users/${userId}/confirm-email/`, {
        method: 'POST'
      });
      showNotif(res.message || 'E-Mail-Adresse manuell als bestätigt markiert.');
      fetchAdminData();
    } catch (err) {
      setError(err.message || 'Fehler beim Bestätigen der E-Mail.');
    }
  };

  const handleDeleteUser = async (userObj) => {
    if (!window.confirm(`Möchtest du das Benutzerkonto "${userObj.display_name || userObj.username}" (@${userObj.username}) wirklich dauerhaft löschen?`)) {
      return;
    }

    try {
      await apiFetch(`/users/manage-users/${userObj.id}/`, {
        method: 'DELETE'
      });
      setUsersList(usersList.filter(u => u.id !== userObj.id));
      showNotif(`Benutzerkonto ${userObj.username} wurde gelöscht.`);
    } catch (e) {
      setError(e.message || 'Fehler beim Löschen des Benutzers.');
    }
  };

  const handleApprovePendingUser = async (userId) => {
    try {
      await apiFetch(`/users/${userId}/approve/`, { method: 'POST' });
      setPendingUsers(pendingUsers.filter(u => u.id !== userId));
      fetchAdminData();
      showNotif('Benutzer wurde freigeschaltet!');
    } catch (e) {
      setError(e.message || 'Fehler beim Freischalten.');
    }
  };

  const handleRejectPendingUser = async (userId) => {
    try {
      await apiFetch(`/users/${userId}/approve/`, { method: 'DELETE' });
      setPendingUsers(pendingUsers.filter(u => u.id !== userId));
      showNotif('Registrierungsanfrage abgelehnt.');
    } catch (e) {
      setError(e.message || 'Fehler beim Ablehnen.');
    }
  };

  // --- SECURITY SETTINGS ---
  const handleSaveSecuritySettings = async (e) => {
    e.preventDefault();
    try {
      await apiFetch('/users/restriction-setting/', {
        method: 'POST',
        body: JSON.stringify({
          is_restriction_enabled: restrictionEnabled,
          require_admin_approval: requireApproval,
          require_email_verification: requireEmailVerification
        })
      });
      showNotif('Sicherheitseinstellungen gespeichert!');
    } catch (err) {
      setError(err.message || 'Speichern der Sicherheitseinstellungen fehlgeschlagen.');
    }
  };

  const handleAddDomainRule = async (e) => {
    e.preventDefault();
    if (!newDomain.trim()) return;

    try {
      const created = await apiFetch('/users/domain-rules/', {
        method: 'POST',
        body: JSON.stringify({ domain: newDomain.trim(), is_active: true })
      });
      setDomainRules([...domainRules, created]);
      setNewDomain('');
      showNotif(`Domain-Regel "${created.domain}" hinzugefügt.`);
    } catch (err) {
      setError(err.message || 'Hinzufügen der Domain-Regel fehlgeschlagen.');
    }
  };

  const handleDeleteDomainRule = async (id) => {
    try {
      await apiFetch(`/users/domain-rules/${id}/`, { method: 'DELETE' });
      setDomainRules(domainRules.filter(r => r.id !== id));
      showNotif('Domain-Regel entfernt.');
    } catch (err) {
      setError(err.message || 'Fehler beim Löschen der Regel.');
    }
  };

  // --- EVENTS ACTIONS ---
  const handleDeleteEvent = async (eventObj) => {
    if (!window.confirm(`Möchtest du die Veranstaltung "${eventObj.title}" unwiderruflich löschen?`)) return;

    try {
      await apiFetch(`/events/${eventObj.id}/`, { method: 'DELETE' });
      setEventsList(eventsList.filter(e => e.id !== eventObj.id));
      if (onRefreshEvents) onRefreshEvents();
      showNotif('Veranstaltung wurde gelöscht.');
    } catch (err) {
      setError(err.message || 'Löschen fehlgeschlagen.');
    }
  };

  // --- TEMPLATES & SKILLS ACTIONS ---
  const handleCreateSkill = async (e) => {
    e.preventDefault();
    if (!newSkillName.trim()) return;

    try {
      await apiFetch('/skills/', {
        method: 'POST',
        body: JSON.stringify({
          name: newSkillName.trim(),
          description: newSkillDesc.trim(),
          color: newSkillColor
        })
      });
      setNewSkillName('');
      setNewSkillDesc('');
      setNewSkillColor(getRandomSkillColor());
      showNotif('Neue Qualifikation angelegt.');
      if (onRefreshSkills) onRefreshSkills();
    } catch (err) {
      setError(err.message || 'Anlegen der Qualifikation fehlgeschlagen.');
    }
  };

  const handleDeleteSkill = async (skillId) => {
    if (!window.confirm('Fähigkeit wirklich löschen?')) return;
    try {
      await apiFetch(`/skills/${skillId}/`, { method: 'DELETE' });
      showNotif('Qualifikation gelöscht.');
      if (onRefreshSkills) onRefreshSkills();
    } catch (err) {
      setError(err.message || 'Löschen fehlgeschlagen.');
    }
  };

  const handleDeleteTemplate = async (templateId) => {
    if (!window.confirm('Vorlage wirklich löschen?')) return;
    try {
      await apiFetch(`/templates/${templateId}/`, { method: 'DELETE' });
      setTemplatesList(templatesList.filter(t => t.id !== templateId));
      showNotif('Vorlage gelöscht.');
    } catch (err) {
      setError(err.message || 'Löschen der Vorlage fehlgeschlagen.');
    }
  };

  // --- BRANDING SAVE ---
  const handleSaveBranding = async (e) => {
    e.preventDefault();
    setSavingBranding(true);
    try {
      await apiFetch('/branding/', {
        method: 'POST',
        body: JSON.stringify({
          app_name: appName,
          logo_url: logoUrl,
          primary_color: primaryColor,
          custom_banner_text: bannerText,
          show_community_info_box: showCommunityInfoBox,
          community_info_title: communityInfoTitle,
          community_info_text: communityInfoText,
          show_support_box: showSupportBox,
          support_box_title: supportBoxTitle,
          support_box_text: supportBoxText
        })
      });
      onRefreshBranding();
      showNotif('Branding-Einstellungen erfolgreich gespeichert!');
    } catch (e) {
      setError(e.message || 'Speichern des Brandings fehlgeschlagen.');
    } finally {
      setSavingBranding(false);
    }
  };

  // --- SMTP SAVE & TEST ---
  const handleSaveSMTP = async (e) => {
    e.preventDefault();
    setSavingSmtp(true);
    try {
      await apiFetch('/users/smtp-setting/', {
        method: 'POST',
        body: JSON.stringify({
          is_active: smtpActive,
          host: smtpHost,
          port: parseInt(smtpPort) || 587,
          username: smtpUsername,
          password: smtpPassword,
          use_tls: smtpUseTls,
          use_ssl: smtpUseSsl,
          from_email: smtpFromEmail
        })
      });
      showNotif('✅ SMTP-Einstellungen erfolgreich gespeichert!');
    } catch (err) {
      setError(err.message || 'Speichern der SMTP-Einstellungen fehlgeschlagen.');
    } finally {
      setSavingSmtp(false);
    }
  };

  const handleTestSMTP = async () => {
    setTestingSmtp(true);
    try {
      const res = await apiFetch('/users/smtp-setting/test/', {
        method: 'POST',
        body: JSON.stringify({ email: smtpTestEmail })
      });
      showNotif(`✅ ${res.message || 'Test-E-Mail erfolgreich gesendet!'}`);
    } catch (err) {
      setError(err.message || 'Test-E-Mail fehlgeschlagen.');
    } finally {
      setTestingSmtp(false);
    }
  };

  const filteredUsers = usersList.filter(u =>
    u.username.toLowerCase().includes(userSearchQuery.toLowerCase()) ||
    u.email.toLowerCase().includes(userSearchQuery.toLowerCase()) ||
    (u.display_name && u.display_name.toLowerCase().includes(userSearchQuery.toLowerCase()))
  );

  return (
    <div className="space-y-6 max-w-6xl mx-auto animate-in fade-in duration-200 font-sans">
      {/* Header Panel */}
      <div className="hallmark-panel rounded-sm p-6 sm:p-8 border border-grid flex flex-col md:flex-row md:items-center justify-between gap-4">
        <div className="space-y-1">
          <div className="flex items-center gap-2 font-mono text-xs text-indigo-400 font-bold mb-1">
            <Shield className="w-4 h-4" /> [ SYSTEM-STEUERUNG & ADMINDISTRIBUTION ]
          </div>
          <h2 className="font-serif text-3xl sm:text-4xl font-bold uppercase tracking-tight text-main">
            Verwaltungszentrale
          </h2>
          <p className="text-xs text-muted font-mono max-w-2xl mt-1">
            Verwalte Konten, Sicherheit, Domain-Regeln, Vorlagen, SMTP & Live-Sitzungen
          </p>
        </div>
      </div>

      {error && (
        <div className="p-4 rounded-sm bg-red-500/10 border border-red-500/20 text-red-500 text-xs font-mono flex items-center gap-2">
          <AlertCircle className="w-4 h-4 shrink-0" />
          <span>{error}</span>
        </div>
      )}

      {success && (
        <div className="p-4 rounded-sm bg-emerald-500/10 border border-emerald-500/20 text-emerald-400 text-xs font-mono flex items-center gap-2">
          <CheckCircle2 className="w-4 h-4 shrink-0" />
          <span>{success}</span>
        </div>
      )}

      {/* Atelier Stencil Tab Bar */}
      <div className="border-b border-grid pb-2">
        <div className="flex items-center gap-1.5 font-mono text-xs overflow-x-auto no-scrollbar">
          <button
            onClick={() => setActiveAdminTab('users')}
            className={`px-4 py-2 rounded-sm transition flex items-center gap-2 border ${
              activeAdminTab === 'users'
                ? 'bg-surface-hover text-main font-bold border-grid shadow-sm'
                : 'bg-subtle text-muted border-transparent hover:text-main'
            }`}
          >
            <Users className="w-3.5 h-3.5 text-blue-400" /> [ 01: BENUTZER & SICHERHEIT ({usersList.length}) ]
          </button>

          <button
            onClick={() => setActiveAdminTab('events')}
            className={`px-4 py-2 rounded-sm transition flex items-center gap-2 border ${
              activeAdminTab === 'events'
                ? 'bg-surface-hover text-main font-bold border-grid shadow-sm'
                : 'bg-subtle text-muted border-transparent hover:text-main'
            }`}
          >
            <Calendar className="w-3.5 h-3.5 text-emerald-400" /> [ 02: VERANSTALTUNGEN ({eventsList.length}) ]
          </button>

          <button
            onClick={() => setActiveAdminTab('templates')}
            className={`px-4 py-2 rounded-sm transition flex items-center gap-2 border ${
              activeAdminTab === 'templates'
                ? 'bg-surface-hover text-main font-bold border-grid shadow-sm'
                : 'bg-subtle text-muted border-transparent hover:text-main'
            }`}
          >
            <Layers className="w-3.5 h-3.5 text-amber-400" /> [ 03: VORLAGEN & SKILLS ]
          </button>

          <button
            onClick={() => setActiveAdminTab('branding')}
            className={`px-4 py-2 rounded-sm transition flex items-center gap-2 border ${
              activeAdminTab === 'branding'
                ? 'bg-surface-hover text-main font-bold border-grid shadow-sm'
                : 'bg-subtle text-muted border-transparent hover:text-main'
            }`}
          >
            <Palette className="w-3.5 h-3.5 text-indigo-400" /> [ 04: BRANDING & SYSTEM ]
          </button>

          <button
            onClick={() => setActiveAdminTab('smtp')}
            className={`px-4 py-2 rounded-sm transition flex items-center gap-2 border ${
              activeAdminTab === 'smtp'
                ? 'bg-surface-hover text-main font-bold border-grid shadow-sm'
                : 'bg-subtle text-muted border-transparent hover:text-main'
            }`}
          >
            <Mail className="w-3.5 h-3.5 text-purple-400" /> [ 05: E-MAIL & SMTP ]
          </button>

          {isSessionMonitorAuthorized && (
            <button
              onClick={() => setActiveAdminTab('sessions')}
              className={`px-4 py-2 rounded-sm transition flex items-center gap-2 border ${
                activeAdminTab === 'sessions'
                  ? 'bg-surface-hover text-main font-bold border-grid shadow-sm'
                  : 'bg-subtle text-muted border-transparent hover:text-main'
              }`}
            >
              <Activity className="w-3.5 h-3.5 text-rose-400" /> [ 06: LIVE-SITZUNGEN & IP ({activeSessions.length}) ]
            </button>
          )}
        </div>
      </div>

      {loading ? (
        <div className="hallmark-panel p-16 text-center text-xs text-muted font-mono border border-grid">
          Lade Admin-Daten...
        </div>
      ) : (
        <>
          {/* TAB 01: BENUTZER & SICHERHEIT */}
          {activeAdminTab === 'users' && (
            <div className="space-y-6 font-mono text-xs">
              {/* Pending Approvals Section */}
              {pendingUsers.length > 0 && (
                <div className="hallmark-panel rounded-sm p-5 border border-amber-500/40 bg-amber-500/5 space-y-3">
                  <h3 className="font-serif text-lg font-bold uppercase text-amber-500 flex items-center gap-2 border-b border-amber-500/20 pb-2">
                    ⚠️ Ausstehende Registrierungen ({pendingUsers.length})
                  </h3>
                  <div className="space-y-2">
                    {pendingUsers.map(pu => (
                      <div key={pu.id} className="p-3 rounded-sm bg-surface border border-grid flex items-center justify-between text-xs">
                        <div>
                          <div className="font-bold text-main">{pu.display_name} (@{pu.username})</div>
                          <div className="text-[11px] text-muted">{pu.email}</div>
                        </div>
                        <div className="flex items-center gap-2">
                          <button
                            onClick={() => handleConfirmUserEmail(pu.id)}
                            className="px-3 py-1 rounded-sm bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs flex items-center gap-1"
                            title="E-Mail-Adresse und Konto direkt vom Admin bestätigen und freischalten"
                          >
                            <Mail className="w-3.5 h-3.5" /> FREISCHALTEN & BESTÄTIGEN
                          </button>
                          <button
                            onClick={() => handleRejectPendingUser(pu.id)}
                            className="px-3 py-1 rounded-sm bg-red-600/20 text-red-400 hover:bg-red-600/30 border border-red-600/30 font-bold text-xs"
                          >
                            [ ABLEHNEN ]
                          </button>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {/* User Filter Search Bar */}
              <div className="hallmark-panel rounded-sm p-4 border border-grid flex items-center gap-3">
                <Search className="w-4 h-4 text-muted shrink-0" />
                <input
                  type="text"
                  value={userSearchQuery}
                  onChange={(e) => setUserSearchQuery(e.target.value)}
                  placeholder="Nutzer suchen nach Name, Username oder E-Mail..."
                  className="w-full bg-subtle border border-grid px-3 py-1.5 rounded-sm text-xs font-mono text-main focus:outline-none focus:border-muted"
                />
                {userSearchQuery && (
                  <button onClick={() => setUserSearchQuery('')} className="text-xs text-muted hover:text-main font-mono shrink-0">
                    [ CLEAR ]
                  </button>
                )}
              </div>

              {/* User List Table */}
              <div className="hallmark-panel rounded-sm p-5 border border-grid space-y-4">
                <h3 className="font-serif text-lg font-bold uppercase text-main border-b border-grid pb-2">
                  Benutzerkonten & Rechtestatus ({filteredUsers.length})
                </h3>
                <div className="overflow-x-auto">
                  <table className="w-full text-left border-collapse text-xs">
                    <thead>
                      <tr className="border-b border-grid text-muted uppercase text-[10px]">
                        <th className="pb-2 font-bold">Nutzer</th>
                        <th className="pb-2 font-bold">E-Mail</th>
                        <th className="pb-2 font-bold">Freigeschaltet</th>
                        <th className="pb-2 font-bold">E-Mail Bestätigt</th>
                        <th className="pb-2 font-bold">Admin-Rolle</th>
                        <th className="pb-2 font-bold text-right">Aktionen</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-grid">
                      {filteredUsers.map(u => (
                        <tr key={u.id} className="hover:bg-subtle/50 transition">
                          <td className="py-2.5 font-bold text-main">
                            {u.display_name || u.username}
                            <span className="text-[10px] text-muted font-normal block">@{u.username}</span>
                          </td>
                          <td className="py-2.5 text-muted">{u.email}</td>
                          <td className="py-2.5">
                            <span className={`px-2 py-0.5 rounded-sm text-[10px] font-bold border ${
                              u.is_approved ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20' : 'bg-amber-500/10 text-amber-400 border-amber-500/20'
                            }`}>
                              {u.is_approved ? 'JA' : 'NEIN'}
                            </span>
                          </td>
                          <td className="py-2.5">
                            <div className="flex items-center gap-1.5 flex-wrap">
                              <span className={`px-2 py-0.5 rounded-sm text-[10px] font-bold border ${
                                u.is_email_verified ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20' : 'bg-amber-500/10 text-amber-400 border-amber-500/20'
                              }`}>
                                {u.is_email_verified ? 'VERIFIZIERT' : 'AUSSTEHEND'}
                              </span>
                              {!u.is_email_verified && (
                                <button
                                  onClick={() => handleConfirmUserEmail(u.id)}
                                  className="px-2 py-0.5 rounded-sm text-[10px] font-mono font-bold bg-amber-500/20 hover:bg-amber-500/30 text-amber-300 border border-amber-500/40 transition flex items-center gap-1"
                                  title="E-Mail-Adresse für dieses Konto manuell als bestätigt markieren"
                                >
                                  <Mail className="w-3 h-3" /> BESTÄTIGEN
                                </button>
                              )}
                            </div>
                          </td>
                          <td className="py-2.5">
                            <span className={`px-2 py-0.5 rounded-sm text-[10px] font-bold border ${
                              u.is_admin_user || u.is_superuser ? 'bg-indigo-500/10 text-indigo-400 border-indigo-500/20' : 'bg-subtle text-muted border-grid'
                            }`}>
                              {u.is_superuser ? 'SUPERUSER' : u.is_admin_user ? 'ADMIN' : 'USER'}
                            </span>
                          </td>
                          <td className="py-2.5 text-right space-x-1">
                            <button
                              onClick={() => handleToggleUserApproved(u)}
                              className="px-2 py-1 rounded-sm text-[10px] bg-subtle hover:bg-surface-hover border border-grid text-main transition"
                            >
                              {u.is_approved ? 'Sperren' : 'Freischalten'}
                            </button>
                            <button
                              onClick={() => handleToggleUserAdmin(u)}
                              className="px-2 py-1 rounded-sm text-[10px] bg-subtle hover:bg-surface-hover border border-grid text-indigo-400 transition"
                            >
                              {u.is_admin_user ? 'Admin entziehen' : 'Zu Admin machen'}
                            </button>
                            <button
                              onClick={() => handleDeleteUser(u)}
                              className="px-2 py-1 rounded-sm text-[10px] bg-red-500/10 hover:bg-red-500/20 border border-red-500/20 text-red-400 font-bold transition inline-flex items-center gap-1"
                              title="Benutzerkonto dauerhaft löschen"
                            >
                              <Trash2 className="w-3 h-3" /> Löschen
                            </button>
                          </td>
                        </tr>
                      ))}
                    </tbody>
                  </table>
                </div>
              </div>

              {/* Security & Domain Restrictions */}
              <div className="hallmark-panel rounded-sm p-5 border border-grid space-y-4">
                <h3 className="font-serif text-lg font-bold uppercase text-main border-b border-grid pb-2">
                  Registrierungseinschränkungen & Domains
                </h3>

                <form onSubmit={handleSaveSecuritySettings} className="space-y-3">
                  <div className="flex items-center justify-between p-3 rounded-sm bg-subtle border border-grid">
                    <div>
                      <div className="font-bold text-main">Domain-Einschränkung aktivieren</div>
                      <div className="text-[11px] text-muted">Nur E-Mails aus erlaubten Domains zulassen</div>
                    </div>
                    <input
                      type="checkbox"
                      checked={restrictionEnabled}
                      onChange={(e) => setRestrictionEnabled(e.target.checked)}
                      className="w-4 h-4 accent-indigo-500 cursor-pointer"
                    />
                  </div>

                  <div className="flex items-center justify-between p-3 rounded-sm bg-subtle border border-grid">
                    <div>
                      <div className="font-bold text-main">Manuelle Admin-Freischaltung erzwingen</div>
                      <div className="text-[11px] text-muted">Neue Konten sind erst nach Admin-Freigabe aktiv</div>
                    </div>
                    <input
                      type="checkbox"
                      checked={requireApproval}
                      onChange={(e) => setRequireApproval(e.target.checked)}
                      className="w-4 h-4 accent-indigo-500 cursor-pointer"
                    />
                  </div>

                  <div className="flex items-center justify-between p-3 rounded-sm bg-subtle border border-grid">
                    <div>
                      <div className="font-bold text-main">E-Mail-Bestätigung erzwingen</div>
                      <div className="text-[11px] text-muted">Benutzer müssen ihre E-Mail-Adresse per Link verifizieren</div>
                    </div>
                    <input
                      type="checkbox"
                      checked={requireEmailVerification}
                      onChange={(e) => setRequireEmailVerification(e.target.checked)}
                      className="w-4 h-4 accent-indigo-500 cursor-pointer"
                    />
                  </div>

                  <div className="pt-2 flex justify-end">
                    <button
                      type="submit"
                      className="px-4 py-2 rounded-sm bg-indigo-600 hover:bg-indigo-500 text-white font-bold text-xs"
                    >
                      [ EINSTELLUNGEN SPEICHERN ]
                    </button>
                  </div>
                </form>

                {/* Domain Rules Manager */}
                <div className="pt-4 border-t border-grid space-y-3">
                  <h4 className="font-bold text-main text-xs uppercase">Erlaubte E-Mail-Domains</h4>
                  <form onSubmit={handleAddDomainRule} className="flex gap-2">
                    <input
                      type="text"
                      placeholder="z. B. verein.de oder @beispiel.org"
                      value={newDomain}
                      onChange={(e) => setNewDomain(e.target.value)}
                      className="flex-1 bg-subtle border border-grid px-3 py-1.5 rounded-sm text-xs font-mono"
                    />
                    <button
                      type="submit"
                      className="px-4 py-1.5 rounded-sm bg-surface hover:bg-surface-hover text-main border border-grid font-bold text-xs"
                    >
                      [ HINZUFÜGEN ]
                    </button>
                  </form>

                  <div className="space-y-1 pt-2">
                    {domainRules.length === 0 ? (
                      <p className="text-xs text-muted italic">[ Keine Domain-Regeln definiert. Alle E-Mail-Domains sind erlaubt. ]</p>
                    ) : (
                      domainRules.map(r => (
                        <div key={r.id} className="flex items-center justify-between p-2 rounded-sm bg-subtle border border-grid text-xs">
                          <span className="font-mono font-bold text-main">{r.domain}</span>
                          <button
                            onClick={() => handleDeleteDomainRule(r.id)}
                            className="text-red-400 hover:underline text-[11px]"
                          >
                            [ ENTFERNEN ]
                          </button>
                        </div>
                      ))
                    )}
                  </div>
                </div>
              </div>
            </div>
          )}

          {/* TAB 02: VERANSTALTUNGEN */}
          {activeAdminTab === 'events' && (
            <div className="hallmark-panel rounded-sm p-5 border border-grid space-y-4 font-mono text-xs">
              <h3 className="font-serif text-lg font-bold uppercase text-main border-b border-grid pb-2">
                Veranstaltungen verwalten ({eventsList.length})
              </h3>
              <div className="space-y-2">
                {eventsList.map(evt => (
                  <div key={evt.id} className="p-3.5 rounded-sm bg-subtle border border-grid flex items-center justify-between gap-4">
                    <div>
                      <div className="font-bold text-main text-sm flex items-center gap-2">
                        {evt.title}
                        {evt.is_active === false && (
                          <span className="text-[10px] text-amber-500 font-bold">[ DEAKTIVIERT ]</span>
                        )}
                      </div>
                      <div className="text-[11px] text-muted">
                        {new Date(evt.start_date).toLocaleDateString('de-DE')} — {new Date(evt.end_date).toLocaleDateString('de-DE')} {evt.location ? `| Ort: ${evt.location}` : ''}
                      </div>
                    </div>
                    <button
                      onClick={() => handleDeleteEvent(evt)}
                      className="px-3 py-1.5 rounded-sm bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/30 transition font-bold text-xs shrink-0 flex items-center gap-1"
                    >
                      <Trash2 className="w-3.5 h-3.5" /> LÖSCHEN
                    </button>
                  </div>
                ))}
              </div>
            </div>
          )}

          {/* TAB 03: VORLAGEN & SKILLS */}
          {activeAdminTab === 'templates' && (
            <div className="space-y-6 font-mono text-xs">
              {/* Skills Management */}
              <div className="hallmark-panel rounded-sm p-5 border border-grid space-y-4">
                <h3 className="font-serif text-lg font-bold uppercase text-main border-b border-grid pb-2">
                  System-Qualifikationen & Fähigkeiten ({skills.length})
                </h3>

                <form onSubmit={handleCreateSkill} className="grid grid-cols-1 sm:grid-cols-12 gap-2 items-center">
                  <input
                    type="text"
                    required
                    placeholder="Name der Qualifikation (z.B. Baristakurs)"
                    value={newSkillName}
                    onChange={(e) => setNewSkillName(e.target.value)}
                    className="sm:col-span-5 bg-subtle border border-grid px-3 py-1.5 rounded-sm text-xs font-mono"
                  />
                  <input
                    type="text"
                    placeholder="Beschreibung (optional)"
                    value={newSkillDesc}
                    onChange={(e) => setNewSkillDesc(e.target.value)}
                    className="sm:col-span-4 bg-subtle border border-grid px-3 py-1.5 rounded-sm text-xs font-mono"
                  />
                  <input
                    type="color"
                    value={newSkillColor}
                    onChange={(e) => setNewSkillColor(e.target.value)}
                    className="sm:col-span-1 h-8 w-full cursor-pointer bg-subtle p-0.5 border border-grid rounded-sm"
                  />
                  <button
                    type="submit"
                    className="sm:col-span-2 py-1.5 px-3 rounded-sm bg-surface hover:bg-surface-hover text-main border border-grid font-bold text-xs"
                  >
                    [ ANLEGEN ]
                  </button>
                </form>

                <div className="flex flex-wrap gap-2 pt-2">
                  {skills.map(sk => (
                    <div
                      key={sk.id}
                      style={{ backgroundColor: `${sk.color}15`, borderColor: `${sk.color}35`, color: sk.color }}
                      className="px-3 py-1 rounded-sm border font-bold text-xs flex items-center gap-2"
                    >
                      <span>{sk.name}</span>
                      <button
                        onClick={() => handleDeleteSkill(sk.id)}
                        className="hover:opacity-80 transition text-red-400"
                        title="Löschen"
                      >
                        <Trash2 className="w-3 h-3" />
                      </button>
                    </div>
                  ))}
                </div>
              </div>

              {/* Templates Management */}
              <div className="hallmark-panel rounded-sm p-5 border border-grid space-y-4">
                <h3 className="font-serif text-lg font-bold uppercase text-main border-b border-grid pb-2">
                  Veranstaltungsvorlagen ({templatesList.length})
                </h3>
                <div className="space-y-2">
                  {templatesList.map(t => (
                    <div key={t.id} className="p-3 rounded-sm bg-subtle border border-grid flex items-center justify-between">
                      <div>
                        <div className="font-bold text-main">{t.name}</div>
                        <div className="text-[11px] text-muted">{t.description || '[ Keine Beschreibung ]'}</div>
                      </div>
                      <button
                        onClick={() => handleDeleteTemplate(t.id)}
                        className="px-3 py-1.5 rounded-sm bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/30 transition text-xs font-bold"
                      >
                        [ LÖSCHEN ]
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* TAB 04: BRANDING & SYSTEM */}
          {activeAdminTab === 'branding' && (
            <form onSubmit={handleSaveBranding} className="hallmark-panel rounded-sm p-6 border border-grid space-y-6 font-mono text-xs">
              <h3 className="font-serif text-xl font-bold uppercase text-main border-b border-grid pb-2">
                Branding & Design-Einstellungen
              </h3>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div>
                  <label className="block text-main mb-1 font-bold">App-Name</label>
                  <input
                    type="text"
                    value={appName}
                    onChange={(e) => setAppName(e.target.value)}
                    className="w-full px-3 py-2 rounded-sm input-field text-xs"
                  />
                </div>

                <div>
                  <label className="block text-main mb-1 font-bold">Logo-URL (optional)</label>
                  <input
                    type="text"
                    value={logoUrl}
                    onChange={(e) => setLogoUrl(e.target.value)}
                    placeholder="https://..."
                    className="w-full px-3 py-2 rounded-sm input-field text-xs"
                  />
                </div>

                <div>
                  <label className="block text-main mb-1 font-bold">Primärfarbe (Akzent)</label>
                  <div className="flex items-center gap-2">
                    <input
                      type="color"
                      value={primaryColor}
                      onChange={(e) => setPrimaryColor(e.target.value)}
                      className="h-9 w-12 rounded-sm cursor-pointer bg-subtle p-1 border border-grid"
                    />
                    <input
                      type="text"
                      value={primaryColor}
                      onChange={(e) => setPrimaryColor(e.target.value)}
                      className="flex-1 px-3 py-2 rounded-sm input-field text-xs font-mono"
                    />
                  </div>
                </div>

                <div>
                  <label className="block text-main mb-1 font-bold">Benachrichtigungstext (Banner oben)</label>
                  <input
                    type="text"
                    value={bannerText}
                    onChange={(e) => setBannerText(e.target.value)}
                    placeholder="z. B. Willkommen zum Sommerfest-Schichtplan!"
                    className="w-full px-3 py-2 rounded-sm input-field text-xs"
                  />
                </div>
              </div>

              {/* Info Box 1: Verein & Infos */}
              <div className="p-4 rounded-sm bg-subtle border border-grid space-y-3">
                <div className="flex items-center justify-between">
                  <span className="font-bold text-main uppercase">Info-Box 1: Verein & Informationen</span>
                  <input
                    type="checkbox"
                    checked={showCommunityInfoBox}
                    onChange={(e) => setShowCommunityInfoBox(e.target.checked)}
                    className="w-4 h-4 accent-indigo-500 cursor-pointer"
                  />
                </div>
                {showCommunityInfoBox && (
                  <div className="space-y-2">
                    <input
                      type="text"
                      value={communityInfoTitle}
                      onChange={(e) => setCommunityInfoTitle(e.target.value)}
                      className="w-full px-3 py-1.5 rounded-sm input-field text-xs font-bold"
                    />
                    <textarea
                      rows={2}
                      value={communityInfoText}
                      onChange={(e) => setCommunityInfoText(e.target.value)}
                      className="w-full px-3 py-1.5 rounded-sm input-field text-xs font-sans"
                    />
                  </div>
                )}
              </div>

              {/* Info Box 2: Unterstützen */}
              <div className="p-4 rounded-sm bg-subtle border border-grid space-y-3">
                <div className="flex items-center justify-between">
                  <span className="font-bold text-main uppercase">Info-Box 2: Unterstützen & Mitmachen</span>
                  <input
                    type="checkbox"
                    checked={showSupportBox}
                    onChange={(e) => setShowSupportBox(e.target.checked)}
                    className="w-4 h-4 accent-indigo-500 cursor-pointer"
                  />
                </div>
                {showSupportBox && (
                  <div className="space-y-2">
                    <input
                      type="text"
                      value={supportBoxTitle}
                      onChange={(e) => setSupportBoxTitle(e.target.value)}
                      className="w-full px-3 py-1.5 rounded-sm input-field text-xs font-bold"
                    />
                    <textarea
                      rows={2}
                      value={supportBoxText}
                      onChange={(e) => setSupportBoxText(e.target.value)}
                      className="w-full px-3 py-1.5 rounded-sm input-field text-xs font-sans"
                    />
                  </div>
                )}
              </div>

              <div className="pt-2 flex justify-end">
                <button
                  type="submit"
                  disabled={savingBranding}
                  className="px-5 py-2.5 rounded-sm bg-indigo-600 hover:bg-indigo-500 text-white font-bold text-xs"
                >
                  {savingBranding ? '[ SPEICHERN... ]' : '[ BRANDING SPEICHERN ]'}
                </button>
              </div>
            </form>
          )}

          {/* TAB 05: E-MAIL & SMTP */}
          {activeAdminTab === 'smtp' && (
            <div className="space-y-6 font-mono text-xs">
              <form onSubmit={handleSaveSMTP} className="hallmark-panel rounded-sm p-6 border border-grid space-y-4">
                <div className="flex items-center justify-between border-b border-grid pb-2">
                  <h3 className="font-serif text-xl font-bold uppercase text-main flex items-center gap-2">
                    <Mail className="w-5 h-5 text-purple-400" /> SMTP-E-Mail Konfiguration
                  </h3>
                  <label className="flex items-center gap-2 cursor-pointer font-bold">
                    <span>SMTP Aktivieren:</span>
                    <input
                      type="checkbox"
                      checked={smtpActive}
                      onChange={(e) => setSmtpActive(e.target.checked)}
                      className="w-4 h-4 accent-purple-500 cursor-pointer"
                    />
                  </label>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                  <div>
                    <label className="block text-main mb-1 font-bold">SMTP Host</label>
                    <input
                      type="text"
                      required={smtpActive}
                      value={smtpHost}
                      onChange={(e) => setSmtpHost(e.target.value)}
                      className="w-full px-3 py-2 rounded-sm input-field text-xs"
                    />
                  </div>

                  <div>
                    <label className="block text-main mb-1 font-bold">SMTP Port</label>
                    <input
                      type="number"
                      required={smtpActive}
                      value={smtpPort}
                      onChange={(e) => setSmtpPort(e.target.value)}
                      className="w-full px-3 py-2 rounded-sm input-field text-xs font-mono"
                    />
                  </div>

                  <div>
                    <label className="block text-main mb-1 font-bold">Benutzername</label>
                    <input
                      type="text"
                      value={smtpUsername}
                      onChange={(e) => setSmtpUsername(e.target.value)}
                      className="w-full px-3 py-2 rounded-sm input-field text-xs font-mono"
                    />
                  </div>

                  <div>
                    <label className="block text-main mb-1 font-bold">Passwort</label>
                    <div className="relative">
                      <input
                        type={showSmtpPassword ? 'text' : 'password'}
                        value={smtpPassword}
                        onChange={(e) => setSmtpPassword(e.target.value)}
                        className="w-full px-3 py-2 pr-10 rounded-sm input-field text-xs font-mono"
                      />
                      <button
                        type="button"
                        onClick={() => setShowSmtpPassword(!showSmtpPassword)}
                        className="absolute right-2 top-2 text-muted hover:text-main"
                      >
                        {showSmtpPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}
                      </button>
                    </div>
                  </div>

                  <div>
                    <label className="block text-main mb-1 font-bold">Absender E-Mail</label>
                    <input
                      type="email"
                      required={smtpActive}
                      value={smtpFromEmail}
                      onChange={(e) => setSmtpFromEmail(e.target.value)}
                      className="w-full px-3 py-2 rounded-sm input-field text-xs"
                    />
                  </div>

                  <div className="flex items-center gap-6 pt-5">
                    <label className="flex items-center gap-2 cursor-pointer font-bold">
                      <input
                        type="checkbox"
                        checked={smtpUseTls}
                        onChange={(e) => {
                          setSmtpUseTls(e.target.checked);
                          if (e.target.checked) setSmtpUseSsl(false);
                        }}
                        className="w-4 h-4 accent-purple-500 cursor-pointer"
                      />
                      <span>TLS (STARTTLS)</span>
                    </label>

                    <label className="flex items-center gap-2 cursor-pointer font-bold">
                      <input
                        type="checkbox"
                        checked={smtpUseSsl}
                        onChange={(e) => {
                          setSmtpUseSsl(e.target.checked);
                          if (e.target.checked) setSmtpUseTls(false);
                        }}
                        className="w-4 h-4 accent-purple-500 cursor-pointer"
                      />
                      <span>SSL</span>
                    </label>
                  </div>
                </div>

                <div className="pt-2 flex justify-end">
                  <button
                    type="submit"
                    disabled={savingSmtp}
                    className="px-5 py-2.5 rounded-sm bg-purple-600 hover:bg-purple-500 text-white font-bold text-xs"
                  >
                    {savingSmtp ? '[ SPEICHERN... ]' : '[ SMTP EINSTELLUNGEN SPEICHERN ]'}
                  </button>
                </div>
              </form>

              {/* SMTP Test Section */}
              <div className="hallmark-panel rounded-sm p-5 border border-grid space-y-3">
                <h4 className="font-serif text-lg font-bold uppercase text-main flex items-center gap-2">
                  <Send className="w-4 h-4 text-purple-400" /> Test-E-Mail Senden
                </h4>
                <div className="flex gap-2">
                  <input
                    type="email"
                    placeholder="empfaenger@beispiel.de"
                    value={smtpTestEmail}
                    onChange={(e) => setSmtpTestEmail(e.target.value)}
                    className="flex-1 bg-subtle border border-grid px-3 py-1.5 rounded-sm text-xs font-mono"
                  />
                  <button
                    type="button"
                    disabled={testingSmtp || !smtpTestEmail.trim()}
                    onClick={handleTestSMTP}
                    className="px-4 py-1.5 rounded-sm bg-surface hover:bg-surface-hover text-main border border-grid font-bold text-xs disabled:opacity-50"
                  >
                    {testingSmtp ? '[ SENDET... ]' : '[ TEST-MAIL SENDEN ]'}
                  </button>
                </div>
              </div>
            </div>
          )}

          {/* TAB 06: LIVE-SITZUNGEN & IP MONITORING */}
          {activeAdminTab === 'sessions' && isSessionMonitorAuthorized && (
            <div className="space-y-6">
              <div className="hallmark-panel rounded-sm p-5 border border-grid space-y-4 font-mono text-xs">
                <div className="flex items-center justify-between border-b border-grid pb-2">
                  <div>
                    <h3 className="font-serif text-lg font-bold uppercase text-main flex items-center gap-2">
                      <Activity className="w-4 h-4 text-rose-400" /> Live-Sitzungen & Quell-IP Monitoring ({activeSessions.length})
                    </h3>
                    <p className="text-[11px] text-muted font-sans mt-0.5">
                      Einsicht vorbehalten für Django-Benutzergruppe <strong>"{sessionMonitorGroupName}"</strong> & Superuser.
                    </p>
                  </div>
                  <button
                    onClick={fetchAdminData}
                    className="px-3 py-1.5 rounded-sm bg-subtle hover:bg-surface-hover text-main border border-grid transition flex items-center gap-1 font-bold text-xs"
                  >
                    <Clock className="w-3.5 h-3.5" /> AKTUALISIEREN
                  </button>
                </div>

                <div className="overflow-x-auto">
                  <table className="w-full text-left border-collapse text-xs">
                    <thead>
                      <tr className="border-b border-grid text-muted uppercase text-[10px]">
                        <th className="pb-2 font-bold">Nutzer / Gast</th>
                        <th className="pb-2 font-bold">Rolle / Status</th>
                        <th className="pb-2 font-bold">Quell-IP</th>
                        <th className="pb-2 font-bold">Letzte Seite (Pfad)</th>
                        <th className="pb-2 font-bold">Sitzungsschlüssel</th>
                        <th className="pb-2 font-bold text-right">Letzte Aktivität</th>
                      </tr>
                    </thead>
                    <tbody className="divide-y divide-grid">
                      {activeSessions.length === 0 ? (
                        <tr>
                          <td colSpan={6} className="py-6 text-center text-muted italic">
                            Keine aktiven Sitzungen in den letzten 24 Stunden erfasst.
                          </td>
                        </tr>
                      ) : (
                        activeSessions.map((s) => (
                          <tr key={s.id} className="hover:bg-subtle/50 transition">
                            <td className="py-2.5 font-bold text-main">
                              {s.display_name}
                              {s.user && <span className="text-[10px] text-muted font-normal block">@{s.user.username} ({s.user.email})</span>}
                            </td>
                            <td className="py-2.5">
                              <span className={`px-2 py-0.5 rounded-sm text-[10px] font-bold border ${
                                s.user?.is_admin ? 'bg-indigo-500/10 text-indigo-400 border-indigo-500/20' : s.user ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20' : 'bg-amber-500/10 text-amber-400 border-amber-500/20'
                              }`}>
                                {s.user?.is_admin ? 'ADMIN' : s.user ? 'BENUTZER' : 'GAST'}
                              </span>
                            </td>
                            <td className="py-2.5 font-mono font-bold text-indigo-400">{s.ip_address}</td>
                            <td className="py-2.5 font-mono text-muted">{s.last_path || '/'}</td>
                            <td className="py-2.5 font-mono text-[10px] text-muted">{s.session_key}</td>
                            <td className="py-2.5 text-right font-mono text-muted">
                              {new Date(s.last_seen).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit', second: '2-digit' })} Uhr
                            </td>
                          </tr>
                        ))
                      )}
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          )}
        </>
      )}
    </div>
  );
}
