import type { Page, Locator } from '@playwright/test'

/**
 * Fill an input and trigger Vue's v-model reactivity
 * This ensures Vue properly updates its reactive state from Playwright actions
 *
 * This helper works specifically with Nuxt UI's UInput component by:
 * 1. Using Playwright's fill() to set the DOM value
 * 2. Manually triggering the input event that Vue's @input handler expects
 * 3. Waiting for Vue's reactivity to complete
 */
export async function fillInput(input: Locator, value: string) {
  // Use Playwright's fill which properly sets the value
  await input.fill(value)

  // Trigger Vue's input event handler manually
  await input.dispatchEvent('input', { bubbles: true })

  // Wait for Vue reactivity
  await input.page().waitForTimeout(100)
}

/**
 * Language configuration for tests
 * Default language is Dutch (nl-BE)
 */
export const TEST_LANGUAGE = {
  // Auth
  signIn: 'Inloggen',
  signUp: 'Registreren',
  email: 'E-mail',
  password: 'Wachtwoord',
  name: 'Naam',

  // Pages
  createAccount: 'Account Aanmaken',
  forgotPassword: 'Wachtwoord Vergeten',
  resetPassword: 'Wachtwoord Herstellen',
  magicLink: 'Inloggen met Magic Link',

  // Messages
  verifyEmail: /Verifieer Je E-mail|verificatie/i,
  emailSent: /E-mail Verstuurd|Verstuurd/i,
  magicLinkSent: /Magic Link Verstuurd/i,
  passwordResetSuccess: /Wachtwoord Succesvol Hersteld/i,
  invalidToken: /Ongeldige Token|token.*ongeldig|token.*verlopen/i,

  // Validation
  passwordMinLength: /minimaal 8 tekens/i,
  passwordsDoNotMatch: /komen niet overeen/i,

  // Links
  backToLogin: 'Terug naar inloggen',
  forgotPasswordLink: 'Wachtwoord vergeten',
  noAccount: 'Nog geen account',
  hasAccount: 'Al een account',

  // Buttons
  sendResetLink: 'Herstellink Versturen',
  sendMagicLink: 'Magic Link Versturen',
  resetButton: 'Wachtwoord Herstellen',
  updatePassword: 'Wachtwoord Bijwerken',
  deleteAccount: 'Account Verwijderen',

  // Other
  or: /^of$/i,
  linkExpires: /15 minuten/i,
  changePassword: 'Wachtwoord Wijzigen',
  dangerZone: 'Gevarenzone',
  passkeys: 'Passkeys',

  // Error messages (generic patterns)
  errorGeneric: /Invalid|error|failed|incorrect|fout|mislukt|ongeldig/i
}

/**
 * Helper class for authentication-related actions in E2E tests
 */
export class AuthHelper {
  constructor(private page: Page) {}

  /**
   * Register a new user
   */
  async register(email: string, password: string, name: string) {
    await this.page.goto('/auth/register')
    // Use networkidle with extended timeout for CI environments
    await this.page.waitForLoadState('networkidle', { timeout: 60000 })

    const nameInput = this.page.locator('input[type="text"]')
    const emailInput = this.page.locator('input[type="email"]')
    const passwordInput = this.page.locator('input[type="password"]')
    const submitButton = this.page.locator('button[type="submit"]')

    // Fill inputs and trigger Vue's v-model reactivity
    await fillInput(nameInput, name)
    await fillInput(emailInput, email)
    await fillInput(passwordInput, password)

    // Wait for button to be enabled before clicking
    await submitButton.waitFor({ state: 'visible' })
    await submitButton.click({ timeout: 5000 })
  }

  /**
   * Login with email and password
   */
  async login(email: string, password: string) {
    await this.page.goto('/auth')
    // Use networkidle with extended timeout for CI environments
    await this.page.waitForLoadState('networkidle', { timeout: 60000 })

    const emailInput = this.page.locator('input[type="email"]')
    const passwordInput = this.page.locator('input[type="password"]')
    const submitButton = this.page.locator('button[type="submit"]')

    // Fill inputs and trigger Vue's v-model reactivity
    await fillInput(emailInput, email)
    await fillInput(passwordInput, password)

    // Wait for button to be enabled and click
    await submitButton.waitFor({ state: 'visible' })
    await submitButton.click({ timeout: 5000 })
  }
}

/**
 * Generate a unique test email address
 */
export function generateTestEmail(prefix = 'test'): string {
  return `${prefix}-${Date.now()}@example.com`
}

/**
 * Generate a secure test password
 */
export function generateTestPassword(): string {
  return `TestPass${Date.now()}!`
}
