import { DEFAULT_BLOCK_FORMATS } from '../config/constants';
import { findBlockElement } from '../utils/dom';

/**
 * TinyMCE plugin for custom block formats
 */
export default function(editor) {
  let customBlocks = [];

  /**
   * Registers the block formats menu button
   */
  const registerMenuButton = () => {
    editor.ui.registry.addMenuButton('tdblocks', {
      text: 'Paragraph',
      tooltip: 'Block Formats',
      onSetup: (api) => {
        const updateButtonText = () => {
          const selection = editor.selection;
          const selectedNode = selection.getNode();
          const blockElm = findBlockElement(editor, selectedNode);
          
          if (blockElm) {
            const activeBlock = customBlocks.find(
              block => blockElm.nodeName.toLowerCase() === block.tag.toLowerCase()
            );
            api.setText(activeBlock ? activeBlock.title : 'Paragraph');
          } else {
            api.setText('Paragraph');
          }
        };

        // Update on selection change
        editor.on('NodeChange', updateButtonText);
        
        // Initial update
        updateButtonText();

        // Cleanup
        return () => {
          editor.off('NodeChange', updateButtonText);
        };
      },
      fetch: (callback) => {
        const items = customBlocks.map(block => {
          const selection = editor.selection;
          const selectedNode = selection.getNode();
          const blockElm = findBlockElement(editor, selectedNode);
          
          let indicator = '';
          
          // Check if current block matches this block format
          if (blockElm && blockElm.nodeName.toLowerCase() === block.tag.toLowerCase()) {
            indicator = '● ';  // Show active for current block
          }
          
          return {
            type: 'menuitem',
            text: indicator + block.title,
            onAction: () => {
              editor.execCommand('applyCustomBlock', block);
            },
          };
        });
        callback(items);
      },
      width: 120
    });
  };

  /**
   * Registers the custom block command
   */
  const registerCommand = () => {
    editor.addCommand('applyCustomBlock', (block) => {
      const selection = editor.selection;
      const selectedNode = selection.getNode();
      const blockElm = findBlockElement(editor, selectedNode);

      if (!blockElm) return;

      // If the current block is already the target block type, convert to paragraph
      if (blockElm.nodeName.toLowerCase() === block.tag.toLowerCase()) {
        editor.execCommand('FormatBlock', false, 'p');
      } else {
        // Convert to the new block type
        editor.execCommand('FormatBlock', false, block.tag);
        
        // Apply any additional classes if specified
        if (block.classes?.length) {
          block.classes.forEach(className => {
            editor.dom.addClass(blockElm, className);
          });
        }
      }
    });
  };

  // Initialize the plugin
  registerMenuButton();
  registerCommand();

  // Return public API
  return {
    /**
     * Initializes the block formats
     * @param {Array<{title: string, tag: string, classes?: string[]}>|string} block_formats - Custom block formats (array or TinyMCE string format)
     */
    initBlocks: (block_formats) => {
      if (Array.isArray(block_formats) && block_formats.length > 0) {
        customBlocks = block_formats;
      } else if (typeof block_formats === 'string' && block_formats) {
        const parsed = block_formats.split(';').filter(Boolean).map(f => {
          const [title, tag] = f.split('=');
          return { title: title?.trim(), tag: tag?.trim() };
        }).filter(f => f.title && f.tag);
        customBlocks = parsed.length > 0 ? parsed : DEFAULT_BLOCK_FORMATS;
      } else {
        customBlocks = DEFAULT_BLOCK_FORMATS;
      }
    }
  };
} 