/**
 * noUiSlider (range)
 */

import IGDATAPOOLFE from '@dp/ig_datapool_fe.js';

const noUiSliderRangePlugin = {
    initFields(form) {
        this.init(form);
    },
    init(form) {

	// Math.log10 = Math.log10 || function(x) {
	//     return Math.log(x) * Math.LOG10E;
	// };
	const sliders = form.querySelectorAll('.dp-slider-range-slider');
	sliders.forEach(currentSlider => {
            // Find parent and inputs using native DOM traversal
            const currentSliderContainer = currentSlider.closest('.dp-slider-range');
            if (!currentSliderContainer) return;

            const inputFrom = currentSliderContainer.querySelector('.dp-slider-range-from');
            const inputTo = currentSliderContainer.querySelector('.dp-slider-range-to');
            if (!inputFrom || !inputTo) return;

            const step = parseFloat(inputFrom.step || 1);
            const min = parseFloat(inputFrom.min);
            const max = parseFloat(inputTo.max);

	    const startMin = inputFrom.value !== '' ? parseFloat(inputFrom.value) : parseFloat(inputFrom.min);
	    const startMax = inputTo.value !== '' ? parseFloat(inputTo.value) : parseFloat(inputTo.max);
	    
	    // Initialize noUiSlider
            noUiSlider.create(currentSlider, {
                start: [startMin, startMax],
                connect: true,
                step: step,
                range: { min, max }
            });

	    // Update inputs when slider moves
            currentSlider.noUiSlider.on('update', (values, handle, unencoded, tap, positions, sliderInstance) => {
                let value = values[handle];
                const step = sliderInstance.options.step;

                if (step === 1) {
                    value = parseInt(value);
                } else if (step > 0 && step < 1) {
                    const decimals = -Math.floor(Math.log10(step));
                    if (decimals > 0) {
                        value = parseFloat(value).toFixed(decimals);
                    }
                }
                // handle is 0 for the first handle, 1 for the second
                if (handle === 0) {
                    inputFrom.value = value;
                } else {
                    inputTo.value = value;
                }
            });

            // inputs -> slider
            const updateSliderFromInput = () => {
                let fromValue = parseFloat(inputFrom.value);
                let toValue = parseFloat(inputTo.value);

                if (!isNaN(fromValue) && !isNaN(toValue)) {
                    currentSlider.noUiSlider.set([fromValue, toValue]);
                }
            };

            inputFrom.addEventListener('change', updateSliderFromInput);
            inputTo.addEventListener('change', updateSliderFromInput);
        });
    }
};
IGDATAPOOLFE.addPlugin('noUiSliderRange', noUiSliderRangePlugin);

export default noUiSliderRangePlugin;
