document.addEventListener('DOMContentLoaded', () => {
  // --- Full-page loader (logo) until window load, then reveal UI ---
  const pageLoader = document.getElementById('pageLoader');

  function revealPageAfterLoader() {
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        document.body.classList.add('page-loaded');
      });
    });
  }

  if (pageLoader) {
    const loaderReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

    function hideLoader() {
      pageLoader.classList.add('page-loader--hide');
      pageLoader.setAttribute('aria-busy', 'false');
      document.body.classList.remove('is-loading');

      function onLoaderTransitionEnd(e) {
        if (e.target !== pageLoader) return;
        pageLoader.removeEventListener('transitionend', onLoaderTransitionEnd);
        revealPageAfterLoader();
      }

      if (loaderReducedMotion) {
        revealPageAfterLoader();
        return;
      }

      pageLoader.addEventListener('transitionend', onLoaderTransitionEnd);
      window.setTimeout(() => {
        if (!document.body.classList.contains('page-loaded')) {
          revealPageAfterLoader();
        }
      }, 700);
    }

    if (document.readyState === 'complete') {
      hideLoader();
    } else {
      window.addEventListener('load', hideLoader, { once: true });
    }
  } else {
    requestAnimationFrame(() => {
      requestAnimationFrame(() => {
        document.body.classList.add('page-loaded');
      });
    });
  }

  // --- Header Scroll Effect ---
  const header = document.querySelector('.header');
  window.addEventListener('scroll', () => {
    if (window.scrollY > 50) {
      header.classList.add('scrolled');
    } else {
      header.classList.remove('scrolled');
    }
  });

  // --- Mobile Menu Toggle ---
  const menuBtn = document.querySelector('.menu-btn');
  const nav = document.querySelector('.nav');

  if (menuBtn && nav) {
    menuBtn.addEventListener('click', () => {
      nav.classList.toggle('active');
      // Animate hamburger to X
      const spans = menuBtn.querySelectorAll('span');
      if (nav.classList.contains('active')) {
        spans[0].style.transform = 'rotate(45deg) translate(5px, 5px)';
        spans[1].style.opacity = '0';
        spans[2].style.transform = 'rotate(-45deg) translate(12px, -12px)';
      } else {
        spans[0].style.transform = 'none';
        spans[1].style.opacity = '1';
        spans[2].style.transform = 'none';
      }
    });
  }

  // --- Smooth Scroll for Anchor Links ---
  document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
      const targetId = this.getAttribute('href');
      if (targetId === '#') return;

      const targetElement = document.querySelector(targetId);
      if (targetElement) {
        e.preventDefault();

        // Close mobile menu if open
        if (nav && nav.classList.contains('active')) {
          nav.classList.remove('active');
          const spans = menuBtn.querySelectorAll('span');
          spans[0].style.transform = 'none';
          spans[1].style.opacity = '1';
          spans[2].style.transform = 'none';
        }

        window.scrollTo({
          top: targetElement.offsetTop - 80, // adjust for header height
          behavior: 'smooth'
        });
      }
    });
  });

  // --- Reveal elements on scroll (smooth entrance site-wide) ---
  const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;

  const observerOptions = {
    threshold: 0.06,
    rootMargin: '0px 0px -32px 0px'
  };

  const revealObserver = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
      if (!entry.isIntersecting) return;
      entry.target.classList.add('reveal-visible');
      revealObserver.unobserve(entry.target);
    });
  }, observerOptions);

  function revealStagger(selector, delayStep = 0.07, baseDelay = 0) {
    document.querySelectorAll(selector).forEach((el, i) => {
      el.classList.add('reveal-item');
      if (!prefersReducedMotion) {
        el.style.transitionDelay = `${baseDelay + i * delayStep}s`;
      }
      revealObserver.observe(el);
    });
  }

  function revealSingle(selector) {
    document.querySelectorAll(selector).forEach((el) => {
      el.classList.add('reveal-item');
      revealObserver.observe(el);
    });
  }

  function revealFade(selector) {
    document.querySelectorAll(selector).forEach((el) => {
      el.classList.add('reveal-fade');
      revealObserver.observe(el);
    });
  }

  if (!prefersReducedMotion) {
    revealSingle([
      '.section-title',
      '.projects-intro',
      '.projects-cta',
      '.deliver-tagline',
      '.say-yas-desc',
      '.about_side',
      '.about_head p',
      '.say-yas-tagline',
      '.say-yas-btn',
      '.inner-hero__eyebrow',
      '.inner-hero__lead',
      '.inner-section__title',
      '.contact-aside',
      '.process-line',
      '.about-page-hero__tagline',
      '.project-detail-breadcrumb',
      '.project-detail-hero__titles',
      '.project-detail-intro__inner',
      '.project-detail-gallery-section .project-detail-section-title',
      '.project-detail-gallery-hint',
      '.related-projects .project-detail-section-title'
    ].join(', '));

    revealStagger('.main_title span', 0.18, 0.05);
    revealStagger('.about_text .btn', 0.08, 0.15);
    revealStagger('.project-card', 0.08, 0);
    revealStagger('.clients-page .partner-item', 0.05, 0);
    revealStagger('.stat', 0.07, 0);
    revealStagger('.services-list li', 0.06, 0);
    revealStagger('.contact-item', 0.08, 0);
    revealStagger('.inner-section p', 0.05, 0);
    revealStagger('.inner-section .inner-section__lead', 0.05, 0);
    revealStagger('.locations-list li', 0.04, 0);
    revealStagger('.contact-page-form .form-group', 0.05, 0);
    revealStagger('.about-page-hero__cell', 0.06, 0);
    revealStagger('.about-page-thumb', 0.07, 0);
    revealStagger('.about-page-stack__item', 0.08, 0);
    revealStagger('.about-page-mosaic__item', 0.06, 0);
    revealStagger('.about-page-client-strip img', 0.04, 0);
    revealStagger('.about-page-where__grid img', 0.06, 0);
    revealStagger('.project-detail-gallery__cell', 0.05, 0);
    revealFade('.testimonials-carousel');
  }

  // --- Stats counter: count up when section is in view ---
  const statsSection = document.querySelector('.stats-section');
  const statNums = document.querySelectorAll('.stat-num[data-count]');

  function animateValue(el, end, suffix, duration) {
    const start = 0;
    const startTime = performance.now();
    suffix = suffix || '';

    function update(currentTime) {
      const elapsed = currentTime - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const easeOutQuart = 1 - Math.pow(1 - progress, 4);
      const value = Math.floor(easeOutQuart * (end - start) + start);
      el.textContent = value + suffix;
      if (progress < 1) requestAnimationFrame(update);
    }

    requestAnimationFrame(update);
  }

  const statsObserver = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        statsObserver.unobserve(entry.target);
        statNums.forEach((el, i) => {
          const count = parseInt(el.getAttribute('data-count'), 10);
          const suffix = el.getAttribute('data-suffix') || '';
          const delay = i * 120;
          setTimeout(() => {
            animateValue(el, count, suffix, 1600);
          }, delay);
        });
      });
    },
    { threshold: 0.25, rootMargin: '0px' }
  );

  if (statsSection) statsObserver.observe(statsSection);

  // --- Testimonials Carousel (Owl Carousel) ---
  function initTestimonialsCarousel() {
    if (typeof window.jQuery === 'undefined' || !window.jQuery.fn.owlCarousel) return;
    const $ = window.jQuery;
    const $testimonials = $('.testimonials-carousel');
    if (!$testimonials.length) return;
    $testimonials.owlCarousel({
      items: 1,
      loop: true,
      nav: true,
      navText: ["<span class='carousel-btn carousel-btn--prev'>‹</span>", "<span class='carousel-btn carousel-btn--next'>›</span>"],
      dots: true,
      autoplay: true,
      autoplayTimeout: 6000,
      autoplayHoverPause: true,
      smartSpeed: 500
    });
  }
  initTestimonialsCarousel();

  // --- Fancybox (project galleries; group by shared data-fancybox value) ---
  if (typeof window.Fancybox !== 'undefined') {
    window.Fancybox.bind('[data-fancybox]', {});
  }

  // --- Contact page: mailto proposal (opens default email client) ---
  const contactPageForm = document.querySelector('.contact-page-form');
  if (contactPageForm) {
    contactPageForm.addEventListener('submit', (e) => {
      e.preventDefault();
      const fd = new FormData(contactPageForm);
      const name = (fd.get('name') || '').toString().trim();
      const company = (fd.get('company') || '').toString().trim();
      const email = (fd.get('email') || '').toString().trim();
      const phone = (fd.get('phone') || '').toString().trim();
      const campaignType = (fd.get('campaignType') || '').toString().trim();
      const projectDetails = (fd.get('projectDetails') || '').toString().trim();

      if (!name || !email) {
        contactPageForm.reportValidity();
        return;
      }

      const subject = encodeURIComponent(`Proposal request — ${company || name}`);
      const body = encodeURIComponent(
        [
          `Name: ${name}`,
          company ? `Company: ${company}` : null,
          `Email: ${email}`,
          phone ? `Phone: ${phone}` : null,
          campaignType ? `Campaign type: ${campaignType}` : null,
          '',
          'Project details:',
          projectDetails || '—'
        ]
          .filter(Boolean)
          .join('\n')
      );

      window.location.href = `mailto:admin@yasmarketing.ca?subject=${subject}&body=${body}`;
    });
  }
});
const textElements = document.querySelectorAll('.animate-text');

textElements.forEach(el => {
  const text = el.textContent;
  el.innerHTML = '';
  el.style.setProperty('--char-total', text.length);

  // Split text into spans
  text.split('').forEach((char, index) => {
    const span = document.createElement('span');
    span.textContent = char;
    span.style.setProperty('--char-index', index);
    el.appendChild(span);
  });

  // Observer
  const observer = new IntersectionObserver(entries => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        el.classList.add('visible');
      } else {
        el.classList.remove('visible');
      }
    });
  }, { threshold: 0.1 });

  observer.observe(el);
});

document.querySelectorAll('.footer-year').forEach((el) => {
  el.textContent = `YAS MARKETING © ${new Date().getFullYear()}`;
});