/* 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
} 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'

  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);

  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) {}

    } 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 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 erfolgreich freigeschaltet.');
    } catch (e) {
      setError(e.message || 'Freischalten fehlgeschlagen.');
    }
  };

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

  const handleToggleRestriction = async (key, val) => {
    try {
      const payload = {
        is_restriction_enabled: key === 'restriction' ? val : restrictionEnabled,
        require_admin_approval: key === 'approval' ? val : requireApproval,
        require_email_verification: key === 'email_verify' ? val : requireEmailVerification
      };
      const res = await apiFetch('/users/restriction-setting/', {
        method: 'POST',
        body: JSON.stringify(payload)
      });
      setRestrictionEnabled(res.is_restriction_enabled);
      setRequireApproval(res.require_admin_approval);
      setRequireEmailVerification(res.require_email_verification);
      showNotif('Sicherheitseinstellungen aktualisiert.');
    } catch (e) {
      setError(e.message || 'Aktualisierung fehlgeschlagen.');
    }
  };

  const handleAddDomainRule = async (e) => {
    e.preventDefault();
    if (!newDomain.trim()) return;
    try {
      const rule = await apiFetch('/users/domain-rules/', {
        method: 'POST',
        body: JSON.stringify({ domain: newDomain })
      });
      setDomainRules([...domainRules, rule]);
      setNewDomain('');
      showNotif(`Domain-Regel "${rule.domain}" hinzugefügt.`);
    } catch (e) {
      setError(e.message || 'Fehler beim Hinzufügen.');
    }
  };

  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 (e) {
      setError(e.message || 'Fehler beim Löschen.');
    }
  };

  // --- SKILLS & TEMPLATES ---
  const handleCreateSkill = async (e) => {
    e.preventDefault();
    if (!newSkillName.trim()) return;
    try {
      await apiFetch('/skills/', {
        method: 'POST',
        body: JSON.stringify({
          name: newSkillName,
          description: newSkillDesc,
          color: newSkillColor
        })
      });
      setNewSkillName('');
      setNewSkillDesc('');
      setNewSkillColor(getRandomSkillColor());
      onRefreshSkills();
      showNotif('Qualifikation angelegt.');
    } catch (e) {
      setError(e.message || 'Fehler beim Anlegen.');
    }
  };

  const handleDeleteSkill = async (id) => {
    try {
      await apiFetch(`/skills/${id}/`, { method: 'DELETE' });
      onRefreshSkills();
      showNotif('Qualifikation gelöscht.');
    } catch (e) {
      setError(e.message || 'Fehler beim Löschen.');
    }
  };

  const handleDeleteTemplate = async (id) => {
    try {
      await apiFetch(`/templates/${id}/`, { method: 'DELETE' });
      setTemplatesList(templatesList.filter(t => t.id !== id));
      showNotif('Vorlage gelöscht.');
    } catch (e) {
      setError(e.message || 'Fehler beim Löschen.');
    }
  };

  // --- 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-5xl mx-auto animate-in fade-in duration-200 font-sans">
      {/* Header Banner */}
      <div className="hallmark-panel rounded-sm p-6 sm:p-8 border border-grid space-y-2">
        <div className="flex items-center gap-3">
          <div className="w-10 h-10 rounded-sm bg-indigo-500/10 text-indigo-500 border border-indigo-500/20 flex items-center justify-center font-bold">
            <Shield className="w-5 h-5" />
          </div>
          <div>
            <h2 className="font-serif text-3xl font-bold uppercase tracking-tight text-main">
              System Administration
            </h2>
            <p className="text-xs text-muted font-mono mt-0.5">
              Verwaltung von Benutzern, Freischaltungen, Events, Vorlagen, Branding & SMTP-Mailserver
            </p>
          </div>
        </div>
      </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>
        </div>
      </div>

      {/* Notifications */}
      {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>
      )}

      {/* TAB 1: BENUTZER & SICHERHEIT */}
      {activeAdminTab === 'users' && (
        <div className="space-y-6 animate-in fade-in duration-150 font-mono">
          {/* Pending Approval 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={() => handleApprovePendingUser(pu.id)}
                        className="px-3 py-1 rounded-sm bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs"
                      >
                        [ FREISCHALTEN ]
                      </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>

          {/* All Users 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">
                        <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-subtle text-muted border-grid'
                        }`}>
                          {u.is_email_verified ? 'VERIFIZIERT' : 'AUSSTEHEND'}
                        </span>
                      </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">
              Sicherheit & Registrierungs-Einschränkungen
            </h3>

            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              <div className="p-4 rounded-sm bg-subtle border border-grid space-y-2">
                <div className="flex items-center justify-between">
                  <span className="font-bold text-main">E-Mail Bestätigung (Opt-Out)</span>
                  <button
                    onClick={() => handleToggleRestriction('email_verify', !requireEmailVerification)}
                    className={`px-3 py-1 rounded-sm text-xs font-bold transition border ${
                      requireEmailVerification ? 'bg-emerald-600 text-white border-emerald-500' : 'bg-amber-500/10 text-amber-500 border-amber-500/20'
                    }`}
                  >
                    {requireEmailVerification ? '[ PFLICHT ]' : '[ DEAKTIVIERT ]'}
                  </button>
                </div>
                <p className="text-[11px] text-muted font-sans">
                  Bei Pflicht muss die E-Mail vor der Anmeldung verifiziert werden. Bei Deaktivierung ist die Anmeldung direkt möglich.
                </p>
              </div>

              <div className="p-4 rounded-sm bg-subtle border border-grid space-y-2">
                <div className="flex items-center justify-between">
                  <span className="font-bold text-main">Domain-Einschränkung</span>
                  <button
                    onClick={() => handleToggleRestriction('restriction', !restrictionEnabled)}
                    className={`px-3 py-1 rounded-sm text-xs font-bold transition border ${
                      restrictionEnabled ? 'bg-emerald-600 text-white border-emerald-500' : 'bg-surface text-muted border-grid'
                    }`}
                  >
                    {restrictionEnabled ? '[ AKTIV ]' : '[ INAKTIV ]'}
                  </button>
                </div>
                <p className="text-[11px] text-muted font-sans">
                  Erlaubt nur Registrierungen von festgelegten E-Mail-Domains (z. B. `@verein.de`).
                </p>
              </div>

              <div className="p-4 rounded-sm bg-subtle border border-grid space-y-2">
                <div className="flex items-center justify-between">
                  <span className="font-bold text-main">Admin-Freischaltpflicht</span>
                  <button
                    onClick={() => handleToggleRestriction('approval', !requireApproval)}
                    className={`px-3 py-1 rounded-sm text-xs font-bold transition border ${
                      requireApproval ? 'bg-emerald-600 text-white border-emerald-500' : 'bg-surface text-muted border-grid'
                    }`}
                  >
                    {requireApproval ? '[ AKTIV ]' : '[ INAKTIV ]'}
                  </button>
                </div>
                <p className="text-[11px] text-muted font-sans">
                  Erfordert die manuelle Freischaltung durch einen Admin vor der ersten Anmeldung.
                </p>
              </div>
            </div>

            {/* Allowed Domains List */}
            {restrictionEnabled && (
              <div className="space-y-3 pt-3 border-t border-grid">
                <h4 className="font-serif text-sm font-bold uppercase text-main">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 px-3 py-1.5 rounded-sm input-field text-xs font-mono"
                  />
                  <button type="submit" className="px-4 py-1.5 rounded-sm bg-indigo-600 hover:bg-indigo-500 text-white font-bold text-xs">
                    <Plus className="w-3.5 h-3.5 inline" /> Domain Hinzufügen
                  </button>
                </form>
                <div className="flex flex-wrap gap-2">
                  {domainRules.map(r => (
                    <span key={r.id} className="px-2.5 py-1 rounded-sm bg-subtle border border-grid text-xs flex items-center gap-2">
                      <strong className="text-main">{r.domain}</strong>
                      <button onClick={() => handleDeleteDomainRule(r.id)} className="text-muted hover:text-red-400">
                        <Trash2 className="w-3.5 h-3.5" />
                      </button>
                    </span>
                  ))}
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* TAB 2: VERANSTALTUNGEN */}
      {activeAdminTab === 'events' && (
        <div className="space-y-6 animate-in fade-in duration-150 font-mono">
          <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">
              Alle Veranstaltungen ({eventsList.length})
            </h3>
            <div className="space-y-3">
              {eventsList.map(evt => (
                <div key={evt.id} className="p-4 rounded-sm bg-subtle border border-grid flex items-center justify-between text-xs">
                  <div>
                    <h4 className="font-serif font-bold text-main text-sm">{evt.title}</h4>
                    <p className="text-muted text-[11px]">
                      {new Date(evt.start_date).toLocaleDateString('de-DE')} — {evt.location || 'Kein Ort'} | Erstellt von: {evt.created_by_name || 'Admin'}
                    </p>
                  </div>
                  <div className="flex items-center gap-2">
                    <span className={`px-2 py-0.5 rounded-sm text-[10px] font-bold border ${
                      evt.is_active !== false ? 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20' : 'bg-amber-500/10 text-amber-400 border-amber-500/20'
                    }`}>
                      {evt.is_active !== false ? 'AKTIV' : 'DEAKTIVIERT'}
                    </span>
                    <button
                      onClick={async () => {
                        if (window.confirm(`Möchtest du "${evt.title}" und alle Schichten wirklich unwiderruflich löschen?`)) {
                          try {
                            await apiFetch(`/events/${evt.id}/`, { method: 'DELETE' });
                            onRefreshEvents();
                          } catch (e) {
                            alert(e.message);
                          }
                        }
                      }}
                      className="px-2.5 py-1 rounded-sm text-[10px] font-bold bg-red-500/10 hover:bg-red-500/20 text-red-400 border border-red-500/20 transition flex items-center gap-1"
                      title="Veranstaltung löschen"
                    >
                      <Trash2 className="w-3 h-3" /> LÖSCHEN
                    </button>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* TAB 3: VORLAGEN & QUALIFIKATIONEN */}
      {activeAdminTab === 'templates' && (
        <div className="space-y-6 animate-in fade-in duration-150 font-mono">
          {/* 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">
              Erforderliche Qualifikationen (Skills)
            </h3>

            <form onSubmit={handleCreateSkill} className="grid grid-cols-1 sm:grid-cols-3 gap-3">
              <input
                type="text"
                placeholder="Skill Name (z. B. Bar-Erfahrung)"
                required
                value={newSkillName}
                onChange={(e) => setNewSkillName(e.target.value)}
                className="px-3 py-1.5 rounded-sm input-field text-xs font-mono"
              />
              <input
                type="text"
                placeholder="Beschreibung (optional)"
                value={newSkillDesc}
                onChange={(e) => setNewSkillDesc(e.target.value)}
                className="px-3 py-1.5 rounded-sm input-field text-xs font-mono"
              />
              <div className="flex gap-2">
                <input
                  type="color"
                  value={newSkillColor}
                  onChange={(e) => setNewSkillColor(e.target.value)}
                  className="w-8 h-8 rounded-sm border-0 cursor-pointer bg-subtle p-0.5"
                />
                <button type="submit" className="flex-1 px-3 py-1.5 rounded-sm bg-emerald-600 hover:bg-emerald-500 text-white font-bold text-xs">
                  <Plus className="w-3.5 h-3.5 inline" /> Anlegen
                </button>
              </div>
            </form>

            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 pt-2">
              {skills.map(s => (
                <div key={s.id} className="p-3 rounded-sm bg-subtle border border-grid flex items-center justify-between text-xs">
                  <div>
                    <span style={{ color: s.color }} className="font-bold">{s.name}</span>
                    {s.description && <p className="text-[11px] text-muted">{s.description}</p>}
                  </div>
                  <button onClick={() => handleDeleteSkill(s.id)} className="text-muted hover:text-red-400">
                    <Trash2 className="w-3.5 h-3.5" />
                  </button>
                </div>
              ))}
            </div>
          </div>

          {/* Event Templates */}
          <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">
              Gespeicherte Event-Vorlagen ({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 text-xs">
                  <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="text-muted hover:text-red-400">
                    <Trash2 className="w-4 h-4" />
                  </button>
                </div>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* TAB 4: BRANDING & SYSTEM */}
      {activeAdminTab === 'branding' && (
        <div className="space-y-6 animate-in fade-in duration-150 font-mono">
          <form onSubmit={handleSaveBranding} className="hallmark-panel rounded-sm p-6 border border-grid space-y-6">
            <h3 className="font-serif text-lg font-bold uppercase text-main border-b border-grid pb-2 flex items-center gap-2">
              <Palette className="w-5 h-5 text-indigo-400" /> Portal Branding & Erscheinungsbild
            </h3>

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

              <div>
                <label className="block text-muted mb-1">Primärfarbe (Brand Accent)</label>
                <div className="flex gap-2">
                  <input
                    type="color"
                    value={primaryColor}
                    onChange={(e) => setPrimaryColor(e.target.value)}
                    className="w-9 h-9 rounded-sm border-0 cursor-pointer bg-subtle p-0.5"
                  />
                  <input
                    type="text"
                    value={primaryColor}
                    onChange={(e) => setPrimaryColor(e.target.value)}
                    className="flex-1 px-3 py-1.5 rounded-sm input-field font-mono"
                  />
                </div>
              </div>

              <div className="sm:col-span-2">
                <label className="block text-muted mb-1">Logo Bild-URL (optional)</label>
                <input
                  type="text"
                  placeholder="https://beispiel.de/logo.png"
                  value={logoUrl}
                  onChange={(e) => setLogoUrl(e.target.value)}
                  className="w-full px-3 py-1.5 rounded-sm input-field"
                />
              </div>

              <div className="sm:col-span-2">
                <label className="block text-muted mb-1">Ankündigung (Banner-Text)</label>
                <textarea
                  rows={2}
                  placeholder="z. B. Willkommen beim Sommerfest Schichtplaner!"
                  value={bannerText}
                  onChange={(e) => setBannerText(e.target.value)}
                  className="w-full px-3 py-1.5 rounded-sm input-field"
                />
              </div>
            </div>

            <h4 className="font-serif text-base font-bold uppercase text-main pt-4 border-t border-grid">
              Startseiten Sidebar Boxen
            </h4>

            {/* Community Info Box Settings */}
            <div className="p-4 rounded-sm bg-subtle border border-grid space-y-3">
              <div className="flex items-center justify-between border-b border-grid pb-2">
                <span className="font-bold text-xs uppercase text-main">📌 Verein & Infos Box</span>
                <button
                  type="button"
                  onClick={() => setShowCommunityInfoBox(!showCommunityInfoBox)}
                  className={`px-3 py-1 rounded-sm text-xs font-bold transition border ${
                    showCommunityInfoBox ? 'bg-emerald-600 text-white border-emerald-500' : 'bg-surface text-muted border-grid'
                  }`}
                >
                  {showCommunityInfoBox ? '[ AN ]' : '[ AUS ]'}
                </button>
              </div>

              {showCommunityInfoBox && (
                <div className="space-y-3 text-xs">
                  <div>
                    <label className="block text-muted mb-1">Titel</label>
                    <input
                      type="text"
                      value={communityInfoTitle}
                      onChange={(e) => setCommunityInfoTitle(e.target.value)}
                      className="w-full px-3 py-1.5 rounded-sm input-field"
                    />
                  </div>
                  <div>
                    <label className="block text-muted mb-1">Inhalt</label>
                    <textarea
                      rows={3}
                      value={communityInfoText}
                      onChange={(e) => setCommunityInfoText(e.target.value)}
                      className="w-full px-3 py-1.5 rounded-sm input-field"
                    />
                  </div>
                </div>
              )}
            </div>

            {/* Support Box Settings */}
            <div className="p-4 rounded-sm bg-subtle border border-grid space-y-3">
              <div className="flex items-center justify-between border-b border-grid pb-2">
                <span className="font-bold text-xs uppercase text-main">❤️ Unterstützen Box</span>
                <button
                  type="button"
                  onClick={() => setShowSupportBox(!showSupportBox)}
                  className={`px-3 py-1 rounded-sm text-xs font-bold transition border ${
                    showSupportBox ? 'bg-emerald-600 text-white border-emerald-500' : 'bg-surface text-muted border-grid'
                  }`}
                >
                  {showSupportBox ? '[ AN ]' : '[ AUS ]'}
                </button>
              </div>

              {showSupportBox && (
                <div className="space-y-3 text-xs">
                  <div>
                    <label className="block text-muted mb-1">Titel</label>
                    <input
                      type="text"
                      value={supportBoxTitle}
                      onChange={(e) => setSupportBoxTitle(e.target.value)}
                      className="w-full px-3 py-1.5 rounded-sm input-field"
                    />
                  </div>
                  <div>
                    <label className="block text-muted mb-1">Inhalt</label>
                    <textarea
                      rows={3}
                      value={supportBoxText}
                      onChange={(e) => setSupportBoxText(e.target.value)}
                      className="w-full px-3 py-1.5 rounded-sm input-field"
                    />
                  </div>
                </div>
              )}
            </div>

            <div className="pt-3 flex justify-end border-t border-grid">
              <button
                type="submit"
                disabled={savingBranding}
                style={{ backgroundColor: 'var(--brand-primary)' }}
                className="px-6 py-2.5 rounded-sm text-xs font-mono font-bold text-white transition hover:brightness-110 shadow-sm"
              >
                {savingBranding ? 'Speichern...' : 'Einstellungen speichern'}
              </button>
            </div>
          </form>
        </div>
      )}

      {/* TAB 5: E-MAIL & SMTP EINSTELLUNGEN */}
      {activeAdminTab === 'smtp' && (
        <div className="space-y-6 animate-in fade-in duration-150 font-mono">
          <form onSubmit={handleSaveSMTP} className="hallmark-panel rounded-sm p-6 border border-grid space-y-6">
            <div className="flex items-center justify-between border-b border-grid pb-3">
              <h3 className="font-serif text-lg font-bold uppercase text-main flex items-center gap-2">
                <Mail className="w-5 h-5 text-indigo-400" /> SMTP Server & E-Mail-Versand
              </h3>

              <div className="flex items-center gap-2">
                <span className="text-xs text-muted font-bold">SMTP-Versand:</span>
                <button
                  type="button"
                  onClick={() => setSmtpActive(!smtpActive)}
                  className={`px-3 py-1 rounded-sm text-xs font-bold transition border ${
                    smtpActive
                      ? 'bg-emerald-600 text-white border-emerald-500 shadow-sm'
                      : 'bg-subtle text-muted border-grid hover:text-main'
                  }`}
                >
                  {smtpActive ? '[ AKTIV ]' : '[ INAKTIV (Dev Mode) ]'}
                </button>
              </div>
            </div>

            {!smtpActive && (
              <div className="p-3.5 rounded-sm bg-amber-500/10 border border-amber-500/20 text-amber-500 text-xs flex items-center gap-2">
                <AlertCircle className="w-4 h-4 shrink-0" />
                <span>
                  Hinweis: Im inaktiven Modus werden Bestätigungs-Links in der Entwickler-Konsole / Logs ausgegeben.
                </span>
              </div>
            )}

            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 text-xs">
              <div className="sm:col-span-2">
                <label className="block text-main mb-1 font-bold">SMTP Host / Server Adresse</label>
                <input
                  type="text"
                  placeholder="z. B. smtp.domain.de oder mail.gmx.net"
                  value={smtpHost}
                  onChange={(e) => setSmtpHost(e.target.value)}
                  className="w-full px-3.5 py-2 rounded-sm input-field font-mono"
                />
              </div>

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

              <div>
                <label className="block text-main mb-1 font-bold">Absender E-Mail-Adresse (From)</label>
                <input
                  type="email"
                  placeholder="noreply@verein.de"
                  value={smtpFromEmail}
                  onChange={(e) => setSmtpFromEmail(e.target.value)}
                  className="w-full px-3.5 py-2 rounded-sm input-field font-mono"
                />
              </div>

              <div>
                <label className="block text-main mb-1 font-bold">SMTP Benutzername / Login E-Mail</label>
                <input
                  type="text"
                  placeholder="z. B. noreply@verein.de"
                  value={smtpUsername}
                  onChange={(e) => setSmtpUsername(e.target.value)}
                  className="w-full px-3.5 py-2 rounded-sm input-field font-mono"
                />
              </div>

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

              <div className="sm:col-span-2 flex items-center gap-6 pt-2">
                <label className="flex items-center gap-2 cursor-pointer text-main font-bold">
                  <input
                    type="checkbox"
                    checked={smtpUseTls}
                    onChange={(e) => {
                      setSmtpUseTls(e.target.checked);
                      if (e.target.checked) setSmtpUseSsl(false);
                    }}
                    className="rounded-sm"
                  />
                  <span>STARTTLS verwenden (Empfohlen für Port 587)</span>
                </label>

                <label className="flex items-center gap-2 cursor-pointer text-main font-bold">
                  <input
                    type="checkbox"
                    checked={smtpUseSsl}
                    onChange={(e) => {
                      setSmtpUseSsl(e.target.checked);
                      if (e.target.checked) setSmtpUseTls(false);
                    }}
                    className="rounded-sm"
                  />
                  <span>SSL/TLS verwenden (Empfohlen für Port 465)</span>
                </label>
              </div>
            </div>

            <div className="pt-4 border-t border-grid flex flex-wrap items-center justify-between gap-3">
              {/* Test Email Box */}
              <div className="flex items-center gap-2 flex-1 min-w-[260px]">
                <input
                  type="email"
                  placeholder="Empfänger für Test-E-Mail..."
                  value={smtpTestEmail}
                  onChange={(e) => setSmtpTestEmail(e.target.value)}
                  className="px-3 py-1.5 rounded-sm input-field text-xs flex-1 font-mono"
                />
                <button
                  type="button"
                  disabled={testingSmtp}
                  onClick={handleTestSMTP}
                  className="px-3.5 py-1.5 rounded-sm text-xs font-mono font-bold bg-indigo-500/10 text-indigo-400 border border-indigo-500/20 hover:bg-indigo-500/20 transition flex items-center gap-1.5 shrink-0"
                >
                  <Send className="w-3.5 h-3.5" />
                  {testingSmtp ? 'Sende...' : 'Test-Mail Senden'}
                </button>
              </div>

              <button
                type="submit"
                disabled={savingSmtp}
                style={{ backgroundColor: 'var(--brand-primary)' }}
                className="px-6 py-2.5 rounded-sm text-xs font-mono font-bold text-white transition hover:brightness-110 shadow-sm flex items-center gap-2"
              >
                <CheckCircle2 className="w-4 h-4" />
                {savingSmtp ? 'Speichern...' : 'SMTP-Einstellungen Speichern'}
              </button>
            </div>
          </form>
        </div>
      )}
    </div>
  );
}
