<!DOCTYPE html>
<html lang="it">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Login — Console MEB</title>
    <link rel="stylesheet" href="/static/style/style.css">
    <link rel="stylesheet" href="/static/style/login.css">
</head>

<body>
    <div class="container">
        <div class="login">
            <div class="header">
                <h1>Accedi alla <span class="prominent-title">Console MEB</span></h1>
            </div>

            {% if error %}
            <p class="error" id="errorMessage">{{ error }}</p>
            {% endif %}

            <form id="loginForm">
                <input type="hidden" id="redirect" name="redirect" value="{{ redirect }}">
                <input type="hidden" name="_csrf" value="{{ csrf_token }}">
                <div class="group">
                    <label for="username">Username</label>
                    <input type="text" id="username" name="username" required autocomplete="username">
                </div>
                <div class="group">
                    <label for="password">Password</label>
                    <input type="password" id="password" name="password" required autocomplete="current-password">
                </div>

                <button type="submit" class="prominent" id="submitBtn">Login</button>
            </form>
        </div>
    </div>

    <script>
        const form = document.getElementById('loginForm');
        const submitBtn = document.getElementById('submitBtn');
        const errorMessage = document.getElementById('errorMessage');

        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            submitBtn.disabled = true;
            submitBtn.textContent = 'Accesso in corso...';
            if (errorMessage) errorMessage.style.display = 'none';

            const formData = new FormData(form);
            
            try {
                const response = await fetch('/api/auth/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    credentials: 'include',
                    body: JSON.stringify({
                        username: formData.get('username'),
                        password: formData.get('password'),
                        redirect: formData.get('redirect'),
                        _csrf: formData.get('_csrf')
                    })
                });

                const data = await response.json().catch(() => ({}));

                if (response.ok && data.success && data.redirect_url) {
                    window.location.href = data.redirect_url;
                } else {
                    const errorMsg = data.message || 'Errore durante il login';
                    
                    if (errorMessage) {
                        errorMessage.textContent = errorMsg;
                        errorMessage.style.display = 'block';
                    } else {
                        alert(errorMsg);
                    }
                    
                    submitBtn.disabled = false;
                    submitBtn.textContent = 'Login';
                    
                    // Ricarica la pagina per ottenere un nuovo CSRF token
                    setTimeout(() => {
                        window.location.reload();
                    }, 2000);
                }
            } catch (err) {
                const errorMsg = 'Errore di connessione. Riprova più tardi.';
                
                if (errorMessage) {
                    errorMessage.textContent = errorMsg;
                    errorMessage.style.display = 'block';
                } else {
                    alert(errorMsg);
                }
                
                submitBtn.disabled = false;
                submitBtn.textContent = 'Login';
            }
        });
    </script>
</body>

</html>
