import { describe, it, expect, beforeEach } from 'vitest';
import { snapToGrid } from './snap-to-grid.js';
import { mountHost, connectTrait, resetDOM } from '../test-helpers.js';

describe('snap-to-grid', () => {
  beforeEach(resetDOM);

  it('drag-end with x,y rounds to nearest grid increment (default 16)', () => {
    const host = mountHost();
    connectTrait(snapToGrid, host);
    host.dispatchEvent(new CustomEvent('drag-end', { detail: { x: 23, y: 41 } }));
    expect(host.style.translate).toBe('16px 48px');
    expect(host.hasAttribute('data-snap-to-grid-snapped')).toBe(true);
  });

  it('respects data-snap-grid override', () => {
    const host = mountHost('div', { 'data-snap-grid': '50' });
    connectTrait(snapToGrid, host);
    host.dispatchEvent(new CustomEvent('drag-end', { detail: { x: 73, y: 124 } }));
    expect(host.style.translate).toBe('50px 100px');
  });

  it('drag-end without detail is a no-op', () => {
    const host = mountHost();
    connectTrait(snapToGrid, host);
    host.dispatchEvent(new CustomEvent('drag-end', { detail: {} }));
    // happy-dom may return undefined or '' for unset style.translate; both
    // mean "untouched" which is the contract here.
    expect(host.style.translate || '').toBe('');
    expect(host.hasAttribute('data-snap-to-grid-snapped')).toBe(false);
  });

  it('disconnect clears the snapped attribute', () => {
    const host = mountHost();
    const inst = connectTrait(snapToGrid, host);
    host.dispatchEvent(new CustomEvent('drag-end', { detail: { x: 0, y: 0 } }));
    inst.disconnect(host);
    expect(host.hasAttribute('data-snap-to-grid-snapped')).toBe(false);
  });
});
