import { describe, expect, test } from 'vitest'
import { render, screen, fireEvent, within } from '@testing-library/react'
import React, { useState } from 'react'
import SectionCanvas from './SectionCanvas'
import type { Section } from '@/lib/state/store'

function Wrapper() {
  const [sections, setSections] = useState<Section[]>([
    { type: 'hero', props: { heading: 'H', subheading: '' } },
    { type: 'faq', props: { items: [] } },
    { type: 'cta', props: { text: 'Go', href: '#' } },
  ])

  const onMove = (from: number, to: number) => {
    setSections((prev) => {
      const next = prev.slice()
      const [sp] = next.splice(from, 1)
      next.splice(to, 0, sp)
      return next
    })
  }

  return (
    <SectionCanvas
      sections={sections}
      onMove={onMove}
      onRemove={() => {}}
      onSelect={() => {}}
    />
  )
}

describe('SectionCanvas keyboard/fallback reorder', () => {
  test('clicking Down and Up buttons reorders items', () => {
    render(<Wrapper />)

    // initial order: hero, faq, cta
    const list = screen.getByTestId('section-canvas')
    let items = within(list).getAllByTestId(/sec-item-/)
    expect(items[0]).toHaveTextContent('hero')
    expect(items[1]).toHaveTextContent('faq')
    expect(items[2]).toHaveTextContent('cta')

    // move first item (index 0) down
    fireEvent.click(within(items[0]).getByLabelText('Down 0'))

    items = within(list).getAllByTestId(/sec-item-/)
    expect(items[0]).toHaveTextContent('faq')
    expect(items[1]).toHaveTextContent('hero')
    expect(items[2]).toHaveTextContent('cta')

    // move last item up
    fireEvent.click(within(items[2]).getByLabelText('Up 2'))

    items = within(list).getAllByTestId(/sec-item-/)
    expect(items[0]).toHaveTextContent('faq')
    expect(items[1]).toHaveTextContent('cta')
    expect(items[2]).toHaveTextContent('hero')
  })
})
