import { describe, it, expect } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
import { WysiwygBuilderPage } from '@/components/wysiwyg/WysiwygBuilderPage'

describe('WYSIWYG Builder - Layers acceptance', () => {
  it('visible toggle reflects on layer button state', async () => {
    render(<WysiwygBuilderPage />)
    // add two texts
    fireEvent.click(screen.getByRole('button', { name: /^Add Text$/i }))
    fireEvent.click(screen.getByRole('button', { name: /^Add Text$/i }))

    // 레이어 패널에서 visible 토글 버튼 상태만 검증
    const hideBtn = screen.getByTestId('layer-hide-base')
    expect(hideBtn).toHaveAttribute('aria-pressed', 'false')
    fireEvent.click(hideBtn)
    expect(hideBtn).toHaveAttribute('aria-pressed', 'true')
    // 다시 클릭하면 보이도록 토글
    fireEvent.click(hideBtn)
    expect(hideBtn).toHaveAttribute('aria-pressed', 'false')
  })

  it('layer order changes reflect in Canvas DOM stacking order', async () => {
    render(<WysiwygBuilderPage />)
    // Add two layers, each with one text object labeled L1, L2
    fireEvent.click(screen.getByRole('button', { name: /Add Layer/i }))
    fireEvent.click(screen.getByRole('button', { name: /Add Layer/i }))

    const t1 = await screen.findByText('L1')
    const t2 = await screen.findByText('L2')

    // Initially, later layer (L2) should be on top, thus follow L1 in DOM order
    const pos1 = t1.compareDocumentPosition(t2)
    expect(pos1 & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()

    // Move L2 up (towards front doesn't change since it's already last), then move L2 down to go below L1
    const up2 = screen.getByTestId('layer-up-layer-2')
    const down2 = screen.getByTestId('layer-down-layer-2')
    // up no-op when at top boundary (safe click)
    fireEvent.click(up2)
    // now move it down once (below)
    fireEvent.click(down2)

    // After moving L2 down, L1 should now come after L2 in DOM order (L1 on top)
    const pos2 = t2.compareDocumentPosition(t1)
    expect(pos2 & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
  })
})
