/* =============================================================================
   GSAP starter template

   Load order: gsap, ScrollTrigger, SplitText (GSAP 3.13+), then this file.

   Add these classes to your elements in Webflow:
     .anim-intro                         fades up on load
     .anim-menu-toggle, .anim-menu       menu button and panel

   Tip: classes can be renamed by accident in the designer. If you want safer
   hooks, use attributes instead, e.g. data-anim="intro"

============================================================================= */

// Runs one feature in try/catch so a single error never stops the others.
function run(feature, arg) {
  try {
    return feature(arg);
  } catch (error) {
    console.error(`[gsap] ${feature.name} failed:`, error);
  }
}

// Checks that every selector passed in exists before an animation runs
function pageGuard(...selectors) {
  return selectors.every((sel) => document.querySelector(sel));
}

/* =============================================================================
   BOOT
   The only place features start. Add or remove names to turn them on or off.
   Placing it above the features is fine because function declarations are
   hoisted. Just keep the features as "function name() {}", not as const arrows.
============================================================================= */

const mm = gsap.matchMedia();

document.addEventListener("DOMContentLoaded", () => {
  [prioritizeImages, preloader, navAnim, galleryAnim, videoPlayback].forEach(
    (f) => run(f)
  );

  mm.add(
    {
      isDesktop: "(min-width: 992px)",
      isMobile: "(max-width: 991px)",
    },
    (ctx) => {
      const { isDesktop, isMobile } = ctx.conditions;

      if (isDesktop) return run(imageRevealDesktop);
      if (isMobile) return run(imageRevealMobile);
    }
  );
});

window.addEventListener("load", () => {
  [].forEach((f) => run(f));
});

/* =============================================================================
   FEATURES
   Each one returns early if its elements are not on the page, so this single
   file can safely load on every page of the site.
============================================================================= */

/* DOM READY features: no measuring needed, so they can start early. */

function prioritizeImages() {
  const imgs = document.querySelectorAll(".horiz-scroll-desktop img");

  imgs.forEach((img, i) => {
    img.decoding = "async";

    if (i >= 5) return; // leave the rest lazy

    img.loading = "eager";

    // Only the first two get high priority, since priority is relative
    if (i < 2) img.fetchPriority = "high";
  });
}

function preloader() {
  if (!pageGuard("#noni-preloader-video")) {
    autoScroll();
    return;
  }

  const noniPreloader = document.querySelector(".noni-preloader-wrapper");
  const videoParent = document.getElementById("noni-preloader-video");
  const video = videoParent.firstElementChild;
  const logo = document.getElementById("noni-logo-preloader");

  // true: assume the address bar is at the top, so pin the logo to the bottom edge
  // false: assume the address bar is at the bottom, so pin the logo to the top edge
  // Safari on iPhone and iPad defaults to a bottom bar. Chrome, Firefox and Edge
  // on iOS (CriOS, FxiOS, EdgiOS), and all other browsers, default to the top.
  const ua = navigator.userAgent;
  const TOP_ADDRESS_BAR =
    !/iPhone|iPad/i.test(ua) || /CriOS|FxiOS|EdgiOS/i.test(ua);

  let finished = false;

  // Optional: stop page scroll while the preloader is running
  document.documentElement.style.overflow = "hidden";

  // Pins the logo at its current on-screen spot using pixel values
  function lockLogo() {
    const r = logo.getBoundingClientRect(); // where it is right now (includes scale)
    const w = logo.offsetWidth; // layout size (unscaled)
    const h = logo.offsetHeight;

    // Reset to a known origin so we can measure the offset
    logo.style.position = "fixed";
    logo.style.margin = "0";
    logo.style.right = "auto";
    logo.style.bottom = "auto";
    logo.style.top = "0px";
    logo.style.left = "0px";
    logo.style.width = w + "px";
    logo.style.height = h + "px";

    // Move it back to exactly where it was (horizontal always from the left)
    const o = logo.getBoundingClientRect();
    logo.style.left = r.left - o.left + "px";

    if (TOP_ADDRESS_BAR) {
      // Top address bar: the bottom edge never moves, so pin to it
      logo.style.top = "auto";
      logo.style.bottom = "0px";
      const b = logo.getBoundingClientRect();
      logo.style.bottom = b.bottom - r.bottom + "px";
    } else {
      // Bottom address bar: the top edge never moves, so pin to it
      logo.style.top = r.top - o.top + "px";
    }

    // Release the scroll lock
    document.documentElement.style.overflow = "";
  }

  function finish() {
    if (finished) return; // guards against running twice
    finished = true;

    const tl = gsap.timeline({ onComplete: lockLogo });

    tl.set(logo, {
      opacity: 1,
      onComplete: () => {
        videoParent.style.display = "none";
      },
    })
      .to(logo, { left: "30%", scale: 0.6, duration: 0.6 })
      .to(noniPreloader, {
        opacity: 0,
        duration: 0.6,
        onComplete: () => {
          noniPreloader.style.display = "none";
        },
      })
      .to(logo, { opacity: 0.5, duration: 0.6 }, "<")
      .call(autoScroll, null, "-=.5");
  }

  video.addEventListener("ended", finish);

  // Force a clean start
  video.muted = true;
  video.playsInline = true;
  video.defaultPlaybackRate = 1.5;
  video.playbackRate = 1.5;
  video.currentTime = 0;

  const attempt = video.play();
  if (attempt !== undefined) {
    attempt.catch(() => finish()); // autoplay refused, so skip the video
  }
}

