// source --> https://costaglam.com/wp-content/themes/prime-beauty-salon-pro/assets/js/custom.js?ver=7.0 
/**
 * Exoplanet Custom JS
 *
 * @package Exoplanet
 *
 * Distributed under the MIT license - http://opensource.org/licenses/MIT
 */


/* Mobile responsive Menu*/

jQuery(function($) {



  $('.search-icon > i').click(function() {
    $(".serach_outer").slideDown(700);
  });

  $('.closepop i').click(function() {
    $(".serach_outer").slideUp(700);
  });

  /*-------- BLOG --------*/
  $(".blog-contents").hover(function() {
    var st = $(this).attr('style-attr');
    $(this).attr('style', st);
  }, function() {
    $(this).removeAttr('style');
  });

  // Accordian
  $(".collapse").on('show.bs.collapse', function() {
    $(this).parent().find(".fa-plus").removeClass("fa-plus").addClass("fa-minus");

  }).on('hide.bs.collapse', function() {
    $(this).parent().find(".fa-minus").removeClass("fa-minus").addClass("fa-plus");

  });

  $(window).scroll(function() {
    var sticky = $('.sticky-header'),
      scroll = $(window).scrollTop();

    if (scroll >= 100) sticky.addClass('fixed-header');
    else sticky.removeClass('fixed-header');
  });

  // AOS.init();
  AOS.init({
    disable: function() {
      var maxWidth = 800;
      return window.innerWidth < maxWidth;
    }
  });

});

// --------preloader----------

var interval = null;

function show_loading_box() {
  jQuery(".spinner-loading-box").css("display", "none");
  clearInterval(interval);
}
jQuery('document').ready(function() {

  interval = setInterval(show_loading_box, 1000);

});
// ------Sidebar---------
// jQuery(function($) {
//   // document.getElementById("open_nav").addEventListener("click", open);
//
//   function open() {
//     // document.getElementById("sidebar1").style.width = "250px";
//     // document.getElementById("sidebar1").style.display = "block";
//   }
//   // document.getElementById("close_nav").addEventListener("click", close);
//
//   function close() {
//     // document.getElementById("sidebar1").style.width = "0";
//     // document.getElementById("sidebar1").style.display = "none";
//   }
// });

