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')
}

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

describe('Canvas guides - nearest candidate priority', () => {
  it('snaps to the nearest edge candidate among multiple options', async () => {
    render(<WysiwygBuilderPage />)
    const addText = () => fireEvent.click(screen.getByRole('button', { name: /^Add Text$/i }))
    // Create three objects: A (will move), B and C as anchors
    addText() // A
    addText() // B
    addText() // C
    const objs = await screen.findAllByTestId(/obj-text-/)
    const [A, B, C] = objs

    // Place B at x=160 (left), C at x=200 (left) via drags
    // Select B and drag +100 from 60 -> 160
    fireEvent.mouseDown(B, { clientX: 60, clientY: 60 })
    const canvas = screen.getByTestId('wysiwyg-canvas')
    fireEvent.mouseMove(canvas, { clientX: 160, clientY: 60 })
    fireEvent.mouseUp(canvas)
    await waitFor(() => expect(getLeft(B)).toBe(160))

    // Select C and drag +140 from 60 -> 200
    fireEvent.mouseDown(C, { clientX: 60, clientY: 120 })
    fireEvent.mouseMove(canvas, { clientX: 200, clientY: 120 })
    fireEvent.mouseUp(canvas)
    await waitFor(() => expect(getLeft(C)).toBe(200))

    // Now drag A near between 160 and 200, closer to 160, expect snap to 160
    fireEvent.mouseDown(A, { clientX: 60, clientY: 180 })
    fireEvent.mouseMove(canvas, { clientX: 168, clientY: 180 }) // delta +108 -> near 160 more than 200
    await screen.findByTestId('guide-x')
    fireEvent.mouseUp(canvas)

    await waitFor(() => expect(getLeft(A)).toBe(160))
  })
})
