import type { DesktopLoginCodeRedeemResponse } from '@comfyorg/ingest-types'
import { expect } from '@playwright/test'
import type { Page } from '@playwright/test'

import enMessages from '@/locales/en/main.json' with { type: 'json' }

import { agentConsentTest as test } from '@e2e/fixtures/agentConsentFixture'

const build = process.env.QA_BUILD === 'base' ? 'base' : 'fix'
const SHOTS = '/Users/maanilverma/Documents/ComfyUI_frontend/temp/qa-evidence/fe-2808'
const AUTO_SHOWN_KEY = 'Comfy.AgentConsent.AutoShown.test-user-e2e.ws-personal'

async function shot(page: Page, name: string): Promise<void> {
  await page.evaluate(() =>
    Promise.all(
      document
        .getAnimations()
        .filter((a) => a.effect?.getComputedTiming().iterations !== Infinity)
        .map((a) => a.finished.catch(() => {}))
    )
  )
  await page.addStyleTag({
    content:
      '.p-toast,[data-pc-name="toast"],.comfy-toast,.p-toast-message{display:none!important}'
  })
  await page.screenshot({ path: `${SHOTS}/${build}-${name}.png`, fullPage: true })
}

function consentCard(page: Page) {
  return page.getByRole('dialog', { name: enMessages.agent.consent.title })
}

test.describe('QA FE-2808: desktop sign-in approval', { tag: ['@cloud', '@ui'] }, () => {
  test.use({
    agentConsentAccepted: false,
    initialUrl: '/?desktop_login_code=dlc_e2eApprovalCodeFE2808abcdefghijklmnopqrstu'
  })

  test('approval vs automatic Agent card', async ({ comfyPage, agentConsentReads }) => {
    const page = comfyPage.page
    const approval = page.getByRole('dialog', {
      name: enMessages.desktopLogin.confirmSummary
    })
    const approve = approval.getByRole('button', { name: enMessages.g.confirm })
    await page.route('**/api/auth/desktop-login-codes/redeem', (route) =>
      route.fulfill({
        status: 200,
        json: { status: 'redeemed' } satisfies DesktopLoginCodeRedeemResponse
      })
    )
    await expect.poll(() => agentConsentReads.length, { timeout: 15_000 }).toBeGreaterThan(0)

    if (build === 'base') {
      await expect(consentCard(page)).toBeVisible()
      await expect(approval).toHaveCount(0)
      await shot(page, 'approval-covered-by-card')
      return
    }

    await expect(approval).toBeVisible()
    await approve.click({ trial: true })
    await expect(consentCard(page)).toHaveCount(0)
    await shot(page, 'approval-on-top')

    await approve.click()
    await expect(approval).toHaveCount(0)
    await expect(consentCard(page)).toBeVisible()
    await shot(page, 'card-after-approval')
  })
})

test.describe('QA FE-2808: startup template browser', { tag: ['@cloud', '@ui'] }, () => {
  test.use({
    agentConsentAccepted: false,
    initialSettings: { 'Comfy.TutorialCompleted': false },
    initialFeatureFlags: { onboarding_tour_enabled: false }
  })

  test('template browser vs automatic Agent card', async ({ comfyPage, agentConsentReads }) => {
    const page = comfyPage.page
    await expect(comfyPage.templates.content).toBeVisible()
    await expect.poll(() => agentConsentReads.length, { timeout: 15_000 }).toBeGreaterThan(0)

    if (build === 'base') {
      await expect(consentCard(page)).toBeVisible()
      await shot(page, 'template-browser-covered-by-card')
      return
    }

    await expect(consentCard(page)).toHaveCount(0)
    expect(await page.evaluate((k) => localStorage.getItem(k), AUTO_SHOWN_KEY)).toBeNull()
    await shot(page, 'template-browser-first')

    await page.keyboard.press('Escape')
    await expect(comfyPage.templates.content).toHaveCount(0)
    await expect(consentCard(page)).toBeVisible()
    await shot(page, 'card-after-template-browser')
  })
})

test.describe('QA FE-2808: Agent button', { tag: ['@cloud', '@ui'] }, () => {
  test.use({
    agentConsentAccepted: false,
    initialLocalStorage: { [AUTO_SHOWN_KEY]: 'true' }
  })

  test('the button still opens the card right away', async ({ comfyPage, agentPanel }) => {
    const page = comfyPage.page
    await expect(consentCard(page)).toHaveCount(0)
    await agentPanel.openButton.click()
    await expect(consentCard(page)).toBeVisible()
    await shot(page, 'button-opens-card')
  })
})
