import { act, cleanup, render } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";

import type { ScheduledConditionRecord, ScheduledConditionTaskId } from "../types";
import { AgentTaskTicker } from "./agent-task-ticker";

function createRunningCondition(id: string, taskId: ScheduledConditionTaskId): ScheduledConditionRecord {
  return {
    id,
    kind: "condition",
    taskId,
    scheduledAt: "2026-07-08T10:00:00+08:00",
    title: id,
    summary: "Running condition",
    status: "running",
    riskLevel: "normal",
    updatedAt: Date.parse("2026-07-08T10:01:00+08:00"),
    sessionId: id,
    durationMinutes: 10
  };
}

function setDocumentVisibility(visibilityState: DocumentVisibilityState) {
  Object.defineProperty(document, "visibilityState", {
    configurable: true,
    value: visibilityState
  });
  document.dispatchEvent(new Event("visibilitychange"));
}

function getActiveConditionId(container: HTMLElement) {
  const activeCards = container.querySelectorAll<HTMLElement>('article[aria-hidden="false"]');

  return activeCards.item(activeCards.length - 1).dataset.conditionId;
}

afterEach(() => {
  cleanup();
  vi.useRealTimers();
  setDocumentVisibility("visible");
});

describe("AgentTaskTicker page visibility", () => {
  it("does not rotate or retain exiting cards while the page is hidden", () => {
    vi.useFakeTimers();
    setDocumentVisibility("visible");

    const conditions = [
      createRunningCondition("condition-a", "scada-diagnosis"),
      createRunningCondition("condition-b", "smart-dispatch"),
      createRunningCondition("condition-c", "pump-energy"),
      createRunningCondition("condition-d", "network-simulation")
    ];
    const { container } = render(<AgentTaskTicker conditions={conditions} />);
    const initialConditionId = getActiveConditionId(container);

    act(() => {
      setDocumentVisibility("hidden");
      vi.advanceTimersByTime(18_000);
    });

    expect(getActiveConditionId(container)).toBe(initialConditionId);
    expect(container.querySelectorAll("article")).toHaveLength(3);

    act(() => {
      setDocumentVisibility("visible");
    });

    act(() => {
      vi.advanceTimersByTime(6_000);
    });

    expect(getActiveConditionId(container)).not.toBe(initialConditionId);
  });
});
