/* @vitest-environment jsdom */

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

import * as clipboardService from '../../services/clipboard';
import { PlatformErrorDialog } from './PlatformErrorDialog';

vi.mock('../../services/clipboard', () => ({
  copyTextToClipboard: vi.fn(),
}));

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

describe('PlatformErrorDialog', () => {
  test('shows source, message, and copies the full error report', async () => {
    vi.mocked(clipboardService.copyTextToClipboard).mockResolvedValue(true);

    render(
      <PlatformErrorDialog
        error={{
          source: '拼图草稿 puzzle-session-123',
          message: '图片生成失败，请稍后再试。',
        }}
        onClose={() => {}}
      />,
    );

    const dialog = screen.getByRole('dialog', { name: '发生错误' });
    expect(within(dialog).getByText('拼图草稿 puzzle-session-123')).toBeTruthy();
    expect(within(dialog).getByText('图片生成失败，请稍后再试。')).toBeTruthy();

    fireEvent.click(within(dialog).getByRole('button', { name: '复制报错' }));

    expect(clipboardService.copyTextToClipboard).toHaveBeenCalledWith(
      ['来源：拼图草稿 puzzle-session-123', '错误：图片生成失败，请稍后再试。'].join(
        '\n',
      ),
    );
    await waitFor(() => {
      expect(
        within(dialog).getByRole('button', { name: '已复制' }),
      ).toBeTruthy();
    });
  });

  test('does not render when there is no active error', () => {
    render(<PlatformErrorDialog error={null} onClose={() => {}} />);

    expect(screen.queryByRole('dialog', { name: '发生错误' })).toBeNull();
  });
});
