/* ================================================================
   HOTEL FIVE RIVERS — Main JavaScript v2.0
   ================================================================
   Modules:
   1. Navigation (scroll effect + mobile toggle)
   2. Scroll Reveal Animations
   3. River Animation (SVG draw-in)
   4. Hotel Runner Booking Integration
   5. Smooth Scroll for Anchor Links
   6. Lightbox Gallery (room pages)
   7. Initialization
   ================================================================ */

'use strict';

/* ================================================================
   1. NAVIGATION
   ================================================================ */
const Navigation = (() => {
  const nav = document.getElementById('mainNav');
  const toggle = document.getElementById('navToggle');
  const mobileMenu = document.getElementById('mobileMenu');

  if (!nav || !toggle || !mobileMenu) return { init: () => {} };

  const mobileLinks = mobileMenu.querySelectorAll('.mobile-menu__link');

  function handleScroll() {
    nav.classList.toggle('nav--scrolled', window.scrollY > 60);
  }

  function toggleMobileMenu() {
    const isOpen = mobileMenu.classList.contains('mobile-menu--open');
    toggle.classList.toggle('nav__toggle--active', !isOpen);
    toggle.setAttribute('aria-expanded', !isOpen);
    mobileMenu.classList.toggle('mobile-menu--open', !isOpen);
    mobileMenu.setAttribute('aria-hidden', isOpen);
    document.body.style.overflow = isOpen ? '' : 'hidden';
  }

  function closeMobileMenu() {
    toggle.classList.remove('nav__toggle--active');
    toggle.setAttribute('aria-expanded', 'false');
    mobileMenu.classList.remove('mobile-menu--open');
    mobileMenu.setAttribute('aria-hidden', 'true');
    document.body.style.overflow = '';
  }

  function init() {
    // Only add scroll listener on pages without .nav--solid (homepage)
    if (!nav.classList.contains('nav--solid')) {
      window.addEventListener('scroll', handleScroll, { passive: true });
      handleScroll();
    }
    toggle.addEventListener('click', toggleMobileMenu);
    mobileLinks.forEach(link => link.addEventListener('click', closeMobileMenu));
  }

  return { init, closeMobileMenu };
})();


/* ================================================================
   2. SCROLL REVEAL
   ================================================================ */
const ScrollReveal = (() => {
  function init() {
    const elements = document.querySelectorAll('.reveal');
    if (!elements.length) return;

    if (!('IntersectionObserver' in window)) {
      elements.forEach(el => el.classList.add('reveal--visible'));
      return;
    }

    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          entry.target.classList.add('reveal--visible');
          observer.unobserve(entry.target);
        }
      });
    }, { threshold: 0.12, rootMargin: '0px 0px -30px 0px' });

    elements.forEach(el => observer.observe(el));
  }

  return { init };
})();


/* ================================================================
   3. RIVER ANIMATION
   ================================================================ */
const RiverAnimation = (() => {
  function init() {
    const container = document.getElementById('riverAnimation');
    if (!container) return;

    const strands = container.querySelectorAll('.river-strand');

    if (!('IntersectionObserver' in window)) {
      strands.forEach(s => s.classList.add('river-strand--animated'));
      return;
    }

    const observer = new IntersectionObserver((entries) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          strands.forEach(s => s.classList.add('river-strand--animated'));
          observer.unobserve(entry.target);
        }
      });
    }, { threshold: 0.25 });

    observer.observe(container);
  }

  return { init };
})();


/* ================================================================
   4. HOTEL RUNNER BOOKING
   ================================================================ */
const BookingEngine = (() => {
  function openBooking() {
    if (typeof HotelRunnerWidget !== 'undefined' && HotelRunnerWidget.show) {
      HotelRunnerWidget.show(null);
    } else {
      window.open('https://hotel-five-rivers.hotelrunner.com', '_blank');
    }
  }

  function init() {
    document.querySelectorAll('[data-book]').forEach(btn => {
      btn.addEventListener('click', (e) => {
        e.preventDefault();
        openBooking();
      });
    });
  }

  return { init };
})();


/* ================================================================
   5. SMOOTH SCROLL
   ================================================================ */
