/* =====================================================
   TRAVELICA – main.js
   Shared scripts across all pages
   ===================================================== */
document.addEventListener('DOMContentLoaded', () => {

  /* ---- NAVBAR: scroll shadow ---- */
  const navbar = document.getElementById('navbar');
  if (navbar) {
    window.addEventListener('scroll', () => {
      navbar.classList.toggle('scrolled', window.scrollY > 30);
    }, { passive: true });
  }

  /* ---- HAMBURGER ---- */
  const hamburger = document.getElementById('hamburger');
  const mobileNav = document.getElementById('mobileNav');
  const mobileNavOverlay = document.getElementById('mobileNavOverlay');
  const mnClose = document.getElementById('mn-close');

  if (hamburger && mobileNav) {
    const toggleNav = (force) => {
      const isOpen = typeof force === 'boolean' ? force : !mobileNav.classList.contains('open');
      hamburger.classList.toggle('open', isOpen);
      mobileNav.classList.toggle('open', isOpen);
      if (mobileNavOverlay) mobileNavOverlay.classList.toggle('open', isOpen);
      document.body.style.overflow = isOpen ? 'hidden' : '';
    };

    hamburger.addEventListener('click', () => toggleNav());
    mnClose?.addEventListener('click', () => toggleNav(false));
    mobileNavOverlay?.addEventListener('click', () => toggleNav(false));

    mobileNav.querySelectorAll('.mn-link').forEach(l => {
      l.addEventListener('click', () => toggleNav(false));
    });
  }

  /* ---- DESTINATION SLIDER (home page only) ---- */
  const destTrack = document.getElementById('destTrack');
  if (destTrack) {
    let destIdx = 0;
    const getDestCols = () => window.innerWidth <= 480 ? 1 : window.innerWidth <= 768 ? 2 : 4;

    const slideDestTo = (idx) => {
      const cards = destTrack.querySelectorAll('.dest-card');
      const cols = getDestCols();
      const maxIdx = Math.max(0, cards.length - cols);
      destIdx = Math.max(0, Math.min(idx, maxIdx));
      if (window.innerWidth <= 1024) {
        const cardEl = cards[0];
        if (cardEl) {
          const gap = 18;
          destTrack.parentElement.scrollTo({ left: destIdx * (cardEl.offsetWidth + gap), behavior: 'smooth' });
        }
      }
    };

    document.getElementById('dest-prev')?.addEventListener('click', () => slideDestTo(destIdx - 1));
    document.getElementById('dest-next')?.addEventListener('click', () => slideDestTo(destIdx + 1));
    destTrack.parentElement.style.overflowX = 'auto';
    destTrack.parentElement.style.scrollbarWidth = 'none';
  }

  /* ---- TOUR GALLERY SLIDER (home page) ---- */
  const tgTrack = document.getElementById('tgTrack');
  const tgPrevBtn = document.getElementById('tg-prev');
  const tgNextBtn = document.getElementById('tg-next');

  if (tgTrack) {
    const tgSliderWrap = tgTrack.parentElement;
    const getTgScrollAmount = () => {
      const card = tgTrack.querySelector('.tg-card');
      if (card) {
        const gap = 22;
        return card.offsetWidth + gap;
      }
      return 350;
    };

    tgPrevBtn?.addEventListener('click', () => {
      tgSliderWrap.scrollBy({ left: -getTgScrollAmount(), behavior: 'smooth' });
    });

    tgNextBtn?.addEventListener('click', () => {
      tgSliderWrap.scrollBy({ left: getTgScrollAmount(), behavior: 'smooth' });
    });

    // Mouse drag scroll support
    let isTgDown = false;
    let tgStartX = 0;
    let tgScrollLeft = 0;

    tgSliderWrap.addEventListener('mousedown', (e) => {
      isTgDown = true;
      tgStartX = e.pageX - tgSliderWrap.offsetLeft;
      tgScrollLeft = tgSliderWrap.scrollLeft;
      tgSliderWrap.style.cursor = 'grabbing';
    });

    const endTgDrag = () => {
      if (!isTgDown) return;
      isTgDown = false;
      tgSliderWrap.style.cursor = '';
    };

    window.addEventListener('mouseup', endTgDrag);
    tgSliderWrap.addEventListener('mouseleave', endTgDrag);

    tgSliderWrap.addEventListener('mousemove', (e) => {
      if (!isTgDown) return;
      e.preventDefault();
      const x = e.pageX - tgSliderWrap.offsetLeft;
      const walk = (x - tgStartX) * 1.4;
      tgSliderWrap.scrollLeft = tgScrollLeft - walk;
    });
  }

  /* ---- SEARCH (home page only) ---- */
  const sbBtn = document.getElementById('sb-btn');
  const sbInput = document.getElementById('sb-input');

  // Autocomplete dropdown
  const searchbar = document.getElementById('searchbar');
  let sbDropdown = null;
  let sbFetchTimer = null;

  function closeSbDropdown() {
    if (sbDropdown) { sbDropdown.remove(); sbDropdown = null; }
  }

  function doSearch() {
    const q = sbInput?.value?.trim();
    if (q) {
      window.location.href = `search?q=${encodeURIComponent(q)}`;
    }
  }

  sbBtn?.addEventListener('click', doSearch);
  sbInput?.addEventListener('keydown', e => {
    if (e.key === 'Enter') { closeSbDropdown(); doSearch(); }
    if (e.key === 'Escape') closeSbDropdown();
  });

  sbInput?.addEventListener('input', () => {
    clearTimeout(sbFetchTimer);
    const q = sbInput.value.trim();
    if (q.length < 2) { closeSbDropdown(); return; }
    sbFetchTimer = setTimeout(() => {
      fetch(`search?q=${encodeURIComponent(q)}&json=1`)
        .then(r => r.json())
        .then(data => {
          closeSbDropdown();
          if (!data.length) return;
          sbDropdown = document.createElement('div');
          sbDropdown.className = 'sb-dropdown';
          data.forEach(item => {
            const d = document.createElement('div');
            d.className = 'sb-dropdown-item';
            d.innerHTML = `<span class="sb-di-icon">${item.type === 'trip' ? '✈' : '🌍'}</span>
              <span class="sb-di-main">${escHtml(item.name)}</span>
              ${item.sub ? `<span class="sb-di-sub">${escHtml(item.sub)}</span>` : ''}`;
            d.addEventListener('mousedown', e => {
              e.preventDefault();
              window.location.href = item.url;
            });
            sbDropdown.appendChild(d);
          });
          if (searchbar) searchbar.appendChild(sbDropdown);
        })
        .catch(() => {});
    }, 280);
  });

  document.addEventListener('click', e => {
    if (searchbar && !searchbar.contains(e.target)) closeSbDropdown();
  });

  function escHtml(str) {
    return String(str).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
  }

  /* ---- VIDEO PLAY ---- */
  document.getElementById('vs-play')?.addEventListener('click', () => {
    const waLink = document.getElementById('float-wa')?.href || document.getElementById('wa-btn-nav')?.href || '#';
    window.open(waLink, '_blank');
  });

  /* ---- SCROLL REVEAL (all pages) ---- */
  const reveals = document.querySelectorAll('.dest-card, .rv-card, .kp-item');
  if (reveals.length > 0) {
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e, i) => {
        if (e.isIntersecting) {
          setTimeout(() => {
            e.target.style.opacity = '1';
            e.target.style.transform = 'translateY(0)';
          }, i * 60);
          io.unobserve(e.target);
        }
      });
    }, { threshold: 0.1 });

    reveals.forEach(el => {
      el.style.opacity = '0';
      el.style.transform = 'translateY(20px)';
      el.style.transition = 'opacity .4s ease, transform .4s ease';
      io.observe(el);
    });
  }

  /* ---- DEST CARD CLICK (Mobile fallback) ---- */
  document.querySelectorAll('.dest-card').forEach(card => {
    card.style.cursor = 'pointer';
    card.addEventListener('click', function(e) {
      if (e.target.closest('button') || e.target.closest('a')) return;
      const btn = this.querySelector('.dc-btn');
      if (btn && btn.href) {
        window.location.href = btn.href;
      }
    });
  });

  /* ---- TRAVELICA SHOWCASE VIDEO PLAYER & PLAYLIST ---- */
  const mainTravelVideo = document.getElementById('mainTravelVideo');
  const mainVideoOverlay = document.getElementById('mainVideoOverlay');
  const vpTrack = document.getElementById('videoPlaylistTrack');
  const vpPrev = document.getElementById('vpPrev');
  const vpNext = document.getElementById('vpNext');

  if (mainTravelVideo) {
    // Center overlay click
    if (mainVideoOverlay) {
      mainVideoOverlay.addEventListener('click', () => {
        if (mainTravelVideo.paused) {
          mainTravelVideo.play().then(() => {
            mainVideoOverlay.classList.add('hidden');
          }).catch(err => console.log('Video play error:', err));
        } else {
          mainTravelVideo.pause();
          mainVideoOverlay.classList.remove('hidden');
        }
      });
    }

    // Sync play/pause events with overlay
    mainTravelVideo.addEventListener('play', () => {
      if (mainVideoOverlay) mainVideoOverlay.classList.add('hidden');
    });

    mainTravelVideo.addEventListener('pause', () => {
      if (mainVideoOverlay) mainVideoOverlay.classList.remove('hidden');
    });

    mainTravelVideo.addEventListener('ended', () => {
      if (mainVideoOverlay) mainVideoOverlay.classList.remove('hidden');
    });
  }

  // Playlist navigation arrows
  if (vpTrack && vpPrev && vpNext) {
    vpPrev.addEventListener('click', () => {
      vpTrack.scrollBy({ left: -260, behavior: 'smooth' });
    });
    vpNext.addEventListener('click', () => {
      vpTrack.scrollBy({ left: 260, behavior: 'smooth' });
    });
  }

  // Expose switch video function globally for onclick
  window.switchMainVideo = function(data, cardEl) {
    const vid = document.getElementById('mainTravelVideo');
    const titleEl = document.getElementById('mainVideoTitle');
    const descEl = document.getElementById('mainVideoDesc');
    const badgeText = document.getElementById('mainVideoBadgeText');
    const overlay = document.getElementById('mainVideoOverlay');
    if (!vid) return;

    // Highlight card
    document.querySelectorAll('.vp-card').forEach(c => c.classList.remove('active'));
    if (cardEl) cardEl.classList.add('active');

    // Smooth fade transition
    vid.style.transition = 'opacity 0.2s ease';
    vid.style.opacity = '0.2';

    setTimeout(() => {
      vid.src = data.src;
      if (data.poster) {
        vid.poster = data.poster;
      }
      vid.load();
      vid.play().then(() => {
        if (overlay) overlay.classList.add('hidden');
      }).catch(() => {
        if (overlay) overlay.classList.remove('hidden');
      });

      if (titleEl) titleEl.textContent = data.title;
      if (descEl) {
        descEl.textContent = data.desc;
        descEl.style.display = data.desc ? 'block' : 'none';
      }
      if (badgeText) {
        badgeText.textContent = data.duration || 'HD Video';
      }

      vid.style.opacity = '1';
    }, 200);
  };

});

