document.addEventListener('DOMContentLoaded', (event) => {
    const form = document.querySelector('form');
    const formElements = form.elements;

    // Load saved form state
   /* loadFormState(formElements);

    // Save form state on change
    form.addEventListener('change', () => {
        saveFormState(formElements);
    }); */

    setUpNavigation()
});

function nextQuestion() {
        document.currentQuestion++;
        hideNavElementsAndQuestions();
        showQuestion(`q${document.currentQuestion}`);
        setButtonVisiblity('back', true);
        setButtonVisiblity('next', true);
        if (document.currentQuestion === document.lastQuestion) {
            setButtonVisiblity('next', false);
            setButtonVisiblity('submit', true);
        }
        setNextButtonAvailability();
}

function previousQuestion() {
    if (document.currentQuestion > 0) {
        document.currentQuestion--;
        hideNavElementsAndQuestions();
        showQuestion(`q${document.currentQuestion}`);
        setButtonVisiblity('next', true);
        setButtonVisiblity('submit', false);
        document.nextEnabled = true;
    }
    setButtonVisiblity('back', document.currentQuestion !== 0);
    setNextButtonAvailability();
}

function setUpNavigation() {
    const questions = document.querySelectorAll('.question');

    document.currentQuestion = 0;
    document.nextEnabled = false;
    document.lastQuestion = questions.length - 1;

    hideNavElementsAndQuestions();
    showQuestion(`q${document.currentQuestion}`);
    setButtonVisiblity('next', true);


    const nextButton = document.getElementById('next');
    const backButton = document.getElementById('back');
    nextButton.addEventListener('click', nextQuestion);
    backButton.addEventListener('click', previousQuestion);

    setNextButtonAvailability();

    // check if next button should be enabled on every input, checkbox and radio button bellow class of .question change
    const inputs = document.querySelectorAll('.question input, .question select, .question textarea');
    inputs.forEach(input => {
        input.addEventListener('change', setNextButtonAvailability);
    });


}

function setNextButtonAvailability() {
    console.log('Setting next button availability');
    // check if current question is answered
    // and then enable the next button, disable it otherwise
    const currentQuestion = document.getElementById(`q${document.currentQuestion}`);
    const nextButton = document.getElementById('next');
    const submitButton = document.getElementById('submit');
    // check if any input in the current question is checked, or filled in case it is a text input
    let nextEnabled = false;
    const inputs = currentQuestion.querySelectorAll('input, select, textarea');
    for (let input of inputs) {
        // if the input is not visible, skip it
        if (input.checkVisibility() === false) {
            continue;
        }
        if (input.type === 'checkbox' || input.type === 'radio') {
            if (input.checked) {
                nextEnabled = true;
                break;
            }
        } else {
            if (input.value) {
                nextEnabled = true;
                break;
            }
        }
    }
    nextButton.disabled = !nextEnabled;
    submitButton.disabled = !nextEnabled;
}

function saveFormState(elements) {
    const formState = {};
    for (let element of elements) {
        if (element.name) {
            if (element.type === 'select-multiple') {
                formState[element.name] = Array.from(element.selectedOptions).map(option => option.value);
            } else if (element.type === 'checkbox' || element.type === 'radio') {
                formState[element.name] = element.checked ? element.value : formState[element.name] || null;
            } else {
                formState[element.name] = element.value;
            }
        }
    }
    localStorage.setItem('formState', JSON.stringify(formState));
}

function loadFormState(elements) {
    const formState = JSON.parse(localStorage.getItem('formState'));
    if (formState) {
        for (let element of elements) {
            if (element.name && formState[element.name] !== undefined) {
                if (element.type === 'select-multiple') {
                    Array.from(element.options).forEach(option => {
                        option.selected = formState[element.name].includes(option.value);
                    });
                } else if (element.type === 'checkbox' || element.type === 'radio') {
                    element.checked = formState[element.name] === element.value;
                } else {
                    element.value = formState[element.name];
                }
            }
        }
    }
}

function hideNavElementsAndQuestions() {
    const questions = document.querySelectorAll('.question');
    questions.forEach(question => {
        // add bootstrap hidden class to the element
        question.classList.add('d-none');
    });
    const nextButton = document.getElementById('next');
    const backButton = document.getElementById('back');
    const submitButton = document.getElementById('submit');
    nextButton.classList.add('d-none');
    backButton.classList.add('d-none');
    submitButton.classList.add('d-none');
}

function showQuestion(questionId) {
    const question = document.getElementById(questionId);
    question.classList.remove('d-none');
}

function setButtonVisiblity(buttonId, visible) {
    const button = document.getElementById(buttonId);
    if (visible) {
        button.classList.remove('d-none');
    } else {
        button.classList.add('d-none');
    }
}