jQuery('document').ready(function() {


  jQuery('.slider-content-box').owlCarousel({
    loop: true,
    margin: 0,
    nav: true,
    animateIn: 'flipInX',
    navText: ['<i class="fa-solid fa-arrow-left"></i>', '<i class="fa-solid fa-arrow-right"></i>'],
    responsive: {
      0: {
        items: 1
      },
      600: {
        items: 1
      },
      1000: {
        items: 1
      }
    }
  });


  // Team
  var owl = jQuery('#testimonial-o .owl-carousel');
  owl.owlCarousel({
    margin: 45,
    stagePadding: 10,
    nav: true,
    animateOut: 'zoomOut',
    animateIn: 'zoomIn',
    autoplay: false,
    lazyLoad: true,
    autoplayTimeout: 3000,
    loop: true,
    dots: false,
    navText: ['<i class="fa-solid fa-arrow-left"></i>', '<i class="fa-solid fa-arrow-right"></i>'],
    responsive: {
      0: {
        items: 1
      },
      800: {
        items: 1
      },
      1200: {
        items: 1
      },
      1400: {
        items: 1
      }
    },
    autoplayHoverPause: true,
    mouseDrag: true,
  });
  // Our Blog


  // Event Videos




  // Upcoming Events



  var owl = jQuery('.slider-nav.owl-carousel');
  owl.owlCarousel({
    margin: 45,
    stagePadding: 10,
    nav: false,
    autoplay: false,
    lazyLoad: true,
    autoplayTimeout: 3000,
    loop: true,
    dots: false,

    navText: ['<i class="fa fa-arrow-left" aria-hidden="true"></i>', '<i class="fa fa-arrow-right" aria-hidden="true"></i>'],
    responsive: {
      0: {
        items: 1
      },
      767: {
        items: 1
      },
      1200: {
        items: 1
      }
    },
    autoplayHoverPause: true,
    mouseDrag: true,
  });









  // jQuery('.slider-for').owlCarousel({
  //   loop: true,
  //   margin: 10,
  //   items: 1,
  //   dots: false,
  //   URLhashListener: true
  // })
  // jQuery('.slider-nav').owlCarousel({
  //   loop: true,
  //   margin: 10,
  //   nav: true,
  //   items: 3,
  //   dots: false,
  //   center: true,
  //   URLhashListener: true
  // })






  var owl = jQuery('.event-wrapper.owl-carousel');
  owl.owlCarousel({
    margin: 45,
    stagePadding: 10,
    nav: true,
    autoplay: false,
    lazyLoad: true,
    autoplayTimeout: 3000,
    loop: true,
    dots: false,
    navText: ['<i class="fa fa-caret-left" aria-hidden="true"></i>', '<i class="fa fa-caret-right" aria-hidden="true"></i>'],
    responsive: {
      0: {
        items: 1
      },
      868: {
        items: 2
      },
      1200: {
        items: 3
      }
    },
    autoplayHoverPause: true,
    mouseDrag: true,
  });




  var owl = jQuery('#blog-o .owl-carousel');
  owl.owlCarousel({
    responsive: {
      0: {
        items: 1
      },
      767: {
        items: 1
      },
      1200: {
        items: 1
      }
    },
    autoplayHoverPause: true,
    mouseDrag: true,
  });

  // Sticky Header
  jQuery(window).scroll(function() {
    if (jQuery(window).scrollTop() >= 300) {
      jQuery('header').addClass('fixed-header');
      jQuery('header').addClass('visible-title');
    } else {
      jQuery('header').removeClass('fixed-header');
      jQuery('header').removeClass('visible-title');
    }
  });




  jQuery('.slider-btn').click(function() {
    // jQuery('#appointment-form-o').addClass('appointment-form-toggle-block');
    jQuery('#appointment-form-o').css('display', 'block');

  });

  jQuery('#app-form-close').click(function() {
    // console.log('clicked');

    // jQuery('#appointment-form-o').addClass('appointment-form-toggle-none');
    jQuery('#appointment-form-o').css('display', 'none');
  });


  jQuery('.search-btn').click(function() {
    // console.log('clicked');
    jQuery('.search-input').toggleClass('input-toggle');
  });

  jQuery('#open_nav').click(function() {
    // console.log('clicked');
    jQuery('#sidebar1').addClass('ham-toggle');
  });

  jQuery('#close_nav').click(function() {
    jQuery(this).parent('#sidebar1').removeClass('ham-toggle');
  })


  jQuery('label#give-gateway-option-offline').click(function() {
    jQuery('section#form-o #give_purchase_form_wrap').addClass('nadada');
  });

  jQuery('label#give-gateway-option-manual').click(function() {
    jQuery('section#form-o #give_purchase_form_wrap').removeClass('nadada');

  });


  jQuery('span#form-close,.get_tt,.proud_partner_wrapper a,.donate-heart,.donation-i .donation-card-content .btn-price a,.donate-heart').click(function(e) {
    jQuery('#form-o').toggleClass('close-form');
  });

  // jQuery(document).click(function(e) {
  //   var v = e.target.closest('.form-wrapper');
  //   // console.log(v);
  //   if (!v) {
  //     jQuery('#form-o').css('display', 'none');
  //   }
  // });





  jQuery('.nav-item').map(function(i) {
    jQuery(this).click(function(e) {
      e.preventDefault();
      console.log(i);
      var v = i;
      var w = i;
      if (v != 0) {
        jQuery('.tab-pane1').css('display', 'none');
      } else {
        jQuery('.tab-pane1').css('display', 'block');
      }
      jQuery('.tab-pane').map(function(i) {
        if (v == i) {
          jQuery(this).addClass('cl').siblings('.tab-pane').removeClass('cl');
        }
      })
      // if (w != 0) {
      //   jQuery('.nav-item1').css('background', 'red');
      // } else {
      //   jQuery('.nav-item1').css('background', '#000');
      // }
      jQuery('.nav-item').map(function(i) {
        if (w == i) {
          jQuery(this).addClass('cll').parent().siblings().children('.nav-item').removeClass('cll');
        }
      })
    })
  })

});
jQuery(document).ready(function() {
  jQuery('.nav-item1').addClass('cll');



  var logo_source = jQuery('.nav-logo').attr("src");
  console.log(logo_source);
  if (logo_source == '') {
    jQuery('.nav-logo').css('display', 'none');
    jQuery('.nav-text').css('display', 'inline');
  } else {
    jQuery('.nav-logo').css('display', 'block');
    jQuery('.nav-text').css('display', 'none');
  }

  var top_bar_icon_source = jQuery('.tp-br-icon').attr("src");
  if (top_bar_icon_source == '') {
    jQuery('.tp-br-icon').css('display', 'none');
  }

})







