document.addEventListener('DOMContentLoaded', function () {
  var reduceMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  var isTouch = window.matchMedia && window.matchMedia('(hover: none), (pointer: coarse)').matches;

  /* ---------------- Mobile hamburger nav ---------------- */
  var hamburger = document.getElementById('hamburger');
  var mainNav = document.getElementById('main-nav');
  var navClose = document.getElementById('navClose');
  var navBackdrop = document.getElementById('navBackdrop');

  if (hamburger && mainNav) {
    function openNav() {
      mainNav.classList.add('open');
      hamburger.classList.add('open');
      hamburger.setAttribute('aria-expanded', 'true');
      if (navBackdrop) navBackdrop.classList.add('open');
    }
    function closeNav() {
      mainNav.classList.remove('open');
      hamburger.classList.remove('open');
      hamburger.setAttribute('aria-expanded', 'false');
      if (navBackdrop) navBackdrop.classList.remove('open');
    }
    hamburger.addEventListener('click', function () {
      if (mainNav.classList.contains('open')) closeNav(); else openNav();
    });
    if (navClose) navClose.addEventListener('click', closeNav);
    if (navBackdrop) navBackdrop.addEventListener('click', closeNav);
    document.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeNav(); });
    mainNav.querySelectorAll('a').forEach(function (link) { link.addEventListener('click', closeNav); });
  }

  /* ---------------- Sticky header state ---------------- */
  var header = document.getElementById('siteHeader');
  if (header) {
    var onScrollHeader = function () { header.classList.toggle('is-scrolled', window.scrollY > 30); };
    document.addEventListener('scroll', onScrollHeader, { passive: true });
    onScrollHeader();
  }

  /* ---------------- Split-text headline reveal ---------------- */
  document.querySelectorAll('[data-split="words"]').forEach(function (el) {
    var html = el.innerHTML;
    var lines = html.split('<br>');
    el.innerHTML = '';
    var wordIndex = 0;
    lines.forEach(function (line, lineIdx) {
      line.trim().split(' ').forEach(function (word) {
        if (!word) return;
        var span = document.createElement('span');
        span.className = 'word';
        span.textContent = word + ' ';
        span.style.animationDelay = (wordIndex * 0.09) + 's';
        el.appendChild(span);
        wordIndex++;
      });
      if (lineIdx < lines.length - 1) el.appendChild(document.createElement('br'));
    });
  });

  /* ---------------- Custom cursor ---------------- */
  var cursorDot = document.getElementById('cursorDot');
  var cursorRing = document.getElementById('cursorRing');
  if (cursorDot && cursorRing && !isTouch && !reduceMotion) {
    var ringX = 0, ringY = 0;
    document.addEventListener('mousemove', function (e) {
      cursorDot.style.left = e.clientX + 'px';
      cursorDot.style.top = e.clientY + 'px';
      ringX = e.clientX; ringY = e.clientY;
      cursorRing.style.left = ringX + 'px';
      cursorRing.style.top = ringY + 'px';
    });
    document.querySelectorAll('a, button, .magnetic, input, select, textarea, .work-item').forEach(function (el) {
      el.addEventListener('mouseenter', function () { cursorRing.classList.add('grow'); });
      el.addEventListener('mouseleave', function () { cursorRing.classList.remove('grow'); });
    });
  }

  /* ---------------- Magnetic buttons ---------------- */
  if (!isTouch && !reduceMotion) {
    document.querySelectorAll('.magnetic').forEach(function (el) {
      el.addEventListener('mousemove', function (e) {
        var rect = el.getBoundingClientRect();
        var x = e.clientX - rect.left - rect.width / 2;
        var y = e.clientY - rect.top - rect.height / 2;
        el.style.transform = 'translate(' + (x * 0.25) + 'px,' + (y * 0.35) + 'px)';
      });
      el.addEventListener('mouseleave', function () { el.style.transform = 'translate(0,0)'; });
    });
  }

  /* ---------------- Parallax blobs ---------------- */
  var blobs = document.querySelectorAll('.blob');
  if (blobs.length && !reduceMotion) {
    var ticking = false;
    function updateParallax() {
      var y = window.scrollY;
      blobs.forEach(function (blob) {
        var speed = parseFloat(blob.getAttribute('data-speed')) || 0.2;
        blob.style.transform = 'translateY(' + (y * speed) + 'px)';
      });
      ticking = false;
    }
    document.addEventListener('scroll', function () {
      if (!ticking) { requestAnimationFrame(updateParallax); ticking = true; }
    }, { passive: true });
    updateParallax();
  }

  /* ---------------- Clip-path gallery reveal ---------------- */
  var clipEls = document.querySelectorAll('.clip-reveal');
  if (clipEls.length) {
    if (!reduceMotion && 'IntersectionObserver' in window) {
      var clipIo = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
          if (entry.isIntersecting) {
            var delay = parseFloat(entry.target.style.getPropertyValue('--d')) || 0;
            setTimeout(function () { entry.target.classList.add('is-revealed'); }, delay * 1000);
            clipIo.unobserve(entry.target);
          }
        });
      }, { threshold: 0.15 });
      clipEls.forEach(function (el) { clipIo.observe(el); });
    } else {
      clipEls.forEach(function (el) { el.classList.add('is-revealed'); });
    }
  }

  /* ---------------- Animated stat counters ---------------- */
  var statEls = document.querySelectorAll('.stat-number');
  function animateCount(el) {
    var to = parseFloat(el.getAttribute('data-count-to')) || 0;
    var suffix = el.getAttribute('data-suffix') || '';
    if (reduceMotion) { el.textContent = to + suffix; return; }
    var duration = 1200, start = null;
    function step(ts) {
      if (!start) start = ts;
      var progress = Math.min((ts - start) / duration, 1);
      var eased = 1 - Math.pow(1 - progress, 3);
      el.textContent = Math.round(to * eased) + suffix;
      if (progress < 1) requestAnimationFrame(step);
      else el.textContent = to + suffix;
    }
    requestAnimationFrame(step);
  }
  if (statEls.length) {
    if ('IntersectionObserver' in window) {
      var statIo = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
          if (entry.isIntersecting) { animateCount(entry.target); statIo.unobserve(entry.target); }
        });
      }, { threshold: 0.5 });
      statEls.forEach(function (el) { statIo.observe(el); });
    } else {
      statEls.forEach(animateCount);
    }
  }

  /* ---------------- Generic scroll-reveal ---------------- */
  var revealEls = document.querySelectorAll('.reveal');
  if (revealEls.length) {
    if (!reduceMotion && 'IntersectionObserver' in window) {
      var io = new IntersectionObserver(function (entries) {
        entries.forEach(function (entry) {
          if (entry.isIntersecting) { entry.target.classList.add('is-visible'); io.unobserve(entry.target); }
        });
      }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
      revealEls.forEach(function (el) { io.observe(el); });
    } else {
      revealEls.forEach(function (el) { el.classList.add('is-visible'); });
    }
  }
});
