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

const { pushMock } = vi.hoisted(() => ({ pushMock: vi.fn() }))
vi.mock('next/navigation', () => ({ useRouter: () => ({ push: pushMock, refresh: vi.fn() }) }))
vi.mock('@/actions/products', () => ({ restoreProductAction: vi.fn() }))
vi.mock('@/actions/active-product', () => ({ setActiveProductAction: vi.fn() }))
vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }))
vi.mock('@/components/dialogs/product-dialog', () => ({
  ProductDialog: ({ open }: { open: boolean }) => (open ? <div role="dialog">ProductDialog</div> : null),
}))

import { ProductList } from '@/components/dashboard/product-list'

const PRODUCT = {
  id: 'p1',
  name: 'Mijn Product',
  code: 'MP',
  description: 'Een product',
  repo_url: 'https://github.com/foo/bar',
  definition_of_done: 'klaar als het werkt',
  auto_pr: false,
}

beforeEach(() => {
  pushMock.mockClear()
})

describe('ProductList — edit-icoon (todo cmoq3ox51)', () => {
  it('rendert pencil-icoon (Bewerk product) op active card, geen tekstknop "Bewerken"', () => {
    render(<ProductList products={[PRODUCT]} isDemo={false} activeProductId="p1" />)
    expect(screen.getByLabelText('Bewerk product')).toBeTruthy()
    // Oude tekstknop is weg
    expect(screen.queryByText('Bewerken')).toBeNull()
  })

  it('opent ProductDialog op klik (en stopt propagation zodat card-click niet navigeert)', () => {
    render(<ProductList products={[PRODUCT]} isDemo={false} activeProductId="p1" />)
    expect(screen.queryByRole('dialog')).toBeNull()
    fireEvent.click(screen.getByLabelText('Bewerk product'))
    expect(screen.getByRole('dialog')).toBeTruthy()
    expect(pushMock).not.toHaveBeenCalled() // card-navigation niet getriggerd
  })

  it('demo-user: knop is disabled', () => {
    render(<ProductList products={[PRODUCT]} isDemo={true} activeProductId="p1" />)
    const btn = screen.getByLabelText('Bewerk product') as HTMLButtonElement
    expect(btn.disabled).toBe(true)
  })

  it('toont geen edit-icoon bij gearchiveerde producten', () => {
    render(<ProductList products={[PRODUCT]} isDemo={false} showArchived={true} activeProductId={null} />)
    expect(screen.queryByLabelText('Bewerk product')).toBeNull()
  })
})
