// Tier 3-H axe-core a11y audit — runs against each docs page in dark + light
// theme; asserts 0 axe violations of severity 'critical' or 'serious'.
//
// Less-severe findings (moderate / minor) are logged but not failed — they
// represent backlog signals, not v1.0 gates.
//
// Usage:
//   pnpm test:a11y               # all pages, both themes
//   pnpm test:a11y -- --grep button   # single page filter
//
// Note: lives in tests/a11y/ (separate from tests/visual/) so Playwright config
// dedicated `testDir` here doesn't pull visual snapshots into a11y runs.

import type { Page } from '@playwright/test'
import { orderedPages, getPagePath } from '../../playground/docs/navigation'

if (process.env.VITEST) {
  const { test } = await import('vitest')
  test.skip('axe-core a11y suite is run via pnpm test:a11y (Playwright)', () => {})
} else {
  const { test, expect } = await import('@playwright/test')
  // @ts-expect-error — @axe-core/playwright has no shipped .d.ts in CJS resolution mode for this project's ESM context; runtime import works.
  const { default: AxeBuilder } = await import('@axe-core/playwright')

  for (const pageItem of orderedPages) {
    test(`a11y ${pageItem.id}`, async ({ page }: { page: Page }) => {
      await page.goto(getPagePath(pageItem.id))
      await page.waitForLoadState('networkidle')

      // Dark theme (default)
      const darkScan = await new AxeBuilder({ page })
        .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
        .analyze()
      // v1.0 bar: 0 violations of ANY severity (critical / serious / moderate / minor).
      // User decision 2026-05-18: v1.0 must ship clean, no allowlist, no severity threshold.
      const darkBlockers = darkScan.violations
      expect(darkBlockers, `${pageItem.id} dark a11y blockers:\n${darkBlockers.map((v: any) => `  - [${v.impact}] ${v.id}: ${v.help} (${v.nodes.length} nodes)\n    ${v.helpUrl}`).join('\n')}`).toEqual([])

      // Light theme
      await page.click('button.canonical-toggle')
      await page.waitForFunction(
        () => document.documentElement.getAttribute('data-theme') === 'light',
      )

      const lightScan = await new AxeBuilder({ page })
        .withTags(['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa'])
        .analyze()
      const lightBlockers = lightScan.violations
      expect(lightBlockers, `${pageItem.id} light a11y blockers:\n${lightBlockers.map((v: any) => `  - [${v.impact}] ${v.id}: ${v.help} (${v.nodes.length} nodes)\n    ${v.helpUrl}`).join('\n')}`).toEqual([])
    })
  }
}
