try{
    $ = jQuery;
} catch(err) {}
$(document).ready(function(){
    // Initially hide the data content
    $('.kirb-pro-detail-hide').hide();

    $('.prod-detail-button').on('click', function(){
        // Toggle the visibility of the content
        $('.kirb-pro-detail-hide').toggle();

        // Toggle the rotate class on the arrow_icon
        $(this).find('.arrow_icon').toggleClass('rotate');
    });

    $("#kirb_activation_form_overlayfast").click(() => {
        kirb_activation_sidebar_toggle(false);
        closesliderLangfast();
    });

    $("#basic-tab, #setting-tab, #premium-tab").click(function(e){
        $("#settings_form").find("input[name='initial_sub_tab']").val($(this).data('tab'));
    });

    $(".kirb-multi-dropdown-btn").click(function(){
        let dropdown = $(this).next();
        let button = $(this);
        let isOpen = dropdown.css("display") === "block";
        dropdown.css("display", isOpen ? "none" : "block");
        if (isOpen) {
            button.removeClass("rotate");
        } else {
            button.addClass("rotate");
        }
    });
    document.addEventListener("click", function (event) {
        if (!event.target.closest(".kirb-select-page-dropdown")) {
            $(".kirb-multi-dropdown-content").hide();
            $(".kirb-multi-dropdown-btn").removeClass("rotate");
        }
    });

    $("#kirbConsentCheck").change(function() {
        if(this.checked) {
            $(".kirb-consent-card .kirb-consent-accept-btn").prop("disabled", false);
        }else{
            $(".kirb-consent-card .kirb-consent-accept-btn").prop("disabled", true);
        }
    });


    const owl_inner_slider_section = $('.inner-slider-section');

    owl_inner_slider_section.owlCarousel({
        margin: 15,
        loop: true,
        dots: false,
        autoplay: true,
        autoplayHoverPause: true,
        drag: false,
        touchDrag: false,
        mouseDrag: false,
        nav: false,
        slideTransition: 'linear',
        autoplayTimeout: 3000,
        autoplaySpeed: 3000,
        items: 1,
        responsive: {
            400: { items: 2 },
            768: { items: 2.5 }
        }
    });

    const owl_inner_slider_reverse = $('.inner-slider-section-reverse');
    
    owl_inner_slider_reverse.owlCarousel({
        margin: 15,
        loop: true,
        dots: false,
        rtl: true,
        autoplay: true,
        autoplayHoverPause: true,
        drag: false,
        touchDrag: false,
        mouseDrag: false,
        nav: false,
        slideTransition: 'linear',
        autoplayTimeout: 3000,
        autoplaySpeed: 3000,
        items: 1,
        responsive: {
            400: { items: 2 },
            768: { items: 2.5 },
        }
    });

});
function openSliderLang() {
  document.getElementById("mySidenav").style.width = "50%";
  document.getElementById('kirb_activation_form_overlay').classList.add('visible');
  $("body").addClass("no-scroll");
}

function closeSliderLang() {
  document.getElementById("mySidenav").style.width = "0";
  document.getElementById('kirb_activation_form_overlay').classList.remove('visible');
  $("body").removeClass("no-scroll");
}

function openAdminSliderInfoPreview(slider) {
    document.getElementById(`adminSliderInfoPreview-${slider}`).style.width = "30%";
    document.getElementById('kirb_activation_form_overlay_preview').classList.add('visible');
  }
  
function closeAdminSliderInfoPreview(slider) {
    document.getElementById(`adminSliderInfoPreview-${slider}`).style.width = "0";
    document.getElementById('kirb_activation_form_overlay_preview').classList.remove('visible');
}


// if (typeof window !== 'undefined') {
//     window.onscroll = function () {
//         const sidebar = document.querySelector('.sticky-save');
//         const distanceFromTop = window.scrollY;
//         if (sidebar) {
//             if (distanceFromTop >= 100) {
//                 sidebar.style.position = 'fixed';
//                 sidebar.style.top = '30px';
//             } else {
//                 sidebar.style.position = 'initial';
//                 sidebar.style.top = '0';
//             }
//         }
//     };
// }

