import React from 'react';
import { TabComponent, TabItemDirective, TabItemsDirective } from '@syncfusion/ej2-react-navigations';
import { NumericTextBoxComponent, TextBoxComponent } from '@syncfusion/ej2-react-inputs';
import { ButtonComponent, CheckBoxComponent } from '@syncfusion/ej2-react-buttons';
import { ToastComponent } from '@syncfusion/ej2-react-notifications';
import { listHolidays, uploadHolidaysCsv, type Holiday } from './apiHolidays';
import { getSupplementTableSettings, updateSupplementTableSettings, getHolidayBannerSetting, updateHolidayBannerSetting } from './apiSystemSettings';
import { useAuth } from './useAuth';
import { DropDownListComponent } from '@syncfusion/ej2-react-dropdowns';
import { listAcademicPeriods, getActiveAcademicPeriod, setActiveAcademicPeriod, type AcademicPeriod } from './apiAcademicPeriods';
import { Link } from 'react-router-dom';

// Minimal event type for Syncfusion Tab 'selected' callback
type TabSelectedEvent = { selectedIndex?: number };

const Einstellungen: React.FC = () => {
  // Presentation settings state
  const [presentationInterval, setPresentationInterval] = React.useState(10);
  const [presentationPageProgress, setPresentationPageProgress] = React.useState(true);
  const [presentationAutoProgress, setPresentationAutoProgress] = React.useState(true);
  const [presentationBusy, setPresentationBusy] = React.useState(false);

  // Load settings from backend
  const loadPresentationSettings = React.useCallback(async () => {
    try {
      const keys = [
        'presentation_interval',
        'presentation_page_progress',
        'presentation_auto_progress',
      ];
      const results = await Promise.all(keys.map(k => import('./apiSystemSettings').then(m => m.getSetting(k))));
      setPresentationInterval(Number(results[0].value) || 10);
      setPresentationPageProgress(results[1].value === 'true');
      setPresentationAutoProgress(results[2].value === 'true');
    } catch {
      showToast('Fehler beim Laden der Präsentations-Einstellungen', 'e-toast-danger');
    }
  }, []);

  React.useEffect(() => {
    loadPresentationSettings();
  }, [loadPresentationSettings]);

  const onSavePresentationSettings = async () => {
    setPresentationBusy(true);
    try {
      const api = await import('./apiSystemSettings');
      await Promise.all([
        api.updateSetting('presentation_interval', String(presentationInterval)),
        api.updateSetting('presentation_page_progress', presentationPageProgress ? 'true' : 'false'),
        api.updateSetting('presentation_auto_progress', presentationAutoProgress ? 'true' : 'false'),
      ]);
      showToast('Präsentations-Einstellungen gespeichert', 'e-toast-success');
    } catch {
      showToast('Fehler beim Speichern der Präsentations-Einstellungen', 'e-toast-danger');
    } finally {
      setPresentationBusy(false);
    }
  };
  const { user } = useAuth();
  const toastRef = React.useRef<ToastComponent>(null);

  // Holidays state
  const [file, setFile] = React.useState<File | null>(null);
  const [busy, setBusy] = React.useState(false);
  const [message, setMessage] = React.useState<string | null>(null);
  const [holidays, setHolidays] = React.useState<Holiday[]>([]);
  const [periods, setPeriods] = React.useState<AcademicPeriod[]>([]);
  const [activePeriodId, setActivePeriodId] = React.useState<number | null>(null);
  const periodOptions = React.useMemo(() =>
    periods.map(p => ({ id: p.id, name: p.display_name || p.name })),
    [periods]
  );

  // Supplement table state
  const [supplementUrl, setSupplementUrl] = React.useState('');
  const [supplementEnabled, setSupplementEnabled] = React.useState(false);
  const [supplementBusy, setSupplementBusy] = React.useState(false);

  // Holiday banner state
  const [holidayBannerEnabled, setHolidayBannerEnabled] = React.useState(true);
  const [holidayBannerBusy, setHolidayBannerBusy] = React.useState(false);

  // Video defaults state (Admin+)
  const [videoAutoplay, setVideoAutoplay] = React.useState<boolean>(true);
  const [videoLoop, setVideoLoop] = React.useState<boolean>(true);
  const [videoVolume, setVideoVolume] = React.useState<number>(0.8);
  const [videoMuted, setVideoMuted] = React.useState<boolean>(false);
  const [videoBusy, setVideoBusy] = React.useState<boolean>(false);

  // Organization name state (Superadmin only)
  const [organizationName, setOrganizationName] = React.useState<string>('');
  const [organizationBusy, setOrganizationBusy] = React.useState<boolean>(false);

  // Advanced options: Scheduler refresh interval (Superadmin)
  const [refreshSeconds, setRefreshSeconds] = React.useState<number>(0);
  const [refreshBusy, setRefreshBusy] = React.useState<boolean>(false);

  const showToast = (content: string, cssClass: string = 'e-toast-success') => {
    if (toastRef.current) {
      toastRef.current.show({
        content,
        cssClass,
        timeOut: 3000,
      });
    }
  };

  const refresh = React.useCallback(async () => {
    try {
      const data = await listHolidays();
      setHolidays(data.holidays);
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Fehler beim Laden der Ferien';
      setMessage(msg);
      showToast(msg, 'e-toast-danger');
    }
  }, []);

  const loadSupplementSettings = React.useCallback(async () => {
    try {
      const data = await getSupplementTableSettings();
      setSupplementUrl(data.url || '');
      setSupplementEnabled(data.enabled || false);
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Fehler beim Laden der Vertretungsplan-Einstellungen';
      showToast(msg, 'e-toast-danger');
    }
  }, []);

  const loadHolidayBannerSetting = React.useCallback(async () => {
    try {
      const data = await getHolidayBannerSetting();
      setHolidayBannerEnabled(data.enabled);
    } catch (e) {
      console.error('Fehler beim Laden der Ferienbanner-Einstellung:', e);
    }
  }, []);

  // Load video default settings (with fallbacks)
  const loadVideoSettings = React.useCallback(async () => {
    try {
      const api = await import('./apiSystemSettings');
      const keys = ['video_autoplay', 'video_loop', 'video_volume', 'video_muted'] as const;
      const [autoplay, loop, volume, muted] = await Promise.all(
        keys.map(k => api.getSetting(k).catch(() => ({ value: null } as { value: string | null })))
      );
      setVideoAutoplay(autoplay.value == null ? true : autoplay.value === 'true');
      setVideoLoop(loop.value == null ? true : loop.value === 'true');
      const volParsed = volume.value == null ? 0.8 : parseFloat(String(volume.value));
      setVideoVolume(Number.isFinite(volParsed) ? volParsed : 0.8);
      setVideoMuted(muted.value == null ? false : muted.value === 'true');
    } catch (e) {
      // Fallback to defaults on any error
      setVideoAutoplay(true);
      setVideoLoop(true);
      setVideoVolume(0.8);
      setVideoMuted(false);
      const msg = e instanceof Error ? e.message : 'Fehler beim Laden der Video-Standards';
      showToast(msg, 'e-toast-warning');
    }
  }, []);

  // Load organization name (superadmin only, but endpoint is public)
  const loadOrganizationName = React.useCallback(async () => {
    try {
      const api = await import('./apiSystemSettings');
      const data = await api.getOrganizationName();
      setOrganizationName(data.name || '');
    } catch (e) {
      console.error('Fehler beim Laden des Organisationsnamens:', e);
    }
  }, []);

  // Load scheduler refresh seconds (superadmin)
  const loadRefreshSeconds = React.useCallback(async () => {
    try {
      const api = await import('./apiSystemSettings');
      const setting = await api.getSetting('refresh_seconds');
      const parsed = Number(setting.value ?? 0);
      setRefreshSeconds(Number.isFinite(parsed) ? parsed : 0);
    } catch {
      // Default to 0 if not present
      setRefreshSeconds(0);
    }
  }, []);

  const loadAcademicPeriods = React.useCallback(async () => {
    try {
      const [list, active] = await Promise.all([
        listAcademicPeriods(),
        getActiveAcademicPeriod(),
      ]);
      setPeriods(list);
      setActivePeriodId(active ? active.id : null);
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Fehler beim Laden der Schuljahre/Perioden';
      showToast(msg, 'e-toast-danger');
    }
  }, []);

  React.useEffect(() => {
    refresh();
    loadHolidayBannerSetting(); // Everyone can see this
    if (user) {
      // Academic periods for all users
      loadAcademicPeriods();
      // System settings only for admin/superadmin (will render only if allowed)
      if (['admin', 'superadmin'].includes(user.role)) {
        loadSupplementSettings();
        loadPresentationSettings();
        loadVideoSettings();
      }
      // Organization name only for superadmin
      if (user.role === 'superadmin') {
        loadOrganizationName();
        loadRefreshSeconds();
      }
    }
  }, [refresh, loadSupplementSettings, loadAcademicPeriods, loadPresentationSettings, loadVideoSettings, loadHolidayBannerSetting, loadOrganizationName, loadRefreshSeconds, user]);

  const onUpload = async () => {
    if (!file) return;
    setBusy(true);
    setMessage(null);
    try {
      const res = await uploadHolidaysCsv(file);
      const msg = `Import erfolgreich: ${res.inserted} neu, ${res.updated} aktualisiert.`;
      setMessage(msg);
      showToast(msg, 'e-toast-success');
      await refresh();
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Fehler beim Import.';
      setMessage(msg);
      showToast(msg, 'e-toast-danger');
    } finally {
      setBusy(false);
    }
  };

  const onSaveSupplementSettings = async () => {
    setSupplementBusy(true);
    try {
      await updateSupplementTableSettings(supplementUrl, supplementEnabled);
      showToast('Vertretungsplan-Einstellungen erfolgreich gespeichert', 'e-toast-success');
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Fehler beim Speichern der Einstellungen';
      showToast(msg, 'e-toast-danger');
    } finally {
      setSupplementBusy(false);
    }
  };

  const onTestSupplementUrl = () => {
    if (supplementUrl) {
      window.open(supplementUrl, '_blank');
    } else {
      showToast('Bitte geben Sie zuerst eine URL ein', 'e-toast-warning');
    }
  };

  const onSaveHolidayBannerSetting = async () => {
    setHolidayBannerBusy(true);
    try {
      await updateHolidayBannerSetting(holidayBannerEnabled);
      showToast('Ferienbanner-Einstellung gespeichert', 'e-toast-success');
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Fehler beim Speichern';
      showToast(msg, 'e-toast-danger');
    } finally {
      setHolidayBannerBusy(false);
    }
  };

  const onSaveVideoSettings = async () => {
    setVideoBusy(true);
    try {
      const api = await import('./apiSystemSettings');
      await Promise.all([
        api.updateSetting('video_autoplay', videoAutoplay ? 'true' : 'false'),
        api.updateSetting('video_loop', videoLoop ? 'true' : 'false'),
        api.updateSetting('video_volume', String(videoVolume)),
        api.updateSetting('video_muted', videoMuted ? 'true' : 'false'),
      ]);
      showToast('Video-Standardeinstellungen gespeichert', 'e-toast-success');
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Fehler beim Speichern der Video-Standards';
      showToast(msg, 'e-toast-danger');
    } finally {
      setVideoBusy(false);
    }
  };

  const onSaveOrganizationName = async () => {
    setOrganizationBusy(true);
    try {
      const api = await import('./apiSystemSettings');
      await api.updateOrganizationName(organizationName);
      showToast('Organisationsname gespeichert', 'e-toast-success');
      // Trigger a custom event to notify App.tsx to refresh the header
      window.dispatchEvent(new Event('organizationNameUpdated'));
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Fehler beim Speichern des Organisationsnamens';
      showToast(msg, 'e-toast-danger');
    } finally {
      setOrganizationBusy(false);
    }
  };

  const onSaveRefreshSeconds = async () => {
    setRefreshBusy(true);
    try {
      const api = await import('./apiSystemSettings');
      await api.updateSetting('refresh_seconds', String(refreshSeconds));
      showToast('Scheduler-Refresh-Intervall gespeichert', 'e-toast-success');
    } catch (e) {
      const msg = e instanceof Error ? e.message : 'Fehler beim Speichern des Intervalls';
      showToast(msg, 'e-toast-danger');
    } finally {
      setRefreshBusy(false);
    }
  };

  // Determine which tabs to show based on role
  const isAdmin = !!(user && ['admin', 'superadmin'].includes(user.role));
  const isSuperadmin = !!(user && user.role === 'superadmin');

  // Preserve selected nested-tab indices to avoid resets on parent re-render
  const [academicTabIndex, setAcademicTabIndex] = React.useState(0);
  const [displayTabIndex, setDisplayTabIndex] = React.useState(0);
  const [mediaTabIndex, setMediaTabIndex] = React.useState(0);
  const [eventsTabIndex, setEventsTabIndex] = React.useState(0);
  const [usersTabIndex, setUsersTabIndex] = React.useState(0);
  const [systemTabIndex, setSystemTabIndex] = React.useState(0);

  // ---------- Leaf content functions (second-level tabs) ----------
  // Academic Calendar
  // (Old separate Import/List tab contents removed in favor of combined tab)

  // Combined Import + List tab content
  const HolidaysImportAndListContent = () => (
    <div style={{ padding: 20 }}>
      {/* Import Card */}
      <div className="e-card" style={{ marginBottom: 20 }}>
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Schulferien importieren</div>
          </div>
        </div>
        <div className="e-card-content">
          <p style={{ marginBottom: 12, fontSize: '14px', color: '#666' }}>
            Unterstützte Formate:
            <br />• CSV mit Kopfzeile: <code>name</code>, <code>start_date</code>, <code>end_date</code>, optional <code>region</code>
            <br />• TXT/CSV ohne Kopfzeile mit Spalten: interner Name, <strong>Name</strong>, <strong>Start (YYYYMMDD)</strong>, <strong>Ende (YYYYMMDD)</strong>, optional interne Info (ignoriert)
          </p>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
            <input type="file" accept=".csv,text/csv,.txt,text/plain" onChange={e => setFile(e.target.files?.[0] ?? null)} />
            <ButtonComponent cssClass="e-primary" onClick={onUpload} disabled={!file || busy}>
              {busy ? 'Importiere…' : 'CSV/TXT importieren'}
            </ButtonComponent>
          </div>
          {message && <div style={{ marginTop: 8, fontSize: '14px' }}>{message}</div>}
        </div>
      </div>

      {/* List Card */}
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Importierte Ferien</div>
          </div>
        </div>
        <div className="e-card-content">
          {holidays.length === 0 ? (
            <div style={{ fontSize: '14px', color: '#666' }}>Keine Einträge vorhanden.</div>
          ) : (
            <ul style={{ fontSize: '14px', listStyle: 'disc', paddingLeft: 24 }}>
              {holidays.slice(0, 20).map(h => (
                <li key={h.id}>
                  {h.name}: {h.start_date} – {h.end_date}
                  {h.region ? ` (${h.region})` : ''}
                </li>
              ))}
            </ul>
          )}
        </div>
      </div>

      {/* Dashboard Display Settings Card */}
      <div className="e-card" style={{ marginTop: 20 }}>
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Dashboard-Anzeige</div>
          </div>
        </div>
        <div className="e-card-content">
          <div style={{ marginBottom: 16 }}>
            <CheckBoxComponent
              label="Ferienstatus-Banner auf Dashboard anzeigen"
              checked={holidayBannerEnabled}
              change={(e) => setHolidayBannerEnabled(e.checked || false)}
            />
            <div style={{ fontSize: '12px', color: '#666', marginTop: 4, marginLeft: 24 }}>
              Zeigt eine Information an, ob ein Ferienplan für die aktive Periode importiert wurde.
            </div>
          </div>
          <ButtonComponent
            cssClass="e-primary"
            onClick={onSaveHolidayBannerSetting}
            disabled={holidayBannerBusy}
          >
            {holidayBannerBusy ? 'Speichere…' : 'Einstellung speichern'}
          </ButtonComponent>
        </div>
      </div>
    </div>
  );

  const AcademicPeriodsContent = () => (
    <div style={{ padding: 20 }}>
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Akademische Perioden</div>
          </div>
        </div>
        <div className="e-card-content">
          {periods.length === 0 ? (
            <div style={{ fontSize: '14px', color: '#666' }}>Keine Perioden gefunden.</div>
          ) : (
            <div style={{ display: 'flex', gap: 12, alignItems: 'center', flexWrap: 'wrap' }}>
              <div style={{ minWidth: 260 }}>
                <DropDownListComponent
                  dataSource={periodOptions}
                  fields={{ text: 'name', value: 'id' }}
                  value={activePeriodId ?? undefined}
                  change={(e) => setActivePeriodId(Number(e.value))}
                  placeholder="Aktive Periode wählen"
                  popupHeight="250px"
                />
              </div>
              <ButtonComponent
                cssClass="e-primary"
                disabled={activePeriodId == null}
                onClick={async () => {
                  if (activePeriodId == null) return;
                  try {
                    const p = await setActiveAcademicPeriod(activePeriodId);
                    showToast(`Aktive Periode gesetzt: ${p.display_name || p.name}`, 'e-toast-success');
                    await loadAcademicPeriods();
                  } catch (e) {
                    const msg = e instanceof Error ? e.message : 'Fehler beim Setzen der aktiven Periode';
                    showToast(msg, 'e-toast-danger');
                  }
                }}
              >
                Als aktiv setzen
              </ButtonComponent>
            </div>
          )}
        </div>
      </div>
    </div>
  );

  // Display & Clients
  const DisplayDefaultsContent = () => (
    <div style={{ padding: 20 }}>
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Standard-Einstellungen</div>
          </div>
        </div>
        <div className="e-card-content" style={{ color: '#666', fontSize: 14 }}>
          Platzhalter für Anzeige-Defaults (z. B. Heartbeat-Timeout, Screenshot-Aufbewahrung, Standard-Gruppe).
        </div>
      </div>
    </div>
  );

  const ClientsConfigContent = () => (
    <div style={{ padding: 20 }}>
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Client-Konfiguration</div>
          </div>
        </div>
        <div className="e-card-content">
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <Link to="/clients"><ButtonComponent>Infoscreen-Clients öffnen</ButtonComponent></Link>
            <Link to="/infoscr_groups"><ButtonComponent>Raumgruppen öffnen</ButtonComponent></Link>
          </div>
        </div>
      </div>
    </div>
  );
        
  const UploadSettingsContent = () => (
    <div style={{ padding: 20 }}>
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Upload-Einstellungen</div>
          </div>
        </div>
        <div className="e-card-content" style={{ color: '#666', fontSize: 14 }}>
          Platzhalter für Upload-Limits, erlaubte Dateitypen und Standardspeicherorte.
        </div>
      </div>
    </div>
  );

  const ConversionStatusContent = () => (
    <div style={{ padding: 20 }}>
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Konvertierungsstatus</div>
          </div>
        </div>
        <div className="e-card-content" style={{ color: '#666', fontSize: 14 }}>
          Platzhalter – Konversionsstatus-Übersicht kann hier integriert werden (siehe API /api/conversions/...).
        </div>
      </div>
    </div>
  );

  // Events
  const WebUntisSettingsContent = () => (
    <div style={{ padding: 20 }}>
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">WebUntis / Vertretungsplan</div>
          </div>
        </div>
        <div className="e-card-content">
          <div style={{ marginBottom: 16 }}>
            <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>
              Vertretungsplan URL
            </label>
            <TextBoxComponent
              placeholder="https://example.com/vertretungsplan"
              value={supplementUrl}
              change={(e) => setSupplementUrl(e.value || '')}
              cssClass="e-outline"
              width="100%"
            />
            <div style={{ fontSize: '12px', color: '#666', marginTop: 4 }}>
              Diese URL wird verwendet, um die Stundenplan-Änderungstabelle (Vertretungsplan) anzuzeigen.
            </div>
          </div>

          <div style={{ marginBottom: 16 }}>
            <CheckBoxComponent
              label="Vertretungsplan aktiviert"
              checked={supplementEnabled}
              change={(e) => setSupplementEnabled(e.checked || false)}
            />
          </div>

          <div style={{ display: 'flex', gap: 12 }}>
            <ButtonComponent
              cssClass="e-primary"
              onClick={onSaveSupplementSettings}
              disabled={supplementBusy}
            >
              {supplementBusy ? 'Speichere…' : 'Einstellungen speichern'}
            </ButtonComponent>
            <ButtonComponent
              cssClass="e-outline"
              onClick={onTestSupplementUrl}
              disabled={!supplementUrl}
            >
              Vorschau öffnen
            </ButtonComponent>
          </div>
        </div>
      </div>
    </div>
  );

  const PresentationsDefaultsContent = () => (
    <div style={{ padding: 20 }}>
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Präsentationen</div>
          </div>
        </div>
        <div className="e-card-content" style={{ fontSize: 14 }}>
          <div style={{ marginBottom: 16 }}>
            <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>
              Slide-Show Intervall (Sekunden)
            </label>
            <NumericTextBoxComponent
              min={1}
              max={600}
              step={1}
              value={presentationInterval}
              format="n0"
              change={(e: { value: number }) => setPresentationInterval(Number(e.value) || 10)}
              placeholder="Intervall in Sekunden"
              width="120px"
            />
          </div>
          <div style={{ marginBottom: 16 }}>
            <CheckBoxComponent
              label="Seitenfortschritt anzeigen (Fortschrittsbalken)"
              checked={presentationPageProgress}
              change={e => setPresentationPageProgress(e.checked || false)}
            />
          </div>
          <div style={{ marginBottom: 16 }}>
            <CheckBoxComponent
              label="Präsentationsfortschritt anzeigen (Fortschrittsbalken)"
              checked={presentationAutoProgress}
              change={e => setPresentationAutoProgress(e.checked || false)}
            />
          </div>
          <ButtonComponent
            cssClass="e-primary"
            onClick={onSavePresentationSettings}
            style={{ marginTop: 8 }}
            disabled={presentationBusy}
          >
            {presentationBusy ? 'Speichere…' : 'Einstellungen speichern'}
          </ButtonComponent>
        </div>
      </div>
    </div>
  );

  const WebsitesDefaultsContent = () => (
    <div style={{ padding: 20 }}>
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Webseiten</div>
          </div>
        </div>
        <div className="e-card-content" style={{ color: '#666', fontSize: 14 }}>
          Platzhalter für Standardwerte (Lade-Timeout, Intervall, Sandbox/Embedding) für Webseiten.
        </div>
      </div>
    </div>
  );

  const VideosDefaultsContent = () => (
    <div style={{ padding: 20 }}>
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Videos</div>
          </div>
        </div>
        <div className="e-card-content" style={{ fontSize: 14 }}>
          <div style={{ marginBottom: 16 }}>
            <CheckBoxComponent
              label="Automatisch abspielen"
              checked={videoAutoplay}
              change={e => setVideoAutoplay(!!e.checked)}
            />
          </div>

          <div style={{ marginBottom: 16 }}>
            <CheckBoxComponent
              label="In Schleife abspielen"
              checked={videoLoop}
              change={e => setVideoLoop(!!e.checked)}
            />
          </div>

          <div style={{ marginBottom: 16 }}>
            <label style={{ display: 'block', marginBottom: 8, fontWeight: 500 }}>Lautstärke</label>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <NumericTextBoxComponent
                min={0}
                max={1}
                step={0.05}
                value={videoVolume}
                format="n2"
                change={(e: { value: number }) => {
                  const v = typeof e.value === 'number' ? e.value : Number(e.value);
                  if (Number.isFinite(v)) setVideoVolume(Math.max(0, Math.min(1, v)));
                }}
                placeholder="0.0–1.0"
                width="140px"
              />
              <CheckBoxComponent
                label="Ton aus"
                checked={videoMuted}
                change={e => setVideoMuted(!!e.checked)}
              />
            </div>
          </div>

          <ButtonComponent
            cssClass="e-primary"
            onClick={onSaveVideoSettings}
            disabled={videoBusy}
          >
            {videoBusy ? 'Speichere…' : 'Einstellungen speichern'}
          </ButtonComponent>
        </div>
      </div>
    </div>
  );

  const MessagesDefaultsContent = () => (
    <div style={{ padding: 20 }}>
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Mitteilungen</div>
          </div>
        </div>
        <div className="e-card-content" style={{ color: '#666', fontSize: 14 }}>
          Platzhalter für Standardwerte (Dauer, Layout/Styling) für Mitteilungen.
        </div>
      </div>
    </div>
  );

  const OtherDefaultsContent = () => (
    <div style={{ padding: 20 }}>
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Sonstige</div>
          </div>
        </div>
        <div className="e-card-content" style={{ color: '#666', fontSize: 14 }}>
          Platzhalter für sonstige Eventtypen.
        </div>
      </div>
    </div>
  );

  // Users
  const UsersQuickActionsContent = () => (
    <div style={{ padding: 20 }}>
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Schnellaktionen</div>
          </div>
        </div>
        <div className="e-card-content">
          <div style={{ display: 'flex', gap: 12, flexWrap: 'wrap' }}>
            <Link to="/benutzer"><ButtonComponent cssClass="e-primary">Benutzerverwaltung öffnen</ButtonComponent></Link>
            <ButtonComponent disabled title="Demnächst">Benutzer einladen</ButtonComponent>
          </div>
        </div>
      </div>
    </div>
  );

  // System
  const OrganizationInfoContent = () => (
    <div style={{ padding: 20 }}>
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Organisationsinformationen</div>
          </div>
        </div>
        <div className="e-card-content" style={{ padding: '16px' }}>
          <div style={{ marginBottom: 16 }}>
            <label style={{ display: 'block', marginBottom: 8, fontWeight: 600 }}>
              Organisationsname
            </label>
            <TextBoxComponent
              placeholder="z.B. Meine Schule GmbH"
              value={organizationName}
              change={(e) => setOrganizationName(e.value || '')}
              cssClass="e-outline"
              floatLabelType="Never"
              style={{ width: '100%', maxWidth: '500px' }}
            />
            <div style={{ marginTop: 8, color: '#666', fontSize: 13 }}>
              Dieser Name wird im Header des Dashboards angezeigt.
            </div>
          </div>
          <ButtonComponent
            cssClass="e-primary"
            onClick={onSaveOrganizationName}
            disabled={organizationBusy}
          >
            {organizationBusy ? 'Speichern...' : 'Speichern'}
          </ButtonComponent>
        </div>
      </div>
    </div>
  );

  const AdvancedConfigContent = () => (
    <div style={{ padding: 20 }}>
      <div className="e-card">
        <div className="e-card-header">
          <div className="e-card-header-caption">
            <div className="e-card-header-title">Erweiterte Konfiguration</div>
          </div>
        </div>
        <div className="e-card-content" style={{ padding: '16px' }}>
          <div style={{ marginBottom: 20 }}>
            <label style={{ display: 'block', marginBottom: 8, fontWeight: 600 }}>
              Scheduler: Refresh-Intervall (Sekunden)
            </label>
            <NumericTextBoxComponent
              value={refreshSeconds}
              min={0}
              step={1}
              format="n0"
              change={(e) => setRefreshSeconds(Number(e.value ?? 0))}
              cssClass="e-outline"
              width={200}
            />
            <div style={{ marginTop: 8, color: '#666', fontSize: 13 }}>
              Legt fest, wie oft der Scheduler Ereignisse an Clients republiziert, auch wenn sich nichts geändert hat.
              <br />
              <strong>0:</strong> Deaktiviert (Scheduler sendet nur bei Änderungen). 
              <br />
              <strong>&gt;0:</strong> Sekunden zwischen Republizierungen (z.B. 600 = alle 10 Min). 
              <br />
              Der Scheduler liest die Datenbank immer alle 30 Sekunden neu ab und sendet dann bei Bedarf die Änderungen an den Terminen.
            </div>
            <div style={{ marginTop: 12 }}>
              <ButtonComponent cssClass="e-primary" onClick={onSaveRefreshSeconds} disabled={refreshBusy}>
                {refreshBusy ? 'Speichern...' : 'Speichern'}
              </ButtonComponent>
            </div>
          </div>
        </div>
      </div>
    </div>
  );

  // ---------- Nested Tab wrappers (first-level tabs -> second-level content) ----------
  const AcademicCalendarTabs = () => (
    <TabComponent
      heightAdjustMode="Auto"
      selectedItem={academicTabIndex}
      selected={(e: TabSelectedEvent) => setAcademicTabIndex(e.selectedIndex ?? 0)}
    >
      <TabItemsDirective>
        <TabItemDirective header={{ text: '📥 Import & Liste' }} content={HolidaysImportAndListContent} />
        <TabItemDirective header={{ text: '🗂️ Perioden' }} content={AcademicPeriodsContent} />
      </TabItemsDirective>
    </TabComponent>
  );

  const DisplayClientsTabs = () => (
    <TabComponent
      heightAdjustMode="Auto"
      selectedItem={displayTabIndex}
      selected={(e: TabSelectedEvent) => setDisplayTabIndex(e.selectedIndex ?? 0)}
    >
      <TabItemsDirective>
        <TabItemDirective header={{ text: '⚙️ Defaults' }} content={DisplayDefaultsContent} />
        <TabItemDirective header={{ text: '🖥️ Clients' }} content={ClientsConfigContent} />
      </TabItemsDirective>
    </TabComponent>
  );

  const MediaFilesTabs = () => (
    <TabComponent
      heightAdjustMode="Auto"
      selectedItem={mediaTabIndex}
      selected={(e: TabSelectedEvent) => setMediaTabIndex(e.selectedIndex ?? 0)}
    >
      <TabItemsDirective>
        <TabItemDirective header={{ text: '⬆️ Upload' }} content={UploadSettingsContent} />
        <TabItemDirective header={{ text: '🔄 Konvertierung' }} content={ConversionStatusContent} />
      </TabItemsDirective>
    </TabComponent>
  );

  const EventsTabs = () => (
    <TabComponent
      heightAdjustMode="Auto"
      selectedItem={eventsTabIndex}
      selected={(e: TabSelectedEvent) => setEventsTabIndex(e.selectedIndex ?? 0)}
    >
      <TabItemsDirective>
        <TabItemDirective header={{ text: '📘 WebUntis' }} content={WebUntisSettingsContent} />
        <TabItemDirective header={{ text: '🖼️ Präsentation' }} content={PresentationsDefaultsContent} />
        <TabItemDirective header={{ text: '🌐 Webseiten' }} content={WebsitesDefaultsContent} />
        <TabItemDirective header={{ text: '🎬 Videos' }} content={VideosDefaultsContent} />
        <TabItemDirective header={{ text: '💬 Mitteilungen' }} content={MessagesDefaultsContent} />
        <TabItemDirective header={{ text: '🔧 Sonstige' }} content={OtherDefaultsContent} />
      </TabItemsDirective>
    </TabComponent>
  );

  const UsersTabs = () => (
    <TabComponent
      heightAdjustMode="Auto"
      selectedItem={usersTabIndex}
      selected={(e: TabSelectedEvent) => setUsersTabIndex(e.selectedIndex ?? 0)}
    >
      <TabItemsDirective>
        <TabItemDirective header={{ text: '⚡ Schnellaktionen' }} content={UsersQuickActionsContent} />
      </TabItemsDirective>
    </TabComponent>
  );

  const SystemTabs = () => (
    <TabComponent
      heightAdjustMode="Auto"
      selectedItem={systemTabIndex}
      selected={(e: TabSelectedEvent) => setSystemTabIndex(e.selectedIndex ?? 0)}
    >
      <TabItemsDirective>
        <TabItemDirective header={{ text: '🏢 Organisation' }} content={OrganizationInfoContent} />
        <TabItemDirective header={{ text: '🧩 Erweiterte Optionen' }} content={AdvancedConfigContent} />
      </TabItemsDirective>
    </TabComponent>
  );

  // ---------- Top-level (root) tabs ----------
  return (
    <div style={{ padding: 20 }}>
      <ToastComponent ref={toastRef} position={{ X: 'Right', Y: 'Top' }} />

      <h2 style={{ marginBottom: 20, fontSize: '24px', fontWeight: 600 }}>Einstellungen</h2>

      <TabComponent heightAdjustMode="Auto">
        <TabItemsDirective>
          <TabItemDirective header={{ text: '📅 Akademischer Kalender' }} content={AcademicCalendarTabs} />
          {isAdmin && (
            <TabItemDirective header={{ text: '🖥️ Anzeige & Clients' }} content={DisplayClientsTabs} />
          )}
          {isAdmin && (
            <TabItemDirective header={{ text: '🎬 Medien & Dateien' }} content={MediaFilesTabs} />
          )}
          {isAdmin && (
            <TabItemDirective header={{ text: '🗓️ Events' }} content={EventsTabs} />
          )}
          {isAdmin && (
            <TabItemDirective header={{ text: '👥 Benutzer' }} content={UsersTabs} />
          )}
          {isSuperadmin && (
            <TabItemDirective header={{ text: '⚙️ System' }} content={SystemTabs} />
          )}
        </TabItemsDirective>
      </TabComponent>
    </div>
  );
};

export default Einstellungen;
