#include colour.js

const MamiColourPickerSlider = function(name, title, mask, shift) {
    let onChange = () => {};
    let gradient, slider, input;

    const html = <div class={['colpick-slider', `colpick-slider-${name}`]}>
        <div class="colpick-slider-name">{title}</div>
        <div class="colpick-slider-value">
            <div class="colpick-slider-value-slider-container">
                {gradient = <div class="colpick-slider-gradient" onmousedown={ev => { if(ev.button === 0) onChange(Math.floor(255 * (Math.max(0, Math.min(200, (ev.layerX - 5))) / 200)) << shift, mask); }}/>}
                {slider = <input class="colpick-slider-value-slider" type="range" min="0" max="255" oninput={() => onChange(slider.value << shift, mask)}/>}
            </div>
            <div class="colpick-slider-value-input-container">
                {input = <input class="colpick-slider-value-input" type="number" min="0" max="255" oninput={() => onChange(input.value << shift, mask)}/>}
            </div>
        </div>
    </div>;

    return {
        getElement: () => html,
        onChange: handler => onChange = handler,
        updateColour: colour => {
            const masked = colour & mask,
                shifted = masked >> shift,
                inverted = colour & ~mask;

            html.style.setProperty('--colpick-slider-colour', MamiColour.hex(masked));
            slider.value = shifted;
            input.value = shifted;
            gradient.style.background = `linear-gradient(90deg, ${MamiColour.hex(inverted)}, ${MamiColour.hex(inverted | (0xFF << shift))})`;
        },
    };
};

const MamiColourPickerSlidersTab = function() {
    const sliders = [
        new MamiColourPickerSlider('red', 'Red', 0xFF0000, 16),
        new MamiColourPickerSlider('green', 'Green', 0xFF00, 8),
        new MamiColourPickerSlider('blue', 'Blue', 0xFF, 0),
    ];

    const html = <div>{...sliders}</div>;

    return {
        getName: () => 'sliders',
        getTitle: () => 'Sliders',
        getElement: () => html,
        onChange: handler => {
            for(const slider of sliders)
                slider.onChange(handler);
        },
        updateColour: colour => {
            for(const slider of sliders)
                slider.updateColour(colour);
        },
    };
};
