/* @vitest-environment jsdom */

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

import { UnifiedModal } from './UnifiedModal';

test('renders an accessible platform modal', () => {
  render(
    <UnifiedModal open title="统一弹窗" onClose={() => {}} portal={false}>
      <div>窗口内容</div>
    </UnifiedModal>,
  );

  expect(screen.getByRole('dialog', { name: '统一弹窗' })).toBeTruthy();
  expect(screen.getByText('窗口内容')).toBeTruthy();
});

test('closes through backdrop and escape', () => {
  const onClose = vi.fn();
  const { rerender } = render(
    <UnifiedModal open title="统一弹窗" onClose={onClose} portal={false}>
      <div>窗口内容</div>
    </UnifiedModal>,
  );

  fireEvent.click(screen.getByRole('dialog').parentElement as HTMLElement);
  expect(onClose).toHaveBeenCalledTimes(1);

  rerender(
    <UnifiedModal open title="统一弹窗" onClose={onClose} portal={false}>
      <div>窗口内容</div>
    </UnifiedModal>,
  );
  fireEvent.keyDown(window, { key: 'Escape' });
  expect(onClose).toHaveBeenCalledTimes(2);
});

test('respects closeDisabled for every default close path', () => {
  const onClose = vi.fn();
  render(
    <UnifiedModal
      open
      title="生成中"
      onClose={onClose}
      closeDisabled
      portal={false}
    >
      <div>窗口内容</div>
    </UnifiedModal>,
  );

  fireEvent.click(screen.getByRole('dialog').parentElement as HTMLElement);
  fireEvent.keyDown(window, { key: 'Escape' });
  fireEvent.click(screen.getByRole('button', { name: '关闭' }));

  expect(onClose).not.toHaveBeenCalled();
});
