/**
 * Integration test for main page: calendar and header visible, lang from store.
 * Ported from webapp/js/main.test.js applyLangToUi.
 */

import { describe, it, expect, beforeEach, vi } from "vitest";
import { render, screen, waitFor, act } from "@testing-library/react";
import Page from "./page";
import { resetAppStore } from "@/test/test-utils";
import { useAppStore } from "@/store/app-store";
import { useTelegramAuth } from "@/hooks/use-telegram-auth";

vi.mock("next/navigation", () => ({
  useRouter: () => ({ push: vi.fn(), replace: vi.fn(), prefetch: vi.fn() }),
}));

vi.mock("@/hooks/use-telegram-auth", () => ({
  useTelegramAuth: vi.fn(),
}));

vi.mock("@/hooks/use-month-data", () => ({
  useMonthData: () => ({
    retry: vi.fn(),
  }),
}));

describe("Page", () => {
  beforeEach(() => {
    resetAppStore();
    vi.mocked(useTelegramAuth).mockReturnValue({
      initDataRaw: "test-init",
      startParam: undefined,
      isLocalhost: true,
    });
  });

  it("renders calendar and header when store has default state", async () => {
    render(<Page />);
    expect(await screen.findByRole("grid", { name: "Calendar" })).toBeInTheDocument();
    expect(screen.getByRole("button", { name: /previous month/i })).toBeInTheDocument();
    expect(screen.getByRole("button", { name: /next month/i })).toBeInTheDocument();
  });

  it("sets document title and lang from store lang", async () => {
    useAppStore.getState().setLang("en");
    render(<Page />);
    await screen.findByRole("grid", { name: "Calendar" });
    expect(document.title).toBe("Duty Calendar");
    expect(document.documentElement.lang).toBe("en");
  });

  it("sets document title for ru when store lang is ru", async () => {
    useAppStore.getState().setLang("ru");
    render(<Page />);
    await screen.findByRole("grid", { name: "Calendar" });
    expect(document.title).toBe("Календарь дежурств");
    expect(document.documentElement.lang).toBe("ru");
  });

  it("renders AccessDeniedScreen when not allowed and delay has passed", async () => {
    const { RETRY_DELAY_MS } = await import("@/lib/constants");
    vi.mocked(useTelegramAuth).mockReturnValue({
      initDataRaw: undefined,
      startParam: undefined,
      isLocalhost: false,
    });
    vi.useFakeTimers();
    render(<Page />);
    await act(async () => {
      vi.advanceTimersByTime(RETRY_DELAY_MS);
    });
    vi.useRealTimers();
    expect(
      await screen.findByText(/Access denied|Доступ запрещён/i, {}, { timeout: 2000 })
    ).toBeInTheDocument();
    expect(
      screen.getByText(/Open the app again from Telegram|Откройте приложение снова из Telegram/i)
    ).toBeInTheDocument();
    expect(screen.getByRole("button", { name: /Reload|Обновить/i })).toBeInTheDocument();
    expect(screen.queryByRole("grid", { name: "Calendar" })).not.toBeInTheDocument();
  });
});