function autoScroll() {
  const viewport = document.getElementById("viewport");
  const autoplay = !!document.getElementById("track");
  const track =
    document.getElementById("track") || document.querySelector(".main-wrapper");

  if (!track) return;

  if (viewport) {
    viewport.tabIndex = -1;
  }

  const SPEED = 100;
  const TOUCHPAD_SENSITIVITY = 1;
  const SMOOTHING = 0.08; // lower = smoother and slower to catch up, higher = more responsive

  let position = 0;
  let target = 0;
  let direction = 0;
  let manualFrame = null;
  let lastTime = 0;
  let controlled = false;

  let rafId = null;
  let lastTick = 0;

  let animation = null;
  let maxScroll = 0;
  let duration = 0;

  track.style.willChange = "transform";

  // --------------------------------
  // GET SCROLL DISTANCE
  // --------------------------------

  function getMaxScroll() {
    return Math.max(0, track.scrollWidth - window.innerWidth);
  }

  // --------------------------------
  // START AUTO SCROLL
  // --------------------------------

  function startAnimation() {
    maxScroll = getMaxScroll();

    if (!autoplay) {
      controlled = true;
      return;
    }

    console.log("Scroll measurement:", {
      trackWidth: track.scrollWidth,
      windowWidth: window.innerWidth,
      maxScroll,
    });

    if (!maxScroll) {
      console.log("autoScroll: no horizontal overflow");
      return;
    }

    duration = (maxScroll / SPEED) * 1000;

    console.log("Starting animation:", {
      maxScroll,
      duration,
    });

    animation = track.animate(
      [
        { transform: "translate3d(0, 0, 0)" },
        { transform: `translate3d(${-maxScroll}px, 0, 0)` },
      ],
      {
        duration,
        easing: "linear",
        fill: "forwards",
      }
    );
  }

  // --------------------------------
  // PAUSE WHEN TAB IS HIDDEN
  // --------------------------------

  // Don't let the scroll run while the tab is in the background
  function syncWithVisibility() {
    if (controlled || !animation) return;

    if (document.hidden) {
      if (animation.playState === "running") animation.pause();
    } else if (animation.playState === "paused") {
      animation.play();
    }
  }

  // --------------------------------
  // START ONCE
  // --------------------------------

  startAnimation();
  syncWithVisibility(); // handles a page opened in a background tab
  document.addEventListener("visibilitychange", syncWithVisibility);

  // --------------------------------
  // RESIZE
  // --------------------------------

  let resizeTimer;

  window.addEventListener("resize", () => {
    clearTimeout(resizeTimer);

    resizeTimer = setTimeout(() => {
      if (controlled) return;

      const newMaxScroll = getMaxScroll();

      // Nothing changed, so don't restart.
      if (newMaxScroll === maxScroll) {
        return;
      }

      console.log("Track size changed. Recalculating...");

      // Capture current progress before replacing animation.
      const currentTime = animation?.currentTime || 0;
      const progress = duration > 0 ? currentTime / duration : 0;

      if (animation) {
        animation.cancel();
      }

      maxScroll = newMaxScroll;
      duration = (maxScroll / SPEED) * 1000;

      if (!maxScroll) {
        return;
      }

      animation = track.animate(
        [
          { transform: "translate3d(0, 0, 0)" },
          { transform: `translate3d(${-maxScroll}px, 0, 0)` },
        ],
        {
          duration,
          easing: "linear",
          fill: "forwards",
        }
      );

      animation.currentTime = Math.min(1, progress) * duration;
      syncWithVisibility();
    }, 150);
  });

  // --------------------------------
  // RESIZE OBSERVER
  // --------------------------------

  // This catches layout changes caused by Webflow without waiting for every image to load.
  let lastTrackWidth = track.scrollWidth;

  const resizeObserver = new ResizeObserver(() => {
    const currentTrackWidth = track.scrollWidth;

    if (currentTrackWidth === lastTrackWidth) {
      return;
    }

    lastTrackWidth = currentTrackWidth;

    if (controlled) return;

    const newMaxScroll = getMaxScroll();

    if (newMaxScroll === maxScroll) {
      return;
    }

    console.log("Track width changed:", currentTrackWidth);

    const currentTime = animation?.currentTime || 0;
    const progress = duration > 0 ? currentTime / duration : 0;

    if (animation) {
      animation.cancel();
    }

    maxScroll = newMaxScroll;
    duration = (maxScroll / SPEED) * 1000;

    if (!maxScroll) {
      return;
    }

    animation = track.animate(
      [
        { transform: "translate3d(0, 0, 0)" },
        { transform: `translate3d(${-maxScroll}px, 0, 0)` },
      ],
      {
        duration,
        easing: "linear",
        fill: "forwards",
      }
    );

    // Continue from approximately the same point instead of jumping back to zero.
    animation.currentTime = Math.min(1, progress) * duration;
    syncWithVisibility();
  });

  resizeObserver.observe(track);

  // --------------------------------
  // TAKE MANUAL CONTROL
  // --------------------------------

  function takeControl() {
    if (controlled || !animation) {
      return;
    }

    const currentTime = animation.currentTime || 0;

    position = Math.max(
      0,
      Math.min(maxScroll, (currentTime / duration) * maxScroll)
    );
    target = position;

    animation.cancel();
    track.style.transform = `translate3d(${-position}px, 0, 0)`;
    controlled = true;
  }

  // --------------------------------
  // SMOOTH POSITION
  // --------------------------------

  function tick(time) {
    const dt = lastTick ? Math.min(50, time - lastTick) : 16.67;
    lastTick = time;

    // Frame rate independent easing toward the target
    const ease = 1 - Math.pow(1 - SMOOTHING, dt / 16.67);
    position += (target - position) * ease;

    if (Math.abs(target - position) < 0.1) {
      position = target;
      rafId = null;
      lastTick = 0;
    } else {
      rafId = requestAnimationFrame(tick);
    }

    track.style.transform = `translate3d(${-position}px, 0, 0)`;
  }

  function setPosition(value) {
    maxScroll = getMaxScroll();
    target = Math.max(0, Math.min(maxScroll, value));

    if (!rafId) {
      rafId = requestAnimationFrame(tick);
    }
  }

  // --------------------------------
  // TRACKPAD
  // --------------------------------

  if (viewport) {
    viewport.addEventListener(
      "wheel",
      (e) => {
        if (Math.abs(e.deltaY) <= Math.abs(e.deltaX)) {
          return;
        }

        e.preventDefault();

        if (document.activeElement !== viewport) {
          viewport.focus({ preventScroll: true });
        }

        takeControl();
        setPosition(target + e.deltaY * TOUCHPAD_SENSITIVITY);
      },
      { passive: false }
    );
  }

  // --------------------------------
  // KEYBOARD
  // --------------------------------

  function manualScroll(time) {
    if (!direction) {
      manualFrame = null;
      lastTime = 0;
      return;
    }

    if (!lastTime) {
      lastTime = time;
    }

    const delta = Math.min(50, time - lastTime);
    lastTime = time;

    setPosition(target + direction * SPEED * (delta / 1000));
    manualFrame = requestAnimationFrame(manualScroll);
  }

  if (viewport) {
    viewport.addEventListener("keydown", (e) => {
      if (e.key !== "ArrowUp" && e.key !== "ArrowDown") {
        return;
      }

      e.preventDefault();
      takeControl();

      direction = e.key === "ArrowUp" ? -1 : 1;

      if (!manualFrame) {
        manualFrame = requestAnimationFrame(manualScroll);
      }
    });

    viewport.addEventListener("keyup", (e) => {
      if (e.key === "ArrowUp" || e.key === "ArrowDown") {
        direction = 0;
      }
    });

    viewport.addEventListener("blur", () => {
      direction = 0;

      if (manualFrame) {
        cancelAnimationFrame(manualFrame);
        manualFrame = null;
      }

      lastTime = 0;
    });
  }
}

