const initNumberInputs = () => {
    const numberInputs = document.querySelectorAll('.form-number');

    for (const numberInputWrapper of numberInputs) {
        const minus = numberInputWrapper.querySelector('.form-number__btn-minus');
        const plus = numberInputWrapper.querySelector('.form-number__btn-plus');
        const input = numberInputWrapper.querySelector('.form-number__input');

        if (!(minus && plus && input)) return;

        const minAttr = parseInt(input.getAttribute('min'));
        const min = !isNaN(minAttr) ? minAttr : Number.MIN_SAFE_INTEGER;

        const maxAttr = parseInt(input.getAttribute('max'));
        const max = !isNaN(maxAttr) ? maxAttr : Number.MAX_SAFE_INTEGER;

        const initAttr = parseInt(input.value);
        const init = !isNaN(initAttr) ? initAttr : Math.max(min, Math.min(0, max));

        const addValue = (add) => {
            const parsed = parseInt(input.value);
            const val = !isNaN(parsed) ? parsed : init;
            const newVal = val + add;
            input.value = (newVal <= max) && (newVal >= min) ? newVal : val;
            input.dispatchEvent(new Event('change'));
        }

        const update = () => {
            const currentValue = parseInt(input.value);
            if (currentValue <= min) {
                minus.classList.add('form-number__btn--disabled');
                input.value = min;
            } else {
                minus.classList.remove('form-number__btn--disabled');
            }

            if (currentValue >= max) {
                plus.classList.add('form-number__btn--disabled');
                input.value = max;
            } else {
                plus.classList.remove('form-number__btn--disabled');
            }
        }

        minus.addEventListener('click', (e) => {
            e.preventDefault();
            addValue(-1);
        });

        plus.addEventListener('click', (e) => {
            e.preventDefault();
            addValue(1);
        });

        input.addEventListener('change', () => {
            update();
        });
        input.addEventListener('input', () => {
            update();
        });

        input.dispatchEvent(new Event('change'));
    };
}

export { initNumberInputs };
