<!-- src/routes/admin/anmeldungen/+page.svelte -->
<script lang="ts">
  import { onMount } from 'svelte';
  import { goto } from '$app/navigation';
  import AnmeldungenTable from '$lib/components/AnmeldungenTable.svelte';
  import DienststellenDialog from '$lib/components/DienststellenDialog.svelte';
  import AdminHeader from '$lib/components/AdminHeader.svelte';

  interface Anmeldung {
    pdfs: { pfad: string }[];
    anrede: string;
    vorname: string;
    nachname: string;
    email: string;
    noteDeutsch?: string;
    noteMathe?: string;
    sozialverhalten?: string;
    notfallVorname?: string;
    notfallNachname?: string;
    notfallTelefon?: string;
    wunsch1?: { id: number; name: string };
    wunsch2?: { id: number; name: string };
    wunsch3?: { id: number; name: string };
    zeitraum?: { id: number; bezeichnung: string };
    timestamp: number;
    id: number;
    status?: 'pending' | 'accepted' | 'rejected';
    assignedDienststelle?: { id: number; name: string };
    processedBy?: string;
    processedAt?: number;
  }

  interface Zeitraum {
    id: number;
    bezeichnung: string;
    startDatum: string;
    endDatum: string;
  }

  interface EmailConfig {
    subject: string;
    template: string;
  }

  let anmeldungen: Anmeldung[] = [];
  let zeitraeume: Zeitraum[] = [];
  let isLoading = true;
  let error = '';

  // Filter für Status
  let statusFilter: 'all' | 'pending' | 'accepted' | 'rejected' = 'all';
  let filteredAnmeldungen: Anmeldung[] = [];

  // Dialog state
  let showDialog = false;
  let selectedAnmeldungId: number | null = null;
  let selectedDienststelleId: number | null = null;
  let availableWishes: { id: number, name: string }[] = [];

  // E-Mail Konfiguration
  let emailSubject = 'Praktikumsplatz-Zusage';
  let emailTemplate = `Sehr geehrte/r \{anrede\} \{nachname\},

wir freuen uns, Ihnen mitteilen zu können, dass Ihre Bewerbung für ein Praktikum erfolgreich war.

Sie wurden für das Praktikum bei folgender Dienststelle angenommen:
\{dienststelle\}

Weitere Informationen erhalten Sie in den kommenden Tagen.

Mit freundlichen Grüßen
Ihr Praktikumsteam`;

  let showEmailConfig = false;
  let isLoadingEmailConfig = false;
  let isSavingEmailConfig = false;

  // E-Mail Preview Modal State
  let showEmailPreview = false;
  let emailPreviewData: {
    to: string;
    subject: string;
    body: string;
  } | null = null;
  let emailCopied = false;

  // Export Modal State
  let showExportModal = false;
  let selectedExportZeitraum = '';
  let isExporting = false;

  // Status-Badge Funktionen
  function getStatusColor(status: string): string {
    switch (status) {
      case 'pending': return 'bg-yellow-100 text-yellow-800';
      case 'accepted': return 'bg-green-100 text-green-800';
      case 'rejected': return 'bg-red-100 text-red-800';
      default: return 'bg-gray-100 text-gray-800';
    }
  }

  function getStatusText(status: string): string {
    switch (status) {
      case 'pending': return 'Offen';
      case 'accepted': return 'Angenommen';
      case 'rejected': return 'Abgelehnt';
      default: return 'Unbekannt';
    }
  }

  // Filter-Funktionen
  function filterAnmeldungen() {
    if (statusFilter === 'all') {
      filteredAnmeldungen = anmeldungen;
    } else {
      filteredAnmeldungen = anmeldungen.filter(a => (a.status || 'pending') === statusFilter);
    }
  }

  $: {
    anmeldungen, statusFilter, filterAnmeldungen();
  }

  // Zähle angenommene Anmeldungen pro Zeitraum
  function getAcceptedCountForZeitraum(zeitraumId: number): number {
    return anmeldungen.filter(a =>
            a.status === 'accepted' &&
            a.zeitraum?.id === zeitraumId
    ).length;
  }

  async function loadAnmeldungen() {
    try {
      isLoading = true;
      error = '';

      const res = await fetch('/api/admin/anmeldungen');

      if (!res.ok) {
        const errorText = await res.text();
        console.error('❌ API Fehler:', res.status, errorText);
        throw new Error(`Fehler beim Laden: ${res.status} - ${errorText}`);
      }

      const data = await res.json();

      if (!Array.isArray(data)) {
        console.error('❌ Antwort ist kein Array:', data);
        throw new Error('Antwort vom Server ist kein Array');
      }

      anmeldungen = data.map(a => {
        return { ...a, status: a.status || 'pending' };
      });

    } catch (err) {
      error = err instanceof Error ? err.message : 'Unbekannter Fehler';
      console.error('❌ Frontend Fehler beim Laden der Anmeldungen:', err);
    } finally {
      isLoading = false;
    }
  }

  async function loadZeitraeume() {
    try {
      const res = await fetch('/api/zeitraeume');
      if (res.ok) {
        zeitraeume = await res.json();
      }
    } catch (err) {
      console.error('Fehler beim Laden der Zeiträume:', err);
    }
  }

  async function loadEmailConfig() {
    try {
      isLoadingEmailConfig = true;

      const res = await fetch('/api/admin/email-config');

      if (!res.ok) {
        throw new Error(`Fehler beim Laden der E-Mail-Konfiguration: ${res.status}`);
      }

      const config: EmailConfig = await res.json();
      emailSubject = config.subject;
      emailTemplate = config.template;
    } catch (err) {
      console.error('Fehler beim Laden der E-Mail-Konfiguration:', err);
    } finally {
      isLoadingEmailConfig = false;
    }
  }

  async function saveEmailTemplate() {
    try {
      isSavingEmailConfig = true;

      const res = await fetch('/api/admin/email-config', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          subject: emailSubject,
          template: emailTemplate
        })
      });

      if (!res.ok) {
        throw new Error(`Fehler beim Speichern: ${res.status}`);
      }

      showEmailConfig = false;
      alert('E-Mail-Vorlage erfolgreich gespeichert!');
    } catch (err) {
      error = err instanceof Error ? err.message : 'Fehler beim Speichern der E-Mail-Vorlage';
      console.error(err);
    } finally {
      isSavingEmailConfig = false;
    }
  }

  function handleAccept(event: CustomEvent<{id: number}>) {
    const anmeldung = anmeldungen.find(a => a.id === event.detail.id);
    if (!anmeldung) return;

    availableWishes = [
      anmeldung.wunsch1 && { id: anmeldung.wunsch1.id, name: `1. Wunsch: ${anmeldung.wunsch1.name}` },
      anmeldung.wunsch2 && { id: anmeldung.wunsch2.id, name: `2. Wunsch: ${anmeldung.wunsch2.name}` },
      anmeldung.wunsch3 && { id: anmeldung.wunsch3.id, name: `3. Wunsch: ${anmeldung.wunsch3.name}` }
    ].filter(Boolean) as { id: number, name: string }[];

    selectedDienststelleId = availableWishes[0]?.id ?? null;
    selectedAnmeldungId = event.detail.id;
    showDialog = true;
  }

  async function handleConfirmAccept(event: CustomEvent<{dienststelleId: number}>) {
    if (!selectedAnmeldungId) return;

    try {
      const res = await fetch(`/api/admin/anmeldungen?id=${selectedAnmeldungId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ dienststelleId: event.detail.dienststelleId })
      });

      if (!res.ok) {
        const errorData = await res.json();
        throw new Error(errorData.error || `Fehler beim Annehmen (${res.status})`);
      }

      showDialog = false;

      // E-Mail Vorschau öffnen nach erfolgreichem Annehmen
      openEmailPreview(selectedAnmeldungId, event.detail.dienststelleId);

      selectedAnmeldungId = null;
      await loadAnmeldungen();
    } catch (err) {
      error = err instanceof Error ? err.message : 'Fehler beim Annehmen';
      console.error(err);
    }
  }

  function openEmailPreview(anmeldungId: number, dienststelleId: number) {
    const anmeldung = anmeldungen.find(a => a.id === anmeldungId);
    if (!anmeldung) return;

    // Dienststelle finden
    const dienststelle = availableWishes.find(w => w.id === dienststelleId);
    const dienststelleName = dienststelle
            ? dienststelle.name.replace(/^\d+\.\s*Wunsch:\s*/, '')
            : 'Unbekannte Dienststelle';

    // E-Mail Text personalisieren
    const personalizedEmail = emailTemplate
            .replace(/\{anrede\}/g, anmeldung.anrede)
            .replace(/\{vorname\}/g, anmeldung.vorname)
            .replace(/\{nachname\}/g, anmeldung.nachname)
            .replace(/\{dienststelle\}/g, dienststelleName);

    // Modal mit Vorschau öffnen
    emailPreviewData = {
      to: anmeldung.email,
      subject: emailSubject,
      body: personalizedEmail
    };
    emailCopied = false;
    showEmailPreview = true;
  }

  async function copyAndOpenMail() {
    if (!emailPreviewData) return;

    try {
      await navigator.clipboard.writeText(emailPreviewData.body);
      emailCopied = true;

      // Kurz warten, dann Mail öffnen
      setTimeout(() => {
        const mailtoLink = `mailto:${emailPreviewData!.to}?subject=${encodeURIComponent(emailPreviewData!.subject)}`;
        window.location.href = mailtoLink;
      }, 500);

      // Modal nach 2 Sekunden schließen
      setTimeout(() => {
        closeEmailPreview();
      }, 2000);
    } catch (err) {
      console.error('Clipboard-Fehler:', err);
      error = 'Konnte Text nicht kopieren. Bitte manuell markieren und kopieren.';
    }
  }

  function closeEmailPreview() {
    showEmailPreview = false;
    emailPreviewData = null;
    emailCopied = false;
  }

  // Export-Funktionen
  function openExportModal() {
    selectedExportZeitraum = '';
    showExportModal = true;
  }

  function closeExportModal() {
    showExportModal = false;
    selectedExportZeitraum = '';
  }

  async function exportToExcel() {
    if (!selectedExportZeitraum) {
      error = 'Bitte wählen Sie einen Zeitraum aus.';
      return;
    }

    try {
      isExporting = true;
      error = '';

      const res = await fetch(`/api/admin/export?zeitraumId=${selectedExportZeitraum}`);

      if (!res.ok) {
        const errorData = await res.json();
        throw new Error(errorData.error || 'Fehler beim Exportieren');
      }

      // Download auslösen
      const blob = await res.blob();
      const contentDisposition = res.headers.get('Content-Disposition');
      let filename = 'export.xlsx';

      if (contentDisposition) {
        const match = contentDisposition.match(/filename="(.+)"/);
        if (match) {
          filename = match[1];
        }
      }

      const url = window.URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);

      closeExportModal();
    } catch (err) {
      error = err instanceof Error ? err.message : 'Fehler beim Exportieren';
      console.error(err);
    } finally {
      isExporting = false;
    }
  }

  async function handleReject(event: CustomEvent<{id: number}>) {
    if (!confirm('Diese Anmeldung wirklich ablehnen?')) return;

    try {
      const res = await fetch(`/api/admin/anmeldungen?id=${event.detail.id}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'reject' })
      });

      if (!res.ok) {
        throw new Error(`Fehler beim Ablehnen: ${res.status}`);
      }

      await loadAnmeldungen();
    } catch (err) {
      error = err instanceof Error ? err.message : 'Fehler beim Ablehnen';
      console.error(err);
    }
  }

  async function handleDelete(event: CustomEvent<{id: number}>) {
    if (!confirm('Diese Anmeldung wirklich löschen?')) return;

    try {
      const res = await fetch(`/api/admin/anmeldungen?id=${event.detail.id}`, {
        method: 'DELETE'
      });

      if (!res.ok) {
        throw new Error(`Fehler beim Löschen: ${res.status}`);
      }

      await loadAnmeldungen();
    } catch (err) {
      error = err instanceof Error ? err.message : 'Fehler beim Löschen';
      console.error(err);
    }
  }

  function closeDialog() {
    showDialog = false;
    selectedAnmeldungId = null;
  }

  onMount(() => {
    loadAnmeldungen();
    loadZeitraeume();
    loadEmailConfig();
  });
