/**
 * VisibilityManager - Handles visibility observers for hidden editors
 *
 * Manages MutationObservers that watch for editors becoming visible
 * and triggers appropriate refresh/focus actions.
 */

export class VisibilityManager {
  constructor(stateManager) {
    this.stateManager = stateManager;
  }

  /**
   * Set up visibility observer for a hidden editor
   * @param {Object} editor - TinyMCE editor instance
   * @param {Element} element - Editor element
   */
  setupVisibilityObserver(editor, element) {
    const observer = new MutationObserver(mutations => {
      let becameVisible = false;

      mutations.forEach(mutation => {
        if (
          mutation.type === 'attributes' &&
          (mutation.attributeName === 'style' || mutation.attributeName === 'class')
        ) {
          const isNowVisible =
            element.offsetParent !== null &&
            element.style.display !== 'none' &&
            window.getComputedStyle(element).display !== 'none';

          if (isNowVisible && !becameVisible) {
            becameVisible = true;
            console.log(`Editor ${editor.id} became visible, focusing and refreshing`);

            setTimeout(() => {
              try {
                editor.execCommand('mceRepaint');
                editor.focus();
                observer.disconnect();
              } catch (error) {
                console.warn(`Error refreshing visible editor ${editor.id}:`, error);
              }
            }, 50);
          }
        }
      });
    });

    // Observe the element and its ancestors for style/class changes
    observer.observe(element, { attributes: true, attributeFilter: ['style', 'class'] });

    // Also observe parent elements that might control visibility
    let parent = element.parentElement;
    let depth = 0;
    while (parent && depth < 5) {
      observer.observe(parent, { attributes: true, attributeFilter: ['style', 'class'] });
      parent = parent.parentElement;
      depth++;
    }

    // Store observer for cleanup
    if (this.stateManager) {
      this.stateManager.addObserver(observer);
    }

    return observer;
  }

  /**
   * Check if an element is currently visible
   * @param {Element} element - Element to check
   * @returns {boolean}
   */
  isVisible(element) {
    if (!element) return false;

    return (
      element.offsetParent !== null &&
      element.style.display !== 'none' &&
      window.getComputedStyle(element).display !== 'none'
    );
  }

  /**
   * Handle initial visibility check for an editor
   * @param {Object} editor - TinyMCE editor instance
   * @param {Element} element - Editor element
   * @returns {boolean} True if editor is hidden and observer was set up
   */
  handleEditorVisibility(editor, element) {
    const isHidden = !this.isVisible(element);

    if (isHidden) {
      console.log(`Editor ${editor.id} initialized on hidden element, setting up visibility observer`);
      this.setupVisibilityObserver(editor, element);
      return true;
    }

    // Editor is visible, focus it after a short delay
    setTimeout(() => {
      try {
        editor.focus();
      } catch (error) {
        console.warn(`Could not focus editor ${editor.id}:`, error);
      }
    }, 100);

    return false;
  }
}

export default VisibilityManager;
