/**
 * noUiSlider (single value)
 */
import IGDATAPOOLFE from '@dp/ig_datapool_fe.js';

const noUiSliderPlugin = {
    initFields(form) {
        this.init(form);
    },
    init(form) {
	this.form = form;
        form.querySelectorAll('.dp-slider').forEach((wrapper) => {
            const input = wrapper.querySelector('input');
            const sliderEl = wrapper.querySelector('.slider');

            if (!input || !sliderEl) return;

            const min = parseFloat(input.dataset.min);
            const max = parseFloat(input.dataset.max);
            const step = parseFloat(input.dataset.step || 1);
            const orientation = input.dataset.orientation || 'horizontal';

            const current = parseFloat(input.value) || min;
	    noUiSlider.create(sliderEl, {
                start: [current],
                step: step,
                connect: [true, false],
                orientation: orientation,
                range: {
                    min: min,
                    max: max
                }
            });
            sliderEl.noUiSlider.on('update', (values) => {
                input.value = Math.round(values[0]);
            });
	    // input → slider
	    const updateSlider = () => {
		let value = parseFloat(input.value);

		if (isNaN(value)) return;

		// clamp value to range
		value = Math.max(min, Math.min(max, value));

		sliderEl.noUiSlider.set(value);
	    };

	    input.addEventListener('change', updateSlider);
	    input.addEventListener('input', updateSlider);
	    // $('.slider', this).slider({
	    // 	min : parseInt($input.data('min')),
	    // 	max : parseInt($input.data('max')),
	    // 	step : parseFloat($input.data('step')),
	    // 	orientation : $input.data('orientation'),
	    // 	value : current,
	    // 	slide : function(event, ui) {
	    // 	    $input.val(ui.value);
	    // 	}
	    // });
	});
    }
};

IGDATAPOOLFE.addPlugin('noUiSlider', noUiSliderPlugin);

export default noUiSliderPlugin;
