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

export const tiltHover = defineTrait({
  name: 'tilt-hover',
  category: 'animation-feedback',
  description: 'Tilt based on pointer position',
  attributes: ['data-tilt-hover-active'],
  events: [],
  config: [],
  setup({ host }) {
    // Reduced-motion: don't tilt the host; pointer events still fire elsewhere.
    if (prefersReducedMotion()) {
      return () => {};
    }

    function onPointerMove(e) {
      const rect = host.getBoundingClientRect();
      const x = (e.clientX - rect.left) / rect.width - 0.5;
      const y = (e.clientY - rect.top) / rect.height - 0.5;
      const rotateX = -y * 20;
      const rotateY = x * 20;
      host.style.transform = `perspective(600px) rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;
      host.setAttribute('data-tilt-hover-active', '');
    }

    function onPointerLeave() {
      host.style.transition = 'transform 300ms ease';
      host.style.transform = '';
      host.removeAttribute('data-tilt-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.transform = '';
      host.style.transition = '';
      host.removeAttribute('data-tilt-hover-active');
    };
  },
});
