import { describe, it, expect } from 'vitest'
import { render, fireEvent } from '@testing-library/react'
import { Canvas } from '@/components/wysiwyg/Canvas'
import type { Frame } from '@/lib/wysiwyg/schema'

function makeFrame(): Frame {
  return {
    id: 'f1',
    width: 400,
    height: 300,
    background: '#ffffff',
    layers: [
      {
        id: 'l1',
        name: 'L1',
        visible: true,
        locked: false,
        objects: [
          { id: 'o1', type: 'image', x: 100, y: 100, width: 50, height: 40, rotate: 0, zIndex: 0, props: { src: 'x', alt: '' } },
        ],
      },
    ],
  }
}

describe('WYSIWYG Canvas rotate with snap', () => {
  it('rotates with 15deg snap by default', () => {
    const frame = makeFrame()
    const { getByTestId } = render(<Canvas frame={frame} />)
    const handle = getByTestId('rotate-handle-o1')
    const canvas = getByTestId('wysiwyg-canvas')

    // start rotate at 0deg
    fireEvent.mouseDown(handle, { clientX: 100, clientY: 100 })
    // move +16px on x → +16deg → snap15 => 15deg
    fireEvent.mouseMove(canvas, { clientX: 116, clientY: 100 })
    fireEvent.mouseUp(canvas)

    const obj = getByTestId('obj-o1')
    expect(obj).toHaveStyle({ transform: 'rotate(15deg)' })
  })

  it('rotates with 1deg step while holding Shift', () => {
    const frame = makeFrame()
    const { getByTestId } = render(<Canvas frame={frame} />)
    const handle = getByTestId('rotate-handle-o1')
    const canvas = getByTestId('wysiwyg-canvas')

    fireEvent.mouseDown(handle, { clientX: 100, clientY: 100 })
    // move +7px with Shift → +7deg, no snap
    fireEvent.mouseMove(canvas, { clientX: 107, clientY: 100, shiftKey: true })
    fireEvent.mouseUp(canvas)

    const obj = getByTestId('obj-o1')
    expect(obj).toHaveStyle({ transform: 'rotate(7deg)' })
  })
})