function navAnim() {
  if (!pageGuard("#nav-gallery", "#nav-buttons-wrapper")) return;

  const navGallery = document.querySelector("#nav-gallery");
  const navButtonsWrapper = document.querySelector("#nav-buttons-wrapper");
  const navMenu = document.querySelector(".menu-wrapper.nav");

  const images = navGallery.querySelectorAll(".gallery-image");
  const buttons = navButtonsWrapper.querySelectorAll(".menu-button");
  const navBtn = document.querySelectorAll(
    ".nav-icon-wrapper.open, .nav-icon-wrapper.close"
  );

  window.addEventListener("load", () => preloadNavImages(images));

  function getDefaultIndex() {
    const currentPath = window.location.pathname.replace(/\/$/, "");
    let idx = -1;

    buttons.forEach((btn, i) => {
      const btnPath = new URL(btn.href).pathname.replace(/\/$/, "");
      if (btnPath === currentPath) idx = i;
    });

    return idx !== -1 ? idx : 0;
  }

  const defaultIndex = getDefaultIndex();
  let menuTl;

  navBtn.forEach((btn) => {
    btn.addEventListener("click", () => {
      if (menuTl) menuTl.kill();

      if (getComputedStyle(navMenu).display === "none") {
        menuTl = gsap
          .timeline()
          .set(navMenu, { display: "block" })
          .to(navMenu, { opacity: 1, duration: 0.6, ease: "power2.in" });
      } else {
        menuTl = gsap
          .timeline()
          .to(navMenu, { opacity: 0, duration: 0.6, ease: "power2.in" })
          .set(navMenu, { display: "none" });
      }
    });
  });

  let navTl;

  function setActive(activeIndex) {
    if (navTl) navTl.kill();

    navTl = gsap.timeline();

    images.forEach((image, index) => {
      navTl.set(image, { zIndex: index === activeIndex ? 2 : 1 }, 0);
    });

    navTl
      .to(images[activeIndex], {
        opacity: 1,
        duration: 0.4,
        ease: "power2.out",
      })
      .addLabel("activeDone");

    images.forEach((image, index) => {
      if (index !== activeIndex) {
        navTl.set(image, { opacity: 0 }, "activeDone");
      }
    });

    buttons.forEach((button, index) => {
      navTl.to(
        button,
        {
          opacity: index === activeIndex ? 1 : 0.5,
          duration: 0.6,
        },
        0
      );
    });
  }

  // Set initial state on load
  setActive(defaultIndex);

  buttons.forEach((button, index) => {
    button.addEventListener("mouseenter", () => setActive(index));
  });

  // Reset to default page state when mouse leaves the menu
  navMenu.addEventListener("mouseleave", () => setActive(defaultIndex));
}

