/**
 * Unit tests for AccessDeniedScreen: full-screen access denied, reload and back modes.
 */

import { describe, it, expect, beforeEach, vi } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import { AccessDeniedScreen } from "./AccessDeniedScreen";
import { resetAppStore } from "@/test/test-utils";

describe("AccessDeniedScreen", () => {
  beforeEach(() => {
    resetAppStore();
  });

  it("renders translated access denied title and hint", () => {
    render(<AccessDeniedScreen primaryAction="reload" />);
    expect(screen.getByText(/Access denied|Доступ запрещён/i)).toBeInTheDocument();
    expect(
      screen.getByText(/Open the app again from Telegram|Откройте приложение снова из Telegram/i)
    ).toBeInTheDocument();
  });

  it("shows serverDetail when provided", () => {
    render(
      <AccessDeniedScreen primaryAction="reload" serverDetail="Custom 403 message" />
    );
    expect(screen.getByText("Custom 403 message")).toBeInTheDocument();
  });

  it("reload mode shows Reload button", () => {
    render(<AccessDeniedScreen primaryAction="reload" />);
    const button = screen.getByRole("button", { name: /Reload|Обновить/i });
    expect(button).toBeInTheDocument();
    const reloadFn = vi.fn();
    Object.defineProperty(window, "location", {
      value: { ...window.location, reload: reloadFn },
      writable: true,
    });
    fireEvent.click(button);
    expect(reloadFn).toHaveBeenCalled();
  });

  it("back mode shows Back to calendar and calls onBack on click", () => {
    const onBack = vi.fn();
    render(
      <AccessDeniedScreen
        primaryAction="back"
        onBack={onBack}
        openedFromPin={false}
      />
    );
    const button = screen.getByRole("button", {
      name: /Back to calendar|Назад к календарю/i,
    });
    expect(button).toBeInTheDocument();
    fireEvent.click(button);
    expect(onBack).toHaveBeenCalled();
  });

  it("back mode with openedFromPin shows Close button", () => {
    const onBack = vi.fn();
    render(
      <AccessDeniedScreen
        primaryAction="back"
        onBack={onBack}
        openedFromPin={true}
      />
    );
    const button = screen.getByRole("button", { name: /Close|Закрыть/i });
    expect(button).toBeInTheDocument();
    fireEvent.click(button);
    expect(onBack).toHaveBeenCalled();
  });
});
