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

/**
 * 移动端响应式测试
 * 验证 iPhone SE (375px)、iPhone 12 (390px)、iPad (768px) 等常见设备的显示效果
 */

const MOBILE_VIEWPORTS = [
  { name: 'iPhone SE', width: 375, height: 667 },
  { name: 'iPhone 12', width: 390, height: 844 },
  { name: 'iPad Mini', width: 768, height: 1024 },
];

for (const device of MOBILE_VIEWPORTS) {
  test.describe(`移动端适配 - ${device.name} (${device.width}x${device.height})`, () => {

    test.beforeEach(async ({ page }) => {
      await page.setViewportSize({ width: device.width, height: device.height });
      await page.goto('/?mock=true');
      await page.waitForSelector('#dc-grid > *', { timeout: 10000 });
    });

    test('页面无横向滚动', async ({ page }) => {
      const scrollWidth = await page.evaluate(() => document.documentElement.scrollWidth);
      const clientWidth = await page.evaluate(() => document.documentElement.clientWidth);
      expect(scrollWidth).toBeLessThanOrEqual(clientWidth + 1);
    });

    test('标题可见且不溢出', async ({ page }) => {
      const title = page.locator('h1');
      await expect(title).toBeVisible();
      const box = await title.boundingBox();
      expect(box.x).toBeGreaterThanOrEqual(0);
      expect(box.x + box.width).toBeLessThanOrEqual(device.width);
    });

    test('导航 Tab 可见可点击', async ({ page }) => {
      const isMobile = device.width < 768;

      if (isMobile) {
        // 移动端：底部导航
        await expect(page.locator('#mobile-tab-monitor')).toBeVisible();
        await expect(page.locator('#mobile-tab-analytics')).toBeVisible();

        // 可以正常切换
        await page.click('#mobile-tab-analytics');
        await expect(page.locator('#analytics-content')).toBeVisible();

        await page.click('#mobile-tab-monitor');
        await expect(page.locator('#data-content')).toBeVisible();
      } else {
        // 平板/桌面端：顶部导航
        await expect(page.locator('#tab-monitor')).toBeVisible();
        await expect(page.locator('#tab-analytics')).toBeVisible();

        await page.click('#tab-analytics');
        await expect(page.locator('#analytics-content')).toBeVisible();

        await page.click('#tab-monitor');
        await expect(page.locator('#data-content')).toBeVisible();
      }
    });

    test('筛选按钮可滚动或换行显示', async ({ page }) => {
      const filterBar = page.locator('.filter-btn').first();
      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).toBeVisible();
        await btn.click();
        await page.waitForTimeout(200);
      }
    });

    test('充电桩卡片单列或双列显示', async ({ page }) => {
      // DC 卡片应可见
      const dcCards = page.locator('#dc-grid > div');
      await expect(dcCards.first()).toBeVisible();

      // AC 卡片应可见
      const acCards = page.locator('#ac-grid > div');
      await expect(acCards.first()).toBeVisible();

      // 卡片宽度不应超出视口
      const firstCard = dcCards.first();
      const box = await firstCard.boundingBox();
      expect(box.x).toBeGreaterThanOrEqual(0);
      expect(box.x + box.width).toBeLessThanOrEqual(device.width);
    });

    test('底部导航/订阅栏显示逻辑正确', async ({ page }) => {
      const isMobile = device.width < 768;
      const isWeekend = new Date().getDay() === 0 || new Date().getDay() === 6;

      if (isMobile) {
        // 移动端：底部导航栏 + 订阅栏
        const mobileNav = page.locator('#mobile-nav');
        await expect(mobileNav).toBeVisible();

        // 订阅栏在导航上方
        const subscribeBar = page.locator('#mobile-subscribe-bar');
        await expect(subscribeBar).toBeVisible();

        // 检查订阅按钮状态
        const subscribeBtn = page.locator('#mobile-subscribe-btn');
        await expect(subscribeBtn).toBeVisible();

        if (isWeekend) {
          await expect(subscribeBtn).toBeDisabled();
          const className = await subscribeBar.getAttribute('class');
          expect(className).toContain('opacity-50');
        }
      } else {
        // 平板/桌面端：底部订阅栏
        const bottomBar = page.locator('#bottom-bar');
        await expect(bottomBar).toBeVisible();

        if (isWeekend) {
          const className = await bottomBar.getAttribute('class');
          expect(className).toContain('opacity-50');
        }

        const box = await bottomBar.boundingBox();
        expect(box.y).toBeGreaterThanOrEqual(0);
      }
    });

    test('订阅弹窗在移动端正常显示', async ({ page }) => {
      const isWeekend = new Date().getDay() === 0 || new Date().getDay() === 6;
      const isMobile = device.width < 768;

      if (isWeekend) {
        test.skip();
        return;
      }

      // 点击订阅按钮（移动端或桌面端）
      if (isMobile) {
        await page.click('#mobile-subscribe-btn');
      } else {
        await page.click('button:has-text("订阅提醒")');
      }

      await expect(page.locator('#subscribe-modal')).toBeVisible();

      // 弹窗内容不应超出视口
      const modal = page.locator('.modal-content');
      const box = await modal.boundingBox();
      expect(box.x).toBeGreaterThanOrEqual(0);
      expect(box.x + box.width).toBeLessThanOrEqual(device.width + 1);

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

    test('充电桩卡片内容可读', async ({ page }) => {
      // 检查卡片内的文本是否可见
      const firstCard = page.locator('#ac-grid > div').first();
      const text = await firstCard.innerText();
      // 应包含充电桩名称和状态
      expect(text.length).toBeGreaterThan(0);
    });

    // ==================== 新增测试：筛选后组件大小不变 ====================
    test('筛选后卡片大小保持不变', async ({ page }) => {
      // 获取筛选前的卡片尺寸
      const card = page.locator('#dc-grid > div').first();
      const boxBefore = await card.boundingBox();

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

      // 筛选后卡片尺寸应与之前相近（允许 10% 误差）
      const boxAfter = await card.boundingBox();
      expect(Math.abs(boxAfter.width - boxBefore.width)).toBeLessThan(boxBefore.width * 0.1);
      expect(Math.abs(boxAfter.height - boxBefore.height)).toBeLessThan(boxBefore.height * 0.1);
    });

    test('筛选后页面无横向滚动', async ({ page }) => {
      // 点击筛选
      await page.click('#filter-charging');
      await page.waitForTimeout(500);

      // 检查无横向滚动
      const scrollWidth = await page.evaluate(() => document.documentElement.scrollWidth);
      const clientWidth = await page.evaluate(() => document.documentElement.clientWidth);
      expect(scrollWidth).toBeLessThanOrEqual(clientWidth + 1);
    });

    // ==================== 新增测试：数据分析页面可滚动查看 ====================
    test('数据分析页面数据概览可滚动查看', async ({ page }) => {
      const isMobile = device.width < 768;

      // 切换到数据分析
      if (isMobile) {
        await page.click('#mobile-tab-analytics');
      } else {
        await page.click('#tab-analytics');
      }
      await page.waitForTimeout(1000);

      // 数据概览卡片应可见
      const overviewCards = page.locator('#overview-cards');
      await expect(overviewCards).toBeVisible();

      // 验证数据概览卡片在视口内或可滚动到
      const cardsBox = await overviewCards.boundingBox();
      expect(cardsBox).not.toBeNull();

      // 滚动到数据概览区域
      await overviewCards.scrollIntoViewIfNeeded();
      await page.waitForTimeout(300);

      // 验证至少有一个子卡片可见
      const childCards = overviewCards.locator('> div');
      const count = await childCards.count();
      expect(count).toBeGreaterThan(0);

      // 第一个卡片应可见
      await expect(childCards.first()).toBeVisible();
    });

    test('数据分析页面图表可滚动查看', async ({ page }) => {
      const isMobile = device.width < 768;

      // 切换到数据分析
      if (isMobile) {
        await page.click('#mobile-tab-analytics');
      } else {
        await page.click('#tab-analytics');
      }
      await page.waitForTimeout(1000);

      // 向下滚动查看图表
      await page.locator('#rank-chart').scrollIntoViewIfNeeded();
      await page.waitForTimeout(300);

      // 验证排名图表可见
      await expect(page.locator('#rank-chart')).toBeVisible();
    });

    test('数据分析页面无横向滚动', async ({ page }) => {
      const isMobile = device.width < 768;

      // 切换到数据分析
      if (isMobile) {
        await page.click('#mobile-tab-analytics');
      } else {
        await page.click('#tab-analytics');
      }
      await page.waitForTimeout(1000);

      // 检查无横向滚动
      const scrollWidth = await page.evaluate(() => document.documentElement.scrollWidth);
      const clientWidth = await page.evaluate(() => document.documentElement.clientWidth);
      expect(scrollWidth).toBeLessThanOrEqual(clientWidth + 1);
    });
  });
}

test.describe('移动端截图对比', () => {

  test('iPhone SE 首页截图', async ({ page }) => {
    await page.setViewportSize({ width: 375, height: 667 });
    await page.goto('/?mock=true');
    await page.waitForSelector('#dc-grid > *', { timeout: 10000 });
    await page.screenshot({ path: 'test-results/mobile-iphone-se.png', fullPage: true });
  });

  test('iPhone 12 首页截图', async ({ page }) => {
    await page.setViewportSize({ width: 390, height: 844 });
    await page.goto('/?mock=true');
    await page.waitForSelector('#dc-grid > *', { timeout: 10000 });
    await page.screenshot({ path: 'test-results/mobile-iphone-12.png', fullPage: true });
  });
});