jQuery('.side-navigation li').click(function() {
  jQuery('this').toggleClass('active-search');
});

jQuery('.search-main').click(function() {
  // console.log('clic');
  jQuery('.search-form-main').toggleClass('active-search');
});


jQuery('.search').click(function() {
  jQuery('.search, .search-bar').toggleClass('active');
  jQuery('input').focus();
});


// // On Click slider Nav button
jQuery('.owl-prev').click(function() {
  jQuery(this).addClass('background-class').siblings('.owl-next').removeClass('background-class');
  jQuery()
});
jQuery('.owl-next').click(function() {
  jQuery(this).addClass('background-class').siblings('.owl-prev').removeClass('background-class');
  jQuery()
});
// jQuery('.owl-next').click(function() {
//   jQuery(this).css('background', '#EC1D29');
// });





jQuery(window).resize(function() {
  if (jQuery(window).width() < 1040) {
    jQuery('.ham-toggle').addClass('testing')
  }
});


jQuery(document).click(function(e) {
  var v = e.target.closest('.search-main');
  var s = e.target.closest('.fa-search');
  var search = e.target.closest('.top_search');
  var a = e.target.closest('.search-form-main');
  var input = e.target.closest('.search-input');
  if (e.target != v) {
    if (e.target != s) {
      if (e.target != a) {
        if (e.target != input) {
          if (e.target != search) {
            jQuery('.search-form-main').removeClass('active-search');
          }
        }
      }
    }
  }
});

jQuery('.tab-repeater .nav').click(function() {
  jQuery(this).siblings('.tab-content').addClass("visible");
  jQuery(this).closest('.tab-repeater').siblings().find('.tab-content').removeClass('visible');
});
jQuery('.tab-repeater .nav').click(function() {
  jQuery('.tab-repeater .nav').addClass('visibility');
  jQuery(this).closest('.tab-repeater').siblings().find('.nav-pills').removeClass('visibility');
});
jQuery(function() {
  jQuery('.tab-repeater:last-child .nav').addClass('expand');
});
jQuery('.tab-repeater .nav').click(function() {
  jQuery('.tab-repeater .nav').removeClass('expand');
});


// Show the first tab and hide the rest
jQuery('#tabs-nav li:first-child').addClass('active');
jQuery('.tab-content').hide();
jQuery('.tab-content:first').show();

// Click function
jQuery('#tabs-nav li').click(function() {
  jQuery('#tabs-nav li').removeClass('active');
  jQuery(this).addClass('active');
  jQuery('.tab-content').hide();

  var activeTab = jQuery(this).find('a').attr('href');
  jQuery(activeTab).fadeIn();
  return false;
});



// --------------

jQuery('a.accordion-toggle').click(function() {
  jQuery("i", this).toggleClass("fas fa-plus fas fa-minus");
});
new WOW().init();
// -------collection title------
var str = jQuery('.feature-boxx h2').text().split(" ");
jQuery('.feature-boxx h2').empty();
str.forEach(function(a) {
  jQuery('.feature-boxx h2').append('<span>' + a.slice(0, 5) + '</span>' + a.slice(5))
})
// --------scroll to next section-------------
if (jQuery('.scroll-to-next-section').length > 0) {
  jQuery(".scroll-to-next-section button").click(function() {
    jQuery('html, body').animate({
      scrollTop: jQuery(this).closest("section").next().offset().top
    }, "slow");
  });
}


