/**
 * Checks if a given node contains a popup with a nested element identified by a specific test ID.
 *
 * @param node - The node to check.
 * @param nestedElementQuery - The query to look for the nested element.
 * @returns True if the node contains the popup, false otherwise.
 */
export const containsPopupWithNestedElement = (node, nestedElementQuery) => {
  if (!(node instanceof HTMLElement)) {
    return false;
  }

  // Check if node itself has the popup attribute and contains the element matching the nestedElementQuery
  if (node.matches('[data-editor-popup="true"]')) {
    return !!node.querySelector(nestedElementQuery);
  }

  // Check if any direct child with popup attribute contains the element matching the nestedElementQuery
  return !!node.querySelector(`:scope > [data-editor-popup="true"] ${nestedElementQuery}`);
};

/**
 * Returns the popup with a nested element identified by a specific test ID if it exists.
 *
 * @param node - The node to check.
 * @param nestedElementQuery - The query to look for the nested element.
 * @returns Element if the node contains the popup, undefined otherwise.
 */
export const popupWithNestedElement = (node, nestedElementQuery) => {
  if (!(node instanceof HTMLElement)) {
    return undefined;
  }

  // Check if node itself has the popup attribute and contains the element matching the nestedElementQuery
  if (node.matches('[data-editor-popup="true"]')) {
    return node.querySelector(nestedElementQuery);
  }

  // Check if any direct child with popup attribute contains the element matching the nestedElementQuery
  return node.querySelector(`:scope > [data-editor-popup="true"] ${nestedElementQuery}`);
};

/**
 * Searches for the popup container element relative to the provided editor view element.
 *
 * @param editorViewEl - The editor view HTMLElement.
 * @returns The popup container HTMLElement if found, otherwise undefined.
 */
export const getPopupContainerFromEditorView = editorViewEl => {
  const editorContentArea = editorViewEl === null || editorViewEl === void 0 ? void 0 : editorViewEl.closest('.ak-editor-content-area');
  const pluginsComponentsWrapper = editorContentArea === null || editorContentArea === void 0 ? void 0 : editorContentArea.querySelector(':scope > [data-testid="plugins-components-wrapper"]');
  return pluginsComponentsWrapper || undefined;
};

/**
 * Checks if a node matches or contains the node given by the provided query css selector
 *
 * @param query - CSS selector string
 * @returns true if node matches or contains query or false otherwise
 */
export const getNodeQuery = query => node => {
  if (!node || !(node instanceof Element)) {
    return false;
  }
  return node.matches(query) || node.querySelector(query) !== null;
};