import { render, screen, waitFor, act } from "@testing-library/react";
import RescheduleLoadingOverlay from "@/app/[lang]/dashboard/components/RescheduleLoadingOverlay";

describe("RescheduleLoadingOverlay", () => {
  beforeEach(() => {
    jest.useFakeTimers();
  });

  afterEach(() => {
    jest.runOnlyPendingTimers();
    jest.useRealTimers();
  });

  it("renders loading overlay when visible", () => {
    render(<RescheduleLoadingOverlay isVisible={true} lang="en" />);

    expect(screen.getByText("Updating appointment...")).toBeInTheDocument();
    expect(
      screen.getByText("Please do not close this window"),
    ).toBeInTheDocument();
  });

  it("does not render when not visible", () => {
    render(<RescheduleLoadingOverlay isVisible={false} lang="en" />);

    expect(
      screen.queryByText("Updating appointment..."),
    ).not.toBeInTheDocument();
  });

  it("progresses through messages over time", async () => {
    render(<RescheduleLoadingOverlay isVisible={true} lang="en" />);

    // Initially shows first message
    expect(screen.getByText("Updating appointment...")).toBeInTheDocument();

    // After 1 second, shows second message
    act(() => {
      jest.advanceTimersByTime(1100);
    });
    expect(screen.getByText("Syncing with calendar...")).toBeInTheDocument();

    // After 3 seconds total, shows third message
    act(() => {
      jest.advanceTimersByTime(2000);
    });
    expect(screen.getByText("Almost done...")).toBeInTheDocument();
  });

  it("renders in Arabic when lang is ar", () => {
    render(<RescheduleLoadingOverlay isVisible={true} lang="ar" />);

    expect(screen.getByText("جاري تحديث الموعد...")).toBeInTheDocument();
    expect(screen.getByText("يرجى عدم إغلاق هذه النافذة")).toBeInTheDocument();
  });

  it("resets message index when visibility changes", async () => {
    const { rerender } = render(
      <RescheduleLoadingOverlay isVisible={true} lang="en" />,
    );

    // Advance to third message
    act(() => {
      jest.advanceTimersByTime(3100);
    });
    expect(screen.getByText("Almost done...")).toBeInTheDocument();

    // Hide and show again
    rerender(<RescheduleLoadingOverlay isVisible={false} lang="en" />);
    rerender(<RescheduleLoadingOverlay isVisible={true} lang="en" />);

    // Should restart from first message
    expect(screen.getByText("Updating appointment...")).toBeInTheDocument();
  });

  it("displays progress dots", () => {
    const { container } = render(
      <RescheduleLoadingOverlay isVisible={true} lang="en" />,
    );

    // Should have 3 progress dots
    const dots = container.querySelectorAll(".h-2.rounded-full");
    expect(dots).toHaveLength(3);
  });
});
