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", () => ({
  getUserId: vi.fn().mockReturnValue("user-1"),
  getCachedProfile: vi.fn().mockReturnValue({ id: "user-1", username: "testuser", avatar: "🐱" }),
  setCachedProfile: vi.fn(),
  setCachedPreferences: vi.fn(),
  logout: vi.fn(),
}));

vi.mock("@/lib/avatars", () => ({
  getAvatarBg: vi.fn().mockReturnValue("bg-amber-100"),
  AVATARS: [
    { emoji: "🐱", bg: "bg-amber-100" },
    { emoji: "🐶", bg: "bg-orange-100" },
  ],
}));

vi.mock("@/components/ProfileFavoritesCard", () => ({
  default: () => <div data-testid="favorites-card" />,
}));

const mockFetch = vi.fn();
vi.stubGlobal("fetch", mockFetch);

import ProfilePage from "./ProfileClient";

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

function renderPage() {
  return render(
    React.createElement(
      ToastContext.Provider,
      { value: toastCtx },
      React.createElement(ProfilePage, { initialUserId: "user-1" }),
    ),
  );
}

beforeEach(() => {
  vi.clearAllMocks();
  mockFetch.mockResolvedValue({
    ok: true,
    json: () =>
      Promise.resolve({
        id: "user-1",
        username: "testuser",
        avatar: "🐱",
        email: null,
        achievements: {
          totalDecisions: 5,
          unanimousCount: 2,
          roomsCreated: 3,
          streak: 1,
        },
        records: [],
        favorites: [],
      }),
  });
});

describe("ProfilePage", () => {
  it("renders profile heading", async () => {
    renderPage();
    expect(await screen.findByText("个人中心")).toBeInTheDocument();
    await waitFor(() => {
      expect(mockFetch).toHaveBeenCalledWith(
        "/api/user?id=user-1",
      );
    });
  });

  it("fetches user profile data with correct URL", async () => {
    renderPage();
    await waitFor(() => {
      expect(mockFetch).toHaveBeenCalledWith(
        "/api/user?id=user-1",
      );
    });
  });

  it("renders user info after data loads", async () => {
    renderPage();
    await waitFor(() => {
      expect(screen.getByText("testuser")).toBeInTheDocument();
    });
  });

  it("renders navigation element", async () => {
    renderPage();
    await waitFor(() => {
      expect(mockFetch).toHaveBeenCalledWith(
        "/api/user?id=user-1",
      );
    });
    expect(screen.getByRole("navigation")).toBeInTheDocument();
  });
});
