import React from 'react'
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import { act } from 'react-dom/test-utils'
import { Canvas } from '@/components/wysiwyg/Canvas'
import type { Frame } from '@/lib/wysiwyg/schema'

const capture = vi.fn()

type MProps = {
  onDragStart?: () => void
  onDrag?: (e: { left?: number; top?: number }) => void
  onDragEnd?: () => void
}

vi.mock('react-moveable', () => {
  const Mock = (props: Record<string, unknown>) => {
    capture(props)
    return <div data-testid="moveable" />
  }
  return { default: Mock }
})

const frame: Frame = {
  id: 'f-guides-h',
  width: 500,
  height: 400,
  background: '#fff',
  layers: [
    { id: 'l1', name: 'L1', visible: true, locked: false, objects: [
      // 드래그 대상(o1) - 기본 선택이 되도록 첫 번째
      { id: 'o1', type: 'text', x: 10, y: 10, width: 40, height: 40, rotate: 0, zIndex: 1, props: { text: 'A', fontSize: 16, color: '#000' } },
      // 대상(o2) 수평 중심선: y = 65 유지. 에지 간섭 방지 위해 top을 60, height를 10으로 조정(65=60+10/2)
      { id: 'o2', type: 'text', x: 200, y: 60, width: 80, height: 10, rotate: 0, zIndex: 0, props: { text: 'B', fontSize: 16, color: '#000' } },
    ]}
  ]
}

describe('Canvas guidelines advanced (horizontal center snap)', () => {
  beforeEach(() => capture.mockReset())

  it('shows horizontal guide and snaps y to other object center within 8px threshold', async () => {
    render(<Canvas frame={frame} />)
    const last = capture.mock.calls.at(-1)?.[0] as MProps
    expect(last).toBeTruthy()

    await act(async () => { last.onDragStart?.() })

    // o1 height=40 → 중심은 top+20. o2 중심 65에 맞추려면 top=45 필요
    await act(async () => { last.onDrag?.({ left: 10, top: 45 }) })

    const obj = screen.getByTestId('obj-o1') as HTMLElement
    await waitFor(() => {
      expect(obj.style.top).toBe('45px')
    })

    // 수평 가이드 라인 표시
    await screen.findByTestId('guide-y')

    await act(async () => { last.onDragEnd?.() })
    await waitFor(() => {
      expect(screen.queryByTestId('guide-y')).toBeNull()
    })
  })
})
