/**
 * Sprint 7 item 7 — визуально проверяем «?» overlay шорткатов.
 */
import { chromium } from 'playwright'
import { makeClient, login } from '../lib/api.js'

const BASE = process.env.E2E_ADMIN_URL ?? 'https://test.admin.food-market.kz'
const TS = Date.now()
const EMAIL = `shrt-shot-${TS}@food-market.local`
const PASS = 'ShrtShot12345!'

async function ensureSession() {
  const api = makeClient()
  const r = await api.post('/api/auth/signup', {
    email: EMAIL, password: PASS,
    organizationName: `ShrtShot ${TS}`, phone: '+77011190001', plan: 'start',
  })
  if (r.status !== 200) throw new Error(`signup ${r.status}: ${JSON.stringify(r.data)}`)
  return login(EMAIL, PASS)
}

async function main() {
  const sess = await ensureSession()
  const browser = await chromium.launch({ headless: true })
  const ctx = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 1280, height: 800 } })
  const page = await ctx.newPage()
  await page.goto(`${BASE}/`)
  await page.evaluate(({ token }) => localStorage.setItem('fm.access_token', token), { token: sess.accessToken })

  await page.goto(`${BASE}/dashboard`, { waitUntil: 'domcontentloaded' })
  await page.waitForLoadState('networkidle')
  // Жмём «?» — должен открыться overlay.
  await page.keyboard.press('Shift+Slash') // = `?` без AZERTY
  await page.waitForSelector('[aria-labelledby="shortcuts-title"]', { timeout: 5000 })
  await page.screenshot({ path: `reports/shortcuts-overlay-${TS}.png` })
  console.log(`[shot] saved → reports/shortcuts-overlay-${TS}.png`)

  // Esc закрывает
  await page.keyboard.press('Escape')
  await page.waitForTimeout(300)
  const open = await page.locator('[aria-labelledby="shortcuts-title"]').count()
  console.log(`[shot] Esc closes overlay: ${open === 0 ? '✓' : '✗ STILL OPEN'}`)
  await browser.close()
}

main().catch(err => { console.error(err); process.exit(1) })
