
(function(){
  function initOne(root){
    if(!root) return;
    var el = root.querySelector('[data-nikan-swiper]');
    if(!el || el.__nikanInited) return;
    if(typeof Swiper === 'undefined') return;

    var cfg = {};
    try{ cfg = JSON.parse(root.getAttribute('data-nikan-mobile-slider') || '{}'); }catch(e){ cfg = {}; }

    el.__nikanInited = true;

    var options = {
      slidesPerView: cfg.slidesPerView || 1,
      spaceBetween: cfg.spaceBetween || 0,
      loop: !!cfg.loop,
      rewind: !!cfg.rewind,
      watchOverflow: true,
      // Swiper handles RTL by reading dir=rtl from DOM; do not force invalid options.
      pagination: cfg.pagination ? { el: root.querySelector('.swiper-pagination'), clickable: true } : undefined,
      navigation: cfg.navigation ? { nextEl: root.querySelector('.swiper-button-next'), prevEl: root.querySelector('.swiper-button-prev') } : undefined,
      autoplay: cfg.autoplay ? cfg.autoplay : false,
    };

    new Swiper(el, options);
  }

  function scan(){
    document.querySelectorAll('.nikan-ms-root').forEach(initOne);
  }

  // Normal pages
  document.addEventListener('DOMContentLoaded', scan);
  window.addEventListener('load', scan);

  // Elementor editor/preview
  if(window.elementorFrontend && window.elementorFrontend.hooks){
    window.elementorFrontend.hooks.addAction('frontend/element_ready/nikan_mobile_slider_advanced.default', function($scope){
      try{
        var root = $scope[0] || ($scope.get && $scope.get(0));
        if(root) initOne(root);
      }catch(e){}
    });
  } else {
    // fallback retry
    var tries=0, t=setInterval(function(){
      tries++;
      scan();
      if(tries>40) clearInterval(t);
    }, 250);
  }
})();
