import { test, expect } from '@playwright/test'
import { AuthHelper, generateTestEmail, generateTestPassword } from '../helpers/auth'
import { createEmailHelper } from '../helpers/email'

test.describe('solar icon variant UI', () => {
  let testEmail: string
  let testPassword: string

  test.beforeEach(async ({ page, request }) => {
    // Clean email inbox before each test
    const emailHelper = createEmailHelper(request)
    await emailHelper.deleteAllMessages()

    // Create unique test user for each test
    testEmail = generateTestEmail('danger-zone')
    testPassword = generateTestPassword()

    const auth = new AuthHelper(page)

    // 1. Register the user
    await auth.register(testEmail, testPassword, 'Danger Zone Test User')
    await page.waitForLoadState('networkidle')

    // 2. Wait for verification email and get verification link
    // Use longer timeout for CI environments
    const verificationEmail = await emailHelper.waitForEmail(testEmail, {
      subject: /verify/i,
      timeout: 30000
    })
    const verificationLink = await emailHelper.getVerificationLink(verificationEmail.ID)

    if (!verificationLink) {
      throw new Error(`No verification link found in email. Email ID: ${verificationEmail.ID}`)
    }

    // 3. Click verification link
    await page.goto(verificationLink)
    await page.waitForLoadState('networkidle')

    // 4. User should now be verified and logged in automatically
    // Wait for redirect to dashboard (autoSignInAfterVerification: true)
    await page.waitForURL('**/dashboard**', { timeout: 10000 })
  })

  test('changing variant updates rendered icons', async ({ page }) => {
    await page.goto('/dashboard')
    await page.waitForLoadState('networkidle')

    // Open the UserMenu by clicking the avatar button
    const userAvatarButton = page
      .getByRole('button')
      .filter({ has: page.locator('img[alt="Danger Zone Test User"]') })
      .first()

    if (await userAvatarButton.count() === 0) test.skip()
    await userAvatarButton.click()

    // Ensure the "Solar Icons" parent menu item is visible and open its submenu
    const solarIconsMenu = page.getByRole('menuitem', { name: /solar icons/i })
    await expect(solarIconsMenu).toBeVisible()
    await solarIconsMenu.hover()

    // Wait for submenu to render and scope to the active menu container
    const activeMenu = page.getByRole('menu').last()
    await expect(activeMenu).toBeVisible()

    // Target the desired variant within the active submenu
    const variantItem = activeMenu.getByRole('menuitemcheckbox', { name: /bold-duotone/i })
    await expect(variantItem).toBeVisible()
    await variantItem.scrollIntoViewIfNeeded()
    await variantItem.click()

    // The bell icon in navbar should include selected variant
    const bell = page.locator('[class*="i-solar-bell"], [data-icon*="bell"]').first()
    await expect(bell).toBeVisible()
    await expect(bell).toHaveClass(/i-solar-bell-bold-duotone/)
  })
})
