// @vitest-environment happy-dom
import { describe, expect, it, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
import {
  InspectorPane,
  InspectorPaneBody,
  InspectorPaneFooter,
  InspectorPaneHeader,
  InspectorPaneSection,
  SplitPaneLayout,
  SplitPaneList,
} from '../../components/ui/InspectorPane.js'

function Pane({ open }: { open: boolean }) {
  return (
    <SplitPaneLayout>
      <SplitPaneList>
        <table aria-label="Rows" />
      </SplitPaneList>
      <InspectorPane open={open} width={420} aria-label="Row editor">
        <InspectorPaneHeader onClose={() => {}}>
          <span>Editing</span>
        </InspectorPaneHeader>
        <InspectorPaneBody>
          <InspectorPaneSection title="Details">content</InspectorPaneSection>
        </InspectorPaneBody>
        <InspectorPaneFooter>
          <button type="button">Save</button>
        </InspectorPaneFooter>
      </InspectorPane>
    </SplitPaneLayout>
  )
}

describe('InspectorPane', () => {
  it('renders pane content with a labelled region when open', () => {
    render(<Pane open />)
    expect(screen.getByRole('region', { name: 'Row editor' })).toBeTruthy()
    expect(screen.getByText('Editing')).toBeTruthy()
    expect(screen.getByText('Details')).toBeTruthy()
    expect(screen.getByRole('button', { name: 'Save' })).toBeTruthy()
  })

  it('collapses to zero width and hides content when closed', () => {
    const { container } = render(<Pane open={false} />)
    const shell = container.querySelector('[aria-hidden="true"]') as HTMLElement
    expect(shell).toBeTruthy()
    expect(shell.style.width).toBe('0px')
    expect(screen.queryByText('Editing')).toBeNull()
  })

  it('close button in the header fires onClose with an accessible label', () => {
    const onClose = vi.fn()
    render(
      <InspectorPane open width={400} aria-label="Detail">
        <InspectorPaneHeader onClose={onClose} closeLabel="Close detail">
          <span>Title</span>
        </InspectorPaneHeader>
      </InspectorPane>,
    )
    screen.getByRole('button', { name: 'Close detail' }).click()
    expect(onClose).toHaveBeenCalledTimes(1)
  })
})
