{% extends "base.html" %}

{% block title %}TBA-Nutzungsantrag - Mercedes-Benz TBA Marienfelde{% endblock %}

{% block head %}
{{ super() }}
<meta name="csrf-token" content="{{ csrf_token() if csrf_token else '' }}">
{% endblock %}

{% block extra_css %}
<style>
    /* Mercedes-Benz Corporate Design */
    .text-mercedes-black { color: #000000; }
    .text-mercedes-gray { color: #6b7280; }
    .text-mercedes-silver { color: #9ca3af; }
    .text-mercedes-blue { color: #0073ce; }
    .text-mercedes-green { color: #008c32; }
    .text-mercedes-red { color: #dc2626; }
    
    .bg-mercedes-black { background-color: #000000; }
    .bg-mercedes-silver { background-color: #e5e7eb; }
    .bg-mercedes-blue { background-color: #0073ce; }
    .bg-mercedes-green { background-color: #008c32; }
    
    .border-mercedes-silver { border-color: #d1d5db; }
    .border-mercedes-blue { border-color: #0073ce; }
    
    .hover\:border-mercedes-blue:hover { border-color: #0073ce; }
    .focus\:ring-mercedes-blue:focus { 
        --tw-ring-color: #0073ce; 
        --tw-ring-opacity: 0.5;
    }
    .focus\:border-mercedes-blue:focus { border-color: #0073ce; }
    
    /* Enhanced Form Elements */
    .mercedes-form-input {
        transition: all 0.2s ease;
        border: 1px solid #d1d5db;
        background: rgba(255, 255, 255, 0.9);
        backdrop-filter: blur(10px);
        border-radius: 8px;
    }
    
    .mercedes-form-input:focus {
        border-color: #0073ce;
        box-shadow: 
            0 0 0 3px rgba(0, 115, 206, 0.1),
            0 4px 6px -1px rgba(0, 0, 0, 0.1);
        transform: translateY(-1px);
        background: rgba(255, 255, 255, 1);
    }
    
    .dark .mercedes-form-input {
        background: rgba(30, 41, 59, 0.8);
        border-color: #475569;
        color: #f8fafc;
    }
    
    .dark .mercedes-form-input:focus {
        border-color: #0ea5e9;
        box-shadow: 
            0 0 0 3px rgba(14, 165, 233, 0.1),
            0 4px 6px -1px rgba(0, 0, 0, 0.3);
        background: rgba(30, 41, 59, 1);
    }
    
    /* Enhanced File Upload Area */
    .upload-area {
        background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
        border: 2px dashed #cbd5e1;
        border-radius: 12px;
        transition: all 0.3s ease;
        position: relative;
        overflow: hidden;
    }
    
    .dark .upload-area {
        background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
        border-color: #475569;
    }
    
    .upload-area:hover {
        border-color: #0073ce;
        background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
        transform: scale(1.02);
    }
    
    .dark .upload-area:hover {
        background: linear-gradient(135deg, #1e3a8a 0%, #1e40af 100%);
    }
    
    .upload-area.drag-over {
        border-color: #0073ce;
        background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
        transform: scale(1.05);
        box-shadow: 0 8px 25px rgba(0, 115, 206, 0.15);
    }
    
    .dark .upload-area.drag-over {
        background: linear-gradient(135deg, #1e3a8a 0%, #1e40af 100%);
    }
    
    /* Form Validation States */
    .input-error {
        border-color: #dc2626 !important;
        box-shadow: 0 0 0 3px rgba(220, 38, 38, 0.1) !important;
        animation: shake 0.5s ease-in-out;
    }
    
    .input-success {
        border-color: #16a34a !important;
        box-shadow: 0 0 0 3px rgba(22, 163, 74, 0.1) !important;
    }
    
    @keyframes shake {
        0%, 100% { transform: translateX(0); }
        25% { transform: translateX(-5px); }
        75% { transform: translateX(5px); }
    }
    
    /* Progress Indicators */
    .progress-step {
        background: linear-gradient(135deg, #f3f4f6 0%, #e5e7eb 100%);
        border: 2px solid #d1d5db;
        border-radius: 50%;
        width: 2rem;
        height: 2rem;
        display: flex;
        align-items: center;
        justify-content: center;
        font-weight: 600;
        transition: all 0.3s ease;
    }
    
    .progress-step.active {
        background: linear-gradient(135deg, #0073ce 0%, #1e40af 100%);
        color: white;
        border-color: #0073ce;
        transform: scale(1.1);
    }
    
    .progress-step.completed {
        background: linear-gradient(135deg, #16a34a 0%, #15803d 100%);
        color: white;
        border-color: #16a34a;
    }
    
    /* Loading States */
    .loading-skeleton {
        background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
        background-size: 200% 100%;
        animation: loading 2s infinite;
    }
    
    .dark .loading-skeleton {
        background: linear-gradient(90deg, #374151 25%, #4b5563 50%, #374151 75%);
        background-size: 200% 100%;
    }
    
    @keyframes loading {
        0% { background-position: 200% 0; }
        100% { background-position: -200% 0; }
    }
    
    /* File Preview */
    .file-preview {
        background: linear-gradient(135deg, #f0fdf4 0%, #dcfce7 100%);
        border: 1px solid #bbf7d0;
        border-radius: 8px;
        padding: 1rem;
        animation: slideIn 0.3s ease-out;
    }
    
    .dark .file-preview {
        background: linear-gradient(135deg, #14532d 0%, #166534 100%);
        border-color: #16a34a;
    }
    
    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateY(20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
    
    /* Success Animation */
    .success-checkmark {
        animation: checkmark 0.6s ease-in-out;
    }
    
    @keyframes checkmark {
        0% {
            transform: scale(0);
            opacity: 0;
        }
        50% {
            transform: scale(1.2);
            opacity: 1;
        }
        100% {
            transform: scale(1);
            opacity: 1;
        }
    }
    
    /* Responsive Design */
    @media (max-width: 768px) {
        .dashboard-card {
            padding: 1rem !important;
        }
        
        .btn-primary,
        .btn-secondary {
            width: 100%;
            justify-content: center;
        }
        
        .upload-area {
            height: 120px;
        }
    }
    
    /* Accessibility Enhancements */
    @media (prefers-reduced-motion: reduce) {
        *, *::before, *::after {
            animation-duration: 0.01ms !important;
            animation-iteration-count: 1 !important;
            transition-duration: 0.01ms !important;
        }
    }
    
    /* Focus States */
    .btn-primary:focus,
    .btn-secondary:focus {
        outline: 2px solid #0073ce;
        outline-offset: 2px;
    }
    
    /* Enhanced Submit Button Styles */
    .btn-primary {
        position: relative;
        overflow: hidden;
        transition: all 0.3s ease;
        transform-origin: center;
    }
    
    .btn-primary:not(:disabled):hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px rgba(0, 115, 206, 0.3);
    }
    
    .btn-primary:not(:disabled):active {
        transform: translateY(0px);
        box-shadow: 0 4px 15px rgba(0, 115, 206, 0.2);
    }
    
    .btn-primary:disabled {
        cursor: not-allowed;
        position: relative;
    }
    
    .btn-primary:disabled:hover {
        transform: none;
        box-shadow: none;
    }
    
    /* Tooltip Styles */
    #submit-tooltip {
        z-index: 1000;
        backdrop-filter: blur(10px);
    }
    
    /* Progress Indicator Styles */
    #progress-indicator {
        z-index: 10;
    }
    
    #progress-bar {
        background: linear-gradient(90deg, currentColor 0%, currentColor 100%);
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    
    /* Enhanced Success Animation */
    .success-checkmark {
        animation: checkmark 0.6s ease-in-out;
    }
</style>
{% endblock %}

{% block content %}
<div class="space-y-8">
    <!-- Enhanced Page Header -->
    <div class="dashboard-card p-6">
        <div class="flex flex-col md:flex-row md:items-center md:justify-between gap-6">
            <div class="flex items-center gap-6">
                <div class="w-16 h-16 flex-shrink-0 bg-mercedes-blue text-white rounded-xl flex items-center justify-center">
                    <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
                    </svg>
                </div>
                <div>
                    <h1 class="text-4xl font-bold text-mercedes-black dark:text-white tracking-tight">TBA-Nutzungsantrag</h1>
                    <p class="text-mercedes-gray dark:text-slate-400 mt-1 text-lg">Antrag für Drucker-Steckdosen-Nutzung in der TBA</p>
                    <div class="flex items-center mt-2 text-sm text-mercedes-blue">
                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                        <span>Anträge werden von Ausbildern geprüft</span>
                    </div>
                </div>
            </div>
            <div class="flex flex-wrap gap-3">
                <a href="{{ url_for('guest.guest_requests_overview') if url_for else '/guest/requests' }}" 
                   class="btn-secondary flex items-center gap-2">
                    <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="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>
                    <span>Meine Anträge</span>
                </a>
                <a href="{{ url_for('index') if url_for else '/' }}" 
                   class="btn-secondary flex items-center gap-2">
                    <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="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"/>
                    </svg>
                    <span>Startseite</span>
                </a>
            </div>
        </div>
    </div>

    <!-- Progress Indicator -->
    <div class="dashboard-card p-6">
        <div class="mb-8">
            <h2 class="text-lg font-semibold text-mercedes-black dark:text-white mb-4">Antrags-Fortschritt</h2>
            <div class="flex items-center justify-between max-w-md mx-auto">
                <div class="flex items-center">
                    <div class="progress-step active">1</div>
                    <span class="ml-2 text-sm font-medium text-mercedes-black dark:text-white">Antrag stellen</span>
                </div>
                <div class="flex-1 h-1 bg-gray-200 dark:bg-gray-700 mx-4 rounded-full">
                    <div class="h-1 bg-mercedes-blue rounded-full" style="width: 33%"></div>
                </div>
                <div class="flex items-center">
                    <div class="progress-step">2</div>
                    <span class="ml-2 text-sm font-medium text-mercedes-gray dark:text-slate-400">Ausbilder-Prüfung</span>
                </div>
                <div class="flex-1 h-1 bg-gray-200 dark:bg-gray-700 mx-4 rounded-full"></div>
                <div class="flex items-center">
                    <div class="progress-step">3</div>
                    <span class="ml-2 text-sm font-medium text-mercedes-gray dark:text-slate-400">Genehmigung</span>
                </div>
            </div>
        </div>
    </div>

    <!-- Enhanced Form Container -->
    <div class="dashboard-card p-8">
        <div class="mb-8">
            <h2 class="text-2xl font-bold text-mercedes-black dark:text-white mb-3">
                Nutzungsantrag für Drucker-Steckdosen
            </h2>
            <p class="text-mercedes-gray dark:text-slate-400 text-lg">
                Füllen Sie alle erforderlichen Felder aus, um Ihren Antrag für die Nutzung der Drucker-Steckdosen zu stellen. 
                <strong>Der Antrag wird von den TBA-Ausbildern geprüft und genehmigt.</strong>
            </p>
        </div>

        <form id="guestRequestForm" method="POST" enctype="multipart/form-data" class="space-y-8">
            {{ form.hidden_tag() if form }}
            
            <!-- Personal Information Section -->
            <div class="bg-gray-50 dark:bg-slate-800/50 rounded-xl p-6">
                <h3 class="text-lg font-semibold text-mercedes-black dark:text-white mb-4 flex items-center">
                    <svg class="w-5 h-5 mr-2 text-mercedes-blue" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
                    </svg>
                    Persönliche Angaben
                </h3>
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Name -->
                <div>
                        <label for="{{ form.name.id if form else 'name' }}" class="block text-sm font-medium text-mercedes-black dark:text-slate-300 mb-2">
                            Vollständiger Name *
                        </label>
                        {% if form %}
                            {{ form.name(class="mercedes-form-input block w-full px-4 py-3", placeholder="z.B. Max Mustermann", required="required") }}
                        {% else %}
                            <input type="text" id="name" name="name" required
                                   class="mercedes-form-input block w-full px-4 py-3"
                                   placeholder="z.B. Max Mustermann">
                        {% endif %}
                        {% if form and form.name.errors %}
                            <div class="mt-2 text-sm text-mercedes-red">
                            {% for error in form.name.errors %}
                                    <p class="flex items-center">
                                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                        </svg>
                                        {{ error }}
                                    </p>
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>
                
                <!-- E-Mail -->
                <div>
                        <label for="{{ form.email.id if form else 'email' }}" class="block text-sm font-medium text-mercedes-black dark:text-slate-300 mb-2">
                            E-Mail-Adresse *
                        </label>
                        {% if form %}
                            {{ form.email(class="mercedes-form-input block w-full px-4 py-3", placeholder="ihre.email@example.com", required="required") }}
                        {% else %}
                            <input type="email" id="email" name="email" required
                                   class="mercedes-form-input block w-full px-4 py-3"
                                   placeholder="ihre.email@example.com">
                        {% endif %}
                        <p class="mt-1 text-xs text-mercedes-gray dark:text-slate-400">
                            Sie erhalten Status-Updates an diese E-Mail-Adresse
                        </p>
                        {% if form and form.email.errors %}
                            <div class="mt-2 text-sm text-mercedes-red">
                            {% for error in form.email.errors %}
                                    <p class="flex items-center">
                                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                        </svg>
                                        {{ error }}
                                    </p>
                            {% endfor %}
                        </div>
                    {% endif %}
                    </div>
                </div>
            </div>

            <!-- Project Details Section -->
            <div class="bg-gray-50 dark:bg-slate-800/50 rounded-xl p-6">
                <h3 class="text-lg font-semibold text-mercedes-black dark:text-white mb-4 flex items-center">
                    <svg class="w-5 h-5 mr-2 text-mercedes-blue" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"/>
                    </svg>
                    Projekt-Details
                </h3>

            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <!-- Drucker -->
                <div>
                        <label for="{{ form.printer_id.id if form else 'printer_id' }}" class="block text-sm font-medium text-mercedes-black dark:text-slate-300 mb-2">
                            Gewünschte Drucker-Steckdose
                        </label>
                        {% if form %}
                            {{ form.printer_id(class="mercedes-form-input block w-full px-4 py-3") }}
                        {% else %}
                            <select id="printer_id" name="printer_id" class="mercedes-form-input block w-full px-4 py-3">
                                <option value="">Steckdose auswählen...</option>
                                <option value="1">Steckdose 1 - Prusa i3 MK3S+ (Arbeitsplatz A)</option>
                                <option value="2">Steckdose 2 - Ultimaker S3 (Arbeitsplatz B)</option>
                                <option value="3">Steckdose 3 - Formlabs Form 3 (Arbeitsplatz C)</option>
                            </select>
                        {% endif %}
                        <p class="mt-1 text-xs text-mercedes-gray dark:text-slate-400">
                            Wählen Sie die Steckdose für Ihren gewünschten Arbeitsplatz
                        </p>
                        {% if form and form.printer_id.errors %}
                            <div class="mt-2 text-sm text-mercedes-red">
                            {% for error in form.printer_id.errors %}
                                    <p class="flex items-center">
                                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                        </svg>
                                        {{ error }}
                                    </p>
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>
                
                <!-- Geschätzte Dauer -->
                <div>
                        <label for="{{ form.duration_min.id if form else 'duration_min' }}" class="block text-sm font-medium text-mercedes-black dark:text-slate-300 mb-2">
                            Geschätzte Nutzungsdauer *
                        </label>
                    <div class="relative">
                            {% if form %}
                                {{ form.duration_min(class="mercedes-form-input block w-full px-4 py-3 pr-20", placeholder="z.B. 120", required="required") }}
                            {% else %}
                                <input type="number" id="duration_min" name="duration_min" min="1" required
                                       class="mercedes-form-input block w-full px-4 py-3 pr-20"
                                       placeholder="z.B. 120">
                            {% endif %}
                            <div class="absolute inset-y-0 right-0 flex items-center pr-4 pointer-events-none">
                                <span class="text-mercedes-gray dark:text-slate-400 text-sm font-medium">Minuten</span>
                        </div>
                    </div>
                        <p class="mt-1 text-xs text-mercedes-gray dark:text-slate-400">
                            Ungefähre Druckzeit basierend auf der Dateigröße und Komplexität
                        </p>
                        {% if form and form.duration_min.errors %}
                            <div class="mt-2 text-sm text-mercedes-red">
                            {% for error in form.duration_min.errors %}
                                    <p class="flex items-center">
                                        <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                        </svg>
                                        {{ error }}
                                    </p>
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>
            </div>

            <!-- Projektbeschreibung -->
                <div class="mt-6">
                    <label for="{{ form.reason.id if form else 'reason' }}" class="block text-sm font-medium text-mercedes-black dark:text-slate-300 mb-2">
                        Projektbeschreibung *
                    </label>
                    {% if form %}
                        {{ form.reason(class="mercedes-form-input block w-full px-4 py-3 resize-none custom-scroll", rows="5", placeholder="Beschreiben Sie detailliert Ihr Projekt, den geplanten Verwendungszweck, besondere Anforderungen und weitere relevante Informationen...", required="required") }}
                    {% else %}
                        <textarea id="reason" name="reason" rows="5" required
                                  class="mercedes-form-input block w-full px-4 py-3 resize-none custom-scroll"
                                  placeholder="Beschreiben Sie detailliert Ihr Projekt, den geplanten Verwendungszweck, besondere Anforderungen und weitere relevante Informationen..."></textarea>
                    {% endif %}
                    <p class="mt-1 text-xs text-mercedes-gray dark:text-slate-400">
                        Mindestens 50 Zeichen. Je detaillierter die Beschreibung, desto besser können wir Ihren Antrag bewerten.
                    </p>
                    {% if form and form.reason.errors %}
                        <div class="mt-2 text-sm text-mercedes-red">
                        {% for error in form.reason.errors %}
                                <p class="flex items-center">
                                    <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                    </svg>
                                    {{ error }}
                                </p>
                        {% endfor %}
                    </div>
                {% endif %}
            </div>
            </div>

            <!-- File Upload Section -->
            <div class="bg-gray-50 dark:bg-slate-800/50 rounded-xl p-6">
                <h3 class="text-lg font-semibold text-mercedes-black dark:text-white mb-4 flex items-center">
                    <svg class="w-5 h-5 mr-2 text-mercedes-blue" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/>
                            </svg>
                    3D-Datei hochladen (optional)
                </h3>
                
                <div id="file-upload-container">
                    <div class="upload-area flex items-center justify-center w-full h-40 cursor-pointer" id="upload-area">
                        <div class="text-center" id="upload-content">
                            <svg class="w-12 h-12 mb-4 text-mercedes-silver mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/>
                            </svg>
                            <p class="mb-2 text-lg font-semibold text-mercedes-black dark:text-white">
                                Datei hier ablegen oder <span class="text-mercedes-blue">klicken zum Hochladen</span>
                            </p>
                            <p class="text-sm text-mercedes-gray dark:text-slate-400">
                                STL, OBJ, 3MF, GCODE und andere 3D-Dateien (max. 50MB)
                            </p>
                            <div class="mt-4 flex flex-wrap justify-center gap-2 text-xs">
                                <span class="px-2 py-1 bg-mercedes-blue text-white rounded">STL</span>
                                <span class="px-2 py-1 bg-mercedes-blue text-white rounded">OBJ</span>
                                <span class="px-2 py-1 bg-mercedes-blue text-white rounded">3MF</span>
                                <span class="px-2 py-1 bg-mercedes-blue text-white rounded">GCODE</span>
                        </div>
                </div>
                        {% if form %}
                            {{ form.file(class="hidden", id="file-input") }}
                        {% else %}
                            <input type="file" id="file-input" name="file" class="hidden" accept=".stl,.obj,.3mf,.gcode,.ply">
                        {% endif %}
                    </div>
                    
                    <!-- File Preview (Hidden by default) -->
                    <div id="file-preview" class="hidden mt-4"></div>
                </div>
                
                {% if form and form.file.errors %}
                    <div class="mt-4 text-sm text-mercedes-red">
                        {% for error in form.file.errors %}
                            <p class="flex items-center">
                                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                </svg>
                                {{ error }}
                            </p>
                        {% endfor %}
                    </div>
                {% endif %}
            </div>

            <!-- Submit Section -->
            <div class="flex items-center justify-between pt-8 border-t border-mercedes-silver">
                <div class="text-sm text-mercedes-gray dark:text-slate-400">
                    <p class="flex items-center">
                        <svg class="w-4 h-4 mr-1 text-mercedes-red" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                        </svg>
                        * Pflichtfelder
                    </p>
                    <p class="mt-1 text-xs">
                        Alle Daten werden vertraulich behandelt und entsprechen der DSGVO.
                    </p>
                </div>
                
                <div class="flex space-x-4">
                    <button type="button" onclick="resetForm()" 
                            class="btn-secondary">
                        <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
                        </svg>
                        Zurücksetzen
                    </button>
                    
                    <!-- Enhanced Submit Button mit verbessertem Feedback -->
                    <div class="relative group">
                        <button type="submit" id="submit-button"
                                class="btn-primary transition-all duration-300 relative overflow-hidden" disabled>
                            <svg class="w-5 h-5 mr-2" id="submit-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/>
                            </svg>
                            <svg class="w-5 h-5 mr-2 animate-spin hidden" id="submit-spinner" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                            </svg>
                            <span id="submit-text">Antrag einreichen</span>
                            
                            <!-- Glanz-Effekt bei aktivem Button -->
                            <div class="absolute inset-0 -translate-x-full bg-gradient-to-r from-transparent via-white/20 to-transparent skew-x-12 group-hover:translate-x-full transition-transform duration-1000 ease-out"></div>
                        </button>
                        
                        <!-- Tooltip für deaktivierten Button -->
                        <div id="submit-tooltip" class="absolute bottom-full left-1/2 transform -translate-x-1/2 mb-2 px-3 py-2 bg-slate-800 text-white text-sm rounded-lg shadow-lg opacity-0 pointer-events-none transition-opacity duration-200 whitespace-nowrap">
                            <div class="absolute top-full left-1/2 transform -translate-x-1/2 border-4 border-transparent border-t-slate-800"></div>
                            <span id="tooltip-text">Bitte füllen Sie alle Pflichtfelder aus</span>
                        </div>
                        
                        <!-- Fortschrittsanzeige -->
                        <div id="progress-indicator" class="absolute -bottom-8 left-0 right-0">
                            <div class="text-xs text-center text-mercedes-gray mb-1">
                                <span id="progress-text">0 von 5 Feldern ausgefüllt</span>
                            </div>
                            <div class="w-full bg-gray-200 rounded-full h-1">
                                <div id="progress-bar" class="bg-mercedes-blue h-1 rounded-full transition-all duration-300" style="width: 0%"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </form>
    </div>

    <!-- Enhanced Status Check Section -->
    <div class="dashboard-card p-8">
        <div class="text-center">
            <div class="inline-flex items-center justify-center w-16 h-16 bg-mercedes-green text-white rounded-xl mb-6">
                <svg class="w-8 h-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"/>
                </svg>
            </div>
            <h3 class="text-2xl font-bold text-mercedes-black dark:text-white mb-3">
                Status Ihres Antrags prüfen
            </h3>
            <p class="text-mercedes-gray dark:text-slate-400 mb-8 max-w-2xl mx-auto">
                Haben Sie bereits einen Antrag gestellt? Prüfen Sie hier den aktuellen Status Ihrer Anfrage 
                und verfolgen Sie den Fortschritt in Echtzeit.
            </p>
            <div class="flex flex-col sm:flex-row items-center justify-center gap-4">
                <a href="{{ url_for('guest.guest_requests_overview') if url_for else '/guest/requests' }}" 
                   class="btn-primary flex items-center gap-2">
                    <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="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>
                    <span>Meine Anträge</span>
                </a>
                <button onclick="showStatusCheck()" class="btn-secondary flex items-center gap-2">
                    <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="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                    </svg>
                    <span>Status abfragen</span>
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    let selectedFile = null;
    let validationState = {
        name: false,
        email: false,
        printer_id: false,
        duration_min: false,
        reason: false
        // file wurde entfernt da es optional ist
    };
    let isSubmitting = false;

document.addEventListener('DOMContentLoaded', function() {
        initializeGuestRequestForm();
    });

    function initializeGuestRequestForm() {
        setupFileUpload();
        setupFormValidation();
        setupRealTimeValidation();
        setupAccessibility();
        setupFormEnhancements();
        setupProgressTracking();
        setupTooltipBehavior(); // Enhanced Submit Button Tooltips
        updateFormValidation(); // Initial state
    }

    // Enhanced File Upload with Drag & Drop
    function setupFileUpload() {
        const uploadArea = document.getElementById('upload-area');
        const fileInput = document.getElementById('file-input');
        const uploadContent = document.getElementById('upload-content');

        if (!uploadArea || !fileInput) return;

        // Click to upload
        uploadArea.addEventListener('click', (e) => {
            if (!selectedFile && !e.target.closest('.file-preview')) {
                fileInput.click();
            }
        });

        // Drag and drop events
        let dragCounter = 0;

        uploadArea.addEventListener('dragenter', (e) => {
            e.preventDefault();
            dragCounter++;
            uploadArea.classList.add('drag-over');
        });

        uploadArea.addEventListener('dragleave', (e) => {
            e.preventDefault();
            dragCounter--;
            if (dragCounter === 0) {
                uploadArea.classList.remove('drag-over');
            }
        });

        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            dragCounter = 0;
            uploadArea.classList.remove('drag-over');
            
            const files = e.dataTransfer.files;
            if (files.length > 0) {
                handleFileSelection(files[0]);
            }
        });

        // File input change
        fileInput.addEventListener('change', (e) => {
            if (e.target.files.length > 0) {
                handleFileSelection(e.target.files[0]);
            }
        });
    }

    function handleFileSelection(file) {
        const validation = validateFile(file);
        
        if (!validation.valid) {
            showAdvancedMessage(validation.message, 'error');
            return;
        }

        selectedFile = file;
        // validationState.file = true; // Entfernt, da Upload optional ist
        showFilePreview(file);
        updateFormValidation();
        
        if (validation.warning) {
            showAdvancedMessage(validation.warning, 'warning');
        }
    }

    function validateFile(file) {
        const allowedExtensions = ['.stl', '.obj', '.3mf', '.gcode', '.ply'];
        const maxSize = 50 * 1024 * 1024; // 50MB
        const minSize = 1024; // 1KB

        const fileName = file.name.toLowerCase();
        const fileExtension = '.' + fileName.split('.').pop();

        // Check file extension
        if (!allowedExtensions.includes(fileExtension)) {
            return {
                valid: false,
                message: `Ungültiger Dateityp "${fileExtension}". Erlaubte Formate: ${allowedExtensions.join(', ')}`
            };
        }

        // Check file size
        if (file.size > maxSize) {
            return {
                valid: false,
                message: `Datei zu groß (${formatFileSize(file.size)}). Maximum: 50MB`
            };
        }

        if (file.size < minSize) {
            return {
                valid: false,
                message: 'Datei ist zu klein. Mindestgröße: 1KB'
            };
        }

        // Check for potential issues
        let warning = null;
        if (file.size > 25 * 1024 * 1024) {
            warning = 'Große Datei erkannt. Upload kann länger dauern.';
        }

        return { valid: true, warning };
    }

    function showFilePreview(file) {
        const previewContainer = document.getElementById('file-preview');
        const uploadContent = document.getElementById('upload-content');

        // Hide upload content, show preview
        uploadContent.style.display = 'none';
        previewContainer.classList.remove('hidden');

        const fileSize = formatFileSize(file.size);
        const fileType = getFileTypeInfo(file.name);

        previewContainer.innerHTML = `
            <div class="file-preview flex items-center justify-between p-4">
                <div class="flex items-center space-x-4">
                    <div class="w-12 h-12 bg-mercedes-green text-white rounded-lg flex items-center justify-center">
                        <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="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>
                    </div>
                    <div>
                        <h4 class="font-semibold text-mercedes-black dark:text-white">${file.name}</h4>
                        <p class="text-sm text-mercedes-gray dark:text-slate-400">
                            ${fileType} • ${fileSize}
                        </p>
                    </div>
                </div>
                <button onclick="removeFile()" type="button" class="text-mercedes-red hover:text-red-700 transition-colors">
                    <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
                    </svg>
                </button>
            </div>
        `;
    }

    function removeFile() {
        selectedFile = null;
        // validationState.file = false; // Entfernt, da Upload optional ist
        
        const previewContainer = document.getElementById('file-preview');
        const uploadContent = document.getElementById('upload-content');
        const fileInput = document.getElementById('file-input');

        previewContainer.classList.add('hidden');
        uploadContent.style.display = 'block';
        fileInput.value = '';
        
        updateFormValidation();
    }

    // Real-time Form Validation
    function setupRealTimeValidation() {
        const fields = [
            { id: 'name', type: 'text', minLength: 2, required: true },
            { id: 'email', type: 'email', required: true },
            { id: 'printer_id', type: 'select', required: false },
            { id: 'duration_min', type: 'number', min: 1, max: 9999, required: true },
            { id: 'reason', type: 'textarea', minLength: 50, required: true }
        ];

        fields.forEach(field => {
            const element = document.getElementById(field.id) || 
                           document.querySelector(`[name="${field.id}"]`);
            
            if (element) {
                element.addEventListener('input', () => validateField(field, element));
                element.addEventListener('blur', () => validateFieldOnBlur(field, element));
            }
        });
    }

    function validateField(fieldConfig, element) {
        const value = element.value.trim();
        let isValid = true;
        let message = '';

        // Required check
        if (fieldConfig.required && !value) {
            isValid = false;
            message = 'Dieses Feld ist erforderlich';
        }

        // Type-specific validation
        if (value && isValid) {
            switch (fieldConfig.type) {
                case 'email':
                    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailRegex.test(value)) {
                        isValid = false;
                        message = 'Bitte geben Sie eine gültige E-Mail-Adresse ein';
                    }
                    break;
                
                case 'number':
                    const num = parseInt(value);
                    if (isNaN(num) || num < fieldConfig.min || num > fieldConfig.max) {
                        isValid = false;
                        message = `Wert muss zwischen ${fieldConfig.min} und ${fieldConfig.max} liegen`;
                    }
                    break;
                
                case 'text':
                case 'textarea':
                    if (fieldConfig.minLength && value.length < fieldConfig.minLength) {
                        isValid = false;
                        message = `Mindestens ${fieldConfig.minLength} Zeichen erforderlich`;
                    }
                    break;
            }
        }

        validationState[fieldConfig.id] = isValid;
        updateFieldVisualState(element, isValid, message);
        updateFormValidation();
    }

    function validateFieldOnBlur(fieldConfig, element) {
        const value = element.value.trim();
        
        // Enhanced validation on blur
        if (fieldConfig.id === 'email' && value) {
            // Check for common email providers
            const commonDomains = ['gmail.com', 'yahoo.com', 'outlook.com', 'mercedes-benz.com', 'daimler.com'];
            const domain = value.split('@')[1];
            
            if (domain && !commonDomains.includes(domain)) {
                showFieldHint(element, 'Hinweis: Externe E-Mail-Adresse. Stellen Sie sicher, dass Sie E-Mails empfangen können.');
            }
        }
        
        if (fieldConfig.id === 'reason' && value.length > 0 && value.length < 50) {
            showFieldHint(element, `Noch ${50 - value.length} Zeichen bis zur empfohlenen Mindestlänge.`);
        }
    }

    function updateFieldVisualState(element, isValid, message) {
        // Clear previous states
        element.classList.remove('input-error', 'input-success');
        clearFieldMessages(element);

        if (element.value.trim()) {
            if (isValid) {
                element.classList.add('input-success');
            } else {
                element.classList.add('input-error');
                if (message) {
                    showFieldError(element, message);
                }
            }
        }
    }

    function showFieldError(element, message) {
        const errorDiv = document.createElement('div');
        errorDiv.className = 'field-error mt-2 text-sm text-mercedes-red';
        errorDiv.innerHTML = `
            <div class="flex items-center">
                <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
                </svg>
                ${message}
            </div>
        `;
        element.parentNode.appendChild(errorDiv);
    }

    function showFieldHint(element, message) {
        const hintDiv = document.createElement('div');
        hintDiv.className = 'field-hint mt-2 text-sm text-mercedes-blue';
        hintDiv.innerHTML = `
            <div class="flex items-center">
                <svg class="w-4 h-4 mr-1" 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>
                ${message}
            </div>
        `;
        element.parentNode.appendChild(hintDiv);
    }

    function clearFieldMessages(element) {
        const messages = element.parentNode.querySelectorAll('.field-error, .field-hint');
        messages.forEach(msg => msg.remove());
    }

    function updateFormValidation() {
        const submitButton = document.getElementById('submit-button');
        const submitTooltip = document.getElementById('submit-tooltip');
        const tooltipText = document.getElementById('tooltip-text');
        const progressText = document.getElementById('progress-text');
        const progressBar = document.getElementById('progress-bar');
        
        const completedFields = Object.values(validationState).filter(state => state === true).length;
        const totalFields = Object.keys(validationState).length;
        const allValid = completedFields === totalFields;
        const progress = (completedFields / totalFields) * 100;
        
        // Update submit button state
        submitButton.disabled = !allValid;
        
        if (allValid) {
            submitButton.classList.remove('opacity-50', 'cursor-not-allowed');
            submitButton.classList.add('hover:scale-105', 'active:scale-95');
            if (tooltipText) tooltipText.textContent = '✅ Bereit zum Einreichen!';
        } else {
            submitButton.classList.add('opacity-50', 'cursor-not-allowed');
            submitButton.classList.remove('hover:scale-105', 'active:scale-95');
            
            // Update tooltip with missing fields
            const missingFields = [];
            if (!validationState.name) missingFields.push('Name');
            if (!validationState.email) missingFields.push('E-Mail');
            if (!validationState.printer_id) missingFields.push('Drucker');
            if (!validationState.duration_min) missingFields.push('Dauer');
            if (!validationState.reason) missingFields.push('Begründung');
            // if (!validationState.file) missingFields.push('Datei'); // Entfernt, da optional
            
            if (tooltipText) {
                tooltipText.textContent = `Fehlend: ${missingFields.join(', ')}`;
            }
        }
        
        // Update progress indicator
        if (progressText) {
            progressText.textContent = `${completedFields} von ${totalFields} Feldern ausgefüllt`;
        }
        if (progressBar) {
            progressBar.style.width = `${progress}%`;
            
            // Change color based on progress
            if (progress === 100) {
                progressBar.className = 'bg-mercedes-green h-1 rounded-full transition-all duration-300';
            } else if (progress >= 50) {
                progressBar.className = 'bg-mercedes-blue h-1 rounded-full transition-all duration-300';
            } else {
                progressBar.className = 'bg-yellow-500 h-1 rounded-full transition-all duration-300';
            }
        }
        
        // Enhanced tooltip behavior
        setupTooltipBehavior();
        
        // Update overall progress indicator if exists
        updateProgressIndicator();
    }
    
    function setupTooltipBehavior() {
        const submitButton = document.getElementById('submit-button');
        const submitTooltip = document.getElementById('submit-tooltip');
        
        if (!submitButton || !submitTooltip) return;
        
        // Show tooltip on hover for disabled button
        submitButton.addEventListener('mouseenter', () => {
            if (submitButton.disabled) {
                submitTooltip.classList.remove('opacity-0');
                submitTooltip.classList.add('opacity-100');
            }
        });
        
        submitButton.addEventListener('mouseleave', () => {
            submitTooltip.classList.remove('opacity-100');
            submitTooltip.classList.add('opacity-0');
        });
        
        // Also show tooltip on focus (accessibility)
        submitButton.addEventListener('focus', () => {
            if (submitButton.disabled) {
                submitTooltip.classList.remove('opacity-0');
                submitTooltip.classList.add('opacity-100');
            }
        });
        
        submitButton.addEventListener('blur', () => {
            submitTooltip.classList.remove('opacity-100');
            submitTooltip.classList.add('opacity-0');
        });
    }

    // Form Submission
    function setupFormValidation() {
        const form = document.getElementById('guestRequestForm');
        
        if (form) {
            form.addEventListener('submit', handleFormSubmission);
        }
    }

    async function handleFormSubmission(event) {
        event.preventDefault();
        
        if (isSubmitting) return;
        
        // Final validation
        if (!Object.values(validationState).every(state => state === true)) {
            showAdvancedMessage('Bitte füllen Sie alle erforderlichen Felder korrekt aus.', 'error');
            return;
        }

        // Datei ist jetzt optional - keine Validierung mehr erforderlich
        // if (!selectedFile) {
        //     showAdvancedMessage('Bitte wählen Sie eine Datei aus.', 'error');
        //     return;
        // }

        isSubmitting = true;
        showLoadingState();

        try {
            const formData = new FormData();
            formData.append('name', document.getElementById('name').value.trim());
            formData.append('email', document.getElementById('email').value.trim());
            formData.append('printer_id', document.getElementById('printer_id').value);
            formData.append('duration_min', document.getElementById('duration_min').value);
            formData.append('reason', document.getElementById('reason').value.trim());
            
            // Datei nur anhängen, wenn eine ausgewählt wurde
            if (selectedFile) {
                formData.append('file', selectedFile);
            }

            // Add CSRF token
            const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
            if (csrfToken) {
                formData.append('csrf_token', csrfToken);
            }

            const response = await fetch(window.location.href, {
                method: 'POST',
                body: formData
            });

            if (response.ok) {
                const result = await response.text();
                
                if (result.includes('success') || response.redirected) {
                    showSuccessMessage();
                    setTimeout(() => {
                        if (response.redirected) {
                            window.location.href = response.url;
                        } else {
                            window.location.href = '/guest/requests';
                        }
                    }, 2000);
                } else {
                    throw new Error('Unerwartete Antwort vom Server');
                }
            } else {
                const errorData = await response.json().catch(() => ({}));
                throw new Error(errorData.message || `HTTP ${response.status}: Anfrage fehlgeschlagen`);
            }

        } catch (error) {
            console.error('Form submission error:', error);
            showAdvancedMessage(`Fehler beim Einreichen des Antrags: ${error.message}`, 'error');
        } finally {
            isSubmitting = false;
            hideLoadingState();
        }
    }

    function showLoadingState() {
        const submitButton = document.getElementById('submit-button');
        const submitIcon = document.getElementById('submit-icon');
        const submitSpinner = document.getElementById('submit-spinner');
        const submitText = document.getElementById('submit-text');

        submitButton.disabled = true;
        submitIcon.classList.add('hidden');
        submitSpinner.classList.remove('hidden');
        submitText.textContent = 'Wird eingereicht...';
    }

    function hideLoadingState() {
        const submitButton = document.getElementById('submit-button');
        const submitIcon = document.getElementById('submit-icon');
        const submitSpinner = document.getElementById('submit-spinner');
        const submitText = document.getElementById('submit-text');

        submitIcon.classList.remove('hidden');
        submitSpinner.classList.add('hidden');
        submitText.textContent = 'Antrag einreichen';
        updateFormValidation(); // Re-enable if form is valid
    }

    function showSuccessMessage() {
        const overlay = document.createElement('div');
        overlay.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
        overlay.innerHTML = `
            <div class="bg-white dark:bg-slate-800 rounded-xl p-8 max-w-md mx-4 text-center">
                <div class="success-checkmark w-16 h-16 bg-green-100 dark:bg-green-900 text-green-600 dark:text-green-400 rounded-full flex items-center justify-center mx-auto mb-4">
                    <svg class="w-8 h-8" 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>
                <h3 class="text-xl font-bold text-mercedes-black dark:text-white mb-2">Antrag erfolgreich eingereicht!</h3>
                <p class="text-mercedes-gray dark:text-slate-400 mb-4">
                    Ihr Druckantrag wurde erfolgreich übermittelt. Sie erhalten in Kürze eine E-Mail-Bestätigung.
                </p>
                <p class="text-sm text-mercedes-blue">Sie werden automatisch weitergeleitet...</p>
            </div>
        `;
        document.body.appendChild(overlay);
    }

    // Enhanced Form Features
    function setupFormEnhancements() {
        // Character counter for textarea
        const reasonTextarea = document.getElementById('reason');
        if (reasonTextarea) {
            setupCharacterCounter(reasonTextarea, 50, 500);
        }

        // Auto-resize textarea
        setupAutoResize(reasonTextarea);

        // Save form data to localStorage
        setupAutoSave();
    }

    function setupCharacterCounter(textarea, minChars, maxChars) {
        const wrapper = textarea.parentNode;
        const counter = document.createElement('div');
        counter.className = 'character-counter mt-2 text-xs text-right text-mercedes-gray dark:text-slate-400';
        wrapper.appendChild(counter);

        function updateCounter() {
            const length = textarea.value.length;
            counter.textContent = `${length}/${maxChars} Zeichen`;
            
            if (length < minChars) {
                counter.className = 'character-counter mt-2 text-xs text-right text-mercedes-red';
            } else if (length > maxChars * 0.9) {
                counter.className = 'character-counter mt-2 text-xs text-right text-yellow-600';
            } else {
                counter.className = 'character-counter mt-2 text-xs text-right text-mercedes-gray dark:text-slate-400';
            }
        }

        textarea.addEventListener('input', updateCounter);
        updateCounter();
    }

    function setupAutoResize(textarea) {
        if (!textarea) return;
        
        function resize() {
            textarea.style.height = 'auto';
            textarea.style.height = textarea.scrollHeight + 'px';
        }
        
        textarea.addEventListener('input', resize);
        resize();
    }

    function setupAutoSave() {
        const form = document.getElementById('guestRequestForm');
        if (!form) return;

        const fields = form.querySelectorAll('input, select, textarea');
        
        fields.forEach(field => {
            field.addEventListener('input', () => {
                saveFormData();
            });
        });

        // Load saved data on page load
        loadFormData();
    }

    function saveFormData() {
        const formData = {
            name: document.getElementById('name')?.value || '',
            email: document.getElementById('email')?.value || '',
            printer_id: document.getElementById('printer_id')?.value || '',
            duration_min: document.getElementById('duration_min')?.value || '',
            reason: document.getElementById('reason')?.value || ''
        };
        
        localStorage.setItem('guestRequestFormData', JSON.stringify(formData));
    }

    function loadFormData() {
        const savedData = localStorage.getItem('guestRequestFormData');
        if (!savedData) return;

        try {
            const formData = JSON.parse(savedData);
            
            Object.entries(formData).forEach(([key, value]) => {
                const element = document.getElementById(key);
                if (element && value) {
                    element.value = value;
                    // Trigger validation
                    element.dispatchEvent(new Event('input'));
                }
            });
        } catch (error) {
            console.error('Error loading form data:', error);
        }
    }

    function clearSavedFormData() {
        localStorage.removeItem('guestRequestFormData');
    }

    // Accessibility Features
    function setupAccessibility() {
        // Add ARIA labels
        const form = document.getElementById('guestRequestForm');
        if (form) {
            form.setAttribute('aria-describedby', 'form-description');
        }

        // Screen reader announcements
        const srContainer = document.createElement('div');
        srContainer.setAttribute('aria-live', 'polite');
        srContainer.setAttribute('aria-atomic', 'true');
        srContainer.className = 'sr-only';
        srContainer.id = 'sr-announcements';
        document.body.appendChild(srContainer);

        // Keyboard navigation for file upload
        const uploadArea = document.getElementById('upload-area');
        if (uploadArea) {
            uploadArea.setAttribute('tabindex', '0');
            uploadArea.setAttribute('role', 'button');
            uploadArea.setAttribute('aria-label', 'Datei zum Hochladen auswählen');
            
            uploadArea.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    document.getElementById('file-input').click();
                }
            });
        }
    }

    function setupProgressTracking() {
        // Track form completion progress
        window.addEventListener('beforeunload', (e) => {
            const hasData = Object.values(validationState).some(state => state === true);
            if (hasData && !isSubmitting) {
                e.preventDefault();
                e.returnValue = 'Sie haben ungespeicherte Änderungen. Möchten Sie die Seite wirklich verlassen?';
                return e.returnValue;
            }
        });
    }

    // Utility Functions
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }

    function getFileTypeInfo(filename) {
        const extension = filename.toLowerCase().split('.').pop();
        const types = {
            'stl': 'STL-Datei (3D Mesh)',
            'obj': 'OBJ-Datei (3D Object)',
            '3mf': '3MF-Datei (3D Manufacturing)',
            'gcode': 'G-Code-Datei (Druckfertig)',
            'ply': 'PLY-Datei (3D Scan)'
        };
        return types[extension] || 'Unbekannter Dateityp';
    }

    function showAdvancedMessage(message, type) {
        const toast = document.createElement('div');
        toast.className = `fixed top-4 right-4 z-50 p-4 rounded-lg shadow-lg transform transition-all duration-300 translate-x-full opacity-0`;
        
        const colors = {
            'error': 'bg-red-50 border border-red-200 text-red-800 dark:bg-red-900 dark:border-red-700 dark:text-red-200',
            'warning': 'bg-yellow-50 border border-yellow-200 text-yellow-800 dark:bg-yellow-900 dark:border-yellow-700 dark:text-yellow-200',
            'success': 'bg-green-50 border border-green-200 text-green-800 dark:bg-green-900 dark:border-green-700 dark:text-green-200',
            'info': 'bg-blue-50 border border-blue-200 text-blue-800 dark:bg-blue-900 dark:border-blue-700 dark:text-blue-200'
        };
        
        toast.className += ' ' + colors[type];
        
        const icons = {
            'error': '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>',
            'warning': '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"/>',
            'success': '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>',
            'info': '<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"/>'
        };
        
        toast.innerHTML = `
            <div class="flex items-center">
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    ${icons[type]}
                </svg>
                <span>${message}</span>
                <button onclick="this.parentElement.parentElement.remove()" class="ml-4 text-gray-400 hover:text-gray-600">
                    <svg class="w-4 h-4" 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>
        `;
        
        document.body.appendChild(toast);
        
        // Animate in
        setTimeout(() => {
            toast.classList.remove('translate-x-full', 'opacity-0');
        }, 100);
        
        // Auto-remove
        setTimeout(() => {
            toast.classList.add('translate-x-full', 'opacity-0');
            setTimeout(() => toast.remove(), 300);
        }, 5000);
    }

    // Global Functions
    window.resetForm = function() {
        if (confirm('Sind Sie sicher, dass Sie das Formular zurücksetzen möchten? Alle Eingaben gehen verloren.')) {
            document.getElementById('guestRequestForm').reset();
            removeFile();
            Object.keys(validationState).forEach(key => {
                validationState[key] = false;
            });
            updateFormValidation();
            clearSavedFormData();
            
            // Clear all field messages
            document.querySelectorAll('.field-error, .field-hint').forEach(msg => msg.remove());
            document.querySelectorAll('.input-error, .input-success').forEach(el => {
                el.classList.remove('input-error', 'input-success');
            });
            
            showAdvancedMessage('Formular wurde zurückgesetzt', 'info');
        }
    };

    window.showStatusCheck = function() {
        const modal = document.createElement('div');
        modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50';
        modal.innerHTML = `
            <div class="bg-white dark:bg-slate-800 rounded-xl p-8 max-w-md mx-4">
                <h3 class="text-xl font-bold text-mercedes-black dark:text-white mb-4">Status abfragen</h3>
                <p class="text-mercedes-gray dark:text-slate-400 mb-6">
                    Geben Sie Ihre E-Mail-Adresse ein, um den Status Ihrer Anträge zu überprüfen.
                </p>
                <input type="email" id="status-email" class="mercedes-form-input block w-full px-4 py-3 mb-4" placeholder="ihre.email@example.com">
                <div class="flex space-x-4">
                    <button onclick="this.closest('.fixed').remove()" class="btn-secondary flex-1">Abbrechen</button>
                    <button onclick="checkStatus()" class="btn-primary flex-1">Status prüfen</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        
        // Focus email input
        setTimeout(() => {
            document.getElementById('status-email').focus();
        }, 100);
    };

    window.checkStatus = function() {
        const email = document.getElementById('status-email').value.trim();
        if (!email) {
            showAdvancedMessage('Bitte geben Sie eine E-Mail-Adresse ein', 'error');
            return;
        }
        
        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            showAdvancedMessage('Bitte geben Sie eine gültige E-Mail-Adresse ein', 'error');
            return;
        }
        
        // Close modal and redirect
        document.querySelector('.fixed.inset-0').remove();
        window.location.href = `/guest/requests?email=${encodeURIComponent(email)}`;
    };

    function updateProgressIndicator() {
        // Legacy progress indicator support (if exists)
        const completedFields = Object.values(validationState).filter(state => state === true).length;
        const totalFields = Object.keys(validationState).length;
        const progress = (completedFields / totalFields) * 100;
        
        const legacyProgressBar = document.querySelector('.progress-step.active + .flex-1 .bg-mercedes-blue');
        if (legacyProgressBar) {
            legacyProgressBar.style.width = `${Math.min(progress, 100)}%`;
        }
        
        // Update step indicators if they exist
        const progressSteps = document.querySelectorAll('.progress-step');
        progressSteps.forEach((step, index) => {
            if (index < completedFields) {
                step.classList.add('completed');
                step.classList.remove('active');
            } else if (index === completedFields) {
                step.classList.add('active');
                step.classList.remove('completed');
            } else {
                step.classList.remove('active', 'completed');
            }
        });
    }
</script>
{% endblock %} 