// @vitest-environment jsdom

import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { afterEach, describe, expect, test, vi } from 'vitest';

import type { Match3DWorkProfile } from '../../../packages/shared/src/contracts/match3dWorks';
import * as match3dWorksService from '../../services/match3d-works';
import { Match3DResultView } from './Match3DResultView';

vi.mock('../ResolvedAssetImage', () => ({
  ResolvedAssetImage: ({
    src,
    alt,
    className,
  }: {
    src?: string | null;
    alt?: string;
    className?: string;
  }) => (src ? <img src={src} alt={alt} className={className} /> : null),
}));

vi.mock('../../services/match3d-works', () => ({
  publishMatch3DWork: vi.fn(),
  updateMatch3DWork: vi.fn(),
}));

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

function createProfile(
  overrides: Partial<Match3DWorkProfile> = {},
): Match3DWorkProfile {
  return {
    workId: 'match3d-work-1',
    profileId: 'match3d-profile-1',
    ownerUserId: 'user-1',
    sourceSessionId: 'match3d-session-1',
    gameName: '水果抓大鹅',
    themeText: '水果',
    summary: '水果主题的经典消除玩法。',
    tags: ['水果'],
    coverImageSrc: null,
    referenceImageSrc: null,
    clearCount: 4,
    difficulty: 3,
    publicationStatus: 'draft',
    playCount: 0,
    updatedAt: '2026-05-01T00:00:00.000Z',
    publishedAt: null,
    publishReady: false,
    ...overrides,
  };
}

describe('Match3DResultView', () => {
  test('试玩只要求基础配置可保存，不被发布封面门槛阻断', async () => {
    const profile = createProfile();
    const onStartTestRun = vi.fn();
    vi.mocked(match3dWorksService.updateMatch3DWork).mockResolvedValue({
      item: profile,
    });

    render(
      <Match3DResultView
        profile={profile}
        onBack={() => {}}
        onStartTestRun={onStartTestRun}
      />,
    );

    fireEvent.click(screen.getByRole('button', { name: '试玩' }));

    await waitFor(() => {
      expect(match3dWorksService.updateMatch3DWork).toHaveBeenCalledWith(
        'match3d-profile-1',
        expect.objectContaining({
          clearCount: 4,
          difficulty: 3,
          gameName: '水果抓大鹅',
        }),
      );
    });
    expect(onStartTestRun).toHaveBeenCalledWith(profile);
    expect(match3dWorksService.publishMatch3DWork).not.toHaveBeenCalled();
  });

  test('发布仍要求封面和标签数量满足门槛', () => {
    render(
      <Match3DResultView
        profile={createProfile()}
        onBack={() => {}}
        onStartTestRun={() => {}}
      />,
    );

    const publishButton = screen.getByRole('button', { name: '发布' });
    expect(publishButton).toHaveProperty('disabled', true);

    fireEvent.click(publishButton);
    expect(match3dWorksService.publishMatch3DWork).not.toHaveBeenCalled();
  });
});