/* Counter */
jQuery(document).ready(function() {
  jQuery('.count').each(function() {
    jQuery(this).prop('Counter', 0).animate({
      Counter: jQuery(this).text()
    }, {
      duration: 30000,
      easing: 'swing',
      step: function(now) {
        jQuery(this).text(Math.ceil(now));
      }
    });
  });

  // Back to top
  jQuery(document).ready(function() {
    jQuery(window).scroll(function() {
      if (jQuery(this).scrollTop() > 0) {
        jQuery('.scrollup').fadeIn();
      } else {
        jQuery('.scrollup').fadeOut();
      }
    });
    jQuery('.scrollup').click(function() {
      jQuery("html, body").animate({
        scrollTop: 0
      }, 500);
      return false;
    });
  });


  // shop page filter
  jQuery('.multivendor-filter [type="radio"]').on('change', function(event) {
    prime_beauty_salon_pro_filters(event);
  });

  function prime_beauty_salon_pro_filters(event, ui) {
    var data_obj = {};

    data_obj['values'] = jQuery('#product-price-slider').slider("values");

    jQuery('.multivendor-filter [type="radio"]:checked').each(function(index, element) {
      if (!Array.isArray(data_obj[jQuery(element).attr('name')])) {
        data_obj[jQuery(element).attr('name')] = new Array();
      }
      data_obj[jQuery(element).attr('name')].push(jQuery(element).val())
    });

    jQuery.post(ti_customscripts_object.ajaxurl, {
        'action': 'get_shop_page_filter',
        'data': data_obj
      },
      function(response) {
        jQuery('.products.columns-3').html(response.html)
      });

    jQuery('.category-filter-checkbox').map(function() {
      jQuery(this).click(function() {
        if (jQuery(this).is(":checked")) {
          jQuery(this).siblings('.name-count').addClass("checked").parent().parent().siblings('li').children().children('.name-count').removeClass('checked');
        }
      })
    })

  }



  // Price Range Slider

  const rangeInput = document.querySelectorAll(".range-input input"),
    priceInput = document.querySelectorAll(".price-input input"),
    range = document.querySelector(".slider .progress");
  let priceGap = 1000;

  priceInput.forEach((input) => {
    input.addEventListener("input", (e) => {
      let minPrice = parseInt(priceInput[0].value),
        maxPrice = parseInt(priceInput[1].value);

      if (maxPrice - minPrice >= priceGap && maxPrice <= rangeInput[1].max) {
        if (e.target.className === "input-min") {
          rangeInput[0].value = minPrice;
          range.style.left = (minPrice / rangeInput[0].max) * 100 + "%";
        } else {
          rangeInput[1].value = maxPrice;
          range.style.right = 100 - (maxPrice / rangeInput[1].max) * 100 + "%";
        }
      }
    });
  });

  rangeInput.forEach((input) => {
    input.addEventListener("input", (e) => {
      let minVal = parseInt(rangeInput[0].value),
        maxVal = parseInt(rangeInput[1].value);

      if (maxVal - minVal < priceGap) {
        if (e.target.className === "range-min") {
          rangeInput[0].value = maxVal - priceGap;
        } else {
          rangeInput[1].value = minVal + priceGap;
        }
      } else {
        priceInput[0].value = minVal;
        priceInput[1].value = maxVal;
        range.style.left = (minVal / rangeInput[0].max) * 100 + "%";
        range.style.right = 100 - (maxVal / rangeInput[1].max) * 100 + "%";
      }
    });
  });









  jQuery('.product-offer-date').map(function(value, index) {
    const elem = jQuery(this);
    let old_date = elem.attr('upcoming-date') * 1000;
    const new_date = new Date(old_date);
    var timer;
    var compareDate = new_date;
    timer = setInterval(function() {
      var now = new Date();
      var difference = compareDate.getTime() - now.getTime();
      if (difference <= 0) {
        // Timer done
        clearInterval(timer);
      } else {
        var seconds = Math.floor(difference / 1000);
        var minutes = Math.floor(seconds / 60);
        var hours = Math.floor(minutes / 60);
        var days = Math.floor(hours / 24);
        hours %= 24;
        minutes %= 60;
        seconds %= 60;
        elem.find(".days").text(days);
        elem.find(".hours").text(hours);
        elem.find(".minutes").text(minutes);
        elem.find(".seconds").text(seconds);
      }
    }, 1000);
  });

});

// ------------ Sticky Navbar -------------------

var stickyon = jQuery('#sticky-onoff').text().trim();
var a1 = stickyon.length;
var navbar = document.getElementById("site-sticky-menu");
window.onscroll = function() {
  if (a1 == 3) {
    if (navbar != null) {
      myScrollNav();
    }
  }
}

if (navbar != null) {
  var sticky = jQuery(navbar).offset().top;
}

function myScrollNav() {
  if (window.pageYOffset > sticky) {
    //alert(window.pageYOffset);
    navbar.classList.add("sticky");
    navbar.classList.add("stickynavbar");
  } else {
    navbar.classList.remove("sticky");
    navbar.classList.remove("stickynavbar");
  }
}


