/**
 * =============================================================================
 * @package         Blue Raven (Free Version)
 * @Plugin URI      https://enterrahost.com/plugins/blue-raven
 * 
 * @Author          EnterraHost
 * @Author URI      https://enterrahost.com
 * @License         GPL-2.0-or-later
 *  
 * @Copyright       (c) 2025 EnterraHost
 * @Contents        Javascript for the Tools Page
 *
 * =============================================================================
 * 
 * || INDEX:
 * ||   - SIDE BAR
 * ||   - LOAD SIDE BAR PAGES
 * ||   - TOOLS AJAX
 * ||   
 * =============================================================================
 */
 
(function ($) {
    $(document)

    /* =========== Listen to selection changes and update buttons =========== */

    .on('mouseup keyup', '.brtxe-editor', function() {
        const parentWithId = $(this).closest('[id$="-tools"]'); 
        const id = parentWithId.attr('id');  
        if (!id) return; 
        const prefix = id.replace(/-tools$/, ''); 

        updateToolbarButtons(prefix);
    })

    .on('click', '.brtxe-toolbar button', function (e) {
        e.preventDefault();

        const parentWithId = $(this).closest('[id$="-tools"]');

        const id = parentWithId.attr('id');  
        const prefix = id.replace(/-tools$/, ''); 
        const command = $(this).data('command');

        if (command === 'formatBlock') {
            document.execCommand(command, false, $(this).data('value'));
        } else if (command === 'createLink') {
            const selection = window.getSelection();
            const anchorNode = selection.anchorNode;
            const linkNode = $(anchorNode).closest('a');

            if (linkNode.length > 0) {
                document.execCommand('unlink', false, null);
            } else {
                const url = prompt('Enter the URL');
                if (url) document.execCommand('createLink', false, url);
            }
        } else {
            document.execCommand(command, false, null);
        }

        $(this).trigger('focus'); 
        updateToolbarButtons(prefix);
    });


    function updateToolbarButtons(prefix) {
        const editor = $('.' + prefix + '-editor');
        const toolbarButtons = $('#' + prefix + '-tools button');

        const selection = window.getSelection();
        if (!selection || !selection.anchorNode) {
            toolbarButtons.removeClass('active');
            return;
        }

        if (!$.contains(editor[0], selection.anchorNode)) {
            toolbarButtons.removeClass('active');
            return;
        }

        toolbarButtons.removeClass('active');
        
        let currentNode = selection.anchorNode.nodeType === 3 
            ? selection.anchorNode.parentNode
            : selection.anchorNode;

        while (currentNode && currentNode !== editor[0]) {
            const $currentNode = $(currentNode);
            const tag = currentNode.tagName;

/* ===========  Handle text formatting =========== */  

            switch (tag) {
                case 'H2':
                    toolbarButtons.filter('[data-command="formatBlock"][data-value="h2"]').addClass('active');
                    break;
                case 'H3':
                    toolbarButtons.filter('[data-command="formatBlock"][data-value="h3"]').addClass('active');
                    break;
                case 'H4':
                    toolbarButtons.filter('[data-command="formatBlock"][data-value="h4"]').addClass('active');
                    break;
                case 'P':
                    toolbarButtons.filter('[data-command="formatBlock"][data-value="p"]').addClass('active');
                    break;
                case 'B': case 'STRONG':
                    toolbarButtons.filter('[data-command="bold"]').addClass('active');
                    break;
                case 'I': case 'EM':
                    toolbarButtons.filter('[data-command="italic"]').addClass('active');
                    break;
                case 'U':
                    toolbarButtons.filter('[data-command="underline"]').addClass('active');
                    break;
                case 'A':
                    toolbarButtons.filter('[data-command="createLink"]').addClass('active');
                    break;
                case 'LI':
                    if ($currentNode.closest('ul').length) {
                        toolbarButtons.filter('[data-command="insertUnorderedList"]').addClass('active');
                    } else if ($currentNode.closest('ol').length) {
                        toolbarButtons.filter('[data-command="insertOrderedList"]').addClass('active');
                    }
                    break;
            }

/* ===========  Handle alignment =========== */    

            const alignment = $currentNode.css('text-align');
            switch (alignment) {
                case 'center':
                    toolbarButtons.filter('[data-command="justifyCenter"]').addClass('active');
                    break;
                case 'right':
                    toolbarButtons.filter('[data-command="justifyRight"]').addClass('active');
                    break;
                case 'left':
                default:
                    toolbarButtons.filter('[data-command="justifyLeft"]').addClass('active');
                    break;
            }
            
            currentNode = currentNode.parentNode;
        }
    }
})(jQuery); 
