import { defineTrait } from '../define.js';
import { prefersReducedMotion } from '../motion.js';

export const magneticHover = defineTrait({
  name: 'magnetic-hover',
  category: 'interaction-delight',
  description: 'Element subtly follows cursor',
  attributes: ['data-magnetic-hover-active'],
  events: [],
  config: [],
  setup({ host }) {
    // Reduced-motion: don't track the cursor; element stays put.
    if (prefersReducedMotion()) {
      return () => {};
    }

    function onPointerMove(e) {
      const rect = host.getBoundingClientRect();
      const cx = rect.left + rect.width / 2;
      const cy = rect.top + rect.height / 2;
      const dx = (e.clientX - cx) * 0.15;
      const dy = (e.clientY - cy) * 0.15;
      host.style.translate = `${dx}px ${dy}px`;
      host.setAttribute('data-magnetic-hover-active', '');
    }

    function onPointerLeave() {
      host.style.translate = '';
      host.style.transition = 'translate 300ms ease';
      host.removeAttribute('data-magnetic-hover-active');
      setTimeout(() => { host.style.transition = ''; }, 300);
    }

    host.addEventListener('pointermove', onPointerMove);
    host.addEventListener('pointerleave', onPointerLeave);

    return () => {
      host.removeEventListener('pointermove', onPointerMove);
      host.removeEventListener('pointerleave', onPointerLeave);
      host.style.translate = '';
      host.style.transition = '';
      host.removeAttribute('data-magnetic-hover-active');
    };
  },
});
