import { expect, test } from './fixtures';

const moicenUnionid = process.env.MOICEN_E2E_UNIONID?.trim();

test('debug role switcher visibility', async ({ page }) => {
  test.setTimeout(120_000);

  const q = new URLSearchParams({ unionid: moicenUnionid!, status: '2' });
  await page.goto(`/?${q.toString()}`, {
    waitUntil: 'domcontentloaded',
    timeout: 60_000,
  });
  await expect(page.locator('#app')).toBeVisible({ timeout: 60_000 });
  await page.waitForTimeout(5000);

  const roleSelect = page.getByText('请选择您的登录身份');
  if (await roleSelect.isVisible().catch(() => false)) {
    const studentRole = page.locator('.van-grid-item').filter({ hasText: '学生' });
    if (await studentRole.isVisible().catch(() => false)) {
      await studentRole.click();
      await page.waitForTimeout(5000);
    }
  }

  if (page.url().includes('/org/select')) {
    const orgCells = page.locator('#app .van-cell-group .van-cell');
    const n = await orgCells.count();
    console.log(`org cells count: ${n}`);
    expect(n).toBeGreaterThan(0);
    
    // Check token before org select
    const tokenBefore = await page.evaluate(() => window.localStorage.getItem('Authorization'));
    console.log(`token before org select: ${tokenBefore ? 'EXISTS' : 'NONE'}`);
    
    await orgCells.first().click();
    await page.waitForTimeout(5000);
    
    // Check URL and token after org select
    console.log(`URL after org select click + wait: ${page.url()}`);
    const tokenAfter = await page.evaluate(() => window.localStorage.getItem('Authorization'));
    console.log(`token after org select: ${tokenAfter ? 'EXISTS' : 'NONE'}`);
    const currentRole = await page.evaluate(() => window.localStorage.getItem('CurrentUserRole'));
    console.log(`CurrentUserRole: ${currentRole}`);
    const teacherId = await page.evaluate(() => window.localStorage.getItem('CurrentTeacherId'));
    console.log(`CurrentTeacherId: ${teacherId}`);
    
    await page.goto('/student/profile', {
      waitUntil: 'domcontentloaded',
      timeout: 60_000,
    });
    await expect(page.locator('#app')).toBeVisible({ timeout: 60_000 });
    
    // Immediately check URL after navigation
    console.log(`URL right after navigating to /student/profile: ${page.url()}`);
    const tokenNav = await page.evaluate(() => window.localStorage.getItem('Authorization'));
    console.log(`token after navigate: ${tokenNav ? 'EXISTS' : 'NONE'}`);
  }

  await page.waitForTimeout(2000);
  console.log(`URL after 2s: ${page.url()}`);

  // Check full state
  const state = await page.evaluate(() => {
    const keys = Object.keys(window.localStorage);
    const store: Record<string, string | null> = {};
    for (const k of keys) store[k] = window.localStorage.getItem(k);
    return store;
  });
  console.log(`localStorage keys: ${JSON.stringify(Object.keys(state))}`);
  console.log(`Authorization: ${state['Authorization'] ? 'EXISTS' : 'NONE'}`);
  
  const els = await page.evaluate(() => {
    const result: string[] = [];
    document.querySelectorAll('.van-icon').forEach(el => {
      result.push(el.className);
    });
    return result;
  });
  console.log(`icons: ${JSON.stringify(els)}`);
  
  const profileInfo = await page.locator('.info').isVisible().catch(() => false);
  console.log(`profile .info visible: ${profileInfo}`);
  
  const roleSwitcher = await page.locator('.van-icon-exchange').isVisible().catch(() => false);
  console.log(`role switcher visible: ${roleSwitcher}`);
});
