jQuery(document).ready(function ($) {
  $(".fancy-slider").each(function () {
    var $wrapper = $(this);
    var $main = $wrapper.find(".main-carousel");
    var $thumbs = $wrapper.find(".thumb-carousel");

    if (!$main.length || !$thumbs.length) return;

    /* --- CSS --- */
    if (!$("#fancy-slider-style").length) {
      $("head").append(`
        <style id="fancy-slider-style">
          .fancy-slider .main-carousel {
            position: relative;
            overflow: hidden;
            display: flex;
          }

          .fancy-slider .main-carousel .owl-stage-outer,
          .fancy-slider .main-carousel .owl-stage {
            width: 100% !important;
            display: flex !important;
            transform: none !important;
          }

          .fancy-slider .main-carousel .owl-item {
            flex-shrink: 0;
            width: 0 !important;
            overflow: hidden;
            transition: width 1.7s cubic-bezier(0.77, 0, 0.18, 1);
          }

          .fancy-slider .main-carousel .owl-item.active-slide {
            width: 100% !important;
          }

          .fancy-slider .thumb-carousel .owl-item {
            cursor: pointer;
            filter: brightness(0.6);
            transition: filter 0.3s ease;
          }

          .fancy-slider .thumb-carousel .owl-item.current {
            filter: brightness(1);
          }
        </style>
      `);
    }

    /* --- Main carousel --- */
    $main.addClass("owl-carousel").owlCarousel({
      items: 1,
      loop: true,          // ← looping enabled
      nav: false,
      dots: false,
      smartSpeed: 700,
      autoplay: true,
      // autoplayTimeout: 2800,
      autoplayHoverPause: true,
      animateOut: false,
      animateIn: false,
    });

    /* --- Thumb carousel --- */
    $thumbs.addClass("owl-carousel").owlCarousel({
      items: 3,
      margin: 6,
      nav: false,
      dots: false,
      loop: false,
      smartSpeed: 500,
    });

    var totalSlides = $main.find(".owl-item:not(.cloned)").length;

    /* --- Init first slide --- */
    $main.find(".owl-item:not(.cloned)").eq(0).addClass("active-slide");
    $thumbs.find(".owl-item").eq(0).addClass("current");

    /* --- Sync on change --- */
    $main.on("changed.owl.carousel", function (e) {
      // Owl adds cloned items when loop:true — normalize the index
      var idx = e.item.index - e.relatedTarget._clones.length / 2;
      idx = ((idx % totalSlides) + totalSlides) % totalSlides;

      $main.find(".owl-item").removeClass("active-slide");
      $main.find(".owl-item:not(.cloned)").eq(idx).addClass("active-slide");

      $thumbs.find(".owl-item").removeClass("current").eq(idx).addClass("current");
      $thumbs.trigger("to.owl.carousel", [idx, 300, true]);
    });

    /* --- Thumb click --- */
    $thumbs.on("click", ".owl-item", function () {
      var idx = $(this).index();

      // ⛔ وقف autoplay مؤقتًا
      $main.trigger("stop.owl.autoplay");

      // 🎯 روح للسلايد
      $main.trigger("to.owl.carousel", [idx, 300, true]);

      // ✅ تحديث الحالة
      $thumbs.find(".owl-item").removeClass("current");
      $(this).addClass("current");

      // ▶️ رجّع autoplay بعد شوية
      setTimeout(function () {
        $main.trigger("play.owl.autoplay");
      }, 4000); // تقدر تزود/تقلل الوقت
    });
  });
});

document.addEventListener("DOMContentLoaded", function () {
  new Swiper(".collection_swiper", {
    loop: true,
    speed: 600,
    centeredSlides: true,
    grabCursor: true,
    effect: "coverflow",
        autoplay: {
      delay: 3000, // الوقت بين كل سلايد
      disableOnInteraction: false, // يفضل شغال حتى بعد السحب
      pauseOnMouseEnter: true,

    },
    coverflowEffect: {
      rotate: 0,
      stretch: 0,
      depth: 120,
      modifier: 1.5,
      slideShadows: false,
    },

    pagination: {
      el: ".swiper-pagination",
      clickable: true,
    },

    breakpoints: {
      /* 📱 Mobile */
      320: {
        slidesPerView: 1.4,
        spaceBetween: 5,
        coverflowEffect: {
          rotate: -20,
          depth: 90,
          modifier: 1.1,
        },
      },

      /* 📲 Tablet */
      768: {
        slidesPerView: 1.7,
        spaceBetween: 20,
        coverflowEffect: {
          rotate: -15,
          depth: 100,
          modifier: 1.2,
        },
      },

      /* 💻 Laptop */
      1024: {
        slidesPerView: 2,
        spaceBetween: 30,
        coverflowEffect: {
          rotate: -15,
          depth: 120,
          modifier: 1.4,
        },
      },

      /* 🖥 Desktop */
      1440: {
        slidesPerView: 1.7,
        spaceBetween: 5,
        coverflowEffect: {
          rotate: -10,
          depth: 90,
          modifier: 1.6,
        },
      },
    },
  });
});

