import { expect, test } from '@playwright/test'
import { startFixtureCollector, type FixtureCollector } from './fixture-collector'
import { ADAPTER_STATUSES, ALL_ITEMS, ALL_PANELS, PLANS_PANEL } from './fixtures/collector-fixtures'

test.describe.configure({ mode: 'serial' })

let collector: FixtureCollector

const PLAN_RUN = (PLANS_PANEL.data as { runs: Record<string, unknown>[] }).runs[0]!

const FINISHED = { status: 'failed', state: 'failed', pendingDecisions: 0 }

const daysAgo = (days: number) => new Date(Date.parse(PLAN_RUN.updatedAt as string) - days * 86_400_000).toISOString()

/** One plan, run four times across a worktree and a `.product-work` checkout; the live run is the oldest. */
const REPEATED_RUNS = [
  {
    ...PLAN_RUN,
    ...FINISHED,
    runId: 'attempt-1',
    repoRoot: '/home/user/Projects/overdeck',
    attempts: 2,
    updatedAt: daysAgo(1),
  },
  {
    ...PLAN_RUN,
    ...FINISHED,
    runId: 'attempt-2',
    repoRoot: '/home/user/Projects/overdeck/.worktrees/fix',
    updatedAt: daysAgo(2),
  },
  {
    ...PLAN_RUN,
    runId: 'attempt-3',
    repoRoot: '/home/user/Projects/overdeck/.product-work',
    updatedAt: daysAgo(3),
  },
]

function stateWithRuns(runs: unknown[], panelTs: string) {
  return {
    panels: [
      ...ALL_PANELS.filter((panel) => panel.id !== 'plans'),
      { ...PLANS_PANEL, ts: panelTs, data: { runs } },
    ],
    adapters: ADAPTER_STATUSES,
    items: ALL_ITEMS,
  }
}

test.beforeAll(async () => {
  collector = await startFixtureCollector(stateWithRuns(REPEATED_RUNS, new Date().toISOString()))
})

test.afterAll(async () => {
  await collector.close()
})

test('shows one row per plan with its attempt count, not one row per checkout', async ({ page }) => {
  await page.goto('/plans', { waitUntil: 'domcontentloaded' })
  const overdeckGroup = page.getByTestId('project-group-row').filter({ hasText: 'overdeck' })
  await overdeckGroup.getByRole('button', { name: 'Expand overdeck' }).click()

  const rows = page.getByRole('table', { name: 'Plans' }).locator('tbody tr')
  await expect(rows).toHaveCount(1)
  await expect(overdeckGroup).toContainText('1 plan')
  await expect(page.getByTestId('plan-attempts')).toHaveText('×4')
  await expect(rows.first()).toContainText('needs you')
})

test('marks the deck stale when its payload stops advancing', async ({ page }) => {
  collector.replaceState(
    stateWithRuns(REPEATED_RUNS, new Date(Date.now() - 4 * 24 * 60 * 60 * 1000).toISOString()),
  )

  await page.goto('/plans', { waitUntil: 'domcontentloaded' })
  await expect(page.getByText(/^stale · \d+h$/)).toBeVisible()
})
