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

export const scalePress = defineTrait({
  name: 'scale-press',
  category: 'animation-feedback',
  description: 'Subtle scale transform on press',
  attributes: ['data-scale-press-active'],
  events: [],
  config: [],
  setup({ host }) {
    let savedTransform = '';

    function onPointerDown(e) {
      if (host.hasAttribute('disabled')) return;
      savedTransform = host.style.transform;
      host.style.transform = 'scale(0.95)';
      host.setAttribute('data-scale-press-active', '');
    }

    function release() {
      host.style.transform = savedTransform;
      host.removeAttribute('data-scale-press-active');
    }

    function onPointerUp() {
      if (host.hasAttribute('data-scale-press-active')) release();
    }

    function onPointerLeave() {
      if (host.hasAttribute('data-scale-press-active')) release();
    }

    host.addEventListener('pointerdown', onPointerDown);
    host.addEventListener('pointerup', onPointerUp);
    host.addEventListener('pointerleave', onPointerLeave);

    return () => {
      host.removeEventListener('pointerdown', onPointerDown);
      host.removeEventListener('pointerup', onPointerUp);
      host.removeEventListener('pointerleave', onPointerLeave);
      if (host.hasAttribute('data-scale-press-active')) release();
      host.removeAttribute('data-scale-press-active');
    };
  },
});
