/* =====================================================
   GLOBAL VARIABLES
===================================================== */

let players = [];
let introPlayer = null;


/* =====================================================
   LOAD YOUTUBE API SAFELY
===================================================== */

function loadYouTubeAPI() {
  return new Promise(resolve => {

    if (window.YT && window.YT.Player) {
      resolve();
      return;
    }

    const tag = document.createElement("script");
    tag.src = "https://www.youtube.com/iframe_api";

    window.onYouTubeIframeAPIReady = () => resolve();

    document.head.appendChild(tag);
  });
}


/* =====================================================
   DOM READY INITIALISER
===================================================== */

document.addEventListener("DOMContentLoaded", async () => {

  initSettings();
  initAudioCarousel();
  initPopup();
  initParallax();
  initFadeIn();
  initGalleryFilters();
  initLightbox();
  initFeatureCards();
  initAccordion();
  
  await loadYouTubeAPI();
  initYouTubePlayers();
});


/* =====================================================
   SETTINGS + CURSOR HALO
===================================================== */

function initSettings() {

  const savedFontSize = localStorage.getItem("fontSize") || "medium";
  setFontSize(savedFontSize);

  const savedCursorGlow = localStorage.getItem("cursorGlow") || "enabled";
  const halo = document.getElementById("cursorGlow");
  const toggle = document.getElementById("toggleCursorGlow");

  const isTouchDevice =
    "ontouchstart" in window || navigator.maxTouchPoints > 0;

  const glowOption = document.getElementById("cursorGlowOption");
  if (isTouchDevice && glowOption) glowOption.style.display = "none";

  if (!halo || !toggle) return;

  toggle.checked = savedCursorGlow === "enabled" && !isTouchDevice;
  halo.style.display = toggle.checked ? "block" : "none";

  toggle.addEventListener("change", () => {
    const show = toggle.checked && !isTouchDevice;
    halo.style.display = show ? "block" : "none";
    localStorage.setItem("cursorGlow", show ? "enabled" : "disabled");
  });

  document.addEventListener("mousemove", e => {
    if (halo.style.display !== "none") {
      halo.style.left = `${e.clientX - 14}px`;
      halo.style.top = `${e.clientY - 14}px`;
    }
  });
}


/* =====================================================
   AUDIO CAROUSEL
===================================================== */

function initAudioCarousel() {

  document.querySelectorAll("audio").forEach(audio => {
    audio.addEventListener("play", () => {
      document.querySelectorAll("audio").forEach(other => {
        if (other !== audio) other.pause();
      });
    });
  });
}

function scrollAudioCarousel(direction) {
  const carousel = document.getElementById("newAudioCarousel");
  if (!carousel) return;

  const cardWidth =
    carousel.querySelector(".new-audio-card")?.offsetWidth || 300;

  carousel.scrollBy({
    left: direction * (cardWidth + 20),
    behavior: "smooth"
  });
}


/* =====================================================
   SETTINGS POPUP
===================================================== */

function initPopup() {

  const trigger = document.getElementById("popupTrigger");
  const popup = document.getElementById("popupBox");
  const close = document.getElementById("popupClose");

  if (!trigger || !popup || !close) return;

  trigger.onclick = () => (popup.style.display = "flex");
  close.onclick = () => (popup.style.display = "none");

  window.onclick = e => {
    if (e.target === popup) popup.style.display = "none";
  };
}


/* =====================================================
   PARALLAX TEXT
===================================================== */

function initParallax() {

  const box = document.querySelector(".parallaxx-text");
  if (!box) return;

  new IntersectionObserver(entries => {
    if (entries[0].isIntersecting) box.classList.add("reveal");
  }).observe(box);
}


/* =====================================================
   FADE IN SECTIONS
===================================================== */

function initFadeIn() {

  document.querySelectorAll(".fade-in-section").forEach(section => {

    new IntersectionObserver(entries => {
      if (entries[0].isIntersecting) {
        section.classList.add("is-visible");
      }
    }, { threshold: 0.1 }).observe(section);

  });
}

