import { expect, test } from '@playwright/test'
import { startFixtureCollector, type FixtureCollector } from './fixture-collector'

let collector: FixtureCollector
test.beforeAll(async () => { collector = await startFixtureCollector({ panels: [], adapters: [], items: [] }) })
test.afterAll(async () => { await collector.close() })
test.beforeEach(() => { collector.resetHookControls() })

test('hooks control reflects fixture policy and round-trips pessimistically', async ({ page }) => {
  await page.goto('/hooks')
  const control = page.getByLabel('Block agent background jobs')
  await expect(control).toBeChecked()
  await control.click()
  await expect(control).not.toBeChecked()
})

test('hooks control stays checked while a delayed mutation is pending', async ({ page }) => {
  collector.delayNextHookControlToggle(400)
  await page.goto('/hooks')
  const control = page.getByLabel('Block agent background jobs')
  await expect(control).toBeChecked()
  await control.click()
  await expect(control).toBeChecked()
  await expect(control).toBeDisabled()
  await expect(control).not.toBeChecked({ timeout: 2_000 })
})

test('hooks control retains confirmed state and announces a failed mutation', async ({ page }) => {
  collector.failNextHookControlToggle()
  await page.goto('/hooks')
  const control = page.getByLabel('Block agent background jobs')
  await expect(control).toBeChecked()
  await control.click()
  await expect(page.getByRole('alert')).toContainText('forced failure')
  await expect(control).toBeChecked()
})

test('hooks control surfaces issue repair and clears it after repair', async ({ page }) => {
  collector.replaceState({ panels: [], adapters: [], items: [], hookControls: { enabled: true, issue: { code: 'invalid-hook-controls', detail: 'hook-controls.json is not valid JSON', repairable: true } } })
  await page.goto('/hooks')
  const control = page.getByLabel('Block agent background jobs')
  await expect(control).toBeDisabled()
  await expect(page.locator('#hook-control-background-jobs-blocker-error')).toHaveText('hook-controls.json is not valid JSON')
  await page.getByRole('button', { name: 'Repair hook controls' }).click()
  await expect(control).toBeEnabled()
  await expect(page.getByRole('button', { name: 'Repair hook controls' })).toHaveCount(0)
})
test('hooks control hides repair for nonrepairable issues', async ({ page }) => {
  collector.replaceState({ panels: [], adapters: [], items: [], hookControls: { enabled: true, issue: { code: 'invalid-hook-controls', detail: 'hook-controls.json is not a regular file', repairable: false } } })
  await page.goto('/hooks')
  await expect(page.locator('#hook-control-background-jobs-blocker-error')).toHaveText('hook-controls.json is not a regular file')
  await expect(page.getByRole('button', { name: 'Repair hook controls' })).toHaveCount(0)
})