</script>

<svelte:head>
  <title>Anmeldungen verwalten - Admin</title>
</svelte:head>

<div class="min-h-screen bg-gray-50">
  <AdminHeader
          title="Anmeldungen verwalten"
          showBackButton={true}
  />

  <main class="max-w-7xl mx-auto px-4 py-6">
    <!-- Filter, Export und E-Mail Konfiguration -->
    <div class="mb-6 flex flex-wrap justify-between items-center gap-4">
      <!-- Status Filter -->
      <div class="flex items-center space-x-4">
        <label for="status-filter" class="text-sm font-medium text-gray-700">Filter:</label>
        <select
                id="status-filter"
                bind:value={statusFilter}
                class="border border-gray-300 rounded-md px-3 py-2 text-sm focus:ring-blue-500 focus:border-blue-500"
        >
          <option value="all">Alle ({anmeldungen.length})</option>
          <option value="pending">Offen ({anmeldungen.filter(a => (a.status || 'pending') === 'pending').length})</option>
          <option value="accepted">Angenommen ({anmeldungen.filter(a => a.status === 'accepted').length})</option>
          <option value="rejected">Abgelehnt ({anmeldungen.filter(a => a.status === 'rejected').length})</option>
        </select>
      </div>

      <!-- Buttons -->
      <div class="flex items-center space-x-3">
        <!-- Excel Export Button -->
        <button
                on:click={openExportModal}
                class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-md text-sm font-medium inline-flex items-center"
                disabled={anmeldungen.filter(a => a.status === 'accepted').length === 0}
        >
          <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
          </svg>
          Excel-Export
        </button>

        <!-- E-Mail Konfiguration Button -->
        <button
                on:click={() => showEmailConfig = !showEmailConfig}
                class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-md text-sm font-medium inline-flex items-center"
                disabled={isLoadingEmailConfig}
        >
          {#if isLoadingEmailConfig}
            <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
          {:else}
            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
            </svg>
          {/if}
          E-Mail-Vorlage
        </button>
      </div>
    </div>

    <!-- Status Übersicht -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mb-6">
      <div class="bg-white rounded-lg border border-gray-200 p-4">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <div class="w-8 h-8 bg-yellow-100 rounded-full flex items-center justify-center">
              <svg class="w-4 h-4 text-yellow-600" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z" clip-rule="evenodd" />
              </svg>
            </div>
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-600">Offen</p>
            <p class="text-2xl font-semibold text-gray-900">
              {anmeldungen.filter(a => (a.status || 'pending') === 'pending').length}
            </p>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-lg border border-gray-200 p-4">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <div class="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
              <svg class="w-4 h-4 text-green-600" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clip-rule="evenodd" />
              </svg>
            </div>
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-600">Angenommen</p>
            <p class="text-2xl font-semibold text-gray-900">
              {anmeldungen.filter(a => a.status === 'accepted').length}
            </p>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-lg border border-gray-200 p-4">
        <div class="flex items-center">
          <div class="flex-shrink-0">
            <div class="w-8 h-8 bg-red-100 rounded-full flex items-center justify-center">
              <svg class="w-4 h-4 text-red-600" fill="currentColor" viewBox="0 0 20 20">
                <path fill-rule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clip-rule="evenodd" />
              </svg>
            </div>
          </div>
          <div class="ml-4">
            <p class="text-sm font-medium text-gray-600">Abgelehnt</p>
            <p class="text-2xl font-semibold text-gray-900">
              {anmeldungen.filter(a => a.status === 'rejected').length}
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- E-Mail Konfiguration Panel -->
    {#if showEmailConfig}
      <div class="bg-white shadow-sm rounded-lg p-6 mb-6">
        <h3 class="text-lg font-medium text-gray-900 mb-4">E-Mail-Vorlage konfigurieren</h3>

        <div class="space-y-4">
          <div>
            <label for="email-subject" class="block text-sm font-medium text-gray-700 mb-2">
              E-Mail Betreff
            </label>
            <input
                    id="email-subject"
                    type="text"
                    bind:value={emailSubject}
                    class="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500"
                    disabled={isSavingEmailConfig}
            />
          </div>

          <div>
            <label for="email-template" class="block text-sm font-medium text-gray-700 mb-2">
              E-Mail Text
            </label>
            <textarea
                    id="email-template"
                    bind:value={emailTemplate}
                    rows="10"
                    class="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-blue-500 focus:border-blue-500"
                    disabled={isSavingEmailConfig}
            ></textarea>
            <p class="mt-2 text-sm text-gray-500">
              Verfügbare Platzhalter: &#123;anrede&#125;, &#123;vorname&#125;, &#123;nachname&#125;, &#123;dienststelle&#125;
            </p>
          </div>

          <div class="flex justify-end space-x-3">
            <button
                    on:click={() => showEmailConfig = false}
                    class="px-4 py-2 text-sm text-gray-600 hover:text-gray-800"
                    disabled={isSavingEmailConfig}
            >
              Abbrechen
            </button>
            <button
                    on:click={saveEmailTemplate}
                    class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-md text-sm font-medium inline-flex items-center"
                    disabled={isSavingEmailConfig}
            >
              {#if isSavingEmailConfig}
                <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                Speichere...
              {:else}
                Speichern
              {/if}
            </button>
          </div>
        </div>
      </div>
    {/if}

    {#if error}
      <div class="bg-red-50 border border-red-200 rounded-md p-4 mb-6">
        <div class="flex">
          <div class="flex-shrink-0">
            <svg class="h-5 w-5 text-red-400" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
            </svg>
          </div>
          <div class="ml-3">
            <h3 class="text-sm font-medium text-red-800">Fehler</h3>
            <p class="mt-1 text-sm text-red-700">{error}</p>
          </div>
          <button
                  on:click={() => error = ''}
                  class="ml-auto text-red-400 hover:text-red-600"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>
      </div>
    {/if}

    {#if isLoading}
      <div class="flex justify-center items-center h-64">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
        <span class="ml-3 text-gray-600">Lade Anmeldungen...</span>
      </div>
    {:else if filteredAnmeldungen.length === 0}
      <div class="text-center py-12">
        <svg class="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
        </svg>
        <h3 class="mt-2 text-sm font-medium text-gray-900">
          {statusFilter === 'all' ? 'Keine Anmeldungen' : `Keine ${getStatusText(statusFilter).toLowerCase()}en Anmeldungen`}
        </h3>
        <p class="mt-1 text-sm text-gray-500">
          {statusFilter === 'all'
                  ? 'Es sind noch keine Praktikumsanmeldungen eingegangen.'
                  : `Es gibt keine Anmeldungen mit dem Status "${getStatusText(statusFilter).toLowerCase()}".`}
        </p>
      </div>
    {:else}
      <div class="bg-white shadow-sm rounded-lg overflow-hidden">
        <AnmeldungenTable
                anmeldungen={filteredAnmeldungen}
                {getStatusColor}
                {getStatusText}
                on:accept={handleAccept}
                on:reject={handleReject}
                on:delete={handleDelete}
        />
      </div>
    {/if}
  </main>
</div>

<!-- Dienststellen Dialog -->
{#if showDialog}
  <DienststellenDialog
          wishes={availableWishes}
          selectedId={selectedDienststelleId}
          on:confirm={handleConfirmAccept}
          on:cancel={closeDialog}
  />
{/if}

<!-- Export Modal -->
{#if showExportModal}
  <div class="fixed inset-0 z-50 overflow-y-auto">
    <div class="flex min-h-screen items-center justify-center p-4">
      <!-- Backdrop -->
      <!-- svelte-ignore a11y-click-events-have-key-events -->
      <!-- svelte-ignore a11y-no-static-element-interactions -->
      <div
              class="fixed inset-0 bg-black bg-opacity-50 transition-opacity"
              on:click={closeExportModal}
      ></div>

      <!-- Modal -->
      <div class="relative bg-white rounded-lg shadow-xl max-w-md w-full">
        <!-- Header -->
        <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center">
          <div class="flex items-center space-x-3">
            <div class="w-10 h-10 bg-green-100 rounded-full flex items-center justify-center">
              <svg class="w-5 h-5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
              </svg>
            </div>
            <h3 class="text-lg font-medium text-gray-900">Excel-Export</h3>
          </div>
          <button
                  on:click={closeExportModal}
                  class="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <!-- Content -->
        <div class="px-6 py-4">
          <p class="text-sm text-gray-600 mb-4">
            Wählen Sie einen Praktikumszeitraum aus, um alle angenommenen Anmeldungen als Excel-Datei zu exportieren.
          </p>

          <div>
            <label for="export-zeitraum" class="block text-sm font-medium text-gray-700 mb-2">
              Praktikumszeitraum
            </label>
            <select
                    id="export-zeitraum"
                    bind:value={selectedExportZeitraum}
                    class="w-full border border-gray-300 rounded-md px-3 py-2 focus:ring-green-500 focus:border-green-500"
                    disabled={isExporting}
            >
              <option value="" disabled>Zeitraum auswählen...</option>
              {#each zeitraeume as z}
                {@const count = getAcceptedCountForZeitraum(z.id)}
                <option value={z.id} disabled={count === 0}>
                  {z.bezeichnung} ({count} angenommen)
                </option>
              {/each}
            </select>
          </div>
        </div>

        <!-- Footer -->
        <div class="px-6 py-4 border-t border-gray-200 bg-gray-50 flex justify-end space-x-3">
          <button
                  on:click={closeExportModal}
                  class="px-4 py-2 text-sm text-gray-600 hover:text-gray-800"
                  disabled={isExporting}
          >
            Abbrechen
          </button>
          <button
                  on:click={exportToExcel}
                  class="bg-green-600 hover:bg-green-700 text-white px-5 py-2 rounded-md text-sm font-medium inline-flex items-center disabled:opacity-50 disabled:cursor-not-allowed"
                  disabled={!selectedExportZeitraum || isExporting}
          >
            {#if isExporting}
              <div class="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
              Exportiere...
            {:else}
              <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
              </svg>
              Exportieren
            {/if}
          </button>
        </div>
      </div>
    </div>
  </div>
{/if}

<!-- E-Mail Vorschau Modal -->
{#if showEmailPreview && emailPreviewData}
  <div class="fixed inset-0 z-50 overflow-y-auto">
    <div class="flex min-h-screen items-center justify-center p-4">
      <!-- Backdrop -->
      <!-- svelte-ignore a11y-click-events-have-key-events -->
      <!-- svelte-ignore a11y-no-static-element-interactions -->
      <div
              class="fixed inset-0 bg-black bg-opacity-50 transition-opacity"
              on:click={closeEmailPreview}
      ></div>

      <!-- Modal -->
      <div class="relative bg-white rounded-lg shadow-xl max-w-2xl w-full max-h-[90vh] overflow-hidden">
        <!-- Header -->
        <div class="px-6 py-4 border-b border-gray-200 flex justify-between items-center bg-white">
          <div class="flex items-center space-x-3">
            <div class="w-10 h-10 bg-blue-100 rounded-full flex items-center justify-center">
              <svg class="w-5 h-5 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 4.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
              </svg>
            </div>
            <h3 class="text-lg font-medium text-gray-900">E-Mail Vorschau</h3>
          </div>
          <button
                  on:click={closeEmailPreview}
                  class="text-gray-400 hover:text-gray-600 transition-colors"
          >
            <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
            </svg>
          </button>
        </div>

        <!-- Content -->
        <div class="px-6 py-4 overflow-y-auto max-h-[60vh]">
          <div class="space-y-4">
            <!-- Empfänger -->
            <div class="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
              <span class="text-sm font-medium text-gray-500 w-16">An:</span>
              <span class="text-sm text-gray-900">{emailPreviewData.to}</span>
            </div>

            <!-- Betreff -->
            <div class="flex items-center space-x-3 p-3 bg-gray-50 rounded-lg">
              <span class="text-sm font-medium text-gray-500 w-16">Betreff:</span>
              <span class="text-sm text-gray-900">{emailPreviewData.subject}</span>
            </div>

            <!-- Nachricht (editierbar) -->
            <div>
              <label for="email-body" class="block text-sm font-medium text-gray-700 mb-2">
                Nachricht
                <span class="font-normal text-gray-500">(kann bearbeitet werden)</span>
              </label>
              <textarea
                      id="email-body"
                      bind:value={emailPreviewData.body}
                      rows="14"
                      class="w-full border border-gray-300 rounded-lg px-4 py-3 text-sm focus:ring-2 focus:ring-blue-500 focus:border-blue-500 resize-none"
                      disabled={emailCopied}
              ></textarea>
            </div>
          </div>
        </div>

        <!-- Footer -->
        <div class="px-6 py-4 border-t border-gray-200 bg-gray-50">
          {#if emailCopied}
            <div class="flex items-center justify-center py-3">
              <div class="flex items-center space-x-3 text-green-600">
                <div class="w-8 h-8 bg-green-100 rounded-full flex items-center justify-center">
                  <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                  </svg>
                </div>
                <span class="font-medium">Text kopiert – Outlook öffnet sich...</span>
              </div>
            </div>
          {:else}
            <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
              <div class="flex items-start space-x-2 text-sm text-gray-600">
                <svg class="w-5 h-5 text-blue-500 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
                </svg>
                <span>
                  Der Text wird kopiert und Outlook geöffnet.<br class="hidden sm:inline" />
                  Dann mit <kbd class="px-1.5 py-0.5 bg-gray-200 rounded text-xs font-mono">Strg</kbd> + <kbd class="px-1.5 py-0.5 bg-gray-200 rounded text-xs font-mono">V</kbd> einfügen.
                </span>
              </div>
              <div class="flex space-x-3 w-full sm:w-auto">
                <button
                        on:click={closeEmailPreview}
                        class="flex-1 sm:flex-none px-4 py-2.5 text-sm text-gray-600 hover:text-gray-800 hover:bg-gray-100 rounded-lg transition-colors"
                >
                  Abbrechen
                </button>
                <button
                        on:click={copyAndOpenMail}
                        class="flex-1 sm:flex-none bg-blue-600 hover:bg-blue-700 text-white px-5 py-2.5 rounded-lg text-sm font-medium inline-flex items-center justify-center transition-colors"
                >
                  <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 5H6a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2v-1M8 5a2 2 0 002 2h2a2 2 0 002-2M8 5a2 2 0 012-2h2a2 2 0 012 2m0 0h2a2 2 0 012 2v3m2 4H10m0 0l3-3m-3 3l3 3" />
                  </svg>
                  Kopieren & E-Mail öffnen
                </button>
              </div>
            </div>
          {/if}
        </div>
      </div>
    </div>
  </div>
{/if}