/* =====================================================
   FILTER BUTTON LOGIC ON GALLERY PAGE
===================================================== */
const hash = window.location.hash.replace("#", ""); // ie "weddings"
if (hash) {
  setTimeout(() => {
    const buttonToClick = document.getElementById(hash);
    if (buttonToClick) {
      buttonToClick.click();
    } else {
      console.warn("No filter button found with ID:", hash);
    }
  }, 100);
}

/* =====================================================
   GALLERY FILTERS
===================================================== */

function initGalleryFilters() {

  const buttons = document.querySelectorAll(".filter-btn");
  const items = document.querySelectorAll(".gallery-item");

  if (!buttons.length) return;

  let activeFilters = ["photos"];

  function updateGallery() {
    items.forEach(item => {
      const matches = activeFilters.every(tag =>
        item.classList.contains(tag)
      );
      item.style.display = matches ? "block" : "none";
    });
  }

  updateGallery();

  buttons.forEach(btn => {

    btn.onclick = () => {

      const filter = btn.dataset.filter;
      btn.classList.toggle("active");

      const mediaGroup = ["photos", "videos"];
      const categoryGroup = ["birthdays", "weddings", "restaurants", "corporate", "other"];

      [mediaGroup, categoryGroup].forEach(group => {
        if (group.includes(filter) && btn.classList.contains("active")) {
          group.forEach(item => {
            if (item !== filter) {
              document.querySelector(`[data-filter="${item}"]`)
                ?.classList.remove("active");
              activeFilters = activeFilters.filter(f => f !== item);
            }
          });
        }
      });

      if (btn.classList.contains("active")) {
        if (!activeFilters.includes(filter)) activeFilters.push(filter);
      } else {
        activeFilters = activeFilters.filter(f => f !== filter);
      }

      if (!activeFilters.length) {
        activeFilters = ["photos"];
        document.querySelector('[data-filter="photos"]')?.classList.add("active");
      }

      updateGallery();
    };
  });
}

function applyGalleryHashFilter() {

  const hash = window.location.hash.replace("#", "");
  if (!hash) return;

  const button = document.querySelector(`.filter-btn[data-filter="${hash}"]`);

  if (button) {
    setTimeout(() => {
      button.click();
    }, 150); // small delay ensures filters exist
  }
}


/* =====================================================
   YOUTUBE PLAYERS
===================================================== */

function initYouTubePlayers() {

  // INTRO PLAYER
  const introContainer = document.getElementById("player");

  if (introContainer) {
    introPlayer = new YT.Player("player", {
      videoId: "o9cp1hSEp-s",
      playerVars: { playsinline: 1, mute: 1 },
      events: { onReady: setupIntroScrollPlayback }
    });
  }

  // GALLERY PLAYERS
  document.querySelectorAll(".yt-video").forEach((iframe, index) => {

    if (!iframe.id) iframe.id = "yt-player-" + index;

    const player = new YT.Player(iframe.id, {
      events: { onStateChange: onGalleryPlayerStateChange }
    });

    players.push(player);
  });
}


function setupIntroScrollPlayback() {

  window.addEventListener("scroll", () => {

    if (!introPlayer) return;

    const rect = introPlayer.getIframe().getBoundingClientRect();

    const visible =
      rect.top < window.innerHeight &&
      rect.bottom > 0;

    visible ? introPlayer.playVideo() : introPlayer.pauseVideo();
  });
}


function onGalleryPlayerStateChange(event) {

  if (event.data === YT.PlayerState.PLAYING) {

    players.forEach(player => {
      if (player !== event.target) player.pauseVideo();
    });
  }
}


/* =====================================================
   LIGHTBOX
===================================================== */

function initLightbox() {

  const lightbox = document.getElementById("lightbox");
  const content = document.querySelector(".lightbox-content");
  const closeBtn = document.querySelector(".close-btn");

  if (!lightbox || !content || !closeBtn) return;

  document.querySelectorAll(".lightbox-trigger").forEach(trigger => {

    trigger.onclick = () => {

      lightbox.style.display = "flex";
      content.innerHTML = "";

      if (trigger.tagName === "IMG") {

        const img = document.createElement("img");
        img.src = trigger.src;
        content.appendChild(img);

      } else if (trigger.tagName === "VIDEO") {

        const video = document.createElement("video");
        video.src = trigger.querySelector("source").src;
        video.controls = true;
        video.autoplay = true;
        content.appendChild(video);
      }
    };
  });

  closeBtn.onclick = () => {
    lightbox.style.display = "none";
    content.innerHTML = "";
  };

  lightbox.onclick = e => {
    if (e.target === lightbox) closeBtn.onclick();
  };
}


