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

async function finishWidgetLoad(): Promise<void> {
  await act(async () => {
    await vi.advanceTimersByTimeAsync(500);
  });
}

describe("CalendarWidget", (): void => {
  beforeEach((): void => {
    vi.useFakeTimers();
    vi.setSystemTime(new Date("2026-02-01T08:00:00Z"));
  });

  afterEach((): void => {
    vi.useRealTimers();
  });

  it("renders loading state initially", (): void => {
    render(<CalendarWidget id="calendar-1" />);

    expect(screen.getByText("Loading events...")).toBeInTheDocument();
  });

  it("renders upcoming events after loading", async (): Promise<void> => {
    render(<CalendarWidget id="calendar-1" />);

    await finishWidgetLoad();

    expect(screen.getByText("Upcoming Events")).toBeInTheDocument();
    expect(screen.getByText("Team Standup")).toBeInTheDocument();
    expect(screen.getByText("Project Review")).toBeInTheDocument();
    expect(screen.getByText("Sprint Planning")).toBeInTheDocument();
  });

  it("shows relative day labels", async (): Promise<void> => {
    render(<CalendarWidget id="calendar-1" />);

    await finishWidgetLoad();

    expect(screen.getAllByText("Today").length).toBeGreaterThan(0);
    expect(screen.getByText("Tomorrow")).toBeInTheDocument();
  });

  it("shows event locations when present", async (): Promise<void> => {
    render(<CalendarWidget id="calendar-1" />);

    await finishWidgetLoad();

    expect(screen.getByText("Zoom")).toBeInTheDocument();
    expect(screen.getByText("Conference Room A")).toBeInTheDocument();
  });
});
