/**
 * ECP Auth — Client-side JavaScript
 *
 * Handles form validation, file type checking, and
 * UI state management for the ECP authentication flow.
 */

document.addEventListener('DOMContentLoaded', function () {
    'use strict';

    // --- File Validation ---

    /**
     * Validate a PKCS#12 file input.
     * @param {HTMLInputElement} fileInput — The file input element.
     * @returns {boolean} True if the file is valid.
     */
    function validatePKCS12File(fileInput) {
        if (!fileInput.files || fileInput.files.length === 0) {
            showFieldError(fileInput, 'Please select a certificate file.');
            return false;
        }

        var file = fileInput.files[0];
        var validExtensions = ['.p12', '.pfx'];
        var fileName = file.name.toLowerCase();
        var isValid = validExtensions.some(function (ext) {
            return fileName.endsWith(ext);
        });

        if (!isValid) {
            showFieldError(fileInput, 'Please upload a .p12 or .pfx file.');
            return false;
        }

        // Max 5 MB
        var maxSize = 5 * 1024 * 1024;
        if (file.size > maxSize) {
            showFieldError(fileInput, 'File is too large. Maximum size: 5 MB.');
            return false;
        }

        clearFieldError(fileInput);
        return true;
    }

    /**
     * Show a validation error message for a form field.
     * @param {HTMLElement} field — The form field element.
     * @param {string} message — The error message.
     */
    function showFieldError(field, message) {
        clearFieldError(field);
        var errorDiv = document.createElement('div');
        errorDiv.className = 'ecp-field-error';
        errorDiv.textContent = message;
        field.parentNode.appendChild(errorDiv);
    }

    /**
     * Clear validation error messages for a form field.
     * @param {HTMLElement} field — The form field element.
     */
    function clearFieldError(field) {
        var parent = field.parentNode;
        var errors = parent.querySelectorAll('.ecp-field-error');
        errors.forEach(function (el) {
            el.remove();
        });
    }

    // --- Form Submission ---

    /**
     * Disable a submit button and show a loading state.
     * @param {HTMLButtonElement} button — The submit button.
     * @param {string} loadingText — Text to show during loading.
     */
    function setButtonLoading(button, loadingText) {
        button.disabled = true;
        button.dataset.originalText = button.textContent;
        button.innerHTML = '<span class="ecp-spinner"></span> ' + loadingText;
    }

    /**
     * Restore a submit button to its original state.
     * @param {HTMLButtonElement} button — The submit button.
     */
    function resetButton(button) {
        button.disabled = false;
        if (button.dataset.originalText) {
            button.textContent = button.dataset.originalText;
        }
    }

    // --- Login Form ---

    var loginForm = document.getElementById('ecp-login-form');
    if (loginForm) {
        loginForm.addEventListener('submit', function (event) {
            var fileInput = loginForm.querySelector('input[type="file"]');
            if (fileInput && !validatePKCS12File(fileInput)) {
                event.preventDefault();
                return;
            }

            var submitBtn = loginForm.querySelector('button[type="submit"]');
            if (submitBtn) {
                setButtonLoading(submitBtn, 'Authenticating...');
            }
        });
    }

    // --- Challenge Form ---

    var challengeForm = document.getElementById('ecp-challenge-form');
    if (challengeForm) {
        challengeForm.addEventListener('submit', function () {
            var submitBtn = challengeForm.querySelector('button[type="submit"]');
            if (submitBtn) {
                setButtonLoading(submitBtn, 'Verifying...');
            }
        });
    }

    // --- Register Form ---

    var registerForm = document.getElementById('ecp-register-form');
    if (registerForm) {
        registerForm.addEventListener('submit', function (event) {
            var fileInput = registerForm.querySelector('input[type="file"]');
            if (fileInput && !validatePKCS12File(fileInput)) {
                event.preventDefault();
                return;
            }

            var usernameInput = registerForm.querySelector('#id_username');
            if (usernameInput && usernameInput.value.trim().length < 1) {
                event.preventDefault();
                showFieldError(usernameInput, 'Username is required.');
                return;
            }

            var submitBtn = registerForm.querySelector('button[type="submit"]');
            if (submitBtn) {
                setButtonLoading(submitBtn, 'Registering...');
            }
        });
    }
});