function preloadNavImages(elements) {
  elements.forEach((el) => {
    const bg = getComputedStyle(el).backgroundImage;
    for (const m of bg.matchAll(/url\(\s*"([^"]+)"\s*\)/g)) {
      new Image().src = m[1];
    }
  });
}

function galleryAnim() {
  if (!pageGuard("#menu-gallery", "#menu-buttons-wrapper")) return;

  const menuGallery = document.querySelector("#menu-gallery");
  const menuButtonsWrapper = document.querySelector("#menu-buttons-wrapper");

  const images = menuGallery.querySelectorAll(".gallery-image");
  const buttons = menuButtonsWrapper.querySelectorAll(".menu-button");

  function getDefaultIndex() {
    const currentPath = window.location.pathname.replace(/\/$/, "");
    let idx = -1;

    buttons.forEach((btn, i) => {
      const btnPath = new URL(btn.href).pathname.replace(/\/$/, "");
      if (btnPath === currentPath) idx = i;
    });

    return idx !== -1 ? idx : 0;
  }

  const defaultIndex = getDefaultIndex();
  let tl;

  function setActive(activeIndex) {
    if (tl) tl.kill();

    tl = gsap.timeline();

    images.forEach((image, index) => {
      tl.set(image, { zIndex: index === activeIndex ? 2 : 1 }, 0);
    });

    tl.to(images[activeIndex], {
      opacity: 1,
      duration: 0.4,
      ease: "power2.out",
    }).addLabel("activeDone");

    images.forEach((image, index) => {
      if (index !== activeIndex) {
        tl.set(image, { opacity: 0 }, "activeDone");
      }
    });

    buttons.forEach((button, index) => {
      tl.to(
        button,
        {
          opacity: index === activeIndex ? 1 : 0.5,
          duration: 0.6,
        },
        0
      );
    });
  }

  // Set initial state on load
  setActive(defaultIndex);

  buttons.forEach((button, i) => {
    button.addEventListener("mouseenter", () => setActive(i));
  });
}