// topbar timer
// var userDate = document.getElementById("timer").innerHTML;
// var deadline = new Date(userDate).getTime();
// // var deadline = new Date("march 5, 2022 15:37:25").getTime();
// var x = setInterval(function() {
//   var now = new Date().getTime();
//   var t = deadline - now;
//   var days = Math.floor(t / (1000 * 60 * 60 * 24));
//   var hours = Math.floor((t % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
//   var minutes = Math.floor((t % (1000 * 60 * 60)) / (1000 * 60));
//   var seconds = Math.floor((t % (1000 * 60)) / 1000);
//   document.getElementById("timer").innerHTML = days + " days " +
//     hours + ":" + minutes + ":" + seconds + " HURRY UP!!!";
//   if (t < 0) {
//     clearInterval(x);
//     document.getElementById("timer").innerHTML = "EXPIRED";
//   }
// }, 1000);



// jQuery('document').ready(function() {
//
//   jQuery('.multiple-items').slick({
//     infinite: true,
//     slidesToShow: 3,
//     slidesToScroll: 1,
//     arrows: true
//   });
//
//
//   jQuery('.multiple-items-1').slick({
//     infinite: true,
//     slidesToShow: 7,
//     slidesToScroll: 1
//   });
//   if (screen.availWidth < 1024) {
//     jQuery('.brands-i').slick({
//       infinite: true,
//       slidesToShow: 5,
//       slidesToScroll: 1,
//       responsive: [{
//           breakpoint: 990,
//           settings: {
//             slidesToShow: 5,
//             slidesToScroll: 2
//           }
//         },
//         {
//           breakpoint: 767,
//           settings: {
//             slidesToShow: 4,
//             slidesToScroll: 1
//           }
//         },
//         {
//           breakpoint: 640,
//           settings: {
//             slidesToShow: 3,
//             slidesToScroll: 1
//           }
//         },
//         {
//           breakpoint: 480,
//           settings: {
//             slidesToShow: 2,
//             slidesToScroll: 1
//           }
//         }
//       ]
//     });
//   }
// })
jQuery("#app-form-close").click(function() {
  console.log('test');
  jQuery('#appointment-form-o').addClass('display')
});
jQuery("#pop-close-1").click(function() {
  jQuery('#newsletter').css('display', 'none')
});



// function hide() {
//   jQuery.Cookies.set('test', '1');
//   jQuery('#newsletter').css('display', 'none');
//   var cookieValue = jQuery.Cookies.get('test');
//   console.log(cookieValue);
// }
// jQuery('#newsletter').css('display', 'none');

function hide() {
  jQuery('#newsletter').css('display', 'none')
}


jQuery(window).scroll(function() {
  var windowWidth = jQuery(window).width();
  if (windowWidth <= 1024) {
    jQuery('.menu-item').map(function() {
      jQuery(this).click(function() {
        jQuery(this).children('ul').slideToggle('drop').parent().siblings().children('ul').slideUp('drop');
      })
    })
  }
});
// source --> https://costaglam.com/wp-content/plugins/translatepress-multilingual/assets/js/trp-frontend-language-switcher.js?ver=3.2.1 
class BaseSwitcher {
    constructor(rootEl) {
        this.root = rootEl;
        this.list = rootEl?.querySelector('.trp-switcher-dropdown-list') || null;
        this.isOpen = false;
        this._pendingFocusOnOpen = false;
        if (!this.root || !this.list) return;

        if (!this.list.id) {
            this.list.id = `trp-list-${Math.random().toString(36).slice(2, 9)}`;
        }

        // Single transitionend handler to drop .is-transitioning and finalize hidden/inert
        this._onTe = (e) => {
            if (e.target !== this.list || e.propertyName !== 'max-height') return;

            this.root.classList.remove('is-transitioning');

            if (!this.isOpen) {
                this.list.hidden = true;
                this.list.setAttribute('inert', '');
            } else if (this._pendingFocusOnOpen) {
                this._pendingFocusOnOpen = false;
                const first = this.list.querySelector(
                    '[role="option"], a, button, [tabindex]:not([tabindex="-1"])'
                );
                first?.focus?.({ preventScroll: true });
            }
        };
        this.list.addEventListener('transitionend', this._onTe);

        this.collapse();
        this.setAutoWidth();
        this.bindKeyboard();
    }

