/* @vitest-environment jsdom */

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

import { CustomWorldAgentThread } from './CustomWorldAgentThread';

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

test('filters empty recommended replies and avoids duplicate key warnings', () => {
  const consoleErrorSpy = vi
    .spyOn(console, 'error')
    .mockImplementation(() => undefined);

  if (!Element.prototype.scrollIntoView) {
    Element.prototype.scrollIntoView = () => {};
  }

  render(
    <CustomWorldAgentThread
      messages={[
        {
          id: '',
          role: 'assistant',
          kind: 'summary',
          text: '先把世界骨架收出来。',
          createdAt: '2026-04-16T10:00:00.000Z',
          relatedOperationId: null,
        },
        {
          id: '',
          role: 'user',
          kind: 'chat',
          text: '继续。',
          createdAt: '2026-04-16T10:01:00.000Z',
          relatedOperationId: null,
        },
      ]}
      recommendedReplies={[
        '',
        '继续补充冲突',
        '继续补充冲突',
        ' 先确定玩家身份 ',
      ]}
      onRecommendedReply={() => {}}
    />,
  );

  expect(screen.getByRole('button', { name: '继续补充冲突' })).toBeTruthy();
  expect(screen.getByRole('button', { name: '先确定玩家身份' })).toBeTruthy();
  expect(screen.queryByRole('button', { name: /^\s*$/u })).toBeNull();
  expect(screen.getAllByRole('button')).toHaveLength(2);

  const duplicateKeyCalls = consoleErrorSpy.mock.calls.filter((call) =>
    call.some(
      (arg) =>
        typeof arg === 'string' &&
        arg.includes('Encountered two children with the same key'),
    ),
  );

  expect(duplicateKeyCalls).toHaveLength(0);
});

test('renders a streaming assistant bubble without timestamps', () => {
  if (!Element.prototype.scrollIntoView) {
    Element.prototype.scrollIntoView = () => {};
  }

  render(
    <CustomWorldAgentThread
      messages={[
        {
          id: 'message-1',
          role: 'user',
          kind: 'chat',
          text: '我想做一个潮湿压抑的海上世界。',
          createdAt: '2026-04-16T10:01:00.000Z',
          relatedOperationId: null,
        },
      ]}
      streamingReplyText="那我先顺着这个方向收一下，开场时你更想让玩家撞上什么麻烦"
      isStreamingReply
    />,
  );

  expect(
    screen.getByText(/那我先顺着这个方向收一下/u),
  ).toBeTruthy();
  expect(screen.queryByText('10:01')).toBeNull();
});
