(function () {
  // run init when DOM ready (works whether script is in head or body)
  const whenReady = (fn) => {
    if (document.readyState === "loading")
      document.addEventListener("DOMContentLoaded", fn);
    else fn();
  };

  whenReady(() => {
    const $ = (sel, root = document) => root.querySelector(sel);
    const $$ = (sel, root = document) => Array.from(root.querySelectorAll(sel));
    const on = (el, ev, fn) => {
      if (!el) return;
      el.addEventListener(ev, fn);
    };

    const scope = document.getElementById("hHome");
    if (!scope) {
      console.warn("hHome element not found — aborting scoped scripts.");
      return;
    }

    /* ========================= */
    /* HERO SLIDER               */
    /* ========================= */
    try {
      const slides = $$(".hSlide", scope);
      const dotsWrap = $(".hDots", scope);
      let index = 0,
        timer;
      const makeDots = () => {
        if (!dotsWrap || !slides.length) return;
        dotsWrap.innerHTML = "";
        slides.forEach((_, i) => {
          const d = document.createElement("button");
          d.className = "hDot" + (i === 0 ? " active" : "");
          d.setAttribute("aria-label", "Go to slide " + (i + 1));
          d.addEventListener("click", () => go(i));
          dotsWrap.appendChild(d);
        });
      };
      const setActive = (i) => {
        slides.forEach((s, j) => s.classList.toggle("is-active", j === i));
        $$(".hDot", scope).forEach((d, j) =>
          d.classList.toggle("active", j === i)
        );
      };
      const next = () => slides.length && go((index + 1) % slides.length);
      const prev = () =>
        slides.length && go((index - 1 + slides.length) % slides.length);
      const go = (i) => {
        index = i;
        setActive(index);
        resetTimer();
      };
      const resetTimer = () => {
        clearInterval(timer);
        if (slides.length) timer = setInterval(next, 5500);
      };

      if (slides.length && dotsWrap) {
        makeDots();
        resetTimer();
      }
      on($(".hArrow.next", scope), "click", next);
      on($(".hArrow.prev", scope), "click", prev);
    } catch (err) {
      console.error("Hero slider init error:", err);
    }

    /* ========================= */
    /* SCROLL ANIMATIONS         */
    /* ========================= */
    try {
      const io = new IntersectionObserver(
        (entries) => {
          entries.forEach((e) => {
            if (e.isIntersecting) {
              e.target.classList.add("hIn");
              io.unobserve(e.target);
            }
          });
        },
        { threshold: 0.15 }
      );
      $$("[data-animate]", scope).forEach((el) => io.observe(el));
    } catch (err) {
      console.error("Scroll animation error:", err);
    }

    /* ========================= */
    /* ROOMS FILTER              */
    /* ========================= */
    try {
      const filterBtns = $$(".hfilter-btn", scope);
      const cards = $$(".hRoomCard", scope);
      if (filterBtns.length && cards.length) {
        filterBtns.forEach((btn) =>
          btn.addEventListener("click", () => {
            filterBtns.forEach((b) => b.classList.remove("active"));
            btn.classList.add("active");
            const f = btn.dataset.filter;
            cards.forEach((c) => {
              const types = (c.getAttribute("data-type") || "").split(/\s+/);
              const show = f === "all" || types.includes(f);
              c.style.display = show ? "grid" : "none";
            });
          })
        );
      }
    } catch (err) {
      console.error("Rooms filter error:", err);
    }

    /* ========================= */
    /* DINING SCROLLER           */
    /* ========================= */
    try {
      const track = $(".hTrack", scope);
      on(
        $(".hxPrev", scope),
        "click",
        () => track && track.scrollBy({ left: -400, behavior: "smooth" })
      );
      on(
        $(".hxNext", scope),
        "click",
        () => track && track.scrollBy({ left: 400, behavior: "smooth" })
      );
    } catch (err) {
      console.error("Dining scroller error:", err);
    }

    /* ========================= */
    /* PARALLAX                  */
    /* ========================= */
    try {
      const parallax = $(".hParallax", scope);
      if (parallax) {
        const parallaxFx = () => {
          const rect = parallax.getBoundingClientRect();
          const p = rect.top / window.innerHeight;
          parallax.style.backgroundPosition = `center ${p * 30}px`;
        };
        document.addEventListener("scroll", parallaxFx, { passive: true });
        parallaxFx();
      }
    } catch (err) {
      console.error("Parallax error:", err);
    }

    /* ========================= */
    /* TABS                      */
    /* ========================= */
    try {
      const tabBtns = $$(".hTabBtn", scope);
      const panels = $$(".hPanel", scope);
      if (tabBtns.length && panels.length) {
        tabBtns.forEach((b) =>
          b.addEventListener("click", () => {
            tabBtns.forEach((x) => x.classList.remove("active"));
            b.classList.add("active");
            panels.forEach((p) => p.classList.remove("active"));
            const target = $("#tab-" + b.dataset.tab, scope);
            if (target) target.classList.add("active");
          })
        );
      }
    } catch (err) {
      console.error("Tabs error:", err);
    }

    /* ========================= */
    /* VIDEO MODAL               */
    /* ========================= */
    try {
      const modal = document.querySelector(".hModal");
      const playBtn = document.querySelector(".hPlayBtn");
      const iframe = modal ? modal.querySelector("iframe") : null;
      if (modal && playBtn && iframe) {
        const openVideo = () => {
          modal.classList.add("is-open");
          iframe.src =
            "https://www.youtube.com/embed/GljFm1ALtXY?autoplay=1&rel=0";
        };
        const closeVideo = () => {
          modal.classList.remove("is-open");
          iframe.src = "";
        };
        on(playBtn, "click", openVideo);
        on(modal, "click", (e) => {
          if (e.target === modal) closeVideo();
        });
        document.addEventListener("keydown", (e) => {
          if (e.key === "Escape") closeVideo();
        });
      }
    } catch (err) {
      console.error("Video modal error:", err);
    }

    /* ========================= */
    /* GALLERY LIGHTBOX          */
    /* ========================= */
    try {
      const hGalleryItems = $$("#hHome .hGalleryGrid a");
      const hLightbox = document.getElementById("hLightbox");
      const hLightboxImg = document.querySelector("#hHome .hLightbox img");
      const hClose = document.querySelector("#hHome .hLightClose");
      const hPrev = document.querySelector("#hHome .hPrev");
      const hNext = document.querySelector("#hHome .hNext");

      if (!hGalleryItems.length || !hLightbox || !hLightboxImg) {
        // Not a fatal error — gallery simply not present
        // console.info('Gallery elements missing — skipping gallery init.');
      } else {
        let hCurrentIndex = 0;
        function hOpenLightbox(index) {
          hCurrentIndex = index;
          hLightbox.classList.add("is-open");
          document.body.classList.add("no-scroll");
          hLightboxImg.src = hGalleryItems[hCurrentIndex].href;
        }
        function hCloseLightbox() {
          hLightbox.classList.remove("is-open");
          document.body.classList.remove("no-scroll");
        }
        function hShowNext() {
          hCurrentIndex = (hCurrentIndex + 1) % hGalleryItems.length;
          hLightboxImg.src = hGalleryItems[hCurrentIndex].href;
        }
        function hShowPrev() {
          hCurrentIndex =
            (hCurrentIndex - 1 + hGalleryItems.length) % hGalleryItems.length;
          hLightboxImg.src = hGalleryItems[hCurrentIndex].href;
        }

        hGalleryItems.forEach((item, index) => {
          item.addEventListener("click", (e) => {
            e.preventDefault();
            hOpenLightbox(index);
          });
        });
        on(hClose, "click", hCloseLightbox);
        on(hNext, "click", hShowNext);
        on(hPrev, "click", hShowPrev);
        on(hLightbox, "click", (e) => {
          if (e.target === hLightbox) hCloseLightbox();
        });
        document.addEventListener("keydown", (e) => {
          if (!hLightbox.classList.contains("is-open")) return;
          if (e.key === "ArrowRight") hShowNext();
          if (e.key === "ArrowLeft") hShowPrev();
          if (e.key === "Escape") hCloseLightbox();
        });
      }
    } catch (err) {
      console.error("Gallery lightbox error:", err);
    }

    /* ========================= */
    /* TESTIMONIALS CAROUSEL     */
    /* ========================= */
    try {
      const tTrack = document.querySelector("#hHome .hTrackT");
      const tItems = document.querySelectorAll("#hHome .hCardT");
      if (tTrack && tItems.length) {
        let tIndex = 0;

        const tStep = () => {
          const cardWidth = tItems[0].getBoundingClientRect().width + 16; // card width + gap
          tIndex = (tIndex + 1) % tItems.length;
          tTrack.style.transform = `translateX(-${tIndex * cardWidth}px)`;
        };

        setInterval(tStep, 4200);
      }
    } catch (err) {
      console.error("Testimonials error:", err);
    }

    /* ========================= */
    /* NEWSLETTER                 */
    /* ========================= */
    try {
      const form = $(".hForm", scope);
      const toast = $(".hToast");
      if (form) {
        form.addEventListener("submit", (e) => {
          e.preventDefault();
          const v = form.email.value.trim();
          const ok = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v);
          if (!ok) {
            form.email.focus();
            form.email.style.outline = `2px solid var(--h-warn)`;
            return;
          }
          form.reset();
          if (toast) {
            toast.classList.add("show");
            setTimeout(() => toast.classList.remove("show"), 2600);
          }
        });
      }
    } catch (err) {
      console.error("Newsletter error:", err);
    }

    /* ========================= */
    /* BACK TO TOP                */
    /* ========================= */
    try {
      const toTop = $(".hTop");
      if (toTop) {
        document.addEventListener(
          "scroll",
          () => {
            const y = window.scrollY || document.documentElement.scrollTop;
            toTop.classList.toggle("show", y > 480);
          },
          { passive: true }
        );
        on(toTop, "click", () =>
          window.scrollTo({ top: 0, behavior: "smooth" })
        );
      }
    } catch (err) {
      console.error("Back to top error:", err);
    }
  });
})();

// Hamburger menu toggle
const hamburger = document.getElementById("hamburger");
const nav = document.querySelector("nav");
hamburger.addEventListener("click", () => {
  nav.classList.toggle("open");
});
hamburger.addEventListener("keypress", (e) => {
  if (e.key === "Enter" || e.key === " ") nav.classList.toggle("open");
});