    /**
     * Returns true if the list has a non-zero transition duration (for any property).
     * We use this to decide whether to rely on `transitionend` or fall back to sync behavior.
     */
    _hasAnimatedTransition() {
        if (!this.list) return false;

        const cs = getComputedStyle(this.list);
        const durationsRaw = cs.transitionDuration || '';

        if (!durationsRaw) return false;

        const durations = durationsRaw
            .split(',')
            .map(str => parseFloat(str) || 0);

        return durations.some(d => d > 0);
    }

    collapse() {
        this.list.hidden = true;
        this.list.setAttribute('inert', '');
        this.setExpanded(false);
        this.root.classList.remove('is-transitioning');
    }

    /**
     * If width is set to auto, fix it to the calculated width + 20px
     * We do this in order to avoid width shift on hover
     * */
    setAutoWidth() {
        const bonusWidth = 10;

        const cs = getComputedStyle(this.root);
        const declaredWidth = cs.getPropertyValue('--switcher-width').trim();

        if (declaredWidth === 'auto' && this.root.querySelector('.trp-language-item-name')) { // In case trp-language-item-name is not present, we are in flags only mode - so no auto width sizing is needed
            const initialWidth = this.root.getBoundingClientRect().width;

            this.root.style.setProperty('--switcher-width', (initialWidth + bonusWidth) + 'px');
        }
    }

    setExpanded(open) {
        const trigger = this.root.querySelector('.trp-language-item__current[role="button"]');
        const val = String( !!open );
        trigger?.setAttribute('aria-expanded', val);
        this.root.classList.toggle('is-open', !!open);
    }

    setOpen( open, { source = null } = {} ) {
        if ( !this.root || !this.list || open === this.isOpen ) return;

        const prefersReduced = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
        const hasTransition  = !prefersReduced && this._hasAnimatedTransition();

        this.isOpen = open;

        // No transitions (0s duration) OR reduced motion: do everything synchronously,
        if ( !hasTransition ) {
            if ( open ) {
                this.list.hidden = false;
                this.list.removeAttribute( 'inert' );
                this.setExpanded( true );

                this._pendingFocusOnOpen = ( source?.type === 'keydown' );
                if ( this._pendingFocusOnOpen ) {
                    this._pendingFocusOnOpen = false;
                    const first = this.list.querySelector(
                        '[role="option"], a, button, [tabindex]:not([tabindex="-1"])'
                    );
                    first?.focus?.({ preventScroll: true });
                }
            } else {
                this.setExpanded( false );
                this.list.hidden = true;
                this.list.setAttribute( 'inert', '' );
                this._pendingFocusOnOpen = false;
            }
            return;
        }

        // Animated path: rely on transitionend to remove .is-transitioning
        if ( open ) {
            // Must be visible for CSS transition to run
            this.list.hidden = false;
            this.list.removeAttribute( 'inert' );

            this._pendingFocusOnOpen = ( source?.type === 'keydown' );

            this.root.classList.add( 'is-transitioning' );
            // Next frame so browser registers pre-open (max-height: 0) state
            requestAnimationFrame( () => this.setExpanded( true ) );
        } else {
            this.root.classList.add( 'is-transitioning' );
            this.setExpanded( false );
        }
    }

    bindKeyboard() {
        const trigger = this.root.querySelector('.trp-language-item__current[role="button"]');
        if ( !trigger ) return;

        trigger.addEventListener('keydown', (e) => {
            const inList = !!e.target.closest?.('.trp-switcher-dropdown-list');

            if ( e.key === 'Enter' || e.key === ' ' ) {
                e.preventDefault();
                this.setOpen(!this.isOpen, { source: e });
                return;
            }

            if ( e.key === 'ArrowDown' && !this.isOpen ) {
                e.preventDefault();
                this.setOpen(true, { source: e });
            }

            if ( e.key === 'Escape' ) {
                this.setOpen(false, { source: e });
                trigger.focus?.();
            }
        });
    }
}

