/* @vitest-environment jsdom */

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

import type { PlatformPublicGalleryCard } from '../rpg-entry/rpgEntryWorldPresentation';
import { PlatformWorkDetailView } from './PlatformWorkDetailView';

function createPuzzleEntry(): PlatformPublicGalleryCard {
  return {
    sourceType: 'puzzle',
    workId: 'work-1',
    profileId: 'profile-1',
    publicWorkCode: 'PZ-001',
    ownerUserId: 'user-1',
    authorDisplayName: '137****6613',
    worldName: '关键词：逍遥游拼图',
    subtitle: '拼图关卡',
    summaryText: '适合公开游玩的拼图作品。',
    coverImageSrc: null,
    themeTags: ['拼图'],
    playCount: 12,
    remixCount: 3,
    likeCount: 4,
    recentPlayCount7d: 0,
    visibility: 'published',
    publishedAt: '2026-04-20T10:00:00.000Z',
    updatedAt: '2026-04-25T12:00:00.000Z',
  };
}

test('PlatformWorkDetailView renders compact stats and date time', () => {
  render(
    <PlatformWorkDetailView
      entry={createPuzzleEntry()}
      isBusy={false}
      error={null}
      onBack={vi.fn()}
      onLike={vi.fn()}
      onStart={vi.fn()}
      onRemix={vi.fn()}
    />,
  );

  expect(screen.getByText('改造')).toBeTruthy();
  expect(screen.getByText('游玩')).toBeTruthy();
  expect(screen.getAllByText('点赞').length).toBeGreaterThanOrEqual(2);
  expect(screen.getByText('日期')).toBeTruthy();
  expect(screen.queryByText('改造次数')).toBeNull();
  expect(screen.queryByText('游玩次数')).toBeNull();
  expect(screen.queryByText('上线日期')).toBeNull();
  expect(screen.queryByText('最近更新')).toBeNull();
  expect(screen.getByText('2026-04-25')).toBeTruthy();
  expect(screen.getAllByText('次')).toHaveLength(2);
  expect(screen.getByText('赞')).toBeTruthy();
  expect(screen.getByRole('button', { name: '点赞 4赞' })).toBeTruthy();
  expect(screen.getByRole('button', { name: '作品改造' })).toBeTruthy();
  expect(screen.getByRole('button', { name: '启动' })).toBeTruthy();
});

test('PlatformWorkDetailView prefers resolved public user display name', () => {
  render(
    <PlatformWorkDetailView
      entry={createPuzzleEntry()}
      authorDisplayName="新的作者昵称"
      isBusy={false}
      error={null}
      onBack={vi.fn()}
      onLike={vi.fn()}
      onStart={vi.fn()}
      onRemix={vi.fn()}
    />,
  );

  expect(screen.getByText('新的作者昵称')).toBeTruthy();
  expect(screen.queryByText('137****6613')).toBeNull();
});

test('PlatformWorkDetailView calls like handler', () => {
  const onLike = vi.fn();
  render(
    <PlatformWorkDetailView
      entry={createPuzzleEntry()}
      isBusy={false}
      error={null}
      onBack={vi.fn()}
      onLike={onLike}
      onStart={vi.fn()}
      onRemix={vi.fn()}
    />,
  );

  fireEvent.click(screen.getByRole('button', { name: '点赞 4赞' }));

  expect(onLike).toHaveBeenCalledTimes(1);
});
