/* @vitest-environment jsdom */

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

import { PlatformFeedbackView } from './PlatformFeedbackView';

test('PlatformFeedbackView renders reference feedback fields', () => {
  render(<PlatformFeedbackView onBack={vi.fn()} />);

  expect(screen.getByText('帮助与反馈')).toBeTruthy();
  expect(screen.getByText('反馈问题')).toBeTruthy();
  expect(screen.getByLabelText('问题描述')).toBeTruthy();
  expect(screen.getByText('0/200')).toBeTruthy();
  expect(screen.getByText('上传凭证(提供问题截图)')).toBeTruthy();
  expect(screen.getByText('上传凭证')).toBeTruthy();
  expect(screen.getByLabelText('联系电话')).toBeTruthy();
  expect(screen.getByRole('button', { name: '提交' })).toBeTruthy();
  expect(screen.getByRole('button', { name: '查看反馈与投诉记录' })).toBeTruthy();
});

test('PlatformFeedbackView validates minimum description length before submit', () => {
  const onSubmit = vi.fn();
  render(<PlatformFeedbackView onBack={vi.fn()} onSubmit={onSubmit} />);

  fireEvent.change(screen.getByLabelText('问题描述'), {
    target: { value: '太短' },
  });
  fireEvent.click(screen.getByRole('button', { name: '提交' }));

  expect(screen.getByText('请填写10个字以上的问题描述')).toBeTruthy();
  expect(onSubmit).not.toHaveBeenCalled();
});

test('PlatformFeedbackView submits trimmed payload', async () => {
  const onSubmit = vi.fn();
  render(<PlatformFeedbackView onBack={vi.fn()} onSubmit={onSubmit} />);

  fireEvent.change(screen.getByLabelText('问题描述'), {
    target: { value: '  这个反馈页面无法正常上传图片  ' },
  });
  fireEvent.change(screen.getByLabelText('联系电话'), {
    target: { value: '  13800000000  ' },
  });
  fireEvent.click(screen.getByRole('button', { name: '提交' }));

  await waitFor(() => expect(onSubmit).toHaveBeenCalledTimes(1));
  expect(onSubmit).toHaveBeenCalledWith({
    description: '这个反馈页面无法正常上传图片',
    contactPhone: '13800000000',
    evidenceFiles: [],
  });
  await waitFor(() => expect(screen.getByText('反馈已提交')).toBeTruthy());
});

test('PlatformFeedbackView calls back from header home button', () => {
  const onBack = vi.fn();
  render(<PlatformFeedbackView onBack={onBack} />);

  fireEvent.click(screen.getByRole('button', { name: '返回我的页签' }));

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