/* eslint-disable @typescript-eslint/no-unused-vars */
import React from "react";
import { testExamples, render, fireEvent, act } from "@test/utils";
import AlertCloseExample from "../_example/AlertCloseExample";
import AlertCarouselExample from "../_example/AlertCarouselExample";

// 测试组件代码 Example 快照
testExamples(__dirname);

// 测试关闭逻辑
test("<Alert> can be closable", () => {
  const root = render(<AlertCloseExample />);
  expect(root.queryByText("非受控关闭")).not.toBeNull();
  expect(root.queryByText("受控关闭")).not.toBeNull();

  // 关闭非受控的
  act(() => {
    fireEvent.click(root.container.querySelector(".tea-icon-close"));
    jest.advanceTimersByTime(1000);
  });
  expect(root.queryByText("非受控关闭")).toBeNull();

  // 关闭受控的
  act(() => {
    fireEvent.click(root.getByText("关闭"));
    jest.advanceTimersByTime(1000);
  });
  expect(root.queryByText("受控关闭")).toBeNull();

  // 校验受控的关闭按钮
  const root2 = render(<AlertCloseExample />);
  expect(root2.queryByText("受控关闭")).not.toBeNull();
  act(() => {
    fireEvent.click(root2.container.querySelectorAll(".tea-icon-close")[1]);
    jest.advanceTimersByTime(1000);
  });
  expect(root2.queryByText("受控关闭")).toBeNull();
});

// 测试轮播模式
test("<Alert> works in carousel mode", () => {
  const root = render(<AlertCarouselExample />);
  const messages = [
    "小程序云服务器有奖内测中，即刻成为产品体验官",
    "云服务器限时秒杀，首购1C1G仅需99元/年",
    "让企业普惠上云，云服务器最低至2.5折",
  ];

  // 获取当前轮播点
  const dots = () =>
    Array.from(root.container.querySelectorAll(".tea-alert__nav-item"));

  // 采集当前轮播状态
  const captureStates = () => {
    // 可见状态，"1,0,0" 表示第 1 个消息可见
    const visibleStates = messages
      .map(message =>
        root.queryByText(message).style.display !== "none" ? 1 : 0
      )
      .join(",");

    // 选中点状态，"1,0,0" 表示第 1 个点选中了
    const dotStates = dots()
      .map(x => (x.classList.contains("is-current") ? 1 : 0))
      .join(",");
    // 每次可见状态应该和点状态一致
    expect(visibleStates).toEqual(dotStates);
    return visibleStates;
  };

  // 测试 15 秒，应该每个 message 都能看到过
  for (let seconds = 0; seconds < 20; seconds++) {
    // 快照记录
    expect(captureStates()).toMatchSnapshot();
    act(() => {
      // 跳过 1 秒
      jest.advanceTimersByTime(1000);
    });
  }

  // 模拟点击某个轮播点
  for (const index of [0, 1, 2, 1, 1, 2, 0]) {
    act(() => {
      fireEvent.click(dots()[index]);
    });
    expect(captureStates()).toMatchSnapshot();
  }
});
