/// file: public/assets/js/modules/cursor.js

export function initCursor() {
  if (window.__saneksaCursorBound) {
    return;
  }

  const el = document.getElementById('custom-cursor');
  if (!el) {
    return;
  }

  const finePointer = window.matchMedia('(pointer: fine)').matches;
  const anyHover = window.matchMedia('(any-hover: hover)').matches;
  const reduceMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
  /* Pure touch: neither fine pointer nor hover-capable input — skip custom cursor. */
  if (!anyHover && !finePointer) {
    return;
  }

  window.__saneksaCursorBound = true;

  el.classList.add('custom-cursor--on');
  /* Defer hiding the system cursor until the first pointermove; avoids cursor:none before the ring is aligned. */
  el.style.setProperty('opacity', '1', 'important');
  el.style.setProperty('visibility', 'visible', 'important');
  el.style.setProperty('z-index', '2147483647', 'important');
  let xpCursorLocked = false;

  let targetX = window.innerWidth * 0.5;
  let targetY = window.innerHeight * 0.5;
  let x = targetX;
  let y = targetY;
  let raf;
  const damp = reduceMotion ? 1 : 0.22;

  const loop = () => {
    x += (targetX - x) * damp;
    y += (targetY - y) * damp;
    el.style.transform = `translate3d(${x}px, ${y}px, 0) translate(-50%, -50%)`;
    raf = requestAnimationFrame(loop);
  };
  raf = requestAnimationFrame(loop);

  const onPointerMove = (e) => {
    if (!xpCursorLocked) {
      xpCursorLocked = true;
      /* Snap ring to pointer before hiding the system cursor (avoids one frame at viewport center). */
      x = e.clientX;
      y = e.clientY;
      targetX = e.clientX;
      targetY = e.clientY;
      el.style.transform = `translate3d(${x}px, ${y}px, 0) translate(-50%, -50%)`;
      document.documentElement.classList.add('xp-cursor-active');
    }
    targetX = e.clientX;
    targetY = e.clientY;
  };
  window.addEventListener('pointermove', onPointerMove, { passive: true, capture: true });

  const setState = (state, label = '') => {
    el.classList.toggle('is-hover', state === 'hover' || state === 'view');
    el.classList.toggle('is-label', !!label);
    const lab = el.querySelector('.custom-cursor__label');
    if (lab) lab.textContent = label;
  };

  document.querySelectorAll('[data-cursor]').forEach((node) => {
    node.addEventListener('mouseenter', () => {
      const v = node.getAttribute('data-cursor');
      const map = { hover: 'Hover', view: 'View', play: 'Play', close: 'Close', drag: 'Drag' };
      setState(v || 'hover', map[v] || '');
    });
    node.addEventListener('mouseleave', () => setState('default', ''));
  });
}