function decodeQueue(imgs, concurrency = 2) {
  const queue = [...imgs];
  const worker = async () => {
    while (queue.length) {
      const img = queue.shift();
      try {
        await img.decode(); // waits for load, then decodes off the main thread
      } catch (e) {}
    }
  };
  return Promise.all(Array.from({ length: concurrency }, worker));
}

function setupReveal({ selector, childSelector, root, childScale }) {
  const images = document.querySelectorAll(selector);
  if (!images.length) return;

  // FIX 1: tell the browser the real rendered width so it picks a smaller
  // srcset file instead of the 2000px to 2500px one.
  // clientWidth is 0 for the hidden desktop/tablet copy, so it is skipped.
  images.forEach((el) => {
    const img = el.querySelector("img");
    if (img && img.clientWidth) {
      img.sizes = Math.ceil(img.clientWidth * 1.05) + "px"; // 1.05 covers the zoom
    }
  });

  // Hidden state: nearly transparent, never visibility:hidden,
  // so the browser still decodes and rasterizes these layers.
  // FIX 2: no will-change here. WAAPI promotes the layer when the animation starts.
  images.forEach((image) => {
    image.style.opacity = "0.001";
    image.style.scale = "0.9";

    const child = image.querySelector(childSelector);
    if (child) {
      child.style.scale = "0.9";
    }
  });

  // Decode everything ahead of time, in page order (runs during the preloader)
  const imgEls = [...images]
    .map((el) => el.querySelector("img"))
    .filter(Boolean);
  decodeQueue(imgEls, 2);

  function reveal(image) {
    const child = image.querySelector(childSelector);

    const timing = {
      duration: 1000,
      easing: "cubic-bezier(0.215, 0.61, 0.355, 1)", // close to power2.out
      fill: "forwards",
    };

    const a = image.animate({ opacity: [0.001, 1], scale: [0.9, 1] }, timing);
    a.onfinish = () => {
      image.style.opacity = "1";
      image.style.scale = "1";
      a.cancel();
    };

    if (child) {
      const c = child.animate({ scale: [0.9, childScale] }, timing);
      c.onfinish = () => {
        child.style.scale = String(childScale);
        c.cancel();
      };
    }
  }

  const observer = new IntersectionObserver(
    (entries, obs) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        obs.unobserve(entry.target);
        reveal(entry.target);
      });
    },
    { root, threshold: 0.35 } // same trigger as your original
  );

  images.forEach((img) => observer.observe(img));

  return () => observer.disconnect();
}

function imageRevealDesktop() {
  return setupReveal({
    selector: ".image-desktop:not(:has(video))",
    childSelector: ".image-child-desktop:not(.no-zoom)",
    root: document.getElementById("viewport") || null,
    childScale: 1.05,
  });
}

function imageRevealMobile() {
  return setupReveal({
    selector: ".image-tablet:not(:has(video))",
    childSelector: ".image-child-tablet:not(.no-zoom)",
    root: null,
    childScale: 1.02,
  });
}

function videoPlayback() {
  const videos = document.querySelectorAll("#track video");
  if (!videos.length) return;

  videos.forEach((v) => {
    v.muted = true; // required for play() without a user gesture
    v.playsInline = true;
    v.preload = "metadata"; // don't download all 11 MB until needed
    v.pause(); // make sure nothing is running from the start
  });

  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        const v = entry.target;
        if (entry.isIntersecting) {
          const p = v.play();
          if (p !== undefined) p.catch(() => {}); // ignore blocked or interrupted plays
        } else {
          v.pause();
        }
      });
    },
    {
      root: null,
      // Start slightly before the video is visible so it is already playing
      // when it slides in. Left/right for desktop, top/bottom for mobile.
      rootMargin: "10% 25% 10% 25%",
      threshold: 0,
    }
  );

  videos.forEach((v) => observer.observe(v));
}