const SmoothScroll = (() => {
  function init() {
    document.querySelectorAll('a[href^="#"]').forEach(link => {
      link.addEventListener('click', (e) => {
        const href = link.getAttribute('href');
        if (!href || href === '#') return;

        const target = document.querySelector(href);
        if (!target) return;

        e.preventDefault();
        const navEl = document.getElementById('mainNav');
        const offset = navEl ? navEl.offsetHeight : 0;
        const pos = target.getBoundingClientRect().top + window.scrollY - offset;

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

  return { init };
})();


/* ================================================================
   6. LIGHTBOX GALLERY (room pages)
   ================================================================ */
const Lightbox = (() => {
  let lightboxEl = null;
  let imageEl = null;
  let counterEl = null;
  let images = [];
  let currentIndex = 0;

  /**
   * Create the lightbox DOM elements dynamically.
   * Only created once, when first gallery image is clicked.
   */
  function createLightbox() {
    lightboxEl = document.createElement('div');
    lightboxEl.className = 'lightbox';
    lightboxEl.innerHTML = `
      <button class="lightbox__close" aria-label="Close gallery">
        <svg viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
      </button>
      <button class="lightbox__nav lightbox__nav--prev" aria-label="Previous image">
        <svg viewBox="0 0 24 24"><polyline points="15 18 9 12 15 6"/></svg>
      </button>
      <img class="lightbox__image" src="" alt="Gallery image">
      <button class="lightbox__nav lightbox__nav--next" aria-label="Next image">
        <svg viewBox="0 0 24 24"><polyline points="9 18 15 12 9 6"/></svg>
      </button>
      <div class="lightbox__counter"></div>
    `;

    document.body.appendChild(lightboxEl);

    imageEl = lightboxEl.querySelector('.lightbox__image');
    counterEl = lightboxEl.querySelector('.lightbox__counter');

    // Event listeners
    lightboxEl.querySelector('.lightbox__close').addEventListener('click', close);
    lightboxEl.querySelector('.lightbox__nav--prev').addEventListener('click', prev);
    lightboxEl.querySelector('.lightbox__nav--next').addEventListener('click', next);

    // Close on backdrop click
    lightboxEl.addEventListener('click', (e) => {
      if (e.target === lightboxEl) close();
    });

    // Keyboard navigation
    document.addEventListener('keydown', (e) => {
      if (!lightboxEl.classList.contains('lightbox--open')) return;
      if (e.key === 'Escape') close();
      if (e.key === 'ArrowLeft') prev();
      if (e.key === 'ArrowRight') next();
    });
  }

  function open(index) {
    if (!lightboxEl) createLightbox();
    currentIndex = index;
    updateImage();
    lightboxEl.classList.add('lightbox--open');
    document.body.style.overflow = 'hidden';
  }

  function close() {
    lightboxEl.classList.remove('lightbox--open');
    document.body.style.overflow = '';
  }

  function prev() {
    currentIndex = (currentIndex - 1 + images.length) % images.length;
    updateImage();
  }

  function next() {
    currentIndex = (currentIndex + 1) % images.length;
    updateImage();
  }

  function updateImage() {
    imageEl.src = images[currentIndex];
    counterEl.textContent = `${currentIndex + 1} / ${images.length}`;
  }

  /**
   * Initialize lightbox for all gallery items on the page.
   */
  function init() {
    const galleryItems = document.querySelectorAll('.gallery__item');
    if (!galleryItems.length) return;

    // Collect all image sources
    images = Array.from(galleryItems).map(item => {
      const img = item.querySelector('img');
      return img ? img.src : '';
    }).filter(Boolean);

    // Attach click handlers
    galleryItems.forEach((item, index) => {
      item.addEventListener('click', () => open(index));
    });
  }

  return { init };
})();


/* ================================================================
   7. INITIALIZATION
   ================================================================ */
document.addEventListener('DOMContentLoaded', () => {
  Navigation.init();
  ScrollReveal.init();
  RiverAnimation.init();
  BookingEngine.init();
  SmoothScroll.init();
  Lightbox.init();
});
