import { Page, expect } from '@playwright/test'

/**
 * E2E Test Helpers for SDK Testing
 */

// Wait for page to be loaded (domcontentloaded — networkidle times out
// on pages with polling API calls like CMP dashboard)
export async function waitForPageLoad(page: Page) {
  await page.waitForLoadState('domcontentloaded')
  await page.waitForTimeout(1000)
}

// Handle role selection screen if present
async function handleRoleSelection(page: Page) {
  // Check if role selection screen is visible
  const roleScreen = page.locator('text=Willkommen im Admin Center')
  if (await roleScreen.isVisible({ timeout: 2000 }).catch(() => false)) {
    // Click on DSB (Datenschutzbeauftragter) role for DSR testing
    const dsbButton = page.locator('button:has-text("DSB")')
    if (await dsbButton.isVisible()) {
      await dsbButton.click()
      await page.waitForTimeout(500)
      await waitForPageLoad(page)
    }
  }
}

// Navigate to SDK page and wait for load
export async function navigateToSDK(page: Page, path: string) {
  const targetUrl = `/sdk${path}`

  // First navigate to the page
  await page.goto(targetUrl)
  await waitForPageLoad(page)

  // Handle role selection if it appears
  await handleRoleSelection(page)

  // Always navigate again after role selection to ensure we reach the target
  const currentUrl = page.url()
  if (!currentUrl.includes('/sdk/dsr')) {
    await page.goto(targetUrl)
    await waitForPageLoad(page)
  }
}

// Check if element is visible
export async function isVisible(page: Page, selector: string): Promise<boolean> {
  const element = page.locator(selector)
  return await element.isVisible()
}

// Click and wait for navigation
export async function clickAndWait(page: Page, selector: string) {
  await page.click(selector)
  await waitForPageLoad(page)
}

// Fill form field
export async function fillField(page: Page, selector: string, value: string) {
  await page.fill(selector, value)
}

// Select dropdown option
export async function selectOption(page: Page, selector: string, value: string) {
  await page.selectOption(selector, value)
}

// Get text content of element
export async function getText(page: Page, selector: string): Promise<string> {
  const element = page.locator(selector)
  return await element.textContent() || ''
}

// Count elements
export async function countElements(page: Page, selector: string): Promise<number> {
  const elements = page.locator(selector)
  return await elements.count()
}

// Wait for element to appear
export async function waitForElement(page: Page, selector: string, timeout = 10000) {
  await page.waitForSelector(selector, { timeout })
}

// Check page title contains text
export async function checkTitleContains(page: Page, text: string) {
  await expect(page).toHaveTitle(new RegExp(text, 'i'))
}

// Check URL contains path
export async function checkUrlContains(page: Page, path: string) {
  await expect(page).toHaveURL(new RegExp(path))
}

// Take screenshot with timestamp
export async function takeScreenshot(page: Page, name: string) {
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-')
  await page.screenshot({ path: `e2e/screenshots/${name}-${timestamp}.png` })
}

// Check for console errors
export function setupConsoleErrorListener(page: Page): string[] {
  const errors: string[] = []
  page.on('console', msg => {
    if (msg.type() === 'error') {
      errors.push(msg.text())
    }
  })
  return errors
}

// Wait for API response
export async function waitForAPI(page: Page, urlPattern: string | RegExp) {
  await page.waitForResponse(response =>
    response.url().match(urlPattern) !== null && response.status() === 200
  )
}

// SDK specific helpers
export const SDK_PAGES = {
  // Phase 1
  useCaseWorkshop: '/advisory-board',
  screening: '/screening',
  modules: '/modules',
  requirements: '/requirements',
  controls: '/controls',
  evidence: '/evidence',
  auditChecklist: '/audit-checklist',
  risks: '/risks',
  // Phase 2
  aiAct: '/ai-act',
  obligations: '/obligations',
  dsfa: '/dsfa',
  tom: '/tom',
  einwilligungen: '/einwilligungen',
  loeschfristen: '/loeschfristen',
  vvt: '/vvt',
  consent: '/consent',
  cookieBanner: '/cookie-banner',
  dsr: '/dsr',
  escalations: '/escalations',
}

// DSR specific helpers
export const DSR_TYPES = {
  access: 'Art. 15',
  rectification: 'Art. 16',
  erasure: 'Art. 17',
  restriction: 'Art. 18',
  portability: 'Art. 20',
  objection: 'Art. 21',
}

export const DSR_STATUSES = {
  intake: 'Eingang',
  identity_verification: 'ID-Pruefung',
  processing: 'In Bearbeitung',
  completed: 'Abgeschlossen',
  rejected: 'Abgelehnt',
}
