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

test('debug login flow with subdomain redirect', async ({ page }) => {
  // Navigate to login page first
  await page.goto('http://lvh.me:5173');

  // Clear storage
  await page.context().clearCookies();
  await page.evaluate(() => {
    localStorage.clear();
    sessionStorage.clear();
  });

  console.log('Step 1: On login page');
  await expect(page.getByRole('heading', { name: /sign in to your account/i })).toBeVisible();

  // Fill credentials
  await page.getByPlaceholder(/username/i).fill('poduck');
  await page.getByPlaceholder(/password/i).fill('starry12');

  console.log('Step 2: Filled credentials');

  // Click sign in and wait for navigation
  await Promise.all([
    page.waitForURL(/platform\.lvh\.me|lvh\.me/, { timeout: 10000 }),
    page.getByRole('button', { name: /sign in/i }).click(),
  ]);

  const urlAfterLogin = page.url();
  console.log('Step 3: URL after login click:', urlAfterLogin);

  // Wait a bit for any redirects/reloads
  await page.waitForTimeout(3000);

  const finalUrl = page.url();
  console.log('Step 4: Final URL:', finalUrl);

  // Take screenshot
  await page.screenshot({ path: 'login-debug.png', fullPage: true });

  // Check what's on the page
  const pageContent = await page.content();
  console.log('Page title:', await page.title());
  console.log('Has "Platform Dashboard":', pageContent.includes('Platform Dashboard'));
  console.log('Has "Loading":', pageContent.includes('Loading'));
  console.log('Has "Sign in":', pageContent.includes('Sign in'));

  // Check localStorage
  const tokens = await page.evaluate(() => ({
    access: localStorage.getItem('access_token'),
    refresh: localStorage.getItem('refresh_token'),
  }));
  console.log('Tokens in localStorage:', {
    access: tokens.access ? tokens.access.substring(0, 20) + '...' : 'null',
    refresh: tokens.refresh ? tokens.refresh.substring(0, 20) + '...' : 'null',
  });
});
