import React from "react";
import { render, screen, fireEvent } from "@testing-library/react";
import { act } from "react-dom/test-utils";
import { jest } from "@jest/globals";
import RoleChangedPopup from "../components/RoleChangedPopup.js";

jest.useFakeTimers();

describe("RoleChangedPopup", () => {
  let onLogout;

  beforeEach(() => {
    onLogout = jest.fn();
    jest.clearAllTimers();
    jest.clearAllMocks();
  });

  it("renders dialog when open is true", () => {
    render(<RoleChangedPopup open onLogout={onLogout} />);
    expect(
      screen.getByText(/You will be logged out automatically in/i)
    ).toBeInTheDocument();
    expect(screen.getByRole("button", { name: /Logout Now/i })).toBeInTheDocument();
  });

  it("does not render dialog when open is false", () => {
    render(<RoleChangedPopup open={false} onLogout={onLogout} />);
    expect(screen.queryByText(/Role Changed/i)).not.toBeInTheDocument();
    expect(
      screen.queryByText(/You will be logged out automatically in/i)
    ).not.toBeInTheDocument();
  });

  it('calls onLogout when "Logout Now" button is clicked', () => {
    render(<RoleChangedPopup open onLogout={onLogout} />);
    fireEvent.click(screen.getByRole("button", { name: /Logout Now/i }));
    expect(onLogout).toHaveBeenCalledTimes(1);
  });

  it("shows countdown and decrements seconds", () => {
    render(<RoleChangedPopup open onLogout={onLogout} />);
    expect(screen.getByText(/in 5 seconds/i)).toBeInTheDocument();

    act(() => {
      jest.advanceTimersByTime(1000);
    });
    expect(screen.getByText(/in 4 seconds/i)).toBeInTheDocument();

    act(() => {
      jest.advanceTimersByTime(2000);
    });
    expect(screen.getByText(/in 2 seconds/i)).toBeInTheDocument();
  });

  it("calls onLogout automatically after countdown", () => {
    render(<RoleChangedPopup open onLogout={onLogout} />);
    act(() => {
      jest.advanceTimersByTime(5000);
    });
    expect(onLogout).toHaveBeenCalledTimes(1);
  });

  it("resets countdown when reopened", () => {
    const { rerender } = render(<RoleChangedPopup open onLogout={onLogout} />);
    act(() => {
      jest.advanceTimersByTime(3000);
    });
    expect(screen.getByText(/in 2 seconds/i)).toBeInTheDocument();

    rerender(<RoleChangedPopup open={false} onLogout={onLogout} />);
    rerender(<RoleChangedPopup open onLogout={onLogout} />);
    expect(screen.getByText(/in 5 seconds/i)).toBeInTheDocument();
  });
});
