import { BLOCK_SELECTORS } from '../config/constants';

/**
 * Finds the first block element in the parent hierarchy
 * @param {Editor} editor - TinyMCE editor instance
 * @param {Node} node - The node to start from
 * @returns {Element|null} The first block element or null
 */
export const findBlockElement = (editor, node) => {
  const parents = editor.dom.getParents(node);
  return parents.find(parent => editor.dom.is(parent, BLOCK_SELECTORS));
};

/**
 * Checks if a node has any of the specified classes
 * @param {Editor} editor - TinyMCE editor instance
 * @param {Element} node - The node to check
 * @param {string[]} classes - Array of class names to check for
 * @returns {boolean} True if the node has any of the classes
 */
export const hasAnyClass = (editor, node, classes) => {
  return classes.some(className => editor.dom.hasClass(node, className));
};

/**
 * Removes empty spans from a node
 * @param {Editor} editor - TinyMCE editor instance
 * @param {Node} node - The node to clean
 */
export const removeEmptySpans = (editor, node) => {
  const spans = editor.dom.select('span', node);
  spans.forEach(span => {
    if (!span.className) {
      editor.dom.remove(span, true);
    }
  });
};

/**
 * Resizes an image element based on body width
 * @param {Editor} editor - TinyMCE editor instance
 * @param {Element} element - The image element
 * @param {number} width - The new width
 */
export const resizeImage = (editor, element, width) => {
  const body = editor.dom.getParent(element, 'body');
  const bodyWidth = body.offsetWidth;
  const percent = Math.round(((width / bodyWidth) * 100) / 5) * 5;
  
  if (percent > 100) {
    const captionBlock = editor.dom.getParents(element, '.wp-caption');
    if (captionBlock.length) {
      editor.dom.setStyle(captionBlock[0], 'width', '');
    }
    editor.dom.setStyle(element, 'width', '');
  } else {
    const captionBlock = editor.dom.getParents(element, '.wp-caption');
    if (captionBlock.length) {
      editor.dom.setStyle(captionBlock[0], 'width', `${percent}%`);
    } else {
      editor.dom.setStyle(element, 'width', `${percent}%`);
    }
  }
}; 