class ShortcodeSwitcher extends BaseSwitcher {
    constructor(wrapper) {
        const overlay =
                  wrapper.querySelector('.trp-language-switcher.trp-shortcode-overlay')
                  || [...wrapper.querySelectorAll('.trp-language-switcher')]
                      .find(el => el.classList.contains('trp-shortcode-overlay'));

        // Overlay must be interactable; ensure no accidental hidden/inert from server
        overlay.hidden = false;
        overlay.removeAttribute('hidden');
        overlay.removeAttribute('inert');
        if ('inert' in overlay) overlay.inert = false;

        super(overlay);

        if (!this.root || !this.list) return;

        const control = this.root.querySelector('.trp-language-item__current[role="button"]');
        if (control && this.list && !control.hasAttribute('aria-controls')) {
            control.setAttribute('aria-controls', this.list.id);
        }

        const isClickMode =
                  this.root.classList.contains('trp-open-on-click') ||
                  wrapper.dataset.openMode === 'click' ||
                  wrapper.classList.contains('trp-open-on-click');

        if (isClickMode) {
            // Click anywhere on overlay EXCEPT inside the list
            this.root.addEventListener('click', (e) => {
                const inList = e.target.closest('.trp-switcher-dropdown-list');
                if (!inList) {
                    e.preventDefault();
                    e.stopPropagation();
                    this.setOpen(!this.isOpen, { source: e });
                }
            }, true);

            // Outside click closes
            this.onDocClick = (evt) => {
                if (!wrapper.contains(evt.target)) this.setOpen(false, { source: evt });
            };
            document.addEventListener('click', this.onDocClick, true);

            // Focus leaving wrapper closes
            wrapper.addEventListener('focusout', () => {
                setTimeout(() => {
                    if (!wrapper.contains(document.activeElement)) {
                        this.setOpen(false, { source: 'keyboard' });
                    }
                }, 0);
            });
        } else {
            // Hover mode on overlay
            this.root.addEventListener('mouseenter', (e) => this.setOpen(true,  { source: e }));
            this.root.addEventListener('mouseleave', (e) => this.setOpen(false, { source: e }));
        }
    }
}

class FloaterSwitcher extends BaseSwitcher {
    constructor(el) {
        super(el);

        el.addEventListener('mouseenter', (e) => this.setOpen(true,  { source: e }));
        el.addEventListener('mouseleave', (e) => this.setOpen(false, { source: e }));

        this.onDocClick = (evt) => { if (!el.contains(evt.target)) this.setOpen(false, { source: evt }); };
        document.addEventListener('click', this.onDocClick, true);
    }
}

document.addEventListener('DOMContentLoaded', () => {
    // Front-end or classic admin
    initLanguageSwitchers(document);

    // If no wrapper and we are in Gutenberg, watch for async SSR insert
    if (
        inGutenberg() &&
        !getEditorDoc().querySelector(WRAPPER)
    ) {
        observeWrapperUntilFound();
    }

    if ( !inGutenberg() )
        observeShortcodeSwitcher();
});

/** For shortcode switcher
 *  Mark the shortcodes that were initialized
 * */
const TRP_BOUND = new WeakSet();
const mark = (el) => TRP_BOUND.add(el);
const isMarked = (el) => TRP_BOUND.has(el);

const WRAPPER = '.trp-shortcode-switcher__wrapper';
const OVERLAY = '.trp-language-switcher:not(.trp-opposite-button)';

// Helpers
function inGutenberg() {
    return document.body?.classList?.contains('block-editor-page')
        || !!(window.wp?.data?.select?.('core/block-editor'));
}

// If editor uses an iframe canvas, work inside it
function getEditorDoc() {
    const ifr = document.querySelector('iframe[name="editor-canvas"], .editor-canvas__iframe');

    return (ifr && ifr.contentDocument) ? ifr.contentDocument : document;
}

function initLanguageSwitchers(root = document) {
    const floater = root.querySelector(
        '.trp-language-switcher.trp-ls-dropdown:not(.trp-shortcode-switcher):not(.trp-opposite-language)'
    );

    if (floater)
        new FloaterSwitcher(floater);

    root.querySelectorAll(WRAPPER)
        .forEach(wrapper => {
            const overlay = wrapper.querySelector('.trp-language-switcher:not(.trp-opposite-button)');

            if (overlay && !isMarked(overlay)) {
                mark(overlay);
                new ShortcodeSwitcher(wrapper);
            }
        });
}

/**
 * Observes the document for dynamically inserted shortcode switchers and initializes them automatically when detected.
 */
function observeShortcodeSwitcher() {
    const initWrapper = ( wrapper ) => {
        if ( !wrapper )
            return;

        const overlay = wrapper.querySelector( OVERLAY );

        if ( !overlay || isMarked( overlay ) )
            return;

        mark( overlay );

        new ShortcodeSwitcher( wrapper );
    }

    const mo = new MutationObserver( ( mutations ) => {
        for ( const m of mutations ) {
            for ( const n of m.addedNodes ) {
                if ( n.nodeType !== 1 )
                    continue;

                if ( n.matches?.( WRAPPER ) )
                    initWrapper( n );

                n.querySelectorAll?.( WRAPPER ).forEach( initWrapper );
            }
        }
    });

    mo.observe( document, { childList: true, subtree: true } );
}

/**
 * Observe Gutenberg for the shortcode wrapper being inserted asynchronously.
 *
 * Supports both Blocks API v2 (no editor iframe; wrapper appears in the outer document)
 * and Blocks API v3 (editor content rendered inside an iframe canvas).
 *
 * Strategy:
 *  1) Check the current editor document for `.trp-shortcode-switcher__wrapper` and init immediately.
 *  2) If an editor canvas iframe exists, watch its document (and reattach on iframe load) for the wrapper.
 *  3) If no iframe yet, watch the outer document for either the iframe (v3) or the wrapper itself (v2).
 *
 * Initialization is performed once per context to avoid duplicate bindings.
 */
function observeWrapperUntilFound() {
    // If wrapper already exists in current editor doc, init
    const edDoc = getEditorDoc();
    const existing = edDoc.querySelector(WRAPPER);

    if ( existing ) {
        initLanguageSwitchers( edDoc );
        return;
    }

    // Helper to locate the editor canvas iframe in the OUTER document
    const findCanvasIframe = () => document.querySelector('iframe[name="editor-canvas"], .editor-canvas__iframe');

    // If iframe is already present in the outer doc, start watching inside it
    const iframeNow = findCanvasIframe();
    if ( iframeNow ) {
        watchIframe( iframeNow );
        return;
    }

    // Otherwise, observe the OUTER document until the iframe appears
    const outerMO = new MutationObserver( ( mutations ) => {
        for ( const m of mutations ) {
            for ( const n of m.addedNodes ) {
                if ( n.nodeType !== 1 ) continue;

                const iframe =
                          n.matches?.('iframe[name="editor-canvas"], .editor-canvas__iframe')
                              ? n
                              : n.querySelector?.('iframe[name="editor-canvas"], .editor-canvas__iframe');

                if ( iframe ) {
                    outerMO.disconnect();
                    watchIframe( iframe );
                    return;
                }

                // Also catch shortcode wrapper added directly to the outer document (API v2, no iframe)
                const wrapper =
                          n.matches?.(WRAPPER)
                              ? n
                              : n.querySelector?.(WRAPPER);

                if ( wrapper ) {
                    outerMO.disconnect();
                    initLanguageSwitchers( document );
                    return;
                }

            }
        }
    } );
    outerMO.observe( document, { childList: true, subtree: true } );

    function watchIframe( iframe ) {
        // Try immediately (some builds inject srcdoc synchronously)
        tryAttachInside();

        // Also on load/navigate (Gutenberg may reload the canvas)
        iframe.addEventListener( 'load', tryAttachInside );

        function tryAttachInside() {
            let doc;
            try {
                doc = iframe.contentDocument || iframe.contentWindow?.document;
            } catch (e) {
                console.warn('Cannot access iframe content due to cross-origin restrictions', e);
                return;
            }
            if ( !doc ) return;

            // If wrapper is already there, init once and stop.
            const hit = doc.querySelector(WRAPPER);
            if ( hit ) {
                initLanguageSwitchers( doc );
                return;
            }

            // Observe INSIDE the iframe until wrapper appears
            const innerMO = new MutationObserver( ( muts ) => {
                for ( const mm of muts ) {
                    for ( const nn of mm.addedNodes ) {
                        if ( nn.nodeType !== 1 ) continue;
                        if (
                            nn.matches?.(WRAPPER) ||
                            nn.querySelector?.(WRAPPER)
                        ) {
                            innerMO.disconnect();
                            initLanguageSwitchers( doc );
                            return;
                        }
                    }
                }
                if ( doc.querySelector(WRAPPER) ) {
                    innerMO.disconnect();
                    initLanguageSwitchers( doc );
                }
            } );

            innerMO.observe( doc, { childList: true, subtree: true } );
        }
    }
};