/* =====================================================
   FEATURE CARDS + TESTIMONIALS
===================================================== */

function initFeatureCards() {

  /* ===== FEATURE CARD REVEAL ===== */
  document.querySelectorAll(".card").forEach((card, i) => {

    new IntersectionObserver(entries => {
      if (entries[0].isIntersecting) {
        setTimeout(() => card.classList.add("reveal"), i * 300);
      }
    }).observe(card);

  });


  /* ===== TESTIMONIAL CAROUSEL ===== */
  const containers = document.querySelectorAll(".testimonial-carousel .container");
  if (!containers.length) return;

  let index = 0;
  let interval = null;
  let paused = false;


  /* ---------- SHOW TESTIMONIAL ---------- */
  function show(nextIndex) {
    const current = containers[index];
    const next = containers[nextIndex];

    current.classList.remove("animate-in", "reveal");
    current.classList.add("animate-out");

    next.classList.remove("animate-out");
    next.classList.add("animate-in", "reveal");

    index = nextIndex;
  }


  /* ---------- START CAROUSEL ---------- */
  function startCarousel() {
    clearInterval(interval);

    interval = setInterval(() => {
      const next = (index + 1) % containers.length;
      show(next);
    }, 4000);

    paused = false;
  }


  /* ---------- STOP CAROUSEL ---------- */
  function stopCarousel() {
    clearInterval(interval);
    interval = null;
    paused = true;
  }


  /* ===== INITIAL STATE ===== */
  containers[0].classList.add("animate-in", "reveal");
  startCarousel();


  /* ===== MOBILE TAP TO TOGGLE PAUSE/HIGHLIGHT ===== */
  containers.forEach(card => {
    card.addEventListener("click", (e) => {
      // Only run this logic on mobile/tablets
      if (window.innerWidth <= 768) {
        
        const isCurrentlyActive = card.classList.contains("tap-active");

        if (isCurrentlyActive) {
          // SECOND TAP: Unhighlight and resume
          card.classList.remove("tap-active");
          startCarousel();
        } else {
          // FIRST TAP: Pause and highlight
          stopCarousel();
          
          // Clear any other active highlights first
          containers.forEach(c => c.classList.remove("tap-active"));
          card.classList.add("tap-active");
        }
      }
    });
  });


  /* ===== DESKTOP HOVER ===== */
  containers.forEach(card => {

    card.addEventListener("mouseenter", () => {
      if (window.innerWidth > 768) stopCarousel();
    });

    card.addEventListener("mouseleave", () => {
      if (window.innerWidth > 768) startCarousel();
    });

  });

}



/* =====================================================
   ACCORDION MOBILE
===================================================== */

function initAccordion() {

  const accordion = document.querySelector(".accordion-horizontal");
  if (!accordion) return;

  const sections = accordion.querySelectorAll(".section");

  sections.forEach(section => {

    section.addEventListener("click", function (event) {

      const isMobile = window.innerWidth <= 768;

      if (!isMobile) return;

      if (!section.classList.contains("active")) {

        event.preventDefault();

        sections.forEach(s => s.classList.remove("active"));
        section.classList.add("active");
      }

    });
  });
}



/* =====================================================
   FONT SIZE
===================================================== */

function setFontSize(size) {

  const root = document.documentElement;

  if (size === "small") root.style.setProperty("--base-font-size", "10px");
  if (size === "medium") root.style.setProperty("--base-font-size", "17.5px");
  if (size === "large") root.style.setProperty("--base-font-size", "22px");

  document.querySelectorAll(".font-size-controls button")
    .forEach(btn => btn.classList.remove("selected"));

  document.querySelector(`[data-size="${size}"]`)
    ?.classList.add("selected");

  localStorage.setItem("fontSize", size);
}


/* =====================================================
   MOBILE NAV
===================================================== */

function toggleNav() {
  document.getElementById("mobileNav")?.classList.toggle("open");
  document.querySelector(".custom-navbar")?.classList.toggle("nav-open");
}