{% extends "base.html" %}

{% block title %}Anmelden - Mercedes-Benz MYP Platform{% endblock %}

{% block head %}
{{ super() }}
<meta name="csrf-token" content="{{ csrf_token() }}">
{% 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; }
    
    /* Mercedes Login Container */
    .mercedes-login-container {
        background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        min-height: 100vh;
        position: relative;
        overflow: hidden;
    }
    
    .dark .mercedes-login-container {
        background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
    }
    
    .mercedes-login-container::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='60' height='60' viewBox='0 0 60 60'%3E%3Cg fill-rule='evenodd'%3E%3Cg fill='%23000000' fill-opacity='0.02'%3E%3Ccircle cx='30' cy='30' r='2'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
        animation: backgroundFloat 20s ease-in-out infinite;
    }
    
    @keyframes backgroundFloat {
        0%, 100% { transform: translateY(0px); }
        50% { transform: translateY(-10px); }
    }
    
    /* Mercedes Card Effect */
    .mercedes-card {
        background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
        border: 1px solid #e5e7eb;
        box-shadow: 
            0 25px 50px -12px rgba(0, 0, 0, 0.25),
            0 4px 6px -1px rgba(0, 0, 0, 0.1);
        transition: all 0.3s ease;
        backdrop-filter: blur(10px);
        border-radius: 16px;
    }
    
    .dark .mercedes-card {
        background: linear-gradient(135deg, #1e293b 0%, #0f172a 100%);
        border-color: #334155;
        box-shadow: 
            0 25px 50px -12px rgba(0, 0, 0, 0.5),
            0 4px 6px -1px rgba(0, 0, 0, 0.3);
    }
    
    .mercedes-card:hover {
        transform: translateY(-2px);
        box-shadow: 
            0 32px 64px -12px rgba(0, 0, 0, 0.35),
            0 8px 16px -4px rgba(0, 0, 0, 0.1);
    }
    
    /* Mercedes Logo Animation */
    .mercedes-logo {
        animation: logoFloat 3s ease-in-out infinite;
        filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.1));
    }
    
    @keyframes logoFloat {
        0%, 100% { transform: translateY(0px) rotate(0deg); }
        50% { transform: translateY(-5px) rotate(5deg); }
    }
    
    /* Enhanced Form Inputs */
    .mercedes-input {
        transition: all 0.2s ease;
        border: 1px solid #d1d5db;
        background: rgba(255, 255, 255, 0.9);
        backdrop-filter: blur(10px);
    }
    
    .mercedes-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-input {
        background: rgba(30, 41, 59, 0.8);
        border-color: #475569;
        color: #f8fafc;
    }
    
    .dark .mercedes-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);
    }
    
    /* Mercedes Button */
    .mercedes-button {
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.5px;
        box-shadow: 0 4px 14px 0 rgba(0, 115, 206, 0.39);
        position: relative;
        overflow: hidden;
        transition: all 0.3s ease;
    }
    
    .mercedes-button::before {
        content: '';
        position: absolute;
        top: 0;
        left: -100%;
        width: 100%;
        height: 100%;
        background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
        transition: left 0.5s;
    }
    
    .mercedes-button:hover::before {
        left: 100%;
    }
    
    .mercedes-button:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 25px 0 rgba(0, 115, 206, 0.5);
    }
    
    /* 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); }
    }
    
    /* Loading Animation */
    .loading-overlay {
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        z-index: 9999;
        opacity: 0;
        visibility: hidden;
        transition: all 0.3s ease;
    }
    
    .loading-overlay.active {
        opacity: 1;
        visibility: visible;
    }
    
    .loading-content {
        background: white;
        padding: 2rem;
        border-radius: 12px;
        text-align: center;
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
        transform: scale(0.8);
        transition: transform 0.3s ease;
    }
    
    .loading-overlay.active .loading-content {
        transform: scale(1);
    }
    
    .dark .loading-content {
        background: #1e293b;
        color: #f8fafc;
    }
    
    /* Security Indicator */
    .security-indicator {
        background: linear-gradient(90deg, #16a34a, #22c55e);
        color: white;
        padding: 0.5rem 1rem;
        border-radius: 8px;
        font-size: 0.875rem;
        margin-bottom: 1rem;
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
    }
    
    /* Responsive Design */
    @media (max-width: 768px) {
        .mercedes-card {
            margin: 1rem;
            padding: 1.5rem !important;
        }
        
        .mercedes-logo {
            width: 60px !important;
            height: 60px !important;
        }
    }
    
    /* Dark Mode Enhancements */
    .dark .security-indicator {
        background: linear-gradient(90deg, #15803d, #16a34a);
    }
</style>
{% endblock %}

{% block content %}
<div class="flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8">
        <!-- Header -->
        <div class="text-center">
            <!-- Mercedes-Benz Logo -->
            <div class="mercedes-logo inline-flex items-center justify-center w-20 h-20 bg-white/10 backdrop-blur-sm rounded-full mb-6 border border-white/20">
                <svg class="w-10 h-10 text-mercedes-black dark:text-white" viewBox="0 0 80 80" fill="currentColor">
                <path d="M58.6,4.5C53,1.6,46.7,0,40,0c-6.7,0-13,1.6-18.6,4.5v0C8.7,11.2,0,24.6,0,40c0,15.4,8.7,28.8,21.5,35.5
                C27,78.3,33.3,80,40,80c6.7,0,12.9-1.7,18.5-4.6C71.3,68.8,80,55.4,80,40C80,24.6,71.3,11.2,58.6,4.5z M4,40
                c0-13.1,7-24.5,17.5-30.9v0C26.6,6,32.5,4.2,39,4l-4.5,32.7L21.5,46.8v0L8.3,57.1C5.6,52,4,46.2,4,40z M58.6,70.8
                C53.1,74.1,46.8,76,40,76c-6.8,0-13.2-1.9-18.6-5.2c-4.9-2.9-8.9-6.9-11.9-11.7l11.9-4.9v0L40,46.6l18.6,7.5v0l12,4.9
                C67.6,63.9,63.4,67.9,58.6,70.8z M58.6,46.8L58.6,46.8l-12.9-10L41.1,4c6.3,0.2,12.3,2,17.4,5.1v0C69,15.4,76,26.9,76,40
                c0,6.2-1.5,12-4.3,17.1L58.6,46.8z"/>
            </svg>
        </div>
        
            <h2 class="text-3xl font-bold text-mercedes-black dark:text-white mb-2">
                Bei MYP Platform anmelden
            </h2>
            <p class="text-mercedes-gray dark:text-slate-400">
                Zugang zu Ihrem professionellen 3D-Druck Dashboard
            </p>
            
            <!-- Security Indicator -->
            <div class="security-indicator">
                <svg class="w-4 h-4 inline mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
                        </svg>
                Sichere SSL-Verbindung aktiv
            </div>
        </div>

        <!-- Login Form -->
        <div class="mercedes-card p-8">
            <form id="loginForm" method="POST" action="{{ url_for('login') if url_for else '#' }}" class="space-y-6">
                <!-- CSRF Token -->
                {% if form %}
                    {{ form.hidden_tag() }}
                {% else %}
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}"/>
                {% endif %}
                
                <!-- E-Mail Address -->
                <div>
                    <label for="email" class="block text-sm font-medium text-mercedes-black dark:text-slate-300 mb-2">
                        E-Mail-Adresse
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <svg class="h-5 w-5 text-mercedes-silver" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207"/>
                          </svg>
                        </div>
                        {% if form %}
                            {{ form.email(class="mercedes-input block w-full pl-10 pr-3 py-3 rounded-lg focus:ring-2 focus:ring-mercedes-blue focus:border-mercedes-blue", placeholder="ihre.email@mercedes-benz.com", autocomplete="email") }}
                        {% else %}
                            <input type="email" id="email" name="email" required
                                   class="mercedes-input block w-full pl-10 pr-3 py-3 rounded-lg focus:ring-2 focus:ring-mercedes-blue focus:border-mercedes-blue"
                                   placeholder="ihre.email@mercedes-benz.com" autocomplete="email">
                        {% endif %}
                      </div>
                    {% if form and form.email.errors %}
                        <div class="mt-1 text-sm text-mercedes-red">
                            {% for error in form.email.errors %}
                                <p>{{ error }}</p>
                            {% endfor %}
                        </div>
                    {% endif %}
                  </div>

                <!-- Password -->
                    <div>
                    <label for="password" class="block text-sm font-medium text-mercedes-black dark:text-slate-300 mb-2">
                        Passwort
                        </label>
                    <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <svg class="h-5 w-5 text-mercedes-silver" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
                                </svg>
                        </div>
                        {% if form %}
                            {{ form.password(class="mercedes-input block w-full pl-10 pr-10 py-3 rounded-lg focus:ring-2 focus:ring-mercedes-blue focus:border-mercedes-blue", placeholder="Ihr Passwort", autocomplete="current-password") }}
                        {% else %}
                            <input type="password" id="password" name="password" required
                                   class="mercedes-input block w-full pl-10 pr-10 py-3 rounded-lg focus:ring-2 focus:ring-mercedes-blue focus:border-mercedes-blue"
                                   placeholder="Ihr Passwort" autocomplete="current-password">
                        {% endif %}
                        <button type="button" id="togglePassword" class="absolute inset-y-0 right-0 pr-3 flex items-center">
                            <svg id="eyeOpen" class="h-5 w-5 text-mercedes-silver hover:text-mercedes-blue transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/>
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/>
                            </svg>
                            <svg id="eyeClosed" class="h-5 w-5 text-mercedes-silver hover:text-mercedes-blue transition-colors hidden" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.878 9.878L3 3m6.878 6.878L21 21"/>
                            </svg>
                        </button>
                    </div>
                    <div id="password-strength" class="mt-1 hidden">
                        <div class="flex items-center space-x-1">
                            <div class="flex-1 bg-gray-200 dark:bg-gray-700 rounded-full h-1">
                                <div id="strength-bar" class="h-1 rounded-full transition-all duration-300"></div>
                            </div>
                            <span id="strength-text" class="text-xs font-medium"></span>
                        </div>
                    </div>
                    {% if form and form.password.errors %}
                        <div class="mt-1 text-sm text-mercedes-red">
                            {% for error in form.password.errors %}
                                <p>{{ error }}</p>
                            {% endfor %}
                        </div>
                    {% endif %}
                </div>

                <!-- Remember Me & Forgot Password -->
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        {% if form and form.remember_me %}
                            {{ form.remember_me(class="w-4 h-4 text-mercedes-blue bg-white dark:bg-slate-800 border-mercedes-silver rounded focus:ring-mercedes-blue focus:ring-2") }}
                            {{ form.remember_me.label(class="ml-2 text-sm text-mercedes-black dark:text-slate-300") }}
                        {% else %}
                            <input type="checkbox" id="remember_me" name="remember_me" 
                                   class="w-4 h-4 text-mercedes-blue bg-white dark:bg-slate-800 border-mercedes-silver rounded focus:ring-mercedes-blue focus:ring-2">
                            <label for="remember_me" class="ml-2 text-sm text-mercedes-black dark:text-slate-300">
                            Angemeldet bleiben
                        </label>
                        {% endif %}
                    </div>

                    <div class="text-sm">
                        <a href="{{ url_for('reset_password_request') if url_for and url_for('reset_password_request') else '#' }}" 
                           class="text-mercedes-blue hover:text-blue-700 transition-colors">
                            Passwort vergessen?
                        </a>
                    </div>
                </div>

                <!-- Rate Limiting Warning -->
                <div id="rate-limit-warning" class="hidden bg-yellow-50 dark:bg-yellow-900/20 border border-yellow-200 dark:border-yellow-800 rounded-lg p-3">
                <div class="flex">
                        <svg class="h-5 w-5 text-yellow-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <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"/>
                        </svg>
                    <div class="ml-3">
                            <p class="text-sm text-yellow-800 dark:text-yellow-200">
                                <strong>Sicherheitshinweis:</strong> Bei mehreren fehlgeschlagenen Anmeldeversuchen wird Ihr Konto vorübergehend gesperrt.
                            </p>
                        </div>
                    </div>
                </div>

                <!-- Submit Button -->
                <div>
                    <button type="submit" id="submitBtn"
                            class="mercedes-button w-full flex justify-center items-center py-3 px-4 border border-transparent rounded-lg shadow-sm text-sm font-medium text-white bg-mercedes-blue hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-mercedes-blue disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-300">
                        <svg id="loadingSpinner" class="hidden animate-spin -ml-1 mr-2 h-4 w-4 text-white" fill="none" viewBox="0 0 24 24">
                            <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="submitText">Anmelden</span>
                    </button>
                </div>
            </form>
            </div>

        <!-- Alternative Actions -->
        <div class="text-center space-y-4">
            <div class="relative">
                <div class="absolute inset-0 flex items-center">
                    <div class="w-full border-t border-mercedes-silver"></div>
                </div>
                <div class="relative flex justify-center text-sm">
                    <span class="px-2 bg-white dark:bg-black text-mercedes-gray">
                        Oder
                    </span>
                </div>
            </div>

            <div class="space-y-3">
                <a href="{{ url_for('guest.guest_request_form') if url_for else '#guest-request' }}" 
                   class="w-full flex justify-center items-center py-3 px-4 border border-mercedes-silver rounded-lg shadow-sm text-sm font-medium text-mercedes-black dark:text-slate-300 bg-white dark:bg-slate-800 hover:bg-gray-50 dark:hover:bg-slate-700 transition-colors">
                    <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="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/>
                    </svg>
                    Als Gast eine Anfrage stellen
                </a>
                
                <a href="{{ url_for('index') if url_for else '/' }}" 
                   class="w-full flex justify-center items-center py-3 px-4 border border-transparent rounded-lg text-sm font-medium text-mercedes-blue hover:text-blue-700 transition-colors">
                    <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="M10 19l-7-7m0 0l7-7m-7 7h18"/>
                    </svg>
                    Zurück zur Startseite
                </a>
    </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // TEMPORÄRES DEBUGGING: LocalStorage leeren
        console.log("Clearing login attempts from localStorage...");
        localStorage.removeItem('loginAttempts');
        localStorage.removeItem('lastAttemptTime');
        console.log("Login rate limiting reset");
        
        initializeLoginForm();
        checkRateLimit();
        setupFormValidation();
        setupPasswordFeatures();
        setupKeyboardShortcuts();
        setupAccessibility();
    });

    let loginAttempts = parseInt(localStorage.getItem('loginAttempts') || '0');
    let lastAttemptTime = parseInt(localStorage.getItem('lastAttemptTime') || '0');
    let isFormLocked = false;
    const MAX_ATTEMPTS = 5;
    const LOCKOUT_DURATION = 15 * 60 * 1000; // 15 minutes

    function initializeLoginForm() {
        const form = document.getElementById('loginForm');
        const submitBtn = document.getElementById('submitBtn');
        const submitText = document.getElementById('submitText');
        const loadingSpinner = document.getElementById('loadingSpinner');
        const emailInput = document.getElementById('email');
        const passwordInput = document.getElementById('password');

        // Enhanced form submission handling
        if (form) {
            form.addEventListener('submit', async function(e) {
                e.preventDefault();
                
                if (isFormLocked) {
                    showAdvancedMessage('Zu viele Anmeldeversuche. Bitte warten Sie.', 'error');
                    return;
                }

                // Validate form before submission
                if (!validateLoginForm()) {
                    return;
                }

                await handleLoginSubmission();
            });
        }

        // Auto-focus first empty field
        if (emailInput && !emailInput.value) {
            emailInput.focus();
        } else if (passwordInput && !passwordInput.value) {
            passwordInput.focus();
        }

        // Enhanced tab navigation
        setupTabNavigation();
    }

    function checkRateLimit() {
        const now = Date.now();
        const timeSinceLastAttempt = now - lastAttemptTime;
        
        // TEMPORÄR DEAKTIVIERT FÜR DEBUGGING
        console.log("Rate Limiting temporär deaktiviert");
        return; // Frühes Return verhindert Rate Limiting
        
        if (loginAttempts >= MAX_ATTEMPTS && timeSinceLastAttempt < LOCKOUT_DURATION) {
            const remainingTime = LOCKOUT_DURATION - timeSinceLastAttempt;
            showRateLimitWarning(remainingTime);
            lockForm(remainingTime);
        } else if (timeSinceLastAttempt >= LOCKOUT_DURATION) {
            // Reset attempts after lockout period
            loginAttempts = 0;
            localStorage.setItem('loginAttempts', '0');
        }

        // Show warning at 3 attempts
        if (loginAttempts >= 5 && loginAttempts < MAX_ATTEMPTS) {
            document.getElementById('rate-limit-warning').classList.remove('hidden');
        }
    }

    function setupFormValidation() {
        const emailInput = document.getElementById('email');
        const passwordInput = document.getElementById('password');

        if (emailInput) {
            emailInput.addEventListener('blur', function() {
                validateEmail();
            });
            
            emailInput.addEventListener('input', function() {
                clearError(emailInput);
                if (this.value.trim()) {
                    const isValid = isValidEmail(this.value.trim());
                    if (isValid) {
                        this.classList.add('input-success');
                        this.classList.remove('input-error');
                    } else {
                        this.classList.add('input-error');
                        this.classList.remove('input-success');
                    }
                } else {
                    this.classList.remove('input-error', 'input-success');
                }
            });
        }

        if (passwordInput) {
            passwordInput.addEventListener('input', function() {
                clearError(passwordInput);
                updatePasswordStrength(this.value);
            });

            passwordInput.addEventListener('focus', function() {
                document.getElementById('password-strength').classList.remove('hidden');
            });
        }
    }

    function setupPasswordFeatures() {
        const togglePassword = document.getElementById('togglePassword');
        const passwordInput = document.getElementById('password');
        const eyeOpen = document.getElementById('eyeOpen');
        const eyeClosed = document.getElementById('eyeClosed');

        if (togglePassword && passwordInput) {
            togglePassword.addEventListener('click', function() {
                const isPassword = passwordInput.type === 'password';
                passwordInput.type = isPassword ? 'text' : 'password';
                
                eyeOpen.classList.toggle('hidden', isPassword);
                eyeClosed.classList.toggle('hidden', !isPassword);

                // Accessibility
                this.setAttribute('aria-label', isPassword ? 'Passwort verbergen' : 'Passwort anzeigen');
                
                // Keep focus on password input
                passwordInput.focus();
                
                // Move cursor to end
                setTimeout(() => {
                    const len = passwordInput.value.length;
                    passwordInput.setSelectionRange(len, len);
                }, 10);
            });
        }
    }

    function setupKeyboardShortcuts() {
        document.addEventListener('keypress', function(e) {
            // Enter key submits form
            if (e.key === 'Enter' && e.target.form === document.getElementById('loginForm')) {
        e.preventDefault();
                document.getElementById('loginForm').dispatchEvent(new Event('submit'));
            }
        });

        // Escape key clears form
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape') {
                clearForm();
            }
        });
    }

    function setupAccessibility() {
        // ARIA labels and descriptions
        const form = document.getElementById('loginForm');
        if (form) {
            form.setAttribute('aria-describedby', 'login-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);
    }

    function validateLoginForm() {
        const emailValid = validateEmail();
        const passwordValid = validatePassword();
        
        return emailValid && passwordValid;
    }

    function validateEmail() {
        const emailInput = document.getElementById('email');
        const email = emailInput.value.trim();
        
        if (!email) {
            showError(emailInput, 'E-Mail-Adresse ist erforderlich');
            return false;
        }
        
        if (!isValidEmail(email)) {
            showError(emailInput, 'Bitte geben Sie eine gültige E-Mail-Adresse ein');
            return false;
        }
        
        // Check for corporate domain (optional)
        if (email && !email.includes('@mercedes-benz.com') && !email.includes('@daimler.com')) {
            showWarning(emailInput, 'Hinweis: Externe E-Mail-Adresse erkannt');
        }
        
        clearError(emailInput);
        emailInput.classList.add('input-success');
        return true;
    }

    function validatePassword() {
        const passwordInput = document.getElementById('password');
        const password = passwordInput.value;
        
        if (!password) {
            showError(passwordInput, 'Passwort ist erforderlich');
            return false;
        }
        
        if (password.length < 6) {
            showError(passwordInput, 'Passwort muss mindestens 6 Zeichen lang sein');
            return false;
        }
        
        clearError(passwordInput);
        passwordInput.classList.add('input-success');
        return true;
    }

    function updatePasswordStrength(password) {
        const strengthBar = document.getElementById('strength-bar');
        const strengthText = document.getElementById('strength-text');
        
        if (!password) {
            strengthBar.style.width = '0%';
            strengthText.textContent = '';
            return;
        }

        let score = 0;
        let feedback = '';

        // Length check
        if (password.length >= 8) score += 20;
        if (password.length >= 12) score += 10;

        // Character variety
        if (/[a-z]/.test(password)) score += 20;
        if (/[A-Z]/.test(password)) score += 20;
        if (/\d/.test(password)) score += 20;
        if (/[^A-Za-z0-9]/.test(password)) score += 20;

        // Determine strength level
        if (score < 40) {
            strengthBar.className = 'h-1 rounded-full transition-all duration-300 bg-red-500';
            feedback = 'Schwach';
        } else if (score < 70) {
            strengthBar.className = 'h-1 rounded-full transition-all duration-300 bg-yellow-500';
            feedback = 'Mittel';
        } else if (score < 90) {
            strengthBar.className = 'h-1 rounded-full transition-all duration-300 bg-blue-500';
            feedback = 'Gut';
        } else {
            strengthBar.className = 'h-1 rounded-full transition-all duration-300 bg-green-500';
            feedback = 'Sehr stark';
        }

        strengthBar.style.width = `${Math.min(score, 100)}%`;
        strengthText.textContent = feedback;
        }

    async function handleLoginSubmission() {
        const form = document.getElementById('loginForm');
        const submitBtn = document.getElementById('submitBtn');
        const submitText = document.getElementById('submitText');
        const loadingSpinner = document.getElementById('loadingSpinner');
        
        // Show loading state
        submitBtn.disabled = true;
        loadingSpinner.classList.remove('hidden');
        submitText.textContent = 'Wird angemeldet...';
        
        try {
            // Add CSRF token if available
            const formData = new FormData(form);
            
            // Enhanced submission with proper headers
            const response = await fetch(form.action, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            });

            if (response.ok) {
                const result = await response.json().catch(() => null);
                
                if (result && result.success) {
                    // Clear login attempts on success
                    localStorage.setItem('loginAttempts', '0');
                    
                    // Show success message
                    showSuccessMessage();
                    
                    // Redirect after short delay
                    setTimeout(() => {
                        window.location.href = result.redirect_url || '/dashboard';
                    }, 1500);
                    
                } else {
                    throw new Error(result?.message || 'Anmeldung fehlgeschlagen');
                }
            } else {
                // Handle HTTP errors
                if (response.status === 401) {
                    handleFailedLogin('Ungültige E-Mail-Adresse oder Passwort');
                } else if (response.status === 429) {
                    handleRateLimit();
                } else {
                    throw new Error(`Server-Fehler: ${response.status}`);
            }
            }
            
        } catch (error) {
            console.error('Login error:', error);
            handleFailedLogin(error.message || 'Ein unerwarteter Fehler ist aufgetreten');
            
        } finally {
            // Reset button state
            submitBtn.disabled = false;
            loadingSpinner.classList.add('hidden');
            submitText.textContent = 'Anmelden';
        }
    }

    function handleFailedLogin(message) {
        loginAttempts++;
        lastAttemptTime = Date.now();
        
        localStorage.setItem('loginAttempts', loginAttempts.toString());
        localStorage.setItem('lastAttemptTime', lastAttemptTime.toString());
        
        showAdvancedMessage(message, 'error');
        
        // Show warning after 3 attempts
        if (loginAttempts >= 3 && loginAttempts < MAX_ATTEMPTS) {
            document.getElementById('rate-limit-warning').classList.remove('hidden');
            const remaining = MAX_ATTEMPTS - loginAttempts;
            showAdvancedMessage(`Achtung: Noch ${remaining} Versuche übrig`, 'warning');
        }
        
        // Lock form after max attempts
        if (loginAttempts >= MAX_ATTEMPTS) {
            lockForm(LOCKOUT_DURATION);
            showAdvancedMessage(`Konto gesperrt. Bitte warten Sie ${LOCKOUT_DURATION / 60000} Minuten.`, 'error');
        }
        
        // Shake form animation
        const form = document.getElementById('loginForm');
        form.style.animation = 'shake 0.5s ease-in-out';
        setTimeout(() => {
            form.style.animation = '';
        }, 500);
    }

    function handleRateLimit() {
        showRateLimitWarning(LOCKOUT_DURATION);
        lockForm(LOCKOUT_DURATION);
    }

    function lockForm(duration) {
        isFormLocked = true;
        const form = document.getElementById('loginForm');
        const inputs = form.querySelectorAll('input, button');
        
        inputs.forEach(input => {
            input.disabled = true;
        });
        
        // Start countdown
        startLockoutCountdown(duration);
        
        setTimeout(() => {
            isFormLocked = false;
            inputs.forEach(input => {
                input.disabled = false;
            });
            document.getElementById('rate-limit-warning').classList.add('hidden');
        }, duration);
    }

    function startLockoutCountdown(duration) {
        const warningElement = document.getElementById('rate-limit-warning');
        const startTime = Date.now();
        
        const updateCountdown = () => {
            const elapsed = Date.now() - startTime;
            const remaining = Math.max(0, duration - elapsed);
            
            if (remaining > 0) {
                const minutes = Math.floor(remaining / 60000);
                const seconds = Math.floor((remaining % 60000) / 1000);
                warningElement.querySelector('p').innerHTML = 
                    `<strong>Sicherheitssperre aktiv:</strong> Versuchen Sie es in ${minutes}:${seconds.toString().padStart(2, '0')} erneut.`;
                
                setTimeout(updateCountdown, 1000);
            }
        };
        
        updateCountdown();
    }

    function showRateLimitWarning(remainingTime) {
        const warningElement = document.getElementById('rate-limit-warning');
        warningElement.classList.remove('hidden');
        
        const minutes = Math.floor(remainingTime / 60000);
        const seconds = Math.floor((remainingTime % 60000) / 1000);
        
        warningElement.querySelector('p').innerHTML = 
            `<strong>Sicherheitssperre:</strong> Zu viele fehlgeschlagene Anmeldeversuche. Warten Sie ${minutes}:${seconds.toString().padStart(2, '0')}.`;
    }

    function showSuccessMessage() {
        const overlay = document.createElement('div');
        overlay.className = 'loading-overlay active';
        overlay.innerHTML = `
            <div class="loading-content">
                <div class="w-16 h-16 bg-green-100 dark:bg-green-900 rounded-full flex items-center justify-center mx-auto mb-4">
                    <svg class="w-8 h-8 text-green-600 dark:text-green-400" 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-lg font-semibold text-green-600 dark:text-green-400 mb-2">Anmeldung erfolgreich!</h3>
                <p class="text-sm text-gray-600 dark:text-gray-400">Sie werden weitergeleitet...</p>
            </div>
        `;
        document.body.appendChild(overlay);
    }

    // Utility functions
    function isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }

    function showError(input, message) {
        clearError(input);
        
        input.classList.add('input-error');
        input.classList.remove('input-success');
        
        const errorDiv = document.createElement('div');
        errorDiv.className = 'mt-1 text-sm text-mercedes-red error-message';
        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>
            `;
        
        input.parentNode.appendChild(errorDiv);
        
        // Screen reader announcement
        announceToScreenReader(`Fehler: ${message}`);
    }

    function showWarning(input, message) {
        const warningDiv = document.createElement('div');
        warningDiv.className = 'mt-1 text-sm text-yellow-600 dark:text-yellow-400 warning-message';
        warningDiv.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 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"/>
                </svg>
                ${message}
                </div>
            `;
        input.parentNode.appendChild(warningDiv);
    }

    function clearError(input) {
        input.classList.remove('input-error', 'input-success');
        
        const errorMessage = input.parentNode.querySelector('.error-message');
        if (errorMessage) {
            errorMessage.remove();
        }
        
        const warningMessage = input.parentNode.querySelector('.warning-message');
        if (warningMessage) {
            warningMessage.remove();
        }
    }

    function clearForm() {
        const form = document.getElementById('loginForm');
        form.reset();
        
        const inputs = form.querySelectorAll('input');
    inputs.forEach(input => {
            clearError(input);
        });
        
        document.getElementById('password-strength').classList.add('hidden');
    }

    function showAdvancedMessage(message, type) {
        // Create toast notification
        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`;
        
        if (type === 'error') {
            toast.className += ' bg-red-50 border border-red-200 text-red-800 dark:bg-red-900 dark:border-red-700 dark:text-red-200';
        } else if (type === 'warning') {
            toast.className += ' bg-yellow-50 border border-yellow-200 text-yellow-800 dark:bg-yellow-900 dark:border-yellow-700 dark:text-yellow-200';
        } else {
            toast.className += ' bg-blue-50 border border-blue-200 text-blue-800 dark:bg-blue-900 dark:border-blue-700 dark:text-blue-200';
            }
        
        toast.innerHTML = `
            <div class="flex items-center">
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    ${type === '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"/>' :
                        '<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>${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 after 5 seconds
        setTimeout(() => {
            toast.classList.add('translate-x-full', 'opacity-0');
            setTimeout(() => toast.remove(), 300);
        }, 5000);
        
        // Screen reader announcement
        announceToScreenReader(message);
    }

    function announceToScreenReader(message) {
        const srContainer = document.getElementById('sr-announcements');
        if (srContainer) {
            srContainer.textContent = message;
            setTimeout(() => {
                srContainer.textContent = '';
            }, 1000);
        }
    }

    function setupTabNavigation() {
        const focusableElements = document.querySelectorAll(
            'input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])'
        );
        
        focusableElements.forEach((element, index) => {
            element.addEventListener('keydown', function(e) {
                if (e.key === 'Tab') {
                    // Enhanced tab navigation logic can be added here
                }
            });
        });
    }

    // === DEBUGGING FUNKTIONEN ===
    // Diese Funktionen können nach dem erfolgreichen Login entfernt werden
    
    function enableRateLimiting() {
        console.log("Rate Limiting wieder aktiviert");
        // Entfernen Sie die "return;" Zeile aus checkRateLimit() um es zu reaktivieren
    }
    
    function clearLoginAttempts() {
        localStorage.removeItem('loginAttempts');
        localStorage.removeItem('lastAttemptTime');
        console.log("Login-Versuche zurückgesetzt");
    }
    
    // === ENDE DEBUGGING FUNKTIONEN ===
</script>
{% endblock %} 