import { describe, it, expect } from 'vitest'
import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { WysiwygBuilderPage } from '@/components/wysiwyg/WysiwygBuilderPage'

function getLeft(el: HTMLElement) {
  const style = el.getAttribute('style') || ''
  const m = /left:\s*(\d+)px/
  return Number((style.match(m)?.[1]) || '0')
}

describe('Canvas guides - edge vs center priority', () => {
  it('prefers edge snap over center when both are available (edge>center)', async () => {
    render(<WysiwygBuilderPage />)
    // Add two texts
    const clickAddText = () => fireEvent.click(screen.getByRole('button', { name: /^Add Text$/i }))
    clickAddText()
    clickAddText()
    const objs = await screen.findAllByTestId(/obj-text-/)
    const a = objs[0]
    const b = objs[1]

    // Select A and drag to x≈100 (from x=60, delta≈+40 -> snaps to +40)
    fireEvent.mouseDown(a, { clientX: 60, clientY: 60 })
    const canvas = screen.getByTestId('wysiwyg-canvas')
    fireEvent.mouseMove(canvas, { clientX: 100, clientY: 60 })
    fireEvent.mouseUp(canvas)

    // Now A left≈100, width=160 so center≈180
    await waitFor(() => expect(getLeft(a)).toBe(100))

    // Select B and drag so that B left≈100 too; both edge(L-L) and center-center coincide
    fireEvent.mouseDown(b, { clientX: 120, clientY: 60 })
    fireEvent.mouseMove(canvas, { clientX: 159, clientY: 60 }) // delta≈+39 => snapped +40 → left 100
    // guides should show during drag
    await screen.findByTestId('guide-x')
    fireEvent.mouseUp(canvas)

    await waitFor(() => expect(getLeft(b)).toBe(100))
  })
})
