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: 20, y: 20, width: 50, height: 40, rotate: 0, zIndex: 0, props: { src: 'x', alt: '' } },
          { id: 'o2', type: 'image', x: 120, y: 60, width: 80, height: 30, rotate: 0, zIndex: 1, props: { src: 'y', alt: '' } },
        ],
      },
    ],
  }
}

describe('WYSIWYG Canvas multigroup resize', () => {
  it('resizes all selected objects by the same snapped delta when resizing last-selected', async () => {
    const frame = makeFrame()
    const { getByTestId } = render(<Canvas frame={frame} />)

    // select o1
    const obj1 = getByTestId('obj-o1')
    fireEvent.mouseDown(obj1, { clientX: 25, clientY: 25 })
    // shift+select o2
    const obj2 = getByTestId('obj-o2')
    fireEvent.mouseDown(obj2, { clientX: 125, clientY: 65, shiftKey: true })

    // resize using last-selected (o2) handle
    const handle2 = getByTestId('resize-handle-o2')
    const canvas = getByTestId('wysiwyg-canvas')

    // Start at bottom-right corner; move by +7,+9 (snap8 => +8, +8)
    fireEvent.mouseDown(handle2, { clientX: 200, clientY: 90 })
    fireEvent.mouseMove(canvas, { clientX: 207, clientY: 99 })
    fireEvent.mouseUp(canvas)

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

    await waitFor(() => {
      expect(o2).toHaveStyle({ width: '88px', height: '40px' })
      expect(o1).toHaveStyle({ width: '58px', height: '50px' })
    })
  })
})
