// @vitest-environment happy-dom
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen, within } from '@testing-library/react'

/**
 * CollectionList row interactions with the inline entry detail pane
 * (design Entries split-pane):
 *  - row / title click toggles the 400px detail pane (no navigation)
 *  - "Open full editor" and row double-click open the correct editor route
 *
 * Regression (post-list navigation bug): post-type rows must open the section
 * editor (`/posts/:type/:id/edit`), never the generic `/:collection/:id`
 * route — which 404s when the slug is `posts`.
 */

vi.mock('../../lib/api.js', () => ({
  cmsApi: vi.fn(async () => ({ data: {}, status: 200 })),
  ensureCsrfToken: vi.fn(async () => {}),
}))

let listDocs: any[] = []
vi.mock('../../lib/useApiData.js', () => ({
  useApiData: () => ({
    data: { docs: listDocs, total: listDocs.length },
    loading: false,
    error: null,
    refetch: vi.fn(),
  }),
}))

const { CollectionList } = await import('../../views/CollectionList.js')

const POST_CONFIG = {
  collections: {
    posts: {
      slug: 'posts',
      type: 'post',
      labels: { singular: 'Post', plural: 'Posts' },
      fields: { title: { type: 'text', label: 'Title' } },
    },
  },
}

beforeEach(() => {
  listDocs = []
})

describe('CollectionList entry detail pane + navigation (post collection)', () => {
  it('row click opens the detail pane instead of navigating', () => {
    listDocs = [
      {
        id: '1',
        title: 'Hello',
        status: 'PUBLISHED',
        updatedAt: '2026-06-01T00:00:00Z',
        data: { title: 'Hello' },
      },
    ]
    const onNavigate = vi.fn()
    render(<CollectionList collectionSlug="posts" config={POST_CONFIG} onNavigate={onNavigate} />)

    const titleButton = within(screen.getByRole('table')).getByRole('button', { name: 'Hello' })
    expect(titleButton.getAttribute('aria-expanded')).toBe('false')
    fireEvent.click(titleButton)

    expect(onNavigate).not.toHaveBeenCalled()
    expect(titleButton.getAttribute('aria-expanded')).toBe('true')
    expect(screen.getByRole('region', { name: 'Post details' })).toBeTruthy()

    // Clicking again toggles the pane closed.
    fireEvent.click(titleButton)
    expect(screen.queryByRole('region', { name: 'Post details' })).toBeNull()
  })

  it('"Open full editor" opens the section editor, not the generic route', () => {
    listDocs = [{ id: '1', title: 'Hello', status: 'PUBLISHED', updatedAt: '2026-06-01T00:00:00Z' }]
    const onNavigate = vi.fn()
    render(<CollectionList collectionSlug="posts" config={POST_CONFIG} onNavigate={onNavigate} />)

    fireEvent.click(within(screen.getByRole('table')).getByRole('button', { name: 'Hello' }))
    fireEvent.click(screen.getByRole('button', { name: 'Open full editor' }))

    expect(onNavigate).toHaveBeenCalledWith('/posts/posts/1/edit')
    expect(onNavigate).not.toHaveBeenCalledWith('/posts/1')
  })

  it('row double-click opens the section editor directly', () => {
    listDocs = [{ id: '1', title: 'Hello', status: 'PUBLISHED', updatedAt: '2026-06-01T00:00:00Z' }]
    const onNavigate = vi.fn()
    render(<CollectionList collectionSlug="posts" config={POST_CONFIG} onNavigate={onNavigate} />)

    const row = within(screen.getByRole('table'))
      .getByRole('button', { name: 'Hello' })
      .closest('tr')!
    fireEvent.doubleClick(row)

    expect(onNavigate).toHaveBeenCalledWith('/posts/posts/1/edit')
  })

  it('starts a new post in the section editor', () => {
    const onNavigate = vi.fn()
    render(<CollectionList collectionSlug="posts" config={POST_CONFIG} onNavigate={onNavigate} />)

    // The empty-state CTA ("New Post") creates a document.
    fireEvent.click(screen.getByRole('button', { name: /new post/i }))
    expect(onNavigate).toHaveBeenCalledWith('/posts/posts/new')
  })
})
