import { cleanup, render, waitFor } from '@testing-library/react';
import {
  afterAll,
  afterEach,
  beforeAll,
  describe,
  expect,
  it,
  vi,
} from 'vitest';
import CodeMirrorEditor from '../src/editor/CodeMirrorEditor';

const originalGetClientRects = Range.prototype.getClientRects;

beforeAll(() => {
  Range.prototype.getClientRects = () => [] as unknown as DOMRectList;
});

afterAll(() => {
  Range.prototype.getClientRects = originalGetClientRects;
});

afterEach(cleanup);

describe('CodeMirror themes', () => {
  it('reconfigures the editor when the Toolbox theme changes', async () => {
    const onChange = vi.fn();
    const { container, rerender } = render(
      <div data-toolbox-theme="dark">
        <CodeMirrorEditor value="<root/>" onChange={onChange} ariaLabel="XML" />
      </div>
    );

    const editorHost = container.querySelector<HTMLElement>('.editor-host');
    expect(editorHost?.dataset.editorTheme).toBe('dark');
    expect(container.querySelector('.cm-editor')).toBeTruthy();

    rerender(
      <div data-toolbox-theme="light">
        <CodeMirrorEditor value="<root/>" onChange={onChange} ariaLabel="XML" />
      </div>
    );

    await waitFor(() => {
      expect(editorHost?.dataset.editorTheme).toBe('light');
    });
  });
});
