import { render, screen } from '@testing-library/react';
import { vi, test, expect, beforeEach } from 'vitest';
import DocumentEditor from '../../src/components/DocumentEditor';
import { getDocument, saveDocument } from '../../src/api/client';

vi.mock('../../src/api/client');

vi.mock('@monaco-editor/react', () => ({
  default: ({ value, onChange }: { value: string; onChange: (value: string | undefined) => void }) => (
    <textarea
      data-testid="monaco-editor-mock"
      value={value}
      onChange={(e) => onChange(e.target.value)}
    />
  ),
}));

beforeEach(() => {
  vi.mocked(getDocument).mockReset();
  vi.mocked(saveDocument).mockReset();
});

test('shows a loading state, then loads and displays document content', async () => {
  vi.mocked(getDocument).mockResolvedValue({
    key: '产品文档/架构设计.md',
    content: '# 架构设计',
    contentType: 'text/markdown',
  });

  render(<DocumentEditor documentKey="产品文档/架构设计.md" />);

  expect(screen.getByTestId('document-editor-loading')).toBeInTheDocument();

  const textarea = await screen.findByTestId('monaco-editor-mock');
  expect(textarea).toHaveValue('# 架构设计');
  expect(getDocument).toHaveBeenCalledWith('产品文档/架构设计.md');
  expect(screen.getByTestId('save-status')).toHaveTextContent('已归档');
});

import userEvent from '@testing-library/user-event';
import { waitFor } from '@testing-library/react';

test('typing marks the document dirty and saving clears the dirty state', async () => {
  vi.mocked(getDocument).mockResolvedValue({
    key: '产品文档/架构设计.md',
    content: '# 架构设计',
    contentType: 'text/markdown',
  });
  vi.mocked(saveDocument).mockResolvedValue({
    key: '产品文档/架构设计.md',
    updatedAt: '2026-08-01T10:05:00Z',
  });
  const user = userEvent.setup();

  render(<DocumentEditor documentKey="产品文档/架构设计.md" />);

  const textarea = await screen.findByTestId('monaco-editor-mock');
  await user.clear(textarea);
  await user.type(textarea, '# 新内容');

  expect(screen.getByTestId('save-status')).toHaveTextContent('未保存');

  const saveButton = screen.getByRole('button', { name: '保存' });
  await user.click(saveButton);

  await waitFor(() => {
    expect(saveDocument).toHaveBeenCalledWith('产品文档/架构设计.md', '# 新内容', 'text/markdown');
  });
  await waitFor(() => {
    expect(screen.getByTestId('save-status')).toHaveTextContent('已归档');
  });
});