document.addEventListener("DOMContentLoaded", function () {
  new Swiper(".my_features", {
    loop: true,
    speed: 600,
    centeredSlides: true,
    grabCursor: true,
    effect: "slide",
    pagination: {
      el: ".swiper-pagination",
      clickable: true,
    },

    breakpoints: {
      /* 📱 Mobile */
      320: {
        slidesPerView: 1,
        spaceBetween: 10,
      },

      /* 📲 Tablet */
      768: {
        slidesPerView: 1,
        spaceBetween: 20,
      },

      /* 💻 Laptop */
      1024: {
        slidesPerView: 1,
        spaceBetween: 30,
      },

      /* 🖥 Desktop */
      1440: {
        slidesPerView: 1,
        spaceBetween: 40,
      },
    },
  });
  new Swiper(".features_product", {
    loop: true,
    effect: "fade",
    fadeEffect: {
      crossFade: true,
    },
    autoplay: {
      delay: 3000,
      disableOnInteraction: false,
      pauseOnMouseEnter: true,
    },
    navigation: {
      nextEl: ".features_product .swiper-button-next",
      prevEl: ".features_product .swiper-button-prev",
    },
    pagination: {
      el: ".swiper-pagination",
    },
    scrollbar: {
      el: ".swiper-scrollbar",
    },
  });
  new Swiper(".features_product.features_product_3d", {
    loop: true,
    effect: "fade",
    fadeEffect: {
      crossFade: true,
    },
    autoplay: {
      delay: 3000,
      disableOnInteraction: false,
      pauseOnMouseEnter: true,
    },
    navigation: {
      nextEl: ".features_product.features_product_3d .swiper-button-next",
      prevEl: ".features_product.features_product_3d .swiper-button-prev",
    }
  });
});
document.querySelector('.back-to-top').addEventListener('click', function (e) {
  e.preventDefault();

  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
});

document.querySelectorAll('.wc-block-components-product-button__button').forEach(btn => {
  const span = btn.querySelector('span');
  const observer = new MutationObserver(() => {
  });
  observer.observe(span, { attributes: true, attributeFilter: ['class'] });
});
document.addEventListener('DOMContentLoaded', () => {

  document.querySelectorAll('.wc-block-components-product-button__button').forEach(btn => {

    btn.addEventListener('click', () => {
      btn.dataset.wcState = 'loading';

      const span = btn.querySelector('span');
      const textAtClick = span.textContent.trim(); // snapshot before change

      const observer = new MutationObserver(() => {
        const currentText = span.textContent.trim();
        const textChanged = currentText !== textAtClick;

        if (btn.dataset.wcState === 'loading' && textChanged) {
          btn.dataset.wcState = 'success';

          setTimeout(() => {
            btn.dataset.wcState = '';
            observer.disconnect();
          }, 2000);
        }
      });

      observer.observe(span, {
        attributes: true,
        characterData: true,
        childList: true,  // catches wp text binding updates
        subtree: true,
      });
    });
  });
}); window.addEventListener("load", function () {

  AOS.init({
    duration: 1000,
    once: true
  });

  const observer = new MutationObserver(function () {
    AOS.refreshHard();
  });

  observer.observe(document.body, {
    childList: true,
    subtree: true
  });

});

// header
document.addEventListener('DOMContentLoaded', function () {

  const megaMenu = document.querySelector('.baty-mega-menu');
  const header = document.querySelector('.main-header');

  if (!megaMenu || !header) return;

  let closeTimer;

  function positionMenu() {
    const rect = header.getBoundingClientRect();
    megaMenu.style.width = rect.width + 'px';
    megaMenu.style.left = rect.left + 'px';
    megaMenu.style.top = rect.bottom + 'px';
  }

  function openMenu(triggerLink) {
    clearTimeout(closeTimer);
    positionMenu();
    megaMenu.style.display = 'block';
    megaMenu.style.visibility = 'visible';
    requestAnimationFrame(() => {
      megaMenu.style.opacity = '1';
      megaMenu.style.transform = 'translateY(0)';
    });
    megaMenu.classList.add('is-open');
    if (triggerLink) triggerLink.setAttribute('aria-expanded', 'true');
  }

  function closeMenu() {
    megaMenu.style.opacity = '0';
    megaMenu.style.transform = 'translateY(-8px)';

    closeTimer = setTimeout(() => {
      megaMenu.style.display = 'none';
      megaMenu.classList.remove('is-open');
    }, 250);

    document.querySelectorAll('.rooms-special a, a.rooms-special').forEach(link => {
      link.setAttribute('aria-expanded', 'false');
    });
  }

  /* ── Click Toggle ── */
  document.addEventListener('click', function(e) {
    const trigger = e.target.closest('.rooms-special');
    if (trigger) {
      e.preventDefault();
      e.stopPropagation();
      const link = trigger.tagName === 'A' ? trigger : (trigger.querySelector('a') || trigger);
      const isOpen = megaMenu.classList.contains('is-open');
      if (isOpen) {
        closeMenu();
      } else {
        openMenu(link);
      }
      return;
    }

    if (!megaMenu.contains(e.target)) {
      if (megaMenu.classList.contains('is-open')) {
        closeMenu();
      }
    }
  });

  /* ── Escape key ── */
  document.addEventListener('keydown', e => {
    if (e.key === 'Escape') closeMenu();
  });

  /* ── Reposition on resize ── */
  window.addEventListener('resize', () => {
    if (megaMenu.classList.contains('is-open')) positionMenu();
  });

  /* ── Close on scroll ── */
  window.addEventListener('scroll', () => {
    if (megaMenu.classList.contains('is-open')) {
      closeMenu();
    }
  }, { passive: true });

  /* ── Initial state ── */
  megaMenu.style.display = 'none';
  megaMenu.style.opacity = '0';
  megaMenu.style.transform = 'translateY(-8px)';
  megaMenu.style.transition = 'opacity 0.25s ease, transform 0.25s ease';

});


