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

export const ripple = defineTrait({
  name: 'ripple',
  category: 'animation-feedback',
  description: 'Material-style press ripple effect',
  attributes: ['data-ripple-active'],
  events: [],
  config: [],
  setup({ host }) {
    // Reduced-motion: drop the ripple animation; press feedback comes from pressable instead.
    if (prefersReducedMotion()) {
      host.setAttribute('data-ripple-active', '');
      return () => host.removeAttribute('data-ripple-active');
    }

    host.style.overflow = 'hidden';
    host.style.position = host.style.position || 'relative';
    host.setAttribute('data-ripple-active', '');

    function onClick(e) {
      const rect = host.getBoundingClientRect();
      const x = e.clientX - rect.left;
      const y = e.clientY - rect.top;
      const size = Math.max(rect.width, rect.height) * 2;

      const span = document.createElement('span');
      span.style.cssText = `
        position: absolute; border-radius: 50%; pointer-events: none;
        background: rgba(255,255,255,0.4);
        width: ${size}px; height: ${size}px;
        left: ${x - size / 2}px; top: ${y - size / 2}px;
        transform: scale(0); opacity: 1;
        animation: adia-ripple-expand 600ms ease-out forwards;
      `;

      host.appendChild(span);
      span.addEventListener('animationend', () => span.remove());
    }

    // Inject keyframes once
    if (!document.querySelector('#adia-ripple-keyframes')) {
      const style = document.createElement('style');
      style.id = 'adia-ripple-keyframes';
      style.textContent = `
        @keyframes adia-ripple-expand {
          to { transform: scale(1); opacity: 0; }
        }
      `;
      document.head.appendChild(style);
    }

    host.addEventListener('click', onClick);

    return () => {
      host.removeEventListener('click', onClick);
      host.style.overflow = '';
      host.removeAttribute('data-ripple-active');
    };
  },
});
