import { describe, it, expect } from 'vitest'
import { render, fireEvent, waitFor } 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: 60, y: 60, width: 50, height: 40, rotate: 0, zIndex: 0, props: { src: 'x', alt: '' } },
          { id: 'o2', type: 'image', x: 160, y: 60, width: 80, height: 30, rotate: 0, zIndex: 1, props: { src: 'y', alt: '' } },
        ],
      },
    ],
  }
}

describe('WYSIWYG Canvas multigroup rotate', () => {
  it('rotates all selected objects by same snapped angle when rotating last-selected', async () => {
    const frame = makeFrame()
    const { getByTestId } = render(<Canvas frame={frame} />)

    // select o1 then shift+select o2 (last-selected o2)
    fireEvent.mouseDown(getByTestId('obj-o1'), { clientX: 60, clientY: 60 })
    fireEvent.mouseDown(getByTestId('obj-o2'), { clientX: 160, clientY: 60, shiftKey: true })

    const handle2 = getByTestId('rotate-handle-o2')
    const canvas = getByTestId('wysiwyg-canvas')

    // start rotate at 0deg and move +16px -> snap to 15deg by default
    fireEvent.mouseDown(handle2, { clientX: 100, clientY: 50 })
    fireEvent.mouseMove(canvas, { clientX: 116, clientY: 50 })
    fireEvent.mouseUp(canvas)

    const o1 = getByTestId('obj-o1')
    const o2 = getByTestId('obj-o2')

    await waitFor(() => {
      expect(o2).toHaveStyle({ transform: 'rotate(15deg)' })
      expect(o1).toHaveStyle({ transform: 'rotate(15deg)' })
    })
  })

  it('applies fine rotation delta to all when holding Shift', async () => {
    const frame = makeFrame()
    const { getByTestId } = render(<Canvas frame={frame} />)

    // select o1 then shift+select o2 (last-selected o2)
    fireEvent.mouseDown(getByTestId('obj-o1'), { clientX: 60, clientY: 60 })
    fireEvent.mouseDown(getByTestId('obj-o2'), { clientX: 160, clientY: 60, shiftKey: true })

    const handle2 = getByTestId('rotate-handle-o2')
    const canvas = getByTestId('wysiwyg-canvas')

    // start rotate at 0deg, move +7px with Shift -> 7deg (no snap)
    fireEvent.mouseDown(handle2, { clientX: 100, clientY: 50 })
    fireEvent.mouseMove(canvas, { clientX: 107, clientY: 50, shiftKey: true })
    fireEvent.mouseUp(canvas)

    const o1 = getByTestId('obj-o1')
    const o2 = getByTestId('obj-o2')

    await waitFor(() => {
      expect(o2).toHaveStyle({ transform: 'rotate(7deg)' })
      expect(o1).toHaveStyle({ transform: 'rotate(7deg)' })
    })
  })
})
