export function onLoad() {
    const statementField = document.querySelector('textarea[name="statement"]');
    const generateButton = document.querySelector('button[id="gen"]');
    const symCounter = document.querySelector('p[id="symCounter"]');
    const needMoreText = document.querySelector('p[id="needMoreText"]');
    const maxSym = 600;

    const optionMapping = {
        "Баклан": 1,
        "Маг": 2,
        "Спец": 3
    };
    
    function loadFromLocalStorage() {
        const statement = localStorage.getItem('statement');

        if (statement) {
            statementField.value = statement;
        }
    }

    generateButton.addEventListener('click', async () => {
        // удаляем пробелы в начале и в конце строки
        statementField.value = statementField.value.trim();

        hideLoadingModal(false);
        console.log('Начата генерация заявления');
        generateStatementModal.showModal();

        console.log(localStorage.getItem('ochno'))
        
        const data = {
            "phone": "+7 " + localStorage.getItem('phoneNumber'),
            "kurs": localStorage.getItem('kurs'),
            "isFreeEducation": localStorage.getItem('paid') === "false",
            "isOchno": localStorage.getItem('ochno') === "true",
            "typeOfEducation": optionMapping[localStorage.getItem('option')],
            "reason": localStorage.getItem('statement'),
            "institut": localStorage.getItem('institut'),
            "direction": localStorage.getItem('speciality')
        }

        try {
            const response = await fetch("generateStatement", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });

            if (response.ok) {
                console.log('Заявление успешно сгенерировано');
                location.href='/result';
            } else {
                hideLoadingModal();
                console.log('Ошибка при генерации заявления');
                console.log(response);
            }
        } catch (error) {
            hideLoadingModal();
            console.log('Ошибка при генерации заявления');
            console.log(response);
        }
    });

    function hideLoadingModal(hide = true) {
        var loadingAnim = document.getElementById('loadingAnim');
        var failBlock = document.getElementById('failBlock');
        
        if (hide) {
            loadingAnim.classList.add('hidden');
            failBlock.classList.remove('hidden');
        } else {
            loadingAnim.classList.remove('hidden');
            failBlock.classList.add('hidden');
        }
    }

    function validateField() {
        // если первая буква в lowerCase, то превращаем ее в upperCase
        if (statementField.value.length > 0 && statementField.value[0] === statementField.value[0].toLowerCase()) {
            statementField.value = statementField.value[0].toUpperCase() + statementField.value.slice(1);
        }

        // удаляем пробелы если их больше одного подряд
        statementField.value = statementField.value.replace(/\s{2,}/g, ' ');

        localStorage.setItem('statement', statementField.value);
        
        if (statementField.value.length <= 100)
            needMoreText.classList.remove('hidden');
        else 
            needMoreText.classList.add('hidden');
        
        let percentage = Math.floor(statementField.value.length / maxSym * 100);
        if (percentage > 99) {
            symCounter.classList.add('text-red-500');
            symCounter.classList.remove('text-gray-500');
            symCounter.classList.remove('text-yellow-500');
        } else if (percentage > 85) {
            symCounter.classList.add('text-yellow-500');
            symCounter.classList.remove('text-gray-500');
            symCounter.classList.remove('text-red-500');
        }
        else {
            symCounter.classList.add('text-gray-500');
            symCounter.classList.remove('text-red-500');
            symCounter.classList.remove('text-yellow-500');
        }
        symCounter.innerText = statementField.value.length + '/' + maxSym;

        if (statementField.value.length > 100 && statementField.value.length < maxSym) {
            generateButton.classList.remove('btn-disabled');
        } else
            generateButton.classList.add('btn-disabled');
    }

    statementField.addEventListener('input', validateField);

    loadFromLocalStorage();
    validateField();
}