import { afterEach, describe, expect, test } from 'vitest';
import { isInInteractiveContext } from './focus-utils';

afterEach(() => {
  document.body.innerHTML = '';
});

/** Append `el` to the document, focus it, and return it. */
function mountAndFocus<T extends HTMLElement>(el: T): T {
  document.body.appendChild(el);
  el.focus();
  return el;
}

describe('isInInteractiveContext', () => {
  test('false when nothing is focused', () => {
    expect(isInInteractiveContext()).toBe(false);
  });

  test('true for a focused <input>', () => {
    mountAndFocus(document.createElement('input'));
    expect(isInInteractiveContext()).toBe(true);
  });

  test('true for a focused contenteditable element', () => {
    const div = document.createElement('div');
    div.contentEditable = 'true';
    mountAndFocus(div);
    expect(isInInteractiveContext()).toBe(true);
  });

  test('true when focus is inside the Monaco editor', () => {
    const editor = document.createElement('div');
    editor.className = 'monaco-editor';
    const textarea = document.createElement('textarea');
    textarea.className = 'inputarea';
    editor.appendChild(textarea);
    document.body.appendChild(editor);
    // Focus an inner node: the .monaco-editor ancestor must still count.
    textarea.focus();
    expect(isInInteractiveContext()).toBe(true);
  });

  test('false for a focused <button>', () => {
    mountAndFocus(document.createElement('button'));
    expect(isInInteractiveContext()).toBe(false);
  });
});
