/**
 * =============================================================================
 * @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 The Mail Form Tool
 *
 * =============================================================================
 * 
 * || INDEX:
 * ||   - SIDE BAR
 * ||   - LOAD SIDE BAR PAGES
 * ||   - CONNECT TO A SERVER
 * ||   
 * =============================================================================
 */
    
(function ($) {
    $(document)
    
/*
============================================================
    CONTROLS 
============================================================
*/
    
    .on('click', '#post-new-mail-block', BlueRaven_createNewForm)
    .on('click', '.mli-delete', BlueRaven_deleteForm)
    .on('click', '.mli-edit', BlueRaven_toggleMailBuilder)
    .on('mousedown', '.draggable-block', BlueRaven_onDraggableMouseDown)   
    .on('click', '#remove-block', BlueRaven_deleteBlock)
    .on('click', '#copy-block', BlueRaven_doupBlock)
    .on('click', '#post-save-mail-block', BlueRaven_saveBlock)
    .on('click', '#element-dropdown-item-add', BlueRaven_addDropdownItem)
    
/*
============================================================
    FORM BLOCK CONTROLS  
============================================================
*/   
   
    .on('click', '.block-edit', function (e) { BlueRaven_OpenBuilder($(this).data('type'), '', e.target); })
    .on('click', '#br-mf-t, #br-mf-t-b', function (e) { BlueRaven_OpenBuilder('title', $('#br-mf-t'), e.target); })
    .on('click', '#br-mf-f-b', function (e) { BlueRaven_OpenBuilder('form', $('#br-mf-f'), e.target);  })
    .on('click', '#br-mf-l', function (e) { BlueRaven_OpenBuilder('', $('#br-mf-f'), e.target);  })
    .on('click', '#br-mf-r', function (e) { BlueRaven_OpenBuilder('', $('#br-mf-f'), e.target);  })
    .on('click', '#br-mf-m, #br-mf-m-b', function (e) { BlueRaven_OpenBuilder('message', $('#br-mf-m'), e.target); })
    .on('click', '#br-mf-s, #br-mf-s-b', function (e) { BlueRaven_OpenBuilder('submit', $('#br-mf-s'), e.target); })
    .on('click', '#br-mf-a-b', function (e) { BlueRaven_OpenBuilder('admin', '', e.target); })
    
    .on('click', '#tool-box-botton-text', function() { BlueRaven_hideAllBlocks(); $('#text-edit-block').show(); BlueRaven_showEnabled('#tool-box-botton-text');})     
    .on('click', '#tool-box-botton-block', function() {BlueRaven_hideAllBlocks(); $('#block-edit-block').show(); BlueRaven_showEnabled('#tool-box-botton-block');})
    .on('click', '#tool-box-botton-spacing', function() {BlueRaven_hideAllBlocks(); $('#spacing-edit-block').show(); BlueRaven_showEnabled('#tool-box-botton-spacing');})
    .on('click', '#tool-box-botton-dropdown', function() {BlueRaven_hideAllBlocks(); $('#drop-down-edit-block').show(); BlueRaven_showEnabled('#tool-box-botton-dropdown');})
    .on('click', '#tool-box-botton-adv', function() {BlueRaven_hideAllBlocks(); $('#advacned-edit-block').show(); BlueRaven_showEnabled('#tool-box-botton-adv');})
    .on('click', '#tool-box-botton-messages', function() {BlueRaven_hideAllBlocks(); $('#message-edit-block').show(); BlueRaven_showEnabled('#tool-box-botton-messages');})
    .on('click', '#tool-box-botton-bot', function() {BlueRaven_hideAllBlocks(); $('#captcha-settings-block').show(); BlueRaven_showEnabled('#tool-box-botton-bot');})
    .on('click', '#tool-box-botton-send', function() {BlueRaven_hideAllBlocks(); $('#mail-settings-block').show(); BlueRaven_showEnabled('#tool-box-botton-send'); BlueRaven_getPlaceholders()})
    
    .on('click', '#post-create-mail-block', BlueRaven_closeToolBuilder)
    
/*
============================================================
    UPDATE EDITING ELEMENT FROM FORM
============================================================
*/  
    
    .on('input', '#element-ID', function () {$('.mf-editing').children().attr('id', $(this).val());})
    
    /// -- Text Block 
    
    .on('input', '#element-text', function () {BlueRaven_updateFormTitleAndListItem($(this).val());})
    .on('input', '#element-name', function () {const rawValue = $(this).val();const safeValue = rawValue.replace(/\s+/g, '-'); if (rawValue !== safeValue) $(this).val(safeValue);const $c = $('.mf-editing').children();$c.attr($c.is('label') ? 'for' : 'name', safeValue);})
    .on('change', '#element-font-family', function () { $('.mf-editing').children().css('font-family', $(this).val()); })
    .on('change', '#font-shape-underline', function () {$('.mf-editing').children().css('text-decoration', this.checked ? 'underline' : 'none');})
    .on('change', '#font-shape-bold', function () {$('.mf-editing').children().css('font-weight', this.checked ? 'bold' : 'normal');})
    .on('change', '#font-shape-italic', function () {$('.mf-editing').children().css('font-style', this.checked ? 'italic' : 'normal');})
    .on('input', '#element-font-size', function () {$('.mf-editing').children().css('font-size', $(this).val());})
    .on('input', '#element-font-color', function () {$('.mf-editing').children().css('color', $(this).val());})
    
    /// -- Block Block 
     
    .on('change', '#justify-self-left', function () {$('#br-mf-s-w').css('justify-content', 'flex-start');})
    .on('change', '#justify-self-center', function () {$('#br-mf-s-w').css('justify-content', 'center');})
    .on('change', '#justify-self-right', function () {$('#br-mf-s-w').css('justify-content', 'flex-end');})
    .on('change', '#text-align-left', function () { $('.mf-editing').children().each(function() {var cssProperty = this.tagName?.toLowerCase() === 'select' ? 'text-align-last' : 'text-align';$(this).css(cssProperty, 'left');});})
    .on('change', '#text-align-center', function () { $('.mf-editing').children().each(function() {var cssProperty = this.tagName?.toLowerCase() === 'select' ? 'text-align-last' : 'text-align';$(this).css(cssProperty, 'center');});})
    .on('change', '#text-align-right', function () { $('.mf-editing').children().each(function() {var cssProperty = this.tagName?.toLowerCase() === 'select' ? 'text-align-last' : 'text-align';$(this).css(cssProperty, 'right');});})
    .on('change', '#text-align-vertical', function () {$('.mf-editing').children().css('align-content', this.checked ? 'center' : '');})
    .on('input', '#element-background-color', function () {$('.mf-editing').children().css('background-color', $(this).val());})
    .on('input', '#element-border-width, #element-border-color, #element-border-radius', function () { let width = $('#element-border-width').val().trim(); let color = $('#element-border-color').val().trim(); let radius = $('#element-border-radius').val().trim(); if (width && /^\d+$/.test(width)) width += 'px'; if (color && /^\d+$/.test(color)) color = '#' + color; if (radius && /^\d+$/.test(radius)) radius += 'px'; if (!width || width === '0px') { $('.mf-editing').children().css({ 'border': 'none' }); } else { $('.mf-editing').children().css({ 'border': `${width} solid ${color || 'black'}`, 'border-radius': radius || '0px' }); } }).on('input', '#element-height-min', function () {$('.mf-editing').children().css('min-height', $(this).val());})
    .on('input', '#element-height-max', function () {$('.mf-editing').children().css('max-height', $(this).val());})
    .on('input', '#element-height-min', function () {$('.mf-editing').children().css('min-height', $(this).val());})
    .on('input', '#element-width-max', function () {$('.mf-editing').children().css('max-width', $(this).val());})
    .on('input', '#element-width-min', function () {$('.mf-editing').children().css('min-width', $(this).val());})
    .on('change', 'input[name="display-type"]', function () {$('.mf-editing').children().css('display', $(this).val());})
    
    /// -- Spacing Block
    
    .on('input', '#element-padding-top', e => ($('.mf-editing').length ? $('.mf-editing').children() : $('#br-mf-f-b').css('box-shadow') ? $('#br-mf-f') : $()).css('padding-top', $(e.target).val()))
    .on('input', '#element-padding-right', e => ($('.mf-editing').length ? $('.mf-editing').children() : $('#br-mf-f-b').css('box-shadow') ? $('#br-mf-f') : $()).css('padding-right', $(e.target).val()))
    .on('input', '#element-padding-bottom', e => ($('.mf-editing').length ? $('.mf-editing').children() : $('#br-mf-f-b').css('box-shadow') ? $('#br-mf-f') : $()).css('padding-bottom', $(e.target).val()))
    .on('input', '#element-padding-left', e => ($('.mf-editing').length ? $('.mf-editing').children() : $('#br-mf-f-b').css('box-shadow') ? $('#br-mf-f') : $()).css('padding-left', $(e.target).val()))
    .on('input', '#element-margin-top', e => ($('.mf-editing').length ? $('.mf-editing').children() : $('#br-mf-f-b').css('box-shadow') ? $('#br-mf-f') : $()).css('margin-top', $(e.target).val()))
    .on('input', '#element-margin-right', e => ($('.mf-editing').length ? $('.mf-editing').children() : $('#br-mf-f-b').css('box-shadow') ? $('#br-mf-f') : $()).css('margin-right', $(e.target).val()))
    .on('input', '#element-margin-bottom', e => ($('.mf-editing').length ? $('.mf-editing').children() : $('#br-mf-f-b').css('box-shadow') ? $('#br-mf-f') : $()).css('margin-bottom', $(e.target).val()))
    .on('input', '#element-margin-left', e => ($('.mf-editing').length ? $('.mf-editing').children() : $('#br-mf-f-b').css('box-shadow') ? $('#br-mf-f') : $()).css('margin-left', $(e.target).val()))
        
    /// -- Advanced Block 
    
    .on('change', '#edit-adv-required', function () {$('.mf-editing').children().prop('required', this.checked);})
    .on('change', '#edit-adv-hide', function () {$('.mf-editing').children().css('display', this.checked ? 'none' : '');})
    .on('change', '#element-input-type', function () {$('.mf-editing').children().attr('type', $(this).val());})
    .on('change', '#element-div-split', function () {const splitValue = $(this).val();const container = $('#br-mf-f');const left = $('#br-mf-l');const right = $('#br-mf-r');if (splitValue === 'no-split') {container.removeAttr('style');left.removeAttr('style');right.removeAttr('style');} else {const [leftWidth, rightWidth] = splitValue.split('-');container.attr('style', 'display: flex; gap: 1rem; height: 100%;');left.attr('style', `width: ${leftWidth}%; min-height: 3rem;`); right.attr('style', `width: ${rightWidth}%; min-height: 3rem;`);}})
    
    /// -- DropDown Block 
    
    .on('input', '#drop-down-edit-block-inner input', function() {
        const $select = $('.mf-editing').find('select');

        if (!$select.length) return;
    
        const $wrapper = $(this).closest('.flex-sb');
        const $inputs = $wrapper.find('input');
        const optionName = $inputs.eq(0).val().trim();
        const optionValue = $inputs.eq(1).val().trim();
    
        if (!optionName && !optionValue) return;
    
        const index = $('#drop-down-edit-block-inner .flex-sb').index($wrapper);
        const $options = $select.find('option');
    
        if ($options.eq(index).length) {$options.eq(index).text(optionName); $options.eq(index).val(optionValue || optionName);} else {const $newOption = $('<option></option>').text(optionName).val(optionValue || optionName); $select.append($newOption);}
    })
    
    /// -- Form Admin 
    
    .on('click', '.placeholder-name-item', e => $('#mail-body').val($('#mail-body').val() + '\n[' + $(e.currentTarget).text() + ']'))
      
/*
============================================================
    OPEN TOOLBOX
============================================================
*/ 

    function BlueRaven_OpenBuilder(option, addingBlock, elementClicked){
    
    // =========== Editing Select =========== //   
        
        let editingElement = elementClicked;
        
        if(option === ''){
            const tag = elementClicked.tagName.toLowerCase();
            
            switch (tag) {
                case 'label':
                    option = 'label';
                    break;
                case 'input':
                    option = 'input';
                    break;
                case 'textarea':
                    option = 'text';
                    break;
                case 'select':
                    option = 'dropdown';
                    break;
                default:
                    option = null;
            }
        }
        
        $('#mail-canvas .mf-editing').each(function () {if ($(elementClicked).prop('tagName') === 'DIV') return;$(this).children().unwrap();});
        
        if(option != 'admin'){
            $('#tool-box-title').text('Tool Box for the Selected Block.')
            
            if (addingBlock != '') {
                if (!$(elementClicked).is('[data-type]')) {
                    if ($(elementClicked).prop('tagName') === 'DIV') return;
    
                    const $clicked = $(elementClicked);
                    const displayValue = $clicked.css('display');
                    const isInlineBlock = displayValue === 'inline-block';
                    
                    if (!$clicked.parent().hasClass('mf-editing')) {const styleAttr = isInlineBlock ? 'position: relative; display: inline-block;' : 'position: relative;';$clicked.wrap(`<div class="mf-editing" style="${styleAttr}"></div>`);}

                } else if ($(addingBlock).attr('id') === 'br-mf-t' || $(addingBlock).attr('id') === 'br-mf-m' || $(addingBlock).attr('id') === 'br-mf-s') {
                    $(addingBlock).wrap('<div class="mf-editing" style="position: relative;"></div>');
                    editingElement = addingBlock;
                }
            }else{
                const type = $(elementClicked).data('type');
                let newElement;
                
                switch (type) {
                    case 'label':
                        newElement = $('<label>', {
                            text: 'New Label',
                            class: 'draggable-block',
                            style: 'display: block; line-height: normal;'
                        });
                        
                        editingElement = newElement;
                        break;
                    case 'input':
                        newElement = $('<input>', {
                            type: 'text',
                            class: 'draggable-block',
                            style: 'display: block; line-height: normal; min-width: 100%;'
                        });
                        
                        editingElement = newElement;
                        break;
                    case 'text':
                        newElement = $('<textarea>', {
                            class: 'draggable-block',
                            style: 'display: block; line-height: normal; min-width: 100%;'
                        });
                        
                        editingElement = newElement;
                        break;
                    case 'dropdown':
                        newElement = $('<select>', {
                            class: 'draggable-block mfm-select',
                            style: 'display: block; line-height: normal; width: 100%; max-width: 100%; position: relative;'
                        });   

                        editingElement = newElement;
                        break;   
                       
                    default:
                        return;
                }
                
                const wrappedElement = $(newElement).wrap('<div class="mf-editing" style="position: relative;"></div>').parent();
                $('#br-mf-l').append(wrappedElement);
            }
        }else{
            $('#tool-box-title').text('Tool Box for the Form Administration settings.')
        }
        
    // =========== Button Handling =========== //    
        
        document.querySelectorAll('.enterra-secondary-button-color').forEach(el => { el.style.boxShadow = 'none'; });
        
        if (elementClicked.classList.contains('enterra-secondary-button-color')) {
            elementClicked.style.boxShadow = `0 0 8px var(--Primary_Color)`;
        }else{
            if (elementClicked.id === 'br-mf-t') {$('#br-mf-t-b').css('box-shadow', '0 0 8px var(--Primary_Color)');}
            else if (elementClicked.id === 'br-mf-m') {$('#br-mf-m-b').css('box-shadow', '0 0 8px var(--Primary_Color)');}
            else if (elementClicked.id === 'br-mf-s') {$('#br-mf-s-b').css('box-shadow', '0 0 8px var(--Primary_Color)');}
            else if (elementClicked.id === 'br-mf-s') {$('#br-mf-s-b').css('box-shadow', '0 0 8px var(--Primary_Color)');}
            else if (elementClicked.id === 'br-mf-a') {$('#br-mf-a-b').css('box-shadow', '0 0 8px var(--Primary_Color)');}
            else if (elementClicked.tagName === 'LABEL') {$('#br-mf-lb-b').css('box-shadow', '0 0 8px var(--Primary_Color)');}
            else if (elementClicked.tagName === 'INPUT') {$('#br-mf-ip-b').css('box-shadow', '0 0 8px var(--Primary_Color)');}
            else if (elementClicked.tagName === 'TEXTAREA') {$('#br-mf-ta-b').css('box-shadow', '0 0 8px var(--Primary_Color)');}
            else if (elementClicked.tagName === 'SELECT') {$('#br-mf-dd-b').css('box-shadow', '0 0 8px var(--Primary_Color)');}
        }
        
    // =========== Toolbox Handling =========== //           
        
        $('#form-tool-box').show();
        $('#tool-box-botton-text, #tool-box-botton-block, #tool-box-botton-spacing, #tool-box-botton-dropdown, #tool-box-botton-adv, #tool-box-botton-messages, #tool-box-botton-bot, #tool-box-botton-send, #element-ID').css('display', 'block').show();
        $('#tool-box-botton-extras').show();
        $('#edit-display-block').show();
        $('.edit-setting-block[data-setting-type="text"]').show();
        $('.edit-setting-block[data-setting-type="name"]').show();
        $('#block-justify').hide();
        BlueRaven_hideAllBlocks();
        
        switch (option) {
        case 'title':
            $('#tool-box-botton-dropdown, #tool-box-botton-extras, #tool-box-botton-messages, #tool-box-botton-bot, #tool-box-botton-send').hide();
            $('.edit-setting-block[data-setting-type="name"]').hide();
            $('#required-element-check, #input-element-type, #hide-on-input').hide(); 
            $('#edit-display-block').hide();
            $('#hide-element-check').show();
            
            break;
        case 'form':
            $('#tool-box-botton-text, #tool-box-botton-block, #tool-box-botton-dropdown, #tool-box-botton-extras, #tool-box-botton-messages, #tool-box-botton-bot, #tool-box-botton-send').hide();
            $('#required-element-check, #input-element-type, #hide-element-check').hide(); 
            $('#hide-on-input').show();
            $('#edit-display-block').hide();
            
            break;
        case 'message':
            $('#tool-box-botton-dropdown, #tool-box-botton-adv, #tool-box-botton-extras, #tool-box-botton-messages, #tool-box-botton-bot, #tool-box-botton-send').hide();
            $('.edit-setting-block[data-setting-type="text"]').hide();
            $('.edit-setting-block[data-setting-type="name"]').hide();
            $('#edit-display-block').hide();
            
            break;
        case 'submit':
            $('#tool-box-botton-dropdown, #tool-box-botton-adv, #tool-box-botton-extras, #tool-box-botton-messages, #tool-box-botton-bot, #tool-box-botton-send').hide();
            $('.edit-setting-block[data-setting-type="name"]').hide();
            $('#block-justify').show();
            $('#edit-display-block').hide();
            
            break;
        case 'label':
            $('#tool-box-botton-dropdown, #tool-box-botton-adv, #tool-box-botton-messages, #tool-box-botton-bot, #tool-box-botton-send').hide();
            
            break;
        case 'input':
            $('#tool-box-botton-dropdown, #tool-box-botton-messages, #tool-box-botton-bot, #tool-box-botton-send').hide();
            $('#hide-element-check').hide(); 
            $('#hide-on-input').hide();
            $('#required-element-check, #input-element-type').show();
            
            break;
        case 'text':
            $('#tool-box-botton-dropdown, #tool-box-botton-messages, #tool-box-botton-bot, #tool-box-botton-send').hide();
            $('#required-element-check').show();
            $('#hide-on-input, #input-element-type, #hide-element-check').hide(); 
            
            break;
        case 'dropdown':
            $('#tool-box-botton-adv, #tool-box-botton-messages, #tool-box-botton-bot, #tool-box-botton-send').hide();
            $('.edit-setting-block[data-setting-type="text"]').hide();
            
            break;    
        case 'admin':
            $('#tool-box-botton-text, #tool-box-botton-block, #tool-box-botton-spacing, #tool-box-botton-dropdown, #tool-box-botton-adv, #element-ID, #tool-box-botton-extras').hide();
            
            break;    
        default:
            console.warn('Unknown block type:', option);
            break;
        }
        
        $('#tool-box-select').children('p:visible').first().trigger('click');
        
    /* =========== Load values into took box =========== */
    
        BlueRaven_populateEditFields(editingElement);
    
    }
    
    function BlueRaven_hideAllBlocks() { $('#text-edit-block , #block-edit-block , #spacing-edit-block , #drop-down-edit-block , #advacned-edit-block, #message-edit-block, #captcha-settings-block, #mail-settings-block ').hide(); }
    
/*
============================================================
    POPULATE EDIT FIELDS
============================================================
*/  

    function BlueRaven_populateEditFields(el) {
        
        $('#element-ID').val($(el).attr('id') || '');
        
        const tag = $(el).prop('tagName').toLowerCase();
        const display = $(el).css('display');
        const rgbToHex = rgb => { if (!rgb || rgb === 'transparent') return ''; const m = rgb.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d*\.?\d+))?\)/); if (!m) return ''; const [, r, g, b, a] = m; if (a !== undefined && parseFloat(a) === 0) return ''; return '#' + [r, g, b].map(n => (+n).toString(16).padStart(2, '0')).join(''); };
                
        if (!['label', 'input', 'textarea', 'select'].includes(tag)) {$('#element-ID').prop('readonly', true); } else { $('#element-ID').prop('readonly', false); }
         
        /// -- TEXT 
         
        $('#element-text').val($(el).is('input, textarea') ? ($(el).val().trim() || $(el).attr('placeholder') || '') : $(el).text().trim());
        $('#element-name').val($(el).attr('name') || $(el).attr('for') || '');
        $('#element-font-family').val($(el).css('font-family').replace(/['"]/g, ''));
        $('#font-shape-bold').prop('checked', parseInt($(el).css('font-weight')) >= 600);
        $('#font-shape-italic').prop('checked', $(el).css('font-style') === 'italic');
        $('#font-shape-underline').prop('checked', $(el).css('text-decoration').includes('underline'));
        $('#element-font-size').val($(el).css('font-size'));
        $('#element-font-color').val(rgbToHex($(el).css('color')) || '').attr('placeholder', rgbToHex($(el).css('color')) ? '' : '#000000');
        $('#font-shape-italic').prop('checked', $(el).css('font-style') === 'italic');
        $('#text-align-left').prop('checked', $(el).css('text-align') === 'left' || $(el).css('text-align') === 'start' || $(el).css('text-align-last') === 'left');
        $('#text-align-center').prop('checked', $(el).css('text-align') === 'center' || $(el).css('text-align-last') === 'center');
        $('#text-align-right').prop('checked', $(el).css('text-align') === 'right' || $(el).css('text-align-last') === 'right');
        $('#text-align-vertical').prop('checked', $(el).css('align-content') === 'center'); 
        
        /// -- BLOCK 
        
        $('#element-background-color').val(rgbToHex($(el).css('background-color')) || '').attr('placeholder', rgbToHex($(el).css('background-color')) ? '' : '#000000');
        $('#element-border-width').val($(el).css('border-width'));
        $('#element-border-color').val(rgbToHex($(el).css('border-color')) || '').attr('placeholder', rgbToHex($(el).css('border-color')) ? '' : '#000000');
        $('#element-border-radius').val($(el).css('border-radius'));
        $('#element-height-min').val($(el).css('min-height'));
        $('#element-height-max').val($(el).css('max-height'));
        $('#element-width-min').val($(el).css('min-width'));
        $('#element-width-max').val($(el).css('max-width'));
        $('#display-inline').prop('checked', display === 'inline-block');
        $('#display-block').prop('checked', display === 'block');

        const justifyMap = { 'flex-start': 'left', 'start': 'left','center': 'center', 'flex-end': 'right', 'end': 'right' };
        $('#justify-self-' + (justifyMap[$('#br-mf-s-w').css('justify-content')] || 'left')).prop('checked', true);
                
        /// -- BLOCK 
         
        const styles = ['padding', 'margin'];
        const sides = ['top', 'right', 'bottom', 'left'];
        styles.forEach(style => sides.forEach(side => $(`#element-${style}-${side}`).val($(el).css(`${style}-${side}`) || 0)));
        
        /// -- ADVANCED 
        
        $('#edit-adv-required').prop('checked', $(el).prop('required'));
        $('#element-input-type').val($(el).attr('type'));
        
        let split = 'no-split'; 
        
        if ($('#br-mf-f').css('display') === 'flex') {
            const left = $('#br-mf-l').width();
            const right = $('#br-mf-r').width();
            const total = left + right;
            const leftPct = Math.floor(((left / total) * 100).toFixed(2));
            const rightPct = Math.floor(((right / total) * 100).toFixed(2));
            const validSplits = ['33-66', '40-60', '50-50', '60-40', '66-33'];
            const possibleSplit = `${leftPct}-${rightPct}`;
        
            if (validSplits.includes(possibleSplit)) { split = possibleSplit; }
        } 

        $('#element-div-split').val(split);

        /// -- DROPDOWN 
        
        if ($(el).prop('tagName').toLowerCase() == 'select'){

            const container = document.getElementById('drop-down-edit-block-inner');
            container.innerHTML = '';
            
            if (el.options && el.options.length) {
                Array.from(el.options).forEach(option => {
                    const isExplicit = option.hasAttribute('value');
                    const value = isExplicit ? option.value : '';
            
                    const wrapper = document.createElement('div');
                    wrapper.className = 'flex-sb';
            
                    const inputName = document.createElement('input');
                    inputName.type = 'text';
                    inputName.className = 'br-input';
                    inputName.name = 'element-dropdown-item[]';
                    inputName.placeholder = 'Option Name';
                    inputName.value = option.text;
                    inputName.style.width = '48%';
                    inputName.style.margin = '4px 0px';
            
                    const inputValue = document.createElement('input');
                    inputValue.type = 'text';
                    inputValue.className = 'br-input';
                    inputValue.name = 'element-dropdown-item[]';
                    inputValue.placeholder = 'Option Value';
                    inputValue.value = value;
                    inputValue.style.width = '48%';
                    inputValue.style.margin = '4px 0px';
            
                    wrapper.appendChild(inputName);
                    wrapper.appendChild(inputValue);
                    container.appendChild(wrapper);
                });
            }
        }
    }
    
/*
============================================================
    CONTROLS
============================================================
*/     
    
    // =========== New Mail Form =========== //
    
    function BlueRaven_createNewForm(){ 
        if ($('#mail-builder').is(':visible')) {$('#post-save-mail-block').trigger('click');}
        BlueRaven_toolOperation('', 'create-new-form-block', '', true).then(function(html) {$('#mail-list').html(html); $("#mail-builder").hide(); $('#mail-list .mli-edit').last().click();});
    }
    
    // =========== Delete Mail Form =========== //
    
    function BlueRaven_deleteForm() {
        const $parent = $(this).closest('.mail-list-item'); 
        const formId = $parent.data('id');                   
        const formName = $parent.find('.mli-name').text();   
    
        if (confirm(`Do you want to delete "${formName}"?`)) { $('.post-save-mail-block').trigger('click'); BlueRaven_toolOperation(formId, 'delete-form-block', '', true).then(function(html) { $('#mail-list').html(html); $('#mail-builder').hide();});}
    }
    
    // =========== Edit Button =========== //
    
    function BlueRaven_toggleMailBuilder() {
        const $builder = $('#mail-builder');
        const $clickedButton = $(this);
        const isEditing = $clickedButton.text().trim() == 'Editing';
        
        $('.mli-edit').text('Edit');
        
        if (isEditing) { $('#post-save-mail-block').trigger('click'); $('#mail-builder').hide();return; }
        if ($builder.is(':visible') && !isEditing) { $('#post-save-mail-block').trigger('click');}
        $(this).text('Editing');
             
        const $parent = $clickedButton.closest('.mail-list-item');
        const formId = $parent.data('id');
    
        BlueRaven_toolOperation(formId, 'open-edit-form-block', '', true).then(function(html) {
            $builder.html(html);
    
            if ($('#mail-canvas').html().trim() === '') {
                const defaultHTML = `<h2 id="br-mf-t">New Form</h2><div id="br-mf-f"><div id="br-mf-l"><label class="draggable-block" for="client-name">Your Name</label><input type="text" class="draggable-block" placeholder="enter your name here" name="client-name"></div><div id="br-mf-r"></div></div><h5 id="br-mf-m">This is a sample message, For when a user submits the form. You can edit this message in the &quot;Form Admin&quot; area.</h5><div id="br-mf-s-w"><button id="br-mf-s" style='border: 1px solid black;border-radius: 5px;background-color: white;'>Submit</button></div>`;
                $('#mail-canvas').html(defaultHTML);
                $('#mail-canvas label').first().trigger('click');
                $('#tool-box-botton-text').trigger('click');
            }
    
            $builder.show();
        });
    }
    
    // =========== Done Button =========== //
    
    function BlueRaven_closeToolBuilder(){
        $('#form-tool-box').hide();
        BlueRaven_hideEnabledAll();
    
        $('#mail-canvas .mf-editing').each(function () {
            const $wrapper = $(this);
            if (!$wrapper.hasClass('mf-editing')) return;
            const $inner = $wrapper.children().first();
            $inner.length && $inner.insertBefore($wrapper);
            $wrapper.remove(); 
        });
    }
    
    // =========== Copy Button =========== //
    
    function BlueRaven_doupBlock(){
        const $editing = $('.mf-editing');
        const $inner = $editing.children().first();
        if ($inner.length) { $editing.before($inner.clone()); }
    }
    
    // =========== Trash Button =========== //
    
    function BlueRaven_deleteBlock() {
        if (confirm('Are you sure you want to delete the block you are editing?')) {
            $('.mf-editing').remove();
            $('#post-create-mail-block').trigger('click');
        }
    }
    
    // =========== Save Button =========== //
    
    function BlueRaven_saveBlock(){
        
        $('.mf-editing').each(function () {$(this).children().unwrap();});
            
        let id = $("#edit-id").val();
        let title = $("#br-mf-t").text();
        let formHTML = $('#mail-canvas').html();
        
        let messages = {
            success: $('#success-message').val(),
            error: $('#error-message').val(),
            bot: $('#bot-message').val(),
            missing: $('#missing-message').val()
        };
        
        let messagesJSON = JSON.stringify(messages);

        let bot_prevention = {
            provider: $('#bot-provider').val(),
            site_key: $('#bot-sitekey').val(), 
            secret_key: $('#bot-secret').val()
        };
        
        let botPreventionJSON = JSON.stringify(bot_prevention);

        let email_to = $("#mail-to").val();
        let email_from = $("#mail-from").val();
        let reply_to = $("#mail-reply-to").val();
        let subject = $("#mail-subject").val();
        let template = $("#mail-body").val();

        let content = [id , title , formHTML , messagesJSON , botPreventionJSON , email_to , email_from , reply_to , subject , template  ]
        
        BlueRaven_toolOperation(content, 'save-form-block', '', false)
    }
    
    // =========== DROP DOWN Button =========== //
    
    function BlueRaven_addDropdownItem() {
        const container = document.getElementById('drop-down-edit-block-inner');
    
        const wrapper = document.createElement('div');
        wrapper.className = 'flex-sb';
    
        const inputName = document.createElement('input');
        inputName.type = 'text';
        inputName.className = 'br-input';
        inputName.name = 'element-dropdown-item[]';
        inputName.placeholder = 'Option Name';
        inputName.style.width = '48%';
        inputName.style.margin = '4px 0px';
    
        const inputValue = document.createElement('input');
        inputValue.type = 'text';
        inputValue.className = 'br-input';
        inputValue.name = 'element-dropdown-item[]';
        inputValue.placeholder = 'Option Value';
        inputValue.style.width = '48%';
        inputValue.style.margin = '4px 0px';
    
        wrapper.appendChild(inputName);
        wrapper.appendChild(inputValue);
        container.appendChild(wrapper);
    }
                    
/*
============================================================
    DRAGGING FEATURES
============================================================
*/     

    function BlueRaven_onDraggableMouseDown(e) {
        e.preventDefault();
        
        const $el = $(this);
        let dragActivated = false;
        let timeoutId;
        
    // =========== Hold Timer =========== //
        
        timeoutId = setTimeout(function() {
            dragActivated = true;
            
            $(document).off('.dragging');
            $('.mf-editing').each(function () {$(this).children().unwrap();});
            $('#post-create-mail-block').trigger('click');
   
            $el.data('original-style', $el.attr('style') || '');
            $el.data('original-position', {parent: $el.parent(),index: $el.index(),rect: $el[0].getBoundingClientRect()});
            $el.addClass('is-dragging').css({position: 'fixed',left: e.clientX + 'px',top: e.clientY + 'px',width: '20rem',opacity: 0.8,pointerEvents: 'none'});
    
    // ===========  Mousemove handler =========== //
    
            function BlueRaven_handleMove(e) {
                if (!dragActivated) return;

                $el.css({ left: e.clientX + 'px', top: e.clientY + 'px' });
            
                let $targets = $('.draggable-block').not('.is-dragging');
                let closest = null;
                let closestDistance = Infinity;
                let isInsideFlex = false;
                let flexSide = null;
            
                const $flexContainer = $('#br-mf-f');
                const $leftBlock = $('#br-mf-l');
                const $rightBlock = $('#br-mf-r');
            
                const flexRect = $flexContainer[0].getBoundingClientRect();
                const leftRect = $leftBlock[0].getBoundingClientRect();
                const rightRect = $rightBlock[0].getBoundingClientRect();
                
    // ===========  Determine whether inside flex area =========== //
    
                if (e.clientX >= flexRect.left && e.clientX <= flexRect.right &&e.clientY >= flexRect.top && e.clientY <= flexRect.bottom ) {
                    isInsideFlex = true;
                    
                    if (e.clientX >= leftRect.left && e.clientX <= leftRect.right &&e.clientY >= leftRect.top && e.clientY <= leftRect.bottom ) {
                        flexSide = 'left';
                    } else if (e.clientX >= rightRect.left && e.clientX <= rightRect.right && e.clientY >= rightRect.top && e.clientY <= rightRect.bottom) {
                        flexSide = 'right';
                    }else{
                        flexSide = 'FAIL 2';
                    }
                }else{
                    flexSide = 'FAIL 1';
                }
                
    // =========== Now apply filtering only if inside flex and side is detected =========== //

                if (isInsideFlex && flexSide) {
                    const $targetSide = flexSide === 'left' ? $leftBlock : $rightBlock;
                    $targets = $targets.filter(function () { return $.contains($targetSide[0], this); });
                }
                
    // =========== Determine closest =========== //
    
                $targets.each(function () {
                    const rect = this.getBoundingClientRect();
                    const centerY = rect.top + rect.height / 2;
                    const distance = Math.abs(e.clientY - centerY);
            
                    if (distance < closestDistance && distance < rect.height) { closest = this; closestDistance = distance; }
                });
                
    // ===========  Remove any existing indicators first =========== //
    
                $('.drop-indicator').remove();
    
                if (closest) {
                    const $closest = $(closest);
                    const closestParentFlex = $closest.closest('#br-mf-f');
                    
                    if (closestParentFlex.length > 0) {
                        
                        ///-- Regular case - insert after closest element
                        
                        const $targetSide = (flexSide === 'left') ? $leftBlock : (flexSide === 'right') ? $rightBlock : null;
                        if ($targetSide?.length) {
                            if (!$targetSide[0].contains(closest)) {$targetSide.prepend('<div class="drop-indicator"></div>');} else {$(closest).after('<div class="drop-indicator"></div>');}
                        } else {
                            $(closest).after('<div class="drop-indicator"></div>');
                        }
                    }
                } else if (isInsideFlex) {
                    
                    ///-- No closest element but inside flex container - add to appropriate side
                    
                    (flexSide === 'left' ? $leftBlock : flexSide === 'right' ? $rightBlock : null)?.append('<div class="drop-indicator"></div>');
                }
                
    // =========== Style the indicator if it exists =========== //
    
                const $indicator = $('.drop-indicator');
                if ($indicator.length) { $indicator.css({ height: '4px',backgroundColor: 'var(--Primary_Color)',margin: '2px 0', width: '100%'}); }
            }
    
    // =========== Mouseup handler =========== //
            
            function BlueRaven_handleUp() {
                clearTimeout(timeoutId);
                
                if (dragActivated) {
                    $(document).off('mousemove.dragging mouseup.dragging');
                    
                    const $indicator = $('.drop-indicator');
                    const hasIndicator = $indicator.length > 0;
                    
                    if (hasIndicator) {
                        const $flexParent = $indicator.closest('#br-mf-l, #br-mf-r');
                
                        if ($flexParent.length) {
                            
                            ///-- Dropping into flex container side
                            
                            $indicator.replaceWith($el);
                        } else {
                            
                            ///-- Regular case - insert after previous element
                            
                            const $closest = $indicator.prev('.draggable-block');
                            $closest.length ? $el.insertAfter($closest) : $indicator.parent().prepend($el);
                        }
                    } else {
                        
                        ///-- Return to original position
                        
                        const original = $el.data('original-position');
                        if (original && original.parent) {
                            const $parent = $(original.parent);
                            const $siblings = $parent.children();

                            (original.index > 0 && original.index <= $siblings.length) ? $el.insertAfter($siblings.eq(original.index - 1)) : $parent.prepend($el);
                        }
                    }
                    
    // ===========  Restore original styles =========== //
    
                    $el.attr('style', $el.data('original-style') || null);
                    $el.removeClass('is-dragging');
                    $indicator.remove();
                }
            }
            
    // =========== Add the new listeners =========== //
    
            $(document)
                .on('mousemove.dragging', BlueRaven_handleMove)
                .on('mouseup.dragging', BlueRaven_handleUp);
                
        }, 200); 
    
        $(document).one('mouseup', function() {clearTimeout(timeoutId);});
    }

/*
============================================================
    EXTRAS 
============================================================
*/  

    // =========== Show what tool box is enabled =========== //
        
    function BlueRaven_showEnabled(buttonSelector) {
        $('[id^="tool-box-botton-"]').css('box-shadow', 'none'); 
        $(buttonSelector).css('box-shadow', '0 0 8px var(--Primary_Color)'); 
    }
    
    // =========== Remove glow from what tool box was enabled =========== //
       
    function BlueRaven_hideEnabledAll() {$('.block-edit').css('box-shadow', 'none');}
    
    // =========== Update from Text or PlaceHolder input =========== //
      
    function BlueRaven_updateFormTitleAndListItem(value) {
        const $child = $('.mf-editing').children();
        if ($child.is('input, textarea')) {$child.val(value).attr('placeholder', value);  } else {$child.text(value); }
        if ($child.attr('id') === 'br-mf-t') {const editId = $('#edit-id').val();const $matchingItem = $(`.mail-list-item[data-id="${editId}"]`);$matchingItem.find('.mli-name').text(value);}
    }
    
    // =========== get Form Names from the Form and add it to the space =========== //
      
    function BlueRaven_getPlaceholders(){
        $('#placeholder-name-space').empty();
        $('#br-mf-f').find('input[name], textarea[name], select[name]').each(function() {
            const name = $(this).attr('name');
            
            const $span = $('<span></span>').text(name)
                .addClass('placeholder-name-item')
                .css({
                    display: 'inline-block',
                    padding: '4px 8px',
                    margin: '4px',
                    border: '1px solid lightgrey',
                    borderRadius: '4px',
                    fontSize: '0.9rem',
                    backgroundColor: 'transparent'
                });
        
            $('#placeholder-name-space').append($span);
        });
    }

})(jQuery);   