import { test, expect } from './helpers/fixtures.js'

test.describe('Admin board channels page', () => {
  test('page loads for admin', async ({ adminPage }) => {
    await adminPage.goto('/admin/board-channels')
    await expect(adminPage.getByRole('heading', { name: 'Board Channels' })).toBeVisible({
      timeout: 15000,
    })
    await expect(adminPage.getByRole('button', { name: '+ New Channel' })).toBeVisible()
  })

  test('create, edit, and delete a channel', async ({ adminPage }) => {
    await adminPage.goto('/admin/board-channels')
    await expect(adminPage.getByRole('heading', { name: 'Board Channels' })).toBeVisible({
      timeout: 15000,
    })

    const suffix = Date.now().toString().slice(-6)
    const channelName = `e2e-channel-${suffix}`
    const editedName = `e2e-channel-${suffix}-edited`
    const slackId = `C${suffix}XYZ`

    // --- Create ---
    await adminPage.getByRole('button', { name: '+ New Channel' }).click()
    await expect(adminPage.getByRole('heading', { name: 'New Channel' })).toBeVisible()

    await adminPage.locator('input[placeholder="e.g., #coop-formation"]').fill(channelName)
    await adminPage.locator('input[placeholder="C0123456789"]').fill(slackId)

    // Select the first available cooperative tag if any are present
    const firstTagCheckbox = adminPage.locator('.tag-select input[type="checkbox"]').first()
    if (await firstTagCheckbox.isVisible().catch(() => false)) {
      await firstTagCheckbox.check()
    }

    await adminPage.getByRole('button', { name: 'Create Channel' }).click()

    await expect(adminPage.getByRole('cell', { name: channelName })).toBeVisible({
      timeout: 10000,
    })

    // --- Edit ---
    const row = adminPage.locator('tr', { hasText: channelName })
    await row.getByRole('button', { name: 'Edit' }).click()

    await expect(adminPage.getByRole('heading', { name: 'Edit Channel' })).toBeVisible()
    const nameInput = adminPage.locator('input[placeholder="e.g., #coop-formation"]')
    await nameInput.fill(editedName)
    await adminPage.getByRole('button', { name: 'Save Changes' }).click()

    await expect(adminPage.getByRole('cell', { name: editedName })).toBeVisible({
      timeout: 10000,
    })

    // --- Delete (confirm dialog) ---
    adminPage.once('dialog', (dialog) => dialog.accept())
    const editedRow = adminPage.locator('tr', { hasText: editedName })
    await editedRow.getByRole('button', { name: 'Delete' }).click()

    await expect(adminPage.getByRole('cell', { name: editedName })).not.toBeVisible({
      timeout: 10000,
    })
  })
})