function toggle_instructions_popup() {
    const managePopup = document.querySelector('.manage-popup-main');
    const body = document.body;
    const overlay = document.querySelector('.body-overlay-bg');

    // Toggle visibility of the popup and overlay
    if (managePopup.style.display === 'block') {
        managePopup.style.display = 'none';
        overlay.style.display = 'none';
        body.classList.remove('body-no-scroll'); // Enable body scroll
    } else {
        managePopup.style.display = 'block';
        overlay.style.display = 'block';
        body.classList.add('body-no-scroll'); // Disable body scroll
    }
}

$(document).ready(() => {
    $(".products-per-page span").click(function () {
        $(".products-per-page span").removeClass("active");
        $(this).addClass("active");
        $("input[name='products_per_page']").val($(this).data("val"));
    });

    $(".settings_action_btn").click(function (e) {
        e.preventDefault();
        $("#settings_action").val($(this).data("val"));
        $("#settings_form").submit();
    });

    $(".help_action_btn").click(function (e) {
        e.preventDefault();
        $("#help_action").val($(this).data("val"));
        if($("#kirb_contact_help_form").find("textarea[name='message']").val() != "") {
            $("#kirb_contact_help_form").submit();
        }
    });

    $("#kirb_contact_help_form").find("textarea[name='message']").on("input", function() {
        if($(this).val() != "") {
            $(".help_action_btn").prop("disabled", false);
        }else{
            $(".help_action_btn").prop("disabled", true);
        }
    });

    $(".kirb-help-support-tab").click(function () {
        let data_target_id = $(this).find("button").attr("data-target-id");
        $(`button#${data_target_id}`).click();
    });

    $(".kirb_help_tab").click(function () {
        let data_id = $(this).attr("id") + "-parent";
        $(".kirb-help-support-tab button").removeClass("active");
        $(`.kirb-help-support-tab button#${data_id}`).addClass("active");
    });

    $(".kirb-myplan-price-div .inner-price-section").click(function () {
        $(".kirb-myplan-price-div .inner-price-section").removeClass("active");
        $(this).addClass("active");
    });

    $('.accordion').each(function () {
        $(this).on('click', function () {
            $(this).toggleClass('active');
            var panel = $(this).next();
            panel.slideToggle(0, function(){
                if(panel.is(":visible")) {
                    $(this).prev().find('.sign').text('-');
                } else {
                    $(this).prev().find('.sign').text('+');
                }
            });
        });
    });

    $(".kirb-language-hyperlink").click(()=>{
        $("#lang_region-tab").click();
    });

    $(".kirb-addon-toggle-switch").click(function(){
        let state = $(this).attr("data-state");
        let target = $(this).attr("data-target");
        if(target) {
            $(`#${target}`).toggle(state === 'checked');
        }
    });

    $(".kirb_multi_select_chkbox").click(function(){
        let name = $(this).attr("name");
        let target = $(this).attr("data-target");
        if(target) {
            let checkedNames = $(`input[name='${name}']:checked`).map(function() {
                return this.value;
            }).get();
            $(`#${target}`).toggle(checkedNames.length > 0);
        }
    });

     $('#default_sort_select').on('change', function () {
        const selectedTitle = $(this).find('option:selected').text();
        $('input[type="hidden"][name="addon_default_sort_title"]').val(selectedTitle);
    });

    // Handle image slider on admin panel
    $(".kirb-nav-arrow").click(function() {
        let current_target = $(this).attr("data-target");
        let action = $(this).attr("data-action");
        let target_elem = $(`.kirb_img_slides[data-id="${current_target}"]`);
        let slides_count = $(target_elem).find("img").length; 
        let current_idx = $(target_elem).data("activeIndex");
        if(action == 'prev') {
            current_idx = (current_idx - 1 + slides_count) % slides_count;
        }else if(action == 'next') {
            current_idx = (current_idx + 1) % slides_count;
        }
        $(target_elem).data("activeIndex", current_idx);
        $(target_elem).find("img").hide();
        $(target_elem).find("img").eq(current_idx).show();
    });

    if(KIRB_BOOLS.IS_PLUGIN_INITIAL_SETUP == 'false') {
        toggle_instructions_popup();
    }

    $(".manage-heading").click(function(){
        toggle_instructions_popup();
    });

    // Close the popup and overlay when clicking on the overlay
    document.querySelector('.manage-popup-main .close-popup').addEventListener('click', function() {
        const managePopup = document.querySelector('.manage-popup-main');
        const body = document.body;
        document.querySelector(".body-overlay-bg").style.display = 'none';
        managePopup.style.display = 'none';
        body.classList.remove('body-no-scroll'); // Enable body scroll
    });

    $('.kirb_img_slides img').click(function () {
        let src = $(this).attr('src');
        let current_image_tab = $(this).data("target");
        if(current_image_tab === "setting-tab-image"){
            $('#kirb-basic-images-preview').html(`<img class="kirb-image-preview" src="${src}"/>`);
        } else if(current_image_tab === "more-tab-image"){
            $('#kirb-more-images-preview').html(`<img class="kirb-image-preview" src="${src}"/>`);
        } else if(current_image_tab === "premium-tab-image"){
            $('#kirb-premium-images-preview').html(`<img class="kirb-image-preview" src="${src}"/>`);
        } else if(current_image_tab === "language-tab-image"){
            $('#kirb-language-images-preview').html(`<img class="kirb-image-preview" src="${src}"/>`);
        }
    });

    $(".kirb_catg_switch").click(function(){
        let catg = $(this).attr("name");
        catg = catg.toLowerCase().replace(/ /g, "");
        $(`#kirb-catg-${catg}`).toggle();
    });

    $(".kirb_contact_sales_btn").click(function(e){
        e.preventDefault();
        kirb_contact_sales();
    });

    if($("#kirb_contact_help_form").css('display') == 'none') {
        setTimeout(() => {
            $("#kirb_contact_help_form").show();
            $(".kirb-help-form-submit-msg").hide();
        }, 6000);
    }


    let alert_timeout = null;
    $(".kirb-addon-toggle-switch, .more-setting-input-section input").click(()=>{
        clearTimeout(alert_timeout);
        $(".alert-section").find(".kirb-toast-msg").html('Available in the pro version, <span class="kirb-a-button" onclick="kirb_contact_sales();">Upgrade Now</span>');
        $(".alert-section").fadeIn();
        alert_timeout = setTimeout(() => {
            $(".alert-section").fadeOut();
        }, 6000);
    });


let checkInterval; 
let statusDiv = $('#kirb_import_status');
let loader = $('#kirb_import_loader');
let successIcon = $('#kirb_import_success_icon');
let errorIcon = $('#kirb_import_error_icon');
let importMsg = $('.kirb_import_msg');

$('.kirb_import_products').click(function () {
    let importType = $(this).data('importtype');
  importMsg.hide();
  loader.show();
  successIcon.hide();
  errorIcon.hide();
  statusDiv.removeClass().text('Starting import...').removeClass('d-none');
    $('.kirb_import_products').addClass('disable-button');


  // check for atrributes and terms
    $.post(ajaxurl, { action: 'kirb_check_atrribute'})
      .done(function (response) {
        if (response.success) {
            // Kick off the first batch
            kirb_import_cron();
        } else {
            loader.hide();
          errorIcon.show();
          successIcon.hide();
          statusDiv.text(response.data);
        }
      })
      .fail(function (jqXHR, textStatus, errorThrown) {
          loader.hide();
          errorIcon.show();
          successIcon.hide();
        statusDiv.text('AJAX Error: ' + textStatus + ' — ' + errorThrown);
      });

        function kirb_import_cron(){
               $.post(ajaxurl, { action: 'kirb_trigger_cron_import',  importType: importType }, function (response) {
                if (response.success) {
                     statusDiv.text(response.data.message);
                     checkInterval = setInterval(kirb_checkImportStatus, 15000); //check every 15sec
                } else {
                    statusDiv.text(response.data.message);
                }
            });
        }

});

if(KIRB_importCheck['Import_finish']=="false"){
    clearInterval(checkInterval); 
    checkInterval = setInterval(kirb_checkImportStatus, 15000); 
}

function kirb_checkImportStatus() {
    $.post(ajaxurl, { action: 'kirb_get_import_status' }, function (response) {
      if (response.success) {
        if (response.data.done =='true') {
            successIcon.show();
            loader.hide();
            importMsg.hide();
            statusDiv.text('Demo products imported successfully!');
            clearInterval(checkInterval); // stop polling once complete
            $('.kirb_import_products').removeClass('disable-button');
        }else{
            loader.show();
            importMsg.hide();
            statusDiv.removeClass('d-none').text('Importing');
            $('.kirb_import_products').addClass('disable-button');
        }
      } else {
        errorIcon.show();
        loader.hide();
        statusDiv.text('⚠️ Failed to fetch import status.');
        $('.kirb_import_products').removeClass('disable-button');
      }
    });
}

   
    $('#kirb_create_engagement_ring_cat_btn').on('click', function(e) {
        e.preventDefault();

        var categorySelect = $('#ring_setting_catg'); // Select field
        var loader = $('#kirb_cat_loader'); // Loader element

        loader.show();

        $.post(ajaxurl, {
            action: 'kirb_create_engagement_rings_category',
        }, function(response) {
            loader.hide(); // Hide loader after response
            let categorySlug = response.data.slug;
            let categoryName = response.data.name; // Hardcoded since we're creating it

            // Check if the category already exists in the select field
            if (categorySelect.find('option[value="' + categorySlug + '"]').length === 0) {
                // Append the new option
                categorySelect.append(new Option(categoryName, categorySlug));
            }

            // Set the new category as selected
            categorySelect.val(categorySlug).trigger('change');

        }).fail(function(jqXHR, textStatus) {
            loader.hide(); // Hide loader after response
            alert('AJAX Error: ' + textStatus);
        });
    });

    setTimeout(() => {
        $(".alert-section").fadeOut();
    }, 5000);
});

