let selectColorID = null;
let pickr = null;
let suppressSave = false; // NEW FLAG

function initializePickr(){

    pickr = Pickr.create({
        el: '.mepickr',
        theme: 'nano', // or 'monolith', or 'nano'
        //closeOnScroll: true,

        swatches: [
            '#F44336',
            '#F9C70E',
            '#2AB3D1',
            '#0C32F5',
            '#D11AFF',
            '#1FD4C3',
            '#15C083'
        ],

        components: {

            // Main components
            preview: true,
            opacity: true,
            hue: true,

            // Input / output Options
            interaction: {
                hex: true,
                rgba: false,
                hsla: false,
                hsva: false,
                cmyk: false,
                input: true,
                clear: false,
                save: true
            }
        },

        i18n: {
            'btn:save': 'Save',
            'btn:cancel': 'Cancel',
            'btn:clear': 'Clear',
        }
    });

    pickr.on('save', (color, instance) => {

        const data = color.toHEXA().toString();

        if (selectColorID == null){
            if (!suppressSave) {
                copyToClipboard(data, "");
            }
        }

        if (selectColorID) {
            //console.log("set value of  : #" + selectColorID);
            //console.log("no copy!");
            $(`#${selectColorID}`).val(data).trigger('change');
            selectColorID = null;
        }
        
        pickr.hide();

    }).on('hide', instance => {
        selectColorID = null;
    });


    var pickerFunction = function (e) {

        e.preventDefault();
        let currentColor = $(this).parent().find('.mppanel_color_forms').val();
        
        suppressSave = true;
        setTimeout(function(){
            suppressSave = false;
        },300);

        pickr.setColor(currentColor); //set color will trigger OnSave also!
        //saeed get selectColorID after pickr.setColor because of setColor will trigger onSave!!!
        selectColorID = $(this).parent().find('.mppanel_color_forms').prop('id');

        pickr.show();

    }

    var colorChangeListener = function () {
        //console.log("test1")
        $(this).parent().find(".color_box").css("background", this.value);
    }

    $('.color_selector_box > .color_box').click(pickerFunction);
    $('.mppanel_color_forms').on("change keyup paste", colorChangeListener);

}

(function ($) {

   if($("#color-pickr-wrapper").length > 0) {
        initializePickr();
    }

})(jQuery)