import { fireEvent, render, screen } from '@testing-library/react'
import { NextIntlClientProvider } from 'next-intl'
import { describe, expect, test } from 'vitest'
import BuilderClientPage from './BuilderClientPage'
import messages from '../messages/en.json'

function Wrapper({ children }: { children: React.ReactNode }) {
  return (
    <NextIntlClientProvider messages={messages} locale="en">
      {children}
    </NextIntlClientProvider>
  )
}

describe('Inspector keyboard UX - Features & Testimonials add item', () => {
  test('Features: Space/Enter activates Add Feature Item', () => {
    render(
      <Wrapper>
        <BuilderClientPage />
      </Wrapper>
    )

    // Add features section and select it
    fireEvent.click(screen.getByTestId('card-features'))
    fireEvent.click(screen.getByLabelText('Select 0'))

    const addBtn = screen.getByRole('button', { name: /Add Feature Item/i })

    // Space key
    addBtn.focus()
    fireEvent.keyDown(addBtn, { key: ' ', code: 'Space', charCode: 32 })
    // Expect first input to appear (Feature 0)
    expect(screen.getByLabelText('Feature 0')).toBeInTheDocument()

    // Enter key adds another
    addBtn.focus()
    fireEvent.keyDown(addBtn, { key: 'Enter', code: 'Enter', charCode: 13 })
    expect(screen.getByLabelText('Feature 1')).toBeInTheDocument()
  })

  test('Testimonials: Space/Enter activates Add Testimonial', () => {
    render(
      <Wrapper>
        <BuilderClientPage />
      </Wrapper>
    )

    // Add testimonials section and select it
    fireEvent.click(screen.getByTestId('card-testimonials'))
    fireEvent.click(screen.getByLabelText('Select 0'))

    const addBtn = screen.getByRole('button', { name: /Add Testimonial/i })

    // Space
    addBtn.focus()
    fireEvent.keyDown(addBtn, { key: ' ', code: 'Space', charCode: 32 })
    expect(screen.getByLabelText('Author 0')).toBeInTheDocument()
    expect(screen.getByLabelText('Quote 0')).toBeInTheDocument()

    // Enter adds another
    addBtn.focus()
    fireEvent.keyDown(addBtn, { key: 'Enter', code: 'Enter', charCode: 13 })
    expect(screen.getByLabelText('Author 1')).toBeInTheDocument()
    expect(screen.getByLabelText('Quote 1')).toBeInTheDocument()
  })
})
