import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, expect, test, vi } from 'vitest';
import { EmptyState, InlineError, PageLoading, PanelEmpty, PanelLoading } from './AsyncState';

afterEach(cleanup);

test('uses one semantic loading language for page and panel scopes', () => {
  const view = render(<>
    <PageLoading label="正在加载轨迹回放" />
    <PanelLoading title="正在查询里程" description="结果返回后会自动显示。" />
  </>);

  expect(screen.getAllByRole('status')).toHaveLength(2);
  expect(screen.getByText('正在加载轨迹回放')).toBeInTheDocument();
  expect(screen.getByText('正在查询里程')).toBeInTheDocument();
  expect(view.container.querySelector('.v2-state-surface.is-page.is-loading')).toBeInTheDocument();
  expect(view.container.querySelector('.v2-state-surface.is-panel.is-loading')).toBeInTheDocument();
});

test('keeps empty states consistent while allowing a clear next action', () => {
  const action = vi.fn();
  const view = render(<>
    <PanelEmpty title="还没有客户账号" description="创建后可分配菜单和车辆。" action={<button onClick={action}>创建账号</button>} />
    <EmptyState title="暂无符合条件的车辆" />
  </>);

  expect(view.container.querySelectorAll('.v2-state-empty.semi-empty')).toHaveLength(2);
  fireEvent.click(screen.getByRole('button', { name: '创建账号' }));
  expect(action).toHaveBeenCalledTimes(1);
});

test('announces recoverable errors and exposes a Semi retry action', () => {
  const retry = vi.fn();
  render(<InlineError message="服务暂时不可用" onRetry={retry} />);

  expect(screen.getByRole('alert')).toHaveTextContent('数据暂时无法加载');
  expect(screen.getByRole('alert')).toHaveTextContent('服务暂时不可用');
  const button = screen.getByRole('button', { name: '重试' });
  expect(button).toHaveClass('semi-button');
  fireEvent.click(button);
  expect(retry).toHaveBeenCalledTimes(1);
});
