// Login form handling
document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('login-form');
    const debugInfo = document.getElementById('debug-info');
    const submitBtn = document.getElementById('submit-btn');

    if (window.isDebug) {
        debugInfo.classList.remove('hidden');
    }

    form.addEventListener('submit', function(e) {
        e.preventDefault();

        submitBtn.disabled = true;
        submitBtn.innerHTML = 'Signing in...';

        const formData = new FormData(form);
        const email = formData.get('username');
        const csrfToken = formData.get('csrfmiddlewaretoken');

        if (window.isDebug) {
            debugInfo.innerHTML = `
                <p>Form submission:</p>
                <p>Email: ${email}</p>
                <p>CSRF Token: ${csrfToken ? 'Present' : 'Missing'}</p>
                <p>Action URL: ${form.action}</p>
            `;
        }

        fetch(form.action, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRFToken': csrfToken
            },
            credentials: 'same-origin'
        })
        .then(response => {
            if (response.redirected) {
                window.location.href = response.url;
            } else {
                return response.text().then(html => {
                    document.open();
                    document.write(html);
                    document.close();
                });
            }
        })
        .catch(error => {
            if (window.isDebug) {
                debugInfo.innerHTML += `<p class="text-red-500">Error: ${error}</p>`;
            }
            console.error('Error:', error);
        })
        .finally(() => {
            submitBtn.disabled = false;
            submitBtn.innerHTML = `
                <span class="absolute left-0 inset-y-0 flex items-center pl-3">
                    <svg class="h-5 w-5 text-white group-hover:text-gray-300" 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"></path>
                    </svg>
                </span>
                Sign in
            `;
        });
    });
}); 