import { render, screen, waitFor } from "@testing-library/react";
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { OrchestratorEventsWidget } from "../OrchestratorEventsWidget";

describe("OrchestratorEventsWidget", () => {
  const mockFetch = vi.fn();

  beforeEach(() => {
    global.fetch = mockFetch as unknown as typeof fetch;
  });

  afterEach(() => {
    vi.clearAllMocks();
  });

  it("renders loading state initially", () => {
    mockFetch.mockImplementation(
      // eslint-disable-next-line @typescript-eslint/no-empty-function
      () => new Promise(() => {})
    );

    render(<OrchestratorEventsWidget id="orchestrator-events-1" config={{}} />);
    expect(screen.getByText("Loading orchestrator events...")).toBeInTheDocument();
  });

  it("renders events and matrix signal count", async () => {
    mockFetch.mockImplementation((input: RequestInfo | URL) => {
      const url =
        typeof input === "string" ? input : input instanceof URL ? input.toString() : input.url;

      if (url.includes("/api/orchestrator/health")) {
        return Promise.resolve({
          ok: true,
          json: () => Promise.resolve({ status: "ok" }),
        } as unknown as Response);
      }

      return Promise.resolve({
        ok: true,
        json: () =>
          Promise.resolve({
            events: [
              {
                type: "task.completed",
                timestamp: "2026-02-17T16:40:00.000Z",
                taskId: "TASK-1",
                data: { channelId: "room-123" },
              },
              {
                type: "agent.running",
                timestamp: "2026-02-17T16:41:00.000Z",
                taskId: "TASK-2",
                agentId: "agent-abc12345",
              },
            ],
          }),
      } as unknown as Response);
    });

    render(<OrchestratorEventsWidget id="orchestrator-events-1" config={{}} />);

    await waitFor(() => {
      expect(screen.getByText("task.completed")).toBeInTheDocument();
      expect(screen.getByText("agent.running")).toBeInTheDocument();
      expect(screen.getByText(/Matrix signals: 1/)).toBeInTheDocument();
      expect(screen.getByText("ready")).toBeInTheDocument();
    });
  });

  it("renders error state when API fails", async () => {
    mockFetch.mockResolvedValue({
      ok: false,
      status: 503,
    });

    render(<OrchestratorEventsWidget id="orchestrator-events-1" config={{}} />);

    await waitFor(() => {
      expect(screen.getByText(/Unable to load events: HTTP 503/)).toBeInTheDocument();
    });
  });
});
