/* ============================================================
   YAS MARKETING â€” script.js
   GSAP + ScrollTrigger + Lenis animations
   ============================================================ */

(function () {
  'use strict';

  // ============================================================
  // 1. LENIS SMOOTH SCROLL & GSAP CONFIG
  // ============================================================
  gsap.config({ nullTargetWarn: false });

  const lenis = new Lenis({
    duration: 1.6,
    easing: (t) => Math.min(1, 1.001 - Math.pow(2, -10 * t)),
    direction: 'vertical',
    gestureDirection: 'vertical',
    smooth: true,
    smoothTouch: false,
    touchMultiplier: 2,
  });

  function lenisRaf(time) {
    lenis.raf(time);
    requestAnimationFrame(lenisRaf);
  }
  requestAnimationFrame(lenisRaf);

  lenis.on('scroll', ScrollTrigger.update);
  gsap.ticker.add((time) => { lenis.raf(time * 1000); });
  gsap.ticker.lagSmoothing(0);

  // ============================================================
  // 2. LOADER
  // ============================================================
  const loader = document.getElementById('loader');
  const loaderBar = document.getElementById('loader-bar');
  const loaderPercent = document.getElementById('loader-percent');

  let progress = 0;
  const interval = setInterval(() => {
    progress += Math.random() * 18;
    if (progress >= 100) {
      progress = 100;
      clearInterval(interval);
      loaderBar.style.width = '100%';
      loaderPercent.textContent = '100%';

      gsap.to(loader, {
        yPercent: -100,
        duration: 1.2,
        ease: 'power3.inOut',
        delay: 0.4,
        onComplete: () => {
          loader.style.display = 'none';
          initAnimations();
          if (typeof window.tryPlayWithSound === 'function') window.tryPlayWithSound();
        }
      });
    } else {
      loaderBar.style.width = progress + '%';
      loaderPercent.textContent = Math.floor(progress) + '%';
    }
  }, 80);

  // ============================================================
  // 3. CUSTOM CURSOR
  // ============================================================
  const cursorDot = document.getElementById('cursor-dot');
  const cursorRing = document.getElementById('cursor-ring');
  const cursorText = document.getElementById('cursor-text');

  let mouseX = window.innerWidth / 2;
  let mouseY = window.innerHeight / 2;
  let ringX = mouseX, ringY = mouseY;

  document.addEventListener('mousemove', (e) => {
    mouseX = e.clientX;
    mouseY = e.clientY;
    gsap.to(cursorDot, { x: mouseX, y: mouseY, duration: 0.1, ease: 'none' });
  });

  (function animateCursorRing() {
    ringX += (mouseX - ringX) * 0.1;
    ringY += (mouseY - ringY) * 0.1;
    gsap.set(cursorRing, { x: ringX, y: ringY });
    requestAnimationFrame(animateCursorRing);
  })();

  function addCursorHover(els, type, label) {
    els.forEach(el => {
      el.addEventListener('mouseenter', () => {
        document.body.classList.add('cursor-' + type);
        if (label) cursorText.textContent = label;
      });
      el.addEventListener('mouseleave', () => {
        document.body.classList.remove('cursor-' + type);
        cursorText.textContent = '';
      });
    });
  }

  addCursorHover(document.querySelectorAll('a, button'), 'hover', '');
  addCursorHover(document.querySelectorAll('.work-card'), 'view', 'VIEW');
  addCursorHover(document.querySelectorAll('.service-row'), 'hover', '');

  // ============================================================
  // 4. HEADER SCROLL BEHAVIOUR
  // ============================================================
  const header = document.getElementById('header');
  const menuBtn = document.getElementById('menu-btn');
  const navOverlay = document.getElementById('nav-overlay');

  lenis.on('scroll', ({ scroll }) => {
    header.classList.toggle('scrolled', scroll > 60);
  });

  // ============================================================
  // 5. NAV OVERLAY TOGGLE
  // ============================================================
  let navOpen = false;

  function openNav() {
    navOpen = true;
    navOverlay.classList.add('open');
    navOverlay.setAttribute('aria-hidden', 'false');
    header.classList.add('nav-open');
    menuBtn.setAttribute('aria-expanded', 'true');
    lenis.stop();
    document.body.style.overflow = 'hidden';
  }

  function closeNav() {
    navOpen = false;
    navOverlay.classList.remove('open');
    navOverlay.setAttribute('aria-hidden', 'true');
    header.classList.remove('nav-open');
    menuBtn.setAttribute('aria-expanded', 'false');
    lenis.start();
    document.body.style.overflow = '';
  }

  menuBtn.addEventListener('click', () => { if (navOpen) closeNav(); else openNav(); });
  document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && navOpen) closeNav(); });
  navOverlay.querySelectorAll('a').forEach(link => link.addEventListener('click', closeNav));

  // ============================================================
  // 6. SERVICE HOVER IMAGE â€” follows cursor
  // ============================================================
  document.querySelectorAll('.service-row').forEach(row => {
    const hoverImg = row.querySelector('.service-hover-img');
    if (!hoverImg) return;
    row.addEventListener('mousemove', (e) => {
      gsap.to(hoverImg, { x: e.clientX - 90, y: e.clientY - 90, duration: 0.5, ease: 'power2.out' });
    });
  });

  // ============================================================
  // 7. HERO PARALLAX ON MOUSE MOVE
  // ============================================================
  const heroBear = document.getElementById('hero-bear');
  const heroDare = document.getElementById('hero-dare');
  const heroDiff = document.getElementById('hero-different');

  document.addEventListener('mousemove', (e) => {
    if (!heroBear) return;
    const cx = window.innerWidth / 2;
    const cy = window.innerHeight / 2;
    const dx = (e.clientX - cx) / cx;
    const dy = (e.clientY - cy) / cy;
    gsap.to(heroBear, { x: dx * 20, y: dy * 15, rotateZ: dx * 3, duration: 0.8, ease: 'power2.out' });
    if (heroDare) gsap.to(heroDare, { x: dx * -10, duration: 0.8, ease: 'power2.out' });
    if (heroDiff) gsap.to(heroDiff, { x: dx * 10, duration: 0.8, ease: 'power2.out' });
  });

  // ============================================================
  // 8. MAGNETIC BUTTONS (BikeBear-style)
  // ============================================================
  document.querySelectorAll('.pill-btn, .menu-btn, .nav-badge-circle').forEach(btn => {
    btn.addEventListener('mousemove', (e) => {
      const rect = btn.getBoundingClientRect();
      const dx = (e.clientX - (rect.left + rect.width / 2)) * 0.35;
      const dy = (e.clientY - (rect.top + rect.height / 2)) * 0.35;
      gsap.to(btn, { x: dx, y: dy, duration: 0.3, ease: 'power2.out' });
    });
    btn.addEventListener('mouseleave', () => {
      gsap.to(btn, { x: 0, y: 0, duration: 0.6, ease: 'elastic.out(1, 0.4)' });
    });
  });

  // ============================================================
  // 9. WORK CARD 3-D TILT ON HOVER
  // ============================================================
  document.querySelectorAll('.work-card').forEach(card => {
    card.addEventListener('mousemove', (e) => {
      const r = card.getBoundingClientRect();
      const rx = ((e.clientY - r.top - r.height / 2) / (r.height / 2)) * -7;
      const ry = ((e.clientX - r.left - r.width / 2) / (r.width / 2)) * 7;
      gsap.to(card, { rotateX: rx, rotateY: ry, scale: 1.03, duration: 0.35, ease: 'power2.out', transformPerspective: 800 });
    });
    card.addEventListener('mouseleave', () => {
      gsap.to(card, { rotateX: 0, rotateY: 0, scale: 1, duration: 0.6, ease: 'power3.out' });
    });
  });

  // ============================================================
  // 10. CHAR-SPLIT HEADING REVEAL
  // ============================================================
  function splitAndAnimate(selector, triggerSelector, stagger) {
    document.querySelectorAll(selector).forEach(el => {
      const text = el.textContent.trim();
      el.innerHTML = text.split('').map(ch =>
        ch === ' '
          ? '<span style="display:inline-block;white-space:pre;"> </span>'
          : `<span style="display:inline-block;transform:translateY(110%);opacity:0;">${ch}</span>`
      ).join('');

      ScrollTrigger.create({
        trigger: triggerSelector || el,
        start: 'top 82%',
        once: true,
        onEnter: () => {
          gsap.to(el.querySelectorAll('span'), {
            y: 0, opacity: 1, duration: 0.8, ease: 'power3.out',
            stagger: stagger || 0.025,
          });
        }
      });
    });
  }

  // ============================================================
  // 11. MAIN ANIMATIONS  (called after loader exits)
  // ============================================================
  function initAnimations() {
    gsap.registerPlugin(ScrollTrigger);

    /* â”€â”€â”€ Hero entrance â”€â”€â”€ */
    gsap.timeline({ delay: 0.1 })
      .fromTo('#hero-dare', { yPercent: 120, opacity: 0 }, { yPercent: 0, opacity: 1, duration: 1.45, ease: 'power3.out' })
      .fromTo('.hero-bear', { y: 80, opacity: 0 }, { y: 0, opacity: 1, duration: 1.6, ease: 'power3.out' }, '-=0.9')
      .fromTo('.hero-ticker-bar', { opacity: 0 }, { opacity: 1, duration: 0.75 }, '-=0.4');

    /* Bear floating idle loop */
    gsap.to('.hero-bear', {
      y: '-=18', repeat: -1, yoyo: true, duration: 4, ease: 'sine.inOut', delay: 2
    });

    /* â”€â”€â”€ Char-split section headings â”€â”€â”€ */
    splitAndAnimate('.services-title', '.services', 0.02);
    splitAndAnimate('.work-title', '.work', 0.02);
    splitAndAnimate('.clients-title', '.clients', 0.02);

    /* â”€â”€â”€ Intro text lines â”€â”€â”€ */
    document.querySelectorAll('.intro-line').forEach((line, i) => {
      ScrollTrigger.create({
        trigger: line, start: 'top 85%',
        onEnter: () => gsap.to(line, { y: 0, duration: 1.25, ease: 'power3.out', delay: i * 0.1 })
      });
    });

    gsap.to('.intro-tag span', {
      scrollTrigger: { trigger: '.intro-tag', start: 'top 80%' },
      y: 0, opacity: 1, duration: 0.9, ease: 'power2.out'
    });

    gsap.from('.intro-sub > *', {
      scrollTrigger: { trigger: '.intro-sub', start: 'top 80%' },
      y: 30, opacity: 0, duration: 1.15, stagger: 0.18, ease: 'power2.out', delay: 0.4
    });

    /* â”€â”€â”€ Pawsible: orbit slow parallax â”€â”€â”€ */
    gsap.to('.pawsible-orbit', {
      scrollTrigger: { trigger: '.pawsible', start: 'top bottom', end: 'bottom top', scrub: 2 },
      y: -70, ease: 'none',
    });

    document.querySelectorAll('.paw-line').forEach((line, i) => {
      ScrollTrigger.create({
        trigger: '.pawsible', start: 'top 70%',
        onEnter: () => gsap.to(line, { y: 0, duration: 1.25, ease: 'power3.out', delay: i * 0.12 })
      });
    });

    /* â”€â”€â”€ Services stagger â”€â”€â”€ */
    gsap.from('.service-row', {
      scrollTrigger: { trigger: '.services-list', start: 'top 80%' },
      opacity: 0, y: 40, stagger: 0.12, duration: 1.0, ease: 'power2.out',
    });

    /* â”€â”€â”€ Service row: letter-spacing pulse on hover â”€â”€â”€ */
    document.querySelectorAll('.service-row').forEach(row => {
      const els = [row.querySelector('.service-name'), row.querySelector('.service-num')].filter(Boolean);
      row.addEventListener('mouseenter', () => gsap.to(els, { letterSpacing: '0.06em', duration: 0.3, ease: 'power2.out' }));
      row.addEventListener('mouseleave', () => gsap.to(els, { letterSpacing: '0em', duration: 0.3, ease: 'power2.out' }));
    });

    /* â”€â”€â”€ Work cards: clip-path reveal + depth â”€â”€â”€ */
    document.querySelectorAll('.work-card').forEach((card, i) => {
      gsap.fromTo(card,
        { clipPath: 'inset(100% 0 0 0)', opacity: 0, y: 50 },
        {
          scrollTrigger: { trigger: card, start: 'top 88%' },
          clipPath: 'inset(0% 0 0 0)',
          opacity: 1, y: 0,
          duration: 1.25, ease: 'power3.out',
          delay: (i % 2) * 0.15,
        }
      );
    });

    /* â”€â”€â”€ Work card images: Ken Burns parallax â”€â”€â”€ */
    document.querySelectorAll('.work-card-img').forEach(img => {
      gsap.fromTo(img,
        { scale: 1.12 },
        { scrollTrigger: { trigger: img, start: 'top bottom', end: 'bottom top', scrub: 1.3 }, scale: 1.0, ease: 'none' }
      );
    });

    /* â”€â”€â”€ Clients strip fade â”€â”€â”€ */
    gsap.from('.clients-track', {
      scrollTrigger: { trigger: '.clients', start: 'top 80%' },
      opacity: 0, duration: 1.0, ease: 'power2.out',
    });

    /* â”€â”€â”€ About counters â”€â”€â”€ */
    document.querySelectorAll('.stat-num').forEach(el => {
      ScrollTrigger.create({
        trigger: el, start: 'top 80%', once: true,
        onEnter: () => {
          const target = parseInt(el.dataset.target);
          const suffix = el.dataset.suffix || '';
          const obj = { val: 0 };
          gsap.to(obj, {
            val: target,
            duration: 2.5,
            ease: 'power2.out',
            onUpdate: () => { el.textContent = Math.round(obj.val) + suffix; }
          });
        }
      });
    });

    gsap.from('.about-stat', {
      scrollTrigger: { trigger: '.about-nums', start: 'top 75%' },
      y: 60, opacity: 0, stagger: 0.15, duration: 1.15, ease: 'power3.out'
    });

    /* â”€â”€â”€ Footer "SAY YAS!" â€” words slide in from opposite sides â”€â”€â”€ */
    /* --- Slide-in from sides: apply to ALL .slide-in-left / .slide-in-right --- */
    /* Mobile: balanced offset + smooth one-time animation */
    const isMobile = window.innerWidth < 768;
    const slideOffset = isMobile ? 60 : 120;
    const animateOffset = isMobile ? 46 : 70;

    if (isMobile) {
      /* Mobile: smooth visible motion when section enters view */
      document.querySelectorAll('.slide-in-left').forEach(el => {
        gsap.from(el, {
          scrollTrigger: { trigger: el.parentElement || el, start: 'top 88%', once: true },
          x: -slideOffset,
          duration: 0.9,
          ease: 'power2.inOut',
        });
      });
      document.querySelectorAll('.slide-in-right').forEach(el => {
        gsap.from(el, {
          scrollTrigger: { trigger: el.parentElement || el, start: 'top 88%', once: true },
          x: slideOffset,
          duration: 0.9,
          ease: 'power2.inOut',
        });
      });
      document.querySelectorAll('.animate-slide-left').forEach(el => {
        gsap.from(el, {
          scrollTrigger: { trigger: el.parentElement || el, start: 'top 88%', once: true },
          x: -animateOffset, duration: 0.85, ease: 'power2.inOut',
        });
      });
      document.querySelectorAll('.animate-slide-right').forEach(el => {
        gsap.from(el, {
          scrollTrigger: { trigger: el.parentElement || el, start: 'top 88%', once: true },
          x: animateOffset, duration: 0.85, ease: 'power2.inOut',
        });
      });
    } else {
      /* Desktop: scroll-linked scrub as before */
      document.querySelectorAll('.slide-in-left').forEach(el => {
        gsap.from(el, {
          scrollTrigger: { trigger: el.parentElement || el, start: 'top bottom', end: 'bottom top', scrub: 1.6 },
          x: -slideOffset,
          ease: 'none',
        });
      });
      document.querySelectorAll('.slide-in-right').forEach(el => {
        gsap.from(el, {
          scrollTrigger: { trigger: el.parentElement || el, start: 'top bottom', end: 'bottom top', scrub: 1.6 },
          x: slideOffset,
          ease: 'none',
        });
      });
      document.querySelectorAll('.animate-slide-left').forEach(el => {
        gsap.from(el, {
          scrollTrigger: { trigger: el.parentElement || el, start: 'top bottom', end: 'bottom top', scrub: 1.6 },
          x: -animateOffset, ease: 'none',
        });
      });
      document.querySelectorAll('.animate-slide-right').forEach(el => {
        gsap.from(el, {
          scrollTrigger: { trigger: el.parentElement || el, start: 'top bottom', end: 'bottom top', scrub: 1.6 },
          x: animateOffset, ease: 'none',
        });
      });
    }

    /* â”€â”€â”€ Footer contact stagger â”€â”€â”€ */
    gsap.from('.footer-contact-info > *', {
      scrollTrigger: { trigger: '.footer-contact-info', start: 'top 80%' },
      y: 30, opacity: 0, stagger: 0.15, duration: 1.0, ease: 'power2.out'
    });

    /* â”€â”€â”€ Footer social icons bounce-in â”€â”€â”€ */
    gsap.from('.footer-social, .nav-social', {
      scrollTrigger: { trigger: '.footer-bottom', start: 'top 90%' },
      scale: 0, opacity: 0, stagger: 0.12, duration: 0.65, ease: 'back.out(2)'
    });

    /* â”€â”€â”€ Section tags fade â”€â”€â”€ */
    gsap.utils.toArray('.section-tag').forEach(el => {
      gsap.from(el, {
        scrollTrigger: { trigger: el, start: 'top 85%' },
        y: 25, opacity: 0, duration: 0.9, ease: 'power2.out'
      });
    });

    /* â”€â”€â”€ Marquee strip reveal â”€â”€â”€ */
    gsap.from('.marquee-strip', {
      scrollTrigger: { trigger: '.marquee-strip', start: 'top 90%' },
      opacity: 0, duration: 0.9
    });

    /* â”€â”€â”€ Marquee speed ramps with scroll velocity â”€â”€â”€ */
    lenis.on('scroll', ({ velocity }) => {
      const speed = Math.max(0.4, 1 + Math.min(Math.abs(velocity) * 0.04, 3));
      document.querySelectorAll('.ticker-track').forEach(t => {
        t.style.animationDuration = (28 / speed) + 's';
      });
      document.querySelectorAll('.strip-track').forEach(t => {
        t.style.animationDuration = (28 / speed) + 's';
      });
    });

    ScrollTrigger.refresh();
  }

  // ============================================================
  // 12. SMOOTH ANCHOR SCROLL
  // ============================================================
  document.querySelectorAll('a[href^="#"]').forEach(a => {
    a.addEventListener('click', function (e) {
      const href = this.getAttribute('href');
      if (!href || href === '#') return;
      const target = document.querySelector(href);
      if (target) {
        e.preventDefault();
        lenis.scrollTo(target, { offset: -80, duration: 1.8 });
      }
    });
  });

  // ============================================================
  // 13. NAV BADGE CONTINUOUS SPIN
  // ============================================================
  gsap.to('.badge-rotate-text', {
    rotation: 360,
    repeat: -1,
    duration: 12,
    ease: 'linear',
    transformOrigin: '50% 50%',
  });

  const navBadge = document.getElementById('nav-badge');
  if (navBadge) {
    navBadge.addEventListener('mouseenter', () => gsap.to('.badge-rotate-text', { duration: 5, rotation: '+=360', ease: 'linear', overwrite: true, repeat: -1 }));
    navBadge.addEventListener('mouseleave', () => gsap.to('.badge-rotate-text', { duration: 12, rotation: '+=360', ease: 'linear', overwrite: true, repeat: -1 }));
  }

  // ============================================================
  // 14. ORBIT SVG â€” continuous rotate
  // ============================================================
  gsap.to('.orbit-svg', {
    rotation: 360,
    repeat: -1,
    duration: 14,
    ease: 'linear',
    transformOrigin: '50% 50%',
  });

  // ============================================================
  // 15. COLOR SWITCHER
  // ============================================================
  const colorSwitcher = document.getElementById('color-switcher');
  const colorSwitcherBtn = document.getElementById('color-switcher-btn');
  const colorSwitcherPanel = document.getElementById('color-switcher-panel');
  const colorSwatches = document.querySelectorAll('.color-swatch');

  let switcherOpen = false;

  function openSwitcher() {
    switcherOpen = true;
    colorSwitcher.classList.add('open');
    colorSwitcherPanel.setAttribute('aria-hidden', 'false');
  }

  function closeSwitcher() {
    switcherOpen = false;
    colorSwitcher.classList.remove('open');
    colorSwitcherPanel.setAttribute('aria-hidden', 'true');
  }

  colorSwitcherBtn.addEventListener('click', (e) => {
    e.stopPropagation();
    if (switcherOpen) closeSwitcher(); else openSwitcher();
  });

  // Close when clicking outside
  document.addEventListener('click', (e) => {
    if (switcherOpen && !colorSwitcher.contains(e.target)) closeSwitcher();
  });

  // Swap --main-color on swatch click
  colorSwatches.forEach(swatch => {
    swatch.addEventListener('click', () => {
      const color = swatch.dataset.color;
      document.documentElement.style.setProperty('--main-color', color);

      // Update active state
      colorSwatches.forEach(s => s.classList.remove('active'));
      swatch.classList.add('active');

      // Animate the button border to match
      gsap.to(colorSwitcherBtn, {
        borderColor: color,
        color: color,
        duration: 0.3,
        ease: 'power2.out',
      });

      // Brief pulse effect on the button
      gsap.fromTo(colorSwitcherBtn,
        { scale: 1.2 },
        { scale: 1, duration: 0.4, ease: 'elastic.out(1, 0.5)' }
      );
    });
  });

  // Register swatches with cursor
  addCursorHover(colorSwatches, 'hover', '');
  addCursorHover([colorSwitcherBtn], 'hover', '');

  // ============================================================
  // 16. WINDOW RESIZE
  // ============================================================
  let resizeTimeout;
  window.addEventListener('resize', () => {
    clearTimeout(resizeTimeout);
    resizeTimeout = setTimeout(() => ScrollTrigger.refresh(), 200);
  });

  // ============================================================
  // 17. BACKGROUND AUDIO — autoplay with sound on page load
  // ============================================================
  const bgAudio = document.getElementById('bg-audio');
  const audioBtn = document.getElementById('audio-btn');
  const iconUnmuted = document.getElementById('icon-unmuted');
  const iconMuted = document.getElementById('icon-muted');

  function updateAudioIcons() {
    if (!iconUnmuted || !iconMuted) return;
    if (bgAudio.muted || bgAudio.paused) {
      iconUnmuted.style.display = 'none';
      iconMuted.style.display = 'block';
    } else {
      iconUnmuted.style.display = 'block';
      iconMuted.style.display = 'none';
    }
  }

  function tryPlayWithSound() {
    if (!bgAudio) return;
    bgAudio.muted = false;
    const p = bgAudio.play();
    if (p && typeof p.then === 'function') {
      p.then(() => updateAudioIcons()).catch(() => updateAudioIcons());
    } else {
      updateAudioIcons();
    }
  }
  window.tryPlayWithSound = tryPlayWithSound;

  if (bgAudio) {
    // Try to play with sound as soon as script runs (page load)
    tryPlayWithSound();

    // If blocked, retry on first user interaction
    const playOnInteraction = () => {
      tryPlayWithSound();
      ['click', 'scroll', 'touchstart', 'keydown'].forEach(evt =>
        document.removeEventListener(evt, playOnInteraction)
      );
    };
    ['click', 'scroll', 'touchstart', 'keydown'].forEach(evt =>
      document.addEventListener(evt, playOnInteraction, { once: true, passive: evt !== 'keydown' })
    );

    // Sync icons with actual state (e.g. if autoplay was blocked)
    bgAudio.addEventListener('play', updateAudioIcons);
    bgAudio.addEventListener('pause', updateAudioIcons);
    updateAudioIcons();
  }

  if (audioBtn && bgAudio) {
    audioBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      if (bgAudio.muted) {
        bgAudio.muted = false;
        if (bgAudio.paused) bgAudio.play();
        iconUnmuted.style.display = 'block';
        iconMuted.style.display = 'none';
      } else {
        bgAudio.muted = true;
        iconUnmuted.style.display = 'none';
        iconMuted.style.display = 'block';
      }
    });
    addCursorHover([audioBtn], 'hover', '');
  }

})();

Explain