/* @vitest-environment jsdom */

import { render, screen, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, expect, test, vi } from 'vitest';

import { PlatformProfilePlayedWorksModal } from './PlatformProfilePlayedWorksModal';

describe('PlatformProfilePlayedWorksModal', () => {
  test('renders save archives and played works in one modal', async () => {
    const user = userEvent.setup();
    const onResumeSave = vi.fn();
    const onOpenWork = vi.fn();
    const saveEntry = {
      worldKey: 'custom:save-1',
      ownerUserId: 'user-1',
      profileId: 'save-1',
      worldType: 'custom',
      worldName: '回声群岛',
      subtitle: '雾海码头',
      summaryText: '继续推进上一次保存的故事。',
      coverImageSrc: null,
      lastPlayedAt: '2026-04-19T12:00:00.000Z',
    };
    const playedWork = {
      worldKey: 'custom:world-1',
      ownerUserId: 'user-1',
      profileId: 'world-1',
      worldType: 'CUSTOM',
      worldTitle: '潮雾列岛',
      worldSubtitle: '旧灯塔与失控航路',
      firstPlayedAt: '2026-04-18T12:00:00.000Z',
      lastPlayedAt: '2026-04-19T12:00:00.000Z',
      lastObservedPlayTimeMs: 30 * 60 * 1000,
    };

    render(
      <PlatformProfilePlayedWorksModal
        stats={{
          totalPlayTimeMs: 90 * 60 * 1000,
          playedWorks: [playedWork],
          updatedAt: '2026-04-19T12:00:00.000Z',
        }}
        isLoading={false}
        error={null}
        saveEntries={[saveEntry]}
        saveError={null}
        isResumingSaveWorldKey={null}
        onClose={vi.fn()}
        onOpenWork={onOpenWork}
        onResumeSave={onResumeSave}
      />,
    );

    const dialog = screen.getByRole('dialog', { name: '玩过' });

    expect(within(dialog).getByText('可继续')).toBeTruthy();
    expect(within(dialog).getAllByText('玩过').length).toBeGreaterThan(0);
    expect(within(dialog).getByText('1.5小时')).toBeTruthy();

    await user.click(within(dialog).getByRole('button', { name: /回声群岛/u }));
    expect(onResumeSave).toHaveBeenCalledWith(saveEntry);

    await user.click(within(dialog).getByRole('button', { name: /潮雾列岛/u }));
    expect(onOpenWork).toHaveBeenCalledWith(playedWork);
  });

  test('renders platform empty state when no history exists', () => {
    render(
      <PlatformProfilePlayedWorksModal
        stats={{
          totalPlayTimeMs: 0,
          playedWorks: [],
          updatedAt: '2026-04-19T12:00:00.000Z',
        }}
        isLoading={false}
        error={null}
        saveEntries={[]}
        saveError={null}
        isResumingSaveWorldKey={null}
        onClose={vi.fn()}
        onResumeSave={vi.fn()}
      />,
    );

    const emptyState = screen.getByText('暂无玩过');

    expect(emptyState.className).toContain('platform-empty-state');
    expect(emptyState.className).toContain('text-left');
  });
});
