// @ts-check
const { test, expect } = require('@playwright/test');

const CARD_SELECTOR = '#dc-grid > [data-connector-id], #ac-grid > [data-connector-id]';
const VISIBLE_CARD_SELECTOR = '#dc-grid > [data-connector-id]:visible, #ac-grid > [data-connector-id]:visible';
const DC_CARD_SELECTOR = '#dc-grid > [data-connector-id]';
const AC_CARD_SELECTOR = '#ac-grid > [data-connector-id]';

async function waitForCards(page) {
  await page.waitForSelector(CARD_SELECTOR, { timeout: 10000 });
}

/**
 * 筛选器功能完整测试
 * 验证功能点：
 * 1. 筛选按钮点击切换
 * 2. 筛选后卡片显示/隐藏
 * 3. 筛选后计数更新
 * 4. 筛选按钮样式变化
 * 5. 移动端筛选器滚动
 * 6. 筛选状态持久化（URL参数）
 */

test.describe('筛选器功能测试', () => {

  test.beforeEach(async ({ page }) => {
    await page.addInitScript(() => {
      sessionStorage.setItem('dc_intro_played', '1');
      localStorage.setItem('guide_dismissed_until', String(Date.now() + 30 * 24 * 60 * 60 * 1000));
    });
    await page.goto('/?mock=true');
    await waitForCards(page);
  });

  test.describe('筛选按钮基础交互', () => {

    test('默认选中"全部设备"', async ({ page }) => {
      const allBtn = page.locator('#filter-all');
      await expect(allBtn).toHaveClass(/active/);
      await expect(allBtn).toHaveClass(/bg-slate-800/);
    });

    test('点击"空闲"筛选按钮', async ({ page }) => {
      await page.click('#filter-free');
      await page.waitForTimeout(300);

      const freeBtn = page.locator('#filter-free');
      await expect(freeBtn).toHaveClass(/active/);
      await expect(freeBtn).toHaveClass(/text-emerald-400/);

      // 全部按钮应该取消 active
      const allBtn = page.locator('#filter-all');
      await expect(allBtn).not.toHaveClass(/active/);
    });

    test('点击"充电中"筛选按钮', async ({ page }) => {
      await page.click('#filter-charging');
      await page.waitForTimeout(300);

      const chargingBtn = page.locator('#filter-charging');
      await expect(chargingBtn).toHaveClass(/active/);
      await expect(chargingBtn).toHaveClass(/text-cyan-400/);
    });

    test('点击"占位中"筛选按钮', async ({ page }) => {
      await page.click('#filter-occupied');
      await page.waitForTimeout(300);

      const occupiedBtn = page.locator('#filter-occupied');
      await expect(occupiedBtn).toHaveClass(/active/);
      await expect(occupiedBtn).toHaveClass(/text-orange-400/);
    });

    test('筛选按钮可循环切换', async ({ page }) => {
      const filters = ['filter-free', 'filter-charging', 'filter-occupied', 'filter-all'];

      for (const filterId of filters) {
        await page.click(`#${filterId}`);
        await page.waitForTimeout(200);
        const btn = page.locator(`#${filterId}`);
        await expect(btn).toHaveClass(/active/);
      }
    });
  });

  test.describe('筛选后卡片显示', () => {

    test('筛选"空闲"只显示空闲卡片', async ({ page }) => {
      await page.click('#filter-free');
      await page.waitForTimeout(500);

      // 检查所有可见的卡片都包含"空闲"文字
      const visibleCards = page.locator(VISIBLE_CARD_SELECTOR);
      const count = await visibleCards.count();

      if (count > 0) {
        // 每张可见卡片应包含"空闲"状态
        for (let i = 0; i < count; i++) {
          const card = visibleCards.nth(i);
          const text = await card.innerText();
          expect(text).toContain('空闲');
        }
      }
    });

    test('筛选"充电中"只显示充电中卡片', async ({ page }) => {
      await page.click('#filter-charging');
      await page.waitForTimeout(500);

      const visibleCards = page.locator(VISIBLE_CARD_SELECTOR);
      const count = await visibleCards.count();

      if (count > 0) {
        for (let i = 0; i < count; i++) {
          const card = visibleCards.nth(i);
          const text = await card.innerText();
          // 充电中卡片包含"充电中"或"充电"字样
          const hasCharging = text.includes('充电中') || text.includes('充电');
          expect(hasCharging).toBe(true);
        }
      }
    });

    test('筛选"占位中"只显示占位卡片', async ({ page }) => {
      await page.click('#filter-occupied');
      await page.waitForTimeout(500);

      const visibleCards = page.locator(VISIBLE_CARD_SELECTOR);
      const count = await visibleCards.count();

      if (count > 0) {
        for (let i = 0; i < count; i++) {
          const card = visibleCards.nth(i);
          const text = await card.innerText();
          expect(text).toContain('占位');
        }
      }
    });

    test('筛选"全部"显示所有卡片', async ({ page }) => {
      // 先筛选空闲
      await page.click('#filter-free');
      await page.waitForTimeout(300);

      // 再切回全部
      await page.click('#filter-all');
      await page.waitForTimeout(500);

      // 所有卡片应该可见
      const dcCards = page.locator(DC_CARD_SELECTOR);
      const acCards = page.locator(AC_CARD_SELECTOR);

      const dcCount = await dcCards.count();
      const acCount = await acCards.count();

      expect(dcCount).toBeGreaterThan(0);
      expect(acCount).toBeGreaterThan(0);
    });
  });

  test.describe('筛选后计数更新', () => {

    test('筛选按钮显示正确的计数', async ({ page }) => {
      // 等待数据加载
      await page.waitForTimeout(500);

      // 获取计数
      const countAll = await page.locator('#count-all').textContent();
      const countFree = await page.locator('#count-free').textContent();
      const countCharging = await page.locator('#count-charging').textContent();
      const countOccupied = await page.locator('#count-occupied').textContent();

      // 全部计数应该等于其他三项之和
      const total = parseInt(countAll) || 0;
      const free = parseInt(countFree) || 0;
      const charging = parseInt(countCharging) || 0;
      const occupied = parseInt(countOccupied) || 0;

      expect(total).toBe(free + charging + occupied);
    });

    test('筛选后计数数字保持不变', async ({ page }) => {
      // 获取筛选前的计数
      const countBefore = await page.locator('#count-free').textContent();

      // 点击筛选
      await page.click('#filter-free');
      await page.waitForTimeout(500);

      // 计数应该保持不变
      const countAfter = await page.locator('#count-free').textContent();
      expect(countAfter).toBe(countBefore);
    });
  });

  test.describe('筛选按钮样式变化', () => {

    test('选中状态按钮有背景色', async ({ page }) => {
      await page.click('#filter-free');
      await page.waitForTimeout(200);

      const freeBtn = page.locator('#filter-free');
      await expect(freeBtn).toHaveClass(/bg-emerald-500/);
    });

    test('未选中状态按钮无背景色', async ({ page }) => {
      // 点击空闲
      await page.click('#filter-free');
      await page.waitForTimeout(200);

      // 全部按钮应该没有背景色
      const allBtn = page.locator('#filter-all');
      const className = await allBtn.getAttribute('class');
      // 不应该有 bg-slate-800（active 状态的背景）
      expect(className).not.toMatch(/bg-slate-800(?!\/)/);
    });

    test('筛选按钮 hover 效果', async ({ page }) => {
      const freeBtn = page.locator('#filter-free');

      // hover 前不应该有 hover 类
      await expect(freeBtn).not.toHaveClass(/hover:bg-emerald-500/);

      // hover 后应该有效果（通过 CSS 伪类实现，这里验证按钮可交互）
      await freeBtn.hover();
      await page.waitForTimeout(100);
      await expect(freeBtn).toBeVisible();
    });
  });

  test.describe('筛选器响应式测试', () => {

    test('移动端筛选器可横向滚动', async ({ page }) => {
      await page.setViewportSize({ width: 375, height: 667 });
      await page.goto('/?mock=true');
      await waitForCards(page);

      // 筛选按钮容器
      const filterBar = page.locator('.filter-bar-scroll');
      await expect(filterBar).toBeVisible();

      // 所有筛选按钮应该都存在（可能需要滚动才能看到）
      const filters = ['filter-all', 'filter-free', 'filter-charging', 'filter-occupied'];
      for (const id of filters) {
        const btn = page.locator(`#${id}`);
        await expect(btn).toBeAttached();
      }
    });

    test('移动端筛选功能正常', async ({ page }) => {
      await page.setViewportSize({ width: 375, height: 667 });
      await page.goto('/?mock=true');
      await waitForCards(page);

      // 滚动到筛选按钮区域
      await page.locator('#filter-free').scrollIntoViewIfNeeded();

      // 点击空闲筛选
      await page.click('#filter-free');
      await page.waitForTimeout(500);

      const freeBtn = page.locator('#filter-free');
      await expect(freeBtn).toHaveClass(/active/);
    });

    test('平板端筛选器完整显示', async ({ page }) => {
      await page.setViewportSize({ width: 768, height: 1024 });
      await page.goto('/?mock=true');
      await waitForCards(page);

      // 所有筛选按钮应该可见
      const filters = ['filter-all', 'filter-free', 'filter-charging', 'filter-occupied'];
      for (const id of filters) {
        const btn = page.locator(`#${id}`);
        await expect(btn).toBeVisible();
      }
    });
  });

  test.describe('筛选与其他功能联动', () => {

    test('筛选后刷新数据保持筛选状态', async ({ page }) => {
      // 点击空闲筛选
      await page.click('#filter-free');
      await page.waitForTimeout(300);

      // 刷新数据 - 使用 force 点击绕过 Mock 设置按钮遮挡
      await page.locator('button[title="手动刷新"]').click({ force: true });
      await page.waitForTimeout(500);

      // 筛选状态应该保持
      const freeBtn = page.locator('#filter-free');
      await expect(freeBtn).toHaveClass(/active/);
    });

    test('切换 Tab 后筛选状态保持', async ({ page }) => {
      // 点击空闲筛选
      await page.click('#filter-free');
      await page.waitForTimeout(300);

      // 切换到数据分析
      await page.click('#tab-analytics');
      await page.waitForTimeout(500);

      // 切换回实时监控
      await page.click('#tab-monitor');
      await page.waitForTimeout(500);

      // 筛选状态应该保持为"空闲"（不是重置）
      const freeBtn = page.locator('#filter-free');
      await expect(freeBtn).toHaveClass(/active/);
    });

    test('筛选后订阅弹窗正常打开', async ({ page }) => {
      const isWeekend = new Date().getDay() === 0 || new Date().getDay() === 6;
      if (isWeekend) {
        test.skip();
        return;
      }

      // 点击空闲筛选
      await page.click('#filter-free');
      await page.waitForTimeout(300);

      // 打开订阅弹窗
      await page.click('button:has-text("订阅提醒")');
      await expect(page.locator('#subscribe-modal')).toBeVisible();

      // 关闭弹窗
      await page.locator('#subscribe-modal button[class*="absolute"]').click();
      await expect(page.locator('#subscribe-modal')).toBeHidden();

      // 筛选状态应该保持
      const freeBtn = page.locator('#filter-free');
      await expect(freeBtn).toHaveClass(/active/);
    });
  });

  test.describe('筛选器边界情况', () => {

    test('快速连续点击筛选按钮', async ({ page }) => {
      // 快速连续点击
      await page.click('#filter-free');
      await page.click('#filter-charging');
      await page.click('#filter-occupied');
      await page.click('#filter-all');
      await page.waitForTimeout(500);

      // 最终应该是"全部"状态
      const allBtn = page.locator('#filter-all');
      await expect(allBtn).toHaveClass(/active/);
    });

    test('筛选无结果时的显示', async ({ page }) => {
      // 点击占位筛选（Mock 数据可能没有占位桩）
      await page.click('#filter-occupied');
      await page.waitForTimeout(500);

      // 网格容器应该仍然存在（即使为空）
      await expect(page.locator('#dc-grid')).toBeAttached();
      await expect(page.locator('#ac-grid')).toBeAttached();
    });
  });
});

test.describe('筛选器可访问性测试', () => {

  test.beforeEach(async ({ page }) => {
    await page.addInitScript(() => {
      sessionStorage.setItem('dc_intro_played', '1');
      localStorage.setItem('guide_dismissed_until', String(Date.now() + 30 * 24 * 60 * 60 * 1000));
    });
    await page.goto('/?mock=true');
    await waitForCards(page);
  });

  test('筛选按钮可通过键盘导航', async ({ page }) => {
    // Tab 到筛选按钮区域
    await page.keyboard.press('Tab');
    await page.keyboard.press('Tab');

    // 应该能够聚焦到筛选按钮
    const focusedElement = page.locator(':focus');
    await expect(focusedElement).toBeVisible();
  });

  test('筛选按钮可通过 Enter 键激活', async ({ page }) => {
    // 聚焦到空闲筛选按钮
    await page.locator('#filter-free').focus();
    await page.keyboard.press('Enter');
    await page.waitForTimeout(300);

    const freeBtn = page.locator('#filter-free');
    await expect(freeBtn).toHaveClass(/active/);
  });
});
