import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import QueuePage from '../src/pages/QueuePage.js'
import type { Item } from '../src/types.js'

vi.mock('../src/api.js', async (importOriginal) => {
  const actual = await importOriginal<typeof import('../src/api.js')>()
  return { ...actual, api: { ...actual.api, listCollection: vi.fn(), setRip: vi.fn() } }
})
import { api } from '../src/api.js'

function qItem(id: number, title: string, added: string): Item {
  return {
    id, discogsReleaseId: 1, title, artist: 'Artist', year: 1999, formats: ['CD'], genres: [], labels: [],
    tracklist: [], catno: null, country: null, artworkUrl: null, barcodes: [], dateAdded: added,
    ripOverride: null, ripStatus: 'not_ripped',
  }
}

beforeEach(() => {
  vi.mocked(api.listCollection).mockReset()
  vi.mocked(api.setRip).mockReset()
})

describe('QueuePage', () => {
  it('lists not-ripped items oldest first and marks ripped', async () => {
    vi.mocked(api.listCollection).mockResolvedValue({
      items: [qItem(1, 'Newest', '2026-08-20'), qItem(2, 'Oldest', '2026-08-01')],
      counts: { total: 2, ripped: 0, notRipped: 2 },
    } as never)
    vi.mocked(api.setRip).mockResolvedValue({} as never)
    render(
      <MemoryRouter>
        <QueuePage />
      </MemoryRouter>
    )
    expect(await screen.findByText('Oldest')).toBeTruthy() // oldest first
    const rows = screen.getAllByRole('button', { name: /mark ripped/i })
    await userEvent.click(rows[0]!)
    await waitFor(() => expect(api.setRip).toHaveBeenCalledWith(2, true))
    await waitFor(() => expect(screen.queryByText('Oldest')).toBeNull())
  })

  it('empty state points back to scanning', async () => {
    vi.mocked(api.listCollection).mockResolvedValue({ items: [], counts: { total: 0, ripped: 0, notRipped: 0 } } as never)
    render(
      <MemoryRouter>
        <QueuePage />
      </MemoryRouter>
    )
    expect(await screen.findByText(/nothing waiting/i)).toBeTruthy()
    expect(screen.getByRole('link', { name: /scan something/i }).getAttribute('href')).toBe('/scan')
  })
})
