(function ($) {
  wp.customize.bind("ready", function () {

      const IPPR_SETTINGS = url_params.IPPR_SETTINGS;
      const siteUrl = url_params.siteUrl;
      
      // add divider classes to control
      wp.customize.control.each(function (control) {
        if (control.params.divider) {
            var dividerClass = control.params.divider.ippr_class; 
            var controlWrapper = control.container;

            if (controlWrapper.length > 0) {
                controlWrapper.addClass(dividerClass); 
            }
        }

        if (control.params.tab) {
            var tabTypeClass = control.params.tab;
            var controlWrapper = control.container;
    
            if (controlWrapper.length > 0) {
                controlWrapper.addClass('ippr_tab_type_' + tabTypeClass);
            }
        }

      });
  

      // Properties Per Page
      wp.customize.control(IPPR_SETTINGS + '[archive_property_perpage_control]', function (control) {
        const minusButton = control.container.find(".ippr-minus");
        const plusButton = control.container.find(".ippr-plus");
        const inputField = control.container.find(".ippr-base-control input");

        minusButton.click(function () {
          var value = parseInt(inputField.val());
          if (value > 1) {
            value--;
          }
          inputField.val(value);
          inputField.trigger("change");
        });

        plusButton.click(function () {
          var value = parseInt(inputField.val());
          value++; // Increase the value
          inputField.val(value);
          inputField.trigger("change");
        });
      });


      // Color Picker
      $(".ippr-color-picker-input").wpColorPicker({
        change: function (event, ui) {
          var color = ui.color.toString();
          var settingKey = $(event.target).data("customize-setting-link");
          if (settingKey) {
            wp.customize(settingKey, function (setting) {
              setting.set(color);
            });
            //wp.customize.previewer.refresh();
          }
        },
        clear: function () {
          //wp.customize.previewer.refresh();
        },
      });

      // Customization
      $(".ippr-color-picker-input").each(function () {
        var $container = $(this).closest(".wp-picker-container");
        var $parent_container = $(this).closest(".color-picker-row");
        var $pickerText = $(this)
          .closest($container)
          .find(".wp-color-result-text");
        var $inputWrap = $container.find(".wp-picker-input-wrap");
        var $pickerHolder = $container.find(".wp-picker-holder");
        var tooltipText = $(this).data("tooltip");

        $container.attr("data-tooltip", tooltipText);
        $pickerText.remove();
        $inputWrap
          .add($pickerHolder)
          .wrapAll('<div class="ipp-picker-container"></div>');
      });

    // Section Tabs
    const ippr_primary_btn_tab = $(".control-section-ippr_section .ippr_tab_type_primary");
    const ippr_secondary_btn_tab = $(".control-section-ippr_section .ippr_tab_type_secondary");

    ippr_primary_btn_tab.show();
    ippr_secondary_btn_tab.hide();

    $(".ippr_primary_btn").addClass("nav-tab-active");

    $(".ippr-heading-tabs-button").on("click", function (e) {
        e.preventDefault();

        $(".ippr-heading-tabs-button").removeClass("nav-tab-active");

        $(this).addClass("nav-tab-active");
        
        if ($(this).hasClass("ippr_primary_btn")) {
            ippr_primary_btn_tab.show();
            ippr_secondary_btn_tab.hide();
        } else if ($(this).hasClass("ippr_secondary_btn")) {
            ippr_primary_btn_tab.hide();
            ippr_secondary_btn_tab.show();
        }
    });

    // Toggle the modal on icon click

        $(".ippr-fs-toggle-icon").on("click", function (e) {
            e.preventDefault();
    
            const currentIcon = $(this); // The clicked icon
            const currentModal = currentIcon.closest(".ippr-control-wrapper").next(".ippr-field-settings-wrap").find(".ippr-field-settings-modal");
    
            // Close all other modals and remove 'open' class from other icons
            $(".ippr-fs-toggle-icon").not(currentIcon).removeClass("open");
            $(".ippr-field-settings-modal").not(currentModal).hide();
    
            // Toggle the clicked modal
            currentIcon.toggleClass("open");
            if (currentIcon.hasClass("open")) {
                currentModal.show(); // Open the clicked modal
            } else {
                currentModal.hide(); // Close the clicked modal
            }
        });

        // Close modal when clicking outside
        $(document).on("click", function (e) {
            // Check if the click was outside both the modal and the toggle icon
            if (!$(e.target).closest(".ippr-field-settings-modal, .ippr-fs-toggle-icon").length) {
                $(".ippr-fs-toggle-icon").removeClass("open"); // Remove 'open' class from icons
                $(".ippr-field-settings-modal").hide(); // Close all modals
            }
        });
    
    // Typography Controls
    const button_controls = [
        IPPR_SETTINGS + '[primary_btn_typography_control]',
        IPPR_SETTINGS + '[secondary_btn_typography_control]',
        IPPR_SETTINGS + '[body_typography_control]',
        IPPR_SETTINGS + '[heading_typography_control]',
    ];
    
    button_controls.forEach(function (controlId) {
        wp.customize.control(controlId, function (control) {
            const $control = $(this);
            const settingKey = control.container.find(".ippr-responsive-font-size").data('setting-id');
            const $resDeviceIcon = control.container.find(".ippr-responsive-device-icon");
            const $resDeviceInput = control.container.find(".ippr-responsive-font-size-input");
            const $unitLabel = control.container.find('input[type="radio"]:checked');
            const $resDeviceDefaultIcon = $resDeviceIcon.eq(0);
            const $resDeviceDefaultInput = $resDeviceInput.eq(0);
            const $slider = control.container.find('#ippr-responsive-font-size-slider-input');
    
            // Function to update the slider background fill
            function updateSliderFill(slider) {
                const min = parseFloat(slider.attr('min')) || 0;
                const max = parseFloat(slider.attr('max')) || 100;
                const value = parseFloat(slider.val()) || 0;
                const percentage = ((value - min) / (max - min)) * 100;
    
                slider.css(
                    'background',
                    `linear-gradient(to right, #0284c7 ${percentage}%, #ddd ${percentage}%)`
                );
            }
    
            // Initially hide all device icons and inputs, show only the first one
            $resDeviceIcon.addClass('hidden');
            $resDeviceDefaultIcon.removeClass('hidden').addClass('active');
            $resDeviceInput.addClass('hidden');
            $resDeviceDefaultInput.removeClass('hidden').addClass('active');
    
            // Get the current setting value to initialize the inputs and slider
            wp.customize(settingKey, function (setting) {
                const currentValue = setting.get() || {
                    desktop: '16',
                    tablet: '16',
                    mobile: '16',
                };
    
                // Set the initial value for the active input
                const device = $resDeviceDefaultInput.data('device');
                const initialValue = currentValue[device] || 16;
                $slider.val(initialValue);
                $resDeviceDefaultInput.find('input').val(initialValue);
    
                // Update the slider fill based on the initial value
                updateSliderFill($slider);
            });
    
            // Active label alive
            $($unitLabel).each(function () {
                $(this).parent('label').addClass('active');
            });
    
            // Handle tab switching for device icons
            $resDeviceIcon.on('click', function () {
                const currentIndex = $resDeviceIcon.index(this);
                const nextIndex = (currentIndex + 1) % $resDeviceIcon.length;
    
                // Hide the current button and show the next one
                $resDeviceIcon.eq(currentIndex).addClass('hidden').removeClass('active');
                $resDeviceIcon.eq(nextIndex).removeClass('hidden').addClass('active');
    
                // Show the corresponding input (using the same index logic)
                $resDeviceInput.addClass('hidden').removeClass('active');
                $resDeviceInput.eq(nextIndex).removeClass('hidden').addClass('active');
    
                // Sync slider with the current device input
                const activeValue = $resDeviceInput.eq(nextIndex).find('input').val();
                $slider.val(activeValue);
    
                // Update slider fill
                updateSliderFill($slider);
            });
    
            // Update settings on slider input change
            $slider.on('input', function () {
                const sliderValue = $(this).val(); // Get the slider value
    
                // Update the active input with the slider value
                const $activeInput = control.container.find('.ippr-responsive-font-size-input.active input');
                $activeInput.val(sliderValue);
    
                // Get the device from the active input
                const device = $activeInput.closest('.ippr-responsive-font-size-input').data('device');
    
                // Validate device attribute
                if (!device) {
                    console.error('Device attribute is missing.');
                    return;
                }
    
                wp.customize(settingKey, function (setting) {
                    // Get the current value or initialize the structure if not set
                    const currentValue = setting.get() || {
                        desktop: '16',
                        tablet: '16',
                        mobile: '16',
                    };
    
                    // Clone the current object to ensure immutability
                    const updatedValue = { ...currentValue };
    
                    // Update the specific device font size
                    updatedValue[device] = sliderValue;
    
                    // Set the updated value back to the setting
                    setting.set(updatedValue);
                });
    
                // Update slider fill
                updateSliderFill($slider);
            });
    
            // Update settings when the input value changes
            $resDeviceInput.on('input change', function () {
                const $input = $(this).find('input');
                const inputValue = $input.val(); // Get the input value
    
                // Sync the slider value with the input
                $slider.val(inputValue);
    
                // Update the settings on input change
                const device = $input.closest('.ippr-responsive-font-size-input').data('device');
    
                // Validate device attribute
                if (!device) {
                    console.error('Device attribute is missing.');
                    return;
                }
    
                wp.customize(settingKey, function (setting) {
                    // Get the current value or initialize the structure if not set
                    const currentValue = setting.get() || {
                        desktop: '16',
                        tablet: '16',
                        mobile: '16',
                    };
    
                    // Clone the current object to ensure immutability
                    const updatedValue = { ...currentValue };
    
                    // Update the specific device font size
                    updatedValue[device] = inputValue;
    
                    // Set the updated value back to the setting
                    setting.set(updatedValue);
                });
    
                // Update slider fill
                updateSliderFill($slider);
            });
    
            // Update inputs when settings change
            wp.customize(settingKey, function (setting) {
                setting.bind(function (value) {
                    // Ensure the value is in the expected structure and has values for desktop, tablet, and mobile
                    if (!value || !value.desktop || !value.tablet || !value.mobile) {
                        console.error('The value structure is incorrect or missing fields');
                        return;
                    }
    
                    // Update all inputs based on the updated value
                    for (const [device, fontSize] of Object.entries(value)) {
                        control.container
                            .find(`.ippr-responsive-font-size-input[data-device="${device}"] input`)
                            .val(fontSize);
    
                        // Sync slider with active input
                        if (
                            control.container
                                .find(`.ippr-responsive-font-size-input[data-device="${device}"]`)
                                .hasClass('active')
                        ) {
                            $slider.val(fontSize);
    
                            // Update slider fill
                            updateSliderFill($slider);
                        }
                    }
                });
            });
        });
    });
    
    
    
    




    // Responsive Button
    $('.ippr-responsive-button-control').each(function () {
        const $control = $(this);
        const settingKey = $control.data('setting-id');
        const $buttons = $control.find('.ippr-responsive-button-icon');
        const $inputs = $control.find('.ippr-spacing-input-item');
        const $defaultButton = $buttons.eq(0);
        const $defaultInput = $inputs.eq(0);

        // Set default active button and input
        $buttons.addClass('hidden');
        $defaultButton.removeClass('hidden').addClass('active');

        $inputs.addClass('hidden');
        $defaultInput.removeClass('hidden').addClass('active');
        

        // Handle tab switching
        $buttons.on('click', function () {
        const currentIndex = $buttons.index(this);
        const nextIndex = (currentIndex + 1) % $buttons.length;

        // Hide the current button and show the next one
        $buttons.eq(currentIndex).addClass('hidden').removeClass('active');
        $buttons.eq(nextIndex).removeClass('hidden').addClass('active');

        // Show the corresponding input (using the same index logic)
        $inputs.addClass('hidden').removeClass('active');
        $inputs.eq(nextIndex).removeClass('hidden').addClass('active');
        });


        // Update settings on input change
        $control.find('.ippr-spacing-input-item input').on('input', function () {
            const $input = $(this);
            const device = $input.closest('.ippr-spacing-input-item').data('device'); // Get the device
            const side = $input.data('side'); // Get the side (top, right, bottom, left)
            const value = $input.val(); // Get the input value

            // Validate device and side attributes
            if (!device || !side) {
                console.error('Device or side attribute is missing.');
                return;
            }

            wp.customize(settingKey, function (setting) {
                // Get the current value or initialize the structure
                const currentValue = setting.get() || {
                    desktop: { top: 0, right: 0, bottom: 0, left: 0 },
                    tablet: { top: 0, right: 0, bottom: 0, left: 0 },
                    mobile: { top: 0, right: 0, bottom: 0, left: 0 },
                };

                // Clone the current object to ensure immutability
                const updatedValue = JSON.parse(JSON.stringify(currentValue));

                // Update the specific device and side
                if (!updatedValue[device]) {
                    updatedValue[device] = { top: 0, right: 0, bottom: 0, left: 0 };
                }
                updatedValue[device][side] = value;

                // Set the updated value back to the setting
                setting.set(updatedValue);
            });
        });

        // Listen for changes from the Customizer and update inputs
        wp.customize(settingKey, function (setting) {
            setting.bind(function (value) {
                // Update all inputs based on the updated value
                for (const [device, sides] of Object.entries(value)) {
                    for (const [side, sideValue] of Object.entries(sides)) {
                        $control
                            .find(`.ippr-spacing-input-item[data-device="${device}"] input[data-side="${side}"]`)
                            .val(sideValue);
                    }
                }
            });
        });

        // Button Side Width Uniform
        $inputs.each(function () {
            const wrapper = $(this);
            const inputsUniform = wrapper.find('.ippr-spacing-input');
            const buttonUniform = $control.find('.ippr-spacing-input-item-uniform .toggle-uniform');
            let isUniform = false;
            let isUpdating = false;

            buttonUniform.on('click', function () {
                isUniform = !isUniform;
                $(this).toggleClass('connected', isUniform);
            });

            inputsUniform.on('input change', function () {
                if (isUpdating || !isUniform) return;

                const currentValue = $(this).val();
                isUpdating = true;

                inputsUniform.each(function () {
                    if ($(this).val() !== currentValue) {
                        $(this).val(currentValue).trigger('input');
                    }
                });

                isUpdating = false;
            });

        });

        // Unit Selection Handling
        $('.ippr-button-settings-unit').each(function () {
        const $unitWrapper = $(this);
        const $radioButtons = $unitWrapper.find('input[type="radio"]');

        $radioButtons.each(function () {
            const $label = $(this).parent('label');
            if ($(this).is(':checked')) {
                $label.addClass('active');
            } else {
                $label.removeClass('active');
            }
        });

        // When unit is changed, update the Customizer setting
        $radioButtons.on('change', function () {
            $unitWrapper.find('label').removeClass('active');
            $(this).parent('label').addClass('active');
            
            // Get the selected unit value
            const selectedUnit = $(this).val();

            // Update the unit in the Customizer
            wp.customize(settingKey, function (setting) {
                // Get the current value or initialize it
                const currentValue = setting.get() || {
                    desktop: { top: 0, right: 0, bottom: 0, left: 0 },
                    tablet: { top: 0, right: 0, bottom: 0, left: 0 },
                    mobile: { top: 0, right: 0, bottom: 0, left: 0 },
                    unit: 'px', // Default unit
                };

                // Clone the current object to ensure immutability
                const updatedValue = JSON.parse(JSON.stringify(currentValue));

                // Update the unit value
                updatedValue.unit = selectedUnit;

                // Set the updated value back to the setting
                setting.set(updatedValue);
            });
        });
        });

    
    });
  
  

    
  



















  });
})(jQuery);