document.addEventListener('DOMContentLoaded', function () {

  const cards = document.querySelectorAll('.about-slider .wp-block-column');
  const panoramas = document.querySelectorAll('.panorama-item');

  cards.forEach((card, index) => {

    card.addEventListener('click', function () {

      panoramas.forEach((item) => {
        item.classList.remove('active');
      });

      if (panoramas[index]) {
        panoramas[index].classList.add('active');
      }

    });

  });

});

// ============================================================
// Mobile Navigation – Accordion Submenu
//
// When the mobile panel is open and the user taps a link that
// has a submenu (<li class="has-child">):
//   1. Prevent the default navigation (don't follow the href)
//   2. Programmatically click the sibling toggle <button> so
//      WP's Interactivity API updates aria-expanded, which our
//      CSS then uses to show/hide the submenu.
//
// Only the LINK click is intercepted — the toggle button itself
// is left to WP's own handler.
// ============================================================
// document.addEventListener('click', function (e) {

//   // Target: the <a> link inside a has-child item
//   const link = e.target.closest('.has-child > .wp-block-navigation-item__content');
//   if (!link) return;

//   // Only act when the mobile overlay is open
//   const panel = link.closest('.wp-block-navigation__responsive-container.is-menu-open');
//   if (!panel) return;

//   // Find the parent <li class="has-child">
//   const parentLi = link.closest('.has-child');
//   if (!parentLi) return;

//   // Find WP's native toggle button (sibling of the link)
//   const toggleBtn = parentLi.querySelector(':scope > .wp-block-navigation-submenu__toggle');
//   if (!toggleBtn) return;

//   // Prevent navigating to the link's href
//   e.preventDefault();
//   e.stopPropagation();

//   // Let WP handle the aria-expanded toggle via its own click handler
//   toggleBtn.click();

// }, true); 

// useCapture: true ensures we intercept before WP's listeners

// ============================================================
// Desktop Navigation – Submenu Arrow Toggle
//
// When the user clicks the toggle button (chevron/arrow) next
// to a parent link in the DESKTOP nav (.main-navigation-header):
//   1. Toggle aria-expanded on the button — CSS uses this to
//      show/hide the submenu and rotate the arrow 180°
//   2. Close any other open desktop submenus (accordion style)
// ============================================================
// document.addEventListener('DOMContentLoaded', function () {

//   function closeAllDesktopSubmenus(except) {
//     document.querySelectorAll(
//       '.main-navigation-header .has-child > .wp-block-navigation-submenu__toggle[aria-expanded="true"]'
//     ).forEach(function (btn) {
//       if (btn !== except) {
//         btn.setAttribute('aria-expanded', 'false');
//       }
//     });
//   }

//   document.addEventListener('click', function (e) {

//     // ── Desktop toggle arrow click ──────────────────────────────
//     const desktopToggle = e.target.closest(
//       '.main-navigation-header .has-child > .wp-block-navigation-submenu__toggle'
//     );
//     if (desktopToggle) {
//       // Skip if we are inside the mobile overlay
//       const mobilePanel = desktopToggle.closest(
//         '.wp-block-navigation__responsive-container.is-menu-open'
//       );
//       if (mobilePanel) return;

//       e.preventDefault();
//       e.stopPropagation();

//       const isOpen = desktopToggle.getAttribute('aria-expanded') === 'true';

//       // Close all others first (accordion behaviour)
//       closeAllDesktopSubmenus(desktopToggle);

//       // Toggle this one
//       desktopToggle.setAttribute('aria-expanded', isOpen ? 'false' : 'true');
//       return;
//     }

//     // ── Click outside nav → close all desktop submenus ─────────
//     const insideNav = e.target.closest('.main-navigation-header');
//     if (!insideNav) {
//       closeAllDesktopSubmenus(null);
//     }

//   });

//   // Escape key closes everything
//   document.addEventListener('keydown', function (e) {
//     if (e.key === 'Escape') closeAllDesktopSubmenus(null);
//   });

// });
