const createSelect = (wrapper) => {
    wrapper.classList.add('form-select');
    const formSelect = wrapper.querySelector('select');

    const selected = document.createElement('div');
    selected.setAttribute('class', 'form-select__selected');
    selected.innerHTML = formSelect.options[formSelect.selectedIndex].innerHTML;
    wrapper.appendChild(selected);

    const optionList = document.createElement('div');
    optionList.classList.add('form-select__options');

    for (const formOption of formSelect.options) {
        const option = document.createElement('div');
        option.classList.add('form-select__option');
        option.setAttribute('data-value', formOption.value);
        option.innerHTML = formOption.innerHTML;

        optionList.appendChild(option);

        option.addEventListener('click', (e) => {
            formSelect.value = formOption.value;
            selected.innerHTML = option.innerHTML;

            for (const opt of wrapper.querySelectorAll('.form-select__option')) {
                opt.classList.remove('form-select__option--selected');
            }
            option.classList.add('form-select__option--selected');
        });
    }

    wrapper.appendChild(optionList);
    selected.addEventListener('click', (e) => {
        e.stopPropagation();
        closeAllSelect(wrapper);
        wrapper.classList.toggle('form-select--active');
    });
}

const closeAllSelect = (element) => {
    for (const select of document.querySelectorAll('.form-select')) {
        if (select === element) {
            continue;
        }
        select.classList.remove('form-select--active');
    }
}

const initSelects = (selector) => {
    const selects = document.querySelectorAll(selector);

    for (const select of selects) {
        createSelect(select);
    }

    document.addEventListener('click', closeAllSelect);
}

export { initSelects };