function kirb_contact_sales() {
    const customClickEvent = new Event('click', {
        bubbles: true, // Whether the event bubbles up through the DOM or not
        cancelable: true // Whether the event can be canceled
    });
    document.getElementById("support-tab-parent").dispatchEvent(customClickEvent);
}

function kirb_manageImportButton() {
    let importButton = $('#kirb_import_products');
    let ringSettingCatg = $('#ring_setting_catg').val();

    if (ringSettingCatg) {
        importButton.removeClass('disabled');
    } else {
        importButton.addClass('disabled');
    }
}

const kirb_activation_sidebar_toggle = (toggle) => {
    if (toggle) {
      $("#rightSidebar").addClass("open");
      $("#kirb_activation_form_overlay").addClass("visible");
      $("body").addClass("no-scroll");
    } else {
      $("#rightSidebar").removeClass("open");
      $("#kirb_activation_form_overlay").removeClass("visible");
      $("body").removeClass("no-scroll");
    }
};

function kirbOpenImageSidebar(sidebar) {
    document.getElementById(`kirb-${sidebar}-images`).style.width = "50%";
    document.getElementById(`kirb-${sidebar}-preview-image`).classList.add('visible');
    document.body.classList.add("no-scroll");
}

function kirbcloseImageSidebar(sidebar) {
    document.getElementById(`kirb-${sidebar}-images`).style.width = "0";
    document.getElementById(`kirb-${sidebar}-preview-image`).classList.remove('visible');
    document.body.classList.remove("no-scroll");
}



$(".kirb-preview-image").click(function() {
    let sidebar = $(this).data('sidebar'); 
    kirb_activation_sidebar_toggle(false);
    kirbcloseImageSidebar(sidebar); 
});

////////// DO NOT DELETE OR MODIFY THIS CODE BLOCK ////////////
$(document).ready(function(){
    // Brevo Conversations {literal}
    (function(d, w, c) { w.BrevoConversationsID = '6618c1a6bdae7c0f03217324'; w[c] = w[c] || function() { (w[c].q = w[c].q || []).push(arguments); }; var s = d.createElement('script'); s.async = true; s.src = 'https://conversations-widget.brevo.com/brevo-conversations.js'; if (d.head) d.head.appendChild(s); })(document, window, 'BrevoConversations');
    // /Brevo Conversations {/literal}
});
////////// DO NOT DELETE OR MODIFY THIS CODE BLOCK ////////////