/**
 * DragHandler - Handles drag-and-drop operations for ACF repeater fields
 *
 * Manages the destroy/restore cycle of TinyMCE editors when ACF repeater
 * rows are reordered via drag-and-drop.
 */

export class DragHandler {
  constructor(stateManager, fieldInitializer) {
    this.stateManager = stateManager;
    this.fieldInitializer = fieldInitializer;
    this.isSetup = false;
  }

  /**
   * Set up drag handlers for ACF repeater/flexible content fields
   */
  setup() {
    if (this.isSetup) return;
    this.isSetup = true;

    // Handle jQuery UI sortable start event
    jQuery(document).on('sortstart', '.acf-repeater, .acf-flexible-content', (event, ui) => {
      this.handleDragStart(event, ui);
    });

    // Handle jQuery UI sortable stop event
    jQuery(document).on('sortstop', '.acf-repeater, .acf-flexible-content', (event, ui) => {
      this.handleDragStop(event, ui);
    });

    console.log('Drag handlers initialized for ACF repeater/flexible content');
  }

  /**
   * Handle drag start - destroy editors in dragged element
   * @param {Event} event - Sort start event
   * @param {Object} ui - jQuery UI sortable ui object
   */
  handleDragStart(event, ui) {
    if (this.stateManager.dragState.isDragging) return;

    this.stateManager.dragState.isDragging = true;
    console.log('Sortable drag started, destroying TinyMCE editors in dragged element');

    const draggedElement = ui.item[0];
    const textareas = draggedElement.querySelectorAll(
      '.acf-field.acf-field-textarea textarea[id]'
    );

    textareas.forEach(textarea => {
      const id = textarea.id;
      const editor = window.tinymce?.get(id);

      if (editor && !this.stateManager.dragState.destroyedEditors.has(id)) {
        console.log(`Destroying editor ${id} for drag operation`);

        // Check initialization status BEFORE clearing state
        const wasInitialized = this.stateManager.isInitialized(id);

        // Store editor data for restoration
        this.stateManager.dragState.destroyedEditors.set(id, {
          content: editor.getContent(),
          element: textarea,
          isInitialized: wasInitialized
        });

        // Destroy the editor
        editor.destroy();

        // Update state
        this.stateManager.removeField(id);
      }
    });
  }

  /**
   * Handle drag stop - restore editors after drop
   * @param {Event} event - Sort stop event
   * @param {Object} ui - jQuery UI sortable ui object
   */
  handleDragStop(event, ui) {
    if (!this.stateManager.dragState.isDragging) return;

    console.log('Sortable drag stopped, restoring TinyMCE editors');

    // Small delay to ensure DOM is settled after drop
    setTimeout(() => {
      this.stateManager.dragState.destroyedEditors.forEach((editorData, id) => {
        const { content } = editorData;

        // Check if element still exists in DOM (might have been moved)
        const currentElement = document.getElementById(id);

        if (currentElement) {
          console.log(`Restoring editor ${id} after drag operation`);

          // Set the content back
          currentElement.value = content;

          // Force re-initialization
          this.fieldInitializer.forceInitialize(id, currentElement);
        }
      });

      // Clear drag state
      this.stateManager.dragState.destroyedEditors.clear();
      this.stateManager.dragState.isDragging = false;
    }, 100);
  }

  /**
   * Clean up drag handlers
   */
  cleanup() {
    jQuery(document).off('sortstart', '.acf-repeater, .acf-flexible-content');
    jQuery(document).off('sortstop', '.acf-repeater, .acf-flexible-content');
    this.isSetup = false;

    // Clear any pending drag state
    this.stateManager.dragState.destroyedEditors.clear();
    this.stateManager.dragState.isDragging = false;
  }
}

export default DragHandler;
