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

test.describe('SmartAuth: Passkey Management', () => {
  test.beforeEach(async ({ page }) => {
    await page.goto('/login');
    await page.evaluate(() => {
      localStorage.setItem('admin_access_token', 'mock-token');
      localStorage.setItem('admin_refresh_token', 'mock-refresh');
      localStorage.setItem(
        'admin_auth_user',
        JSON.stringify({
          email: 'admin@example.com',
          name: 'Admin User',
          role: 'super_admin',
        })
      );
    });
  });

  test('passkey management page loads', async ({ page }) => {
    await page.route('**/api/auth/passkeys', async route => {
      await route.fulfill({ status: 200, contentType: 'application/json', body: '[]' });
    });
    await page.goto('/settings/passkeys');
    await expect(page.getByRole('heading', { name: 'Passkeys' })).toBeVisible({ timeout: 10000 });
  });

  test('shows empty state when no passkeys', async ({ page }) => {
    await page.route('**/api/auth/passkeys', async route => {
      await route.fulfill({ status: 200, contentType: 'application/json', body: '[]' });
    });
    await page.goto('/settings/passkeys');
    await expect(page.getByText('No passkeys registered yet')).toBeVisible({ timeout: 10000 });
  });

  test('shows Add passkey button', async ({ page }) => {
    await page.route('**/api/auth/passkeys', async route => {
      await route.fulfill({ status: 200, contentType: 'application/json', body: '[]' });
    });
    await page.goto('/settings/passkeys');
    await expect(page.getByRole('button', { name: /add passkey/i })).toBeVisible({
      timeout: 10000,
    });
  });

  test('renders passkey cards when passkeys exist', async ({ page }) => {
    await page.route('**/api/auth/passkeys', async route => {
      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify([
          {
            id: 'pk-1',
            friendlyName: 'MacBook Pro Touch ID',
            deviceType: 'platform',
            backedUp: true,
            lastUsedAt: new Date().toISOString(),
            createdAt: new Date().toISOString(),
          },
          {
            id: 'pk-2',
            friendlyName: 'YubiKey 5C',
            deviceType: 'cross-platform',
            backedUp: false,
            lastUsedAt: null,
            createdAt: new Date().toISOString(),
          },
        ]),
      });
    });
    await page.goto('/settings/passkeys');
    await expect(page.getByText('MacBook Pro Touch ID')).toBeVisible({ timeout: 10000 });
    await expect(page.getByText('YubiKey 5C')).toBeVisible();
    await expect(page.getByText(/Built-in authenticator/)).toBeVisible();
    await expect(page.getByText('Security key', { exact: true })).toBeVisible();
  });
});
