/* @vitest-environment jsdom */

import { renderHook, waitFor } from '@testing-library/react';
import { beforeEach, expect, test, vi } from 'vitest';

import {
  getStoredAccessToken,
  setStoredAccessToken,
} from '../apiClient';
import { ensureRuntimeGuestToken } from '../authService';
import {
  jumpHopClient,
  type JumpHopLeaderboardResponse,
} from './jumpHopClient';
import { useJumpHopLeaderboard } from './useJumpHopLeaderboard';

vi.mock('../authService', () => ({
  ensureRuntimeGuestToken: vi.fn(),
}));

vi.mock('./jumpHopClient', () => ({
  jumpHopClient: {
    getLeaderboard: vi.fn(),
  },
}));

const leaderboardResponse: JumpHopLeaderboardResponse = {
  profileId: 'jump-hop-profile-test',
  items: [
    {
      rank: 1,
      playerId: 'player-1',
      successfulJumpCount: 10,
      durationMs: 3210,
      updatedAt: '2026-05-27T00:00:00Z',
    },
  ],
  viewerBest: null,
};

beforeEach(() => {
  vi.clearAllMocks();
  setStoredAccessToken('', { emit: false });
  vi.mocked(ensureRuntimeGuestToken).mockResolvedValue({
    token: 'runtime-guest-token',
    expiresAt: '2099-01-01T00:10:00Z',
    subject: 'guest-runtime-test',
    scope: 'public-play',
  });
  vi.mocked(jumpHopClient.getLeaderboard).mockResolvedValue(
    leaderboardResponse,
  );
});

test('跳一跳排行榜在已有登录态时使用本地账号请求，不再额外申请 guest token', async () => {
  setStoredAccessToken('stored-access-token', { emit: false });

  const { result } = renderHook(() =>
    useJumpHopLeaderboard('jump-hop-profile-test'),
  );

  await waitFor(() => expect(result.current.isLoading).toBe(false));
  expect(getStoredAccessToken()).toBe('stored-access-token');
  expect(ensureRuntimeGuestToken).not.toHaveBeenCalled();
  expect(jumpHopClient.getLeaderboard).toHaveBeenCalledWith(
    'jump-hop-profile-test',
    expect.objectContaining({
      authImpact: 'local',
      skipRefresh: true,
    }),
  );
  expect(result.current.leaderboard).toEqual(leaderboardResponse);
});
test('跳一跳排行榜在匿名模式下会申请 guest token', async () => {
  const { result } = renderHook(() =>
    useJumpHopLeaderboard('jump-hop-profile-test'),
  );

  await waitFor(() => expect(result.current.isLoading).toBe(false));
  expect(ensureRuntimeGuestToken).toHaveBeenCalledTimes(1);
  expect(jumpHopClient.getLeaderboard).toHaveBeenCalledWith(
    'jump-hop-profile-test',
    { runtimeGuestToken: 'runtime-guest-token' },
  );
  expect(result.current.leaderboard).toEqual(leaderboardResponse);
});
