import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, waitFor } from "@testing-library/react";
import React from "react";
import { ToastContext, type ToastContextValue } from "@/hooks/useToast";

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

vi.mock("@/lib/userId", () => ({
  getCachedProfile: vi.fn().mockReturnValue({ id: "u1", username: "test", avatar: "🐱" }),
  isRegistered: vi.fn().mockReturnValue(true),
}));

const mockFetch = vi.fn().mockResolvedValue({
  ok: true,
  json: () => Promise.resolve({ rooms: [] }),
});
vi.stubGlobal("fetch", mockFetch);

import BlindboxPage from "./page";

const toastCtx: ToastContextValue = { show: vi.fn() };

function renderPage() {
  return render(
    React.createElement(
      ToastContext.Provider,
      { value: toastCtx },
      React.createElement(BlindboxPage),
    ),
  );
}

beforeEach(() => {
  vi.clearAllMocks();
});

describe("BlindboxPage", () => {
  it("renders page heading", async () => {
    renderPage();
    expect(await screen.findByText("周末契约")).toBeInTheDocument();
    await waitFor(() => {
      expect(mockFetch).toHaveBeenCalled();
    });
  });

  it("renders back button", async () => {
    renderPage();
    await screen.findByText("周末契约");
    const backBtns = screen.getAllByRole("button");
    expect(backBtns.length).toBeGreaterThan(0);
  });

  it("renders subtitle text", async () => {
    renderPage();
    expect(await screen.findByText("ADVENTURE ROULETTE")).toBeInTheDocument();
  });
});
