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

export const snapToGrid = defineTrait({
  name: 'snap-to-grid',
  category: 'motion-positioning',
  description: 'Snaps position to configurable grid',
  attributes: ['data-snap-to-grid-snapped'],
  events: [],
  config: ['data-snap-grid'],
  setup({ host }) {
    const gridSize = parseInt(host.getAttribute('data-snap-grid'), 10) || 16;

    function onDragEnd(e) {
      const { x, y } = e.detail || {};
      if (x == null || y == null) return;

      const snappedX = Math.round(x / gridSize) * gridSize;
      const snappedY = Math.round(y / gridSize) * gridSize;
      host.style.translate = `${snappedX}px ${snappedY}px`;
      host.setAttribute('data-snap-to-grid-snapped', '');
    }

    host.addEventListener('drag-end', onDragEnd);

    return () => {
      host.removeEventListener('drag-end', onDragEnd);
      host.removeAttribute('data-snap-to-grid-snapped');
    };
  },
});
