import { test } from '../support/browser'
test('probe zone taps', async ({ page }, info) => {
  test.setTimeout(1_800_000)
  await page.goto('/e2e/harness/canvas.html')
  await page.locator('[data-anno-id="caudal"]').waitFor({ state: 'attached' })
  const zones = ['caudal', 'sacral', 'lumbar', 'thoracic', 'cervical', 'head-trigger']
  const out: string[] = []
  for (const id of zones) {
    const pts = await page.evaluate((id) => {
      const svg = document.querySelector('[data-testid="anatomy-canvas"] svg') as SVGSVGElement
      const ctm = svg.getScreenCTM()!
      const z = svg.querySelector(`[data-anno-id="${id}"]`) as SVGGeometryElement
      const b = z.getBBox()
      const step = 2 / ctm.a
      const res: { x: number; y: number; hit: string }[] = []
      for (let x = b.x; x <= b.x + b.width; x += step) for (let y = b.y; y <= b.y + b.height; y += step) {
        if (!z.isPointInFill(new DOMPoint(x, y))) continue
        const p = new DOMPoint(x, y).matrixTransform(ctm)
        const hit = document.elementFromPoint(p.x, p.y)?.closest('[data-anno-id]')?.getAttribute('data-anno-id') ?? '-'
        res.push({ x: p.x, y: p.y, hit })
      }
      return res
    }, id)
    const tally: Record<string, number> = {}
    let n = 0
    for (const p of pts) {
      if (p.hit !== id) continue
      n++
      const before = ((await page.getByTestId('clicks').textContent()) ?? '').split(' ').filter(Boolean).length
      await page.touchscreen.tap(p.x, p.y)
      await page.waitForTimeout(400)
      const got = ((await page.getByTestId('clicks').textContent()) ?? '').split(' ').filter(Boolean).slice(before).join(',') || '-'
      tally[got] = (tally[got] ?? 0) + 1
    }
    out.push(`${info.project.name} ${id}: ${n} geometric hits, taps ${JSON.stringify(tally)}`)
  }
  console.log(out.join('\n'))
})
