<script type="text/javascript">
    var contentarea = 1;
</script>

<style type="text/css">

</style>

<?php

global $ID, $post, $post_ID, $wp_meta_boxes, $errors;
delete_option('newsletters_eligible_users_count_tmp');


$isSerialKeyValid = false;
$serial_validation_status = $this -> ci_serial_valid();

if (!is_array($serial_validation_status) && $serial_validation_status ) {
    $isSerialKeyValid = true;
}


$imagespost = $this -> get_option('imagespost');
$p_id = (empty($_POST['p_id'])) ? $imagespost : (int) sanitize_text_field($_POST['p_id']);
$ID = $p_id;
$post_ID = $p_id;
$post = get_post($p_id);

wp_nonce_field('closedpostboxes', 'closedpostboxesnonce', false);
wp_nonce_field('meta-box-order', 'meta-box-order-nonce', false);
$mailtype = $this -> get_option('mailtype');
$disable_drag_and_drop_builder = $this -> get_option('disable_drag_drop_builder');
$disable_autosave = $this -> get_option('disable_autosave');
$autosave_interval = $this -> get_option('autosave_interval');
if (empty($autosave_interval)) { $autosave_interval = 20; }
$disable_ai_assistant = $this -> get_option('disable_ai_assistant');
$disable_ai_rewrite   = $this -> get_option('disable_ai_rewrite');
$ai_assistant_enabled = ($disable_ai_assistant != 'Y');
$ai_rewrite_enabled   = ($disable_ai_rewrite != 'Y');
$ai_features_enabled  = ($ai_assistant_enabled || $ai_rewrite_enabled);
$attach_context_default = $this -> get_option('ai_attach_context_default');
$attach_context_default_enabled = ($attach_context_default !== 'disabled');
$ai_keys = array(
    'gemini'   => $this -> get_option('ai_gemini_pro_api_key'),
    'chatgpt'  => $this -> get_option('ai_chatgpt_api_key'),
    'deepseek' => $this -> get_option('ai_deepseek_pro_api_key'),
);

$builderon = get_user_option('newsletters_builderon', get_current_user_id());
if ((empty($builderon) && !empty($_POST['builderon'])) && $isSerialKeyValid) {
    $builderon = 1;
}

if($mailtype == "api" || !$isSerialKeyValid)
{
    $builderon = 0;
}


if($disable_drag_and_drop_builder || !$isSerialKeyValid)
{

    $builderon = 0;
}

$validation_status = $this -> ci_serial_valid();

$grapeJS_editor = false;
$grapeJS_inDB = get_post_meta($post_ID, 'using_grapeJS', true);
//echo $post_ID . ' ' . $grapeJS_inDB;
if(isset($grapeJS_inDB) && !empty($grapeJS_inDB))
{
    $grapeJS_editor = $grapeJS_inDB;
}

$screen = get_current_screen();
$page = $screen -> id;

?>

<div class="wrap <?php echo $this -> pre; ?> <?php echo $this -> sections -> send; ?> newsletters">
    <?php if (!empty($_GET['id'])) : ?>
        <h1><?php _e('Edit Newsletter', 'wp-mailinglist'); ?> <a href="?page=<?php echo $this -> sections -> send; ?>" class="add-new-h2"><?php _e('Add New', 'wp-mailinglist'); ?></a></h1>
    <?php else : ?>
        <h1><?php _e('Create Newsletter', 'wp-mailinglist'); ?></h1>
    <?php endif; ?>
    <form action="<?php echo admin_url('admin.php?page=' . $this -> sections -> send); ?>" method="post" id="post" name="post" enctype="multipart/form-data">
        <?php wp_nonce_field($this -> sections -> send); ?>
        <input type="hidden" name="newsletter" value="1" />
        <input type="hidden" name="group" value="all" />
        <input type="hidden" id="ishistory" name="ishistory" value="<?php echo isset($_POST['ishistory']) ? esc_attr($_POST['ishistory']) : ''; ?>" />
        <input type="hidden" id="p_id" name="p_id" value="<?php echo isset($_POST['p_id']) ? esc_attr($_POST['p_id']) : ''; ?>" />
        <input type="hidden" name="inctemplate" value="<?php echo isset($_POST['inctemplate']) ? esc_attr($_POST['inctemplate']) : ""; ?>" />
        <input type="hidden" id="builderon" name="builderon" value="<?php echo (($builderon && $grapeJS_inDB) ? "1" : "0"); ?>" />
        <input type="hidden" id="using_grapeJS" name="using_grapeJS" value="<?php echo $grapeJS_inDB; ?>" />

        <input type="hidden" name="recurringsent" value="<?php echo isset($_POST['sendrecurringsent']) ? esc_attr(wp_unslash($_POST['sendrecurringsent'])) : ""; ?>" />
        <input type="hidden" name="post_id" value="<?php echo isset($_POST['post_id']) ? esc_attr(wp_unslash($_POST['post_id'])) : ''; ?>" />

        <div id="poststuff">
            <div id="post-body" class="metabox-holder columns-2">
                <div id="post-body-content">
                    <div id="titlediv">
                        <div id="titlewrap">
                            <label class="screen-reader-text" for="title"></label>
                            <input onclick="jQuery('iframe#content_ifr').attr('tabindex', '2');" tabindex="1" id="title" autocomplete="off" type="text" placeholder="<?php echo esc_attr(wp_unslash(__('Enter email subject here', 'wp-mailinglist'))); ?>" name="subject" value="<?php echo isset($_POST['subject']) ? esc_attr(wp_unslash($_POST['subject'])) : '' ; ?>" />
                        </div>
                        <?php if (!empty($errors['subject'])) : ?>
                            <div class="ui-state-error ui-corner-all">
                                <p><i class="fa-solid fa-triangle-exclamation"></i> <?php echo $errors['subject']; ?></p>
                            </div>
                        <?php endif; ?>
                        <div class="inside">
                            <div id="edit-slug-box" class="hide-if-no-js" style="display:<?php echo (!empty($_POST['ishistory'])) ? 'block' : 'none'; ?>;">
                                <?php $newsletter_url = $Html -> retainquery('newsletters_method=newsletter&id=' . (isset($_POST['ishistory']) ? esc_html($_POST['ishistory']) : ''), home_url()); ?>
                                <strong><?php _e('Permalink:', 'wp-mailinglist'); ?></strong>
                                <span id="sample-permalink" tabindex="-1"><?php echo $newsletter_url; ?></span>
                                <span id="view-post-btn"><a href="<?php echo $newsletter_url; ?>" target="_blank" class="button button-small"><?php _e('View Newsletter', 'wp-mailinglist'); ?></a></span>
                                <input id="shortlink" type="hidden" value="<?php echo $newsletter_url; ?>">
                                <a href="#" class="button button-small" onclick="prompt('URL:', jQuery('#shortlink').val()); return false;"><?php _e('Get Link', 'wp-mailinglist'); ?></a></div>
                        </div>
                    </div>
                    <?php if ($post instanceof WP_Post) : ?>
                        <?php do_action('edit_form_after_title', $post); ?>
                    <?php endif; ?>

           
            <?php if($mailtype != "api" && !$disable_drag_and_drop_builder) { ?>
                <?php if (!is_array($validation_status)  && $validation_status) { ?>

                    <?php if($ai_features_enabled) : ?>
                    <?php if ($ai_assistant_enabled) : ?>
                    <div id="newsletters-ai-assistant-wrap">
                        <button type="button" id="newsletters-ai-assistant" class="button newsletters-has-tooltip<?php //echo (!$isSerialKeyValid) ? ' disabled' : ''; ?>" title="<?php esc_attr_e('Open the AI Assistant modal to generate new content.', 'wp-mailinglist'); ?>" aria-label="<?php esc_attr_e('Open AI Assistant', 'wp-mailinglist'); ?>" <?php echo (!$isSerialKeyValid) ? 'disabled="disabled"' : ''; ?>>
                            <i class="fa-solid fa-wand-magic-sparkles fa-fw" aria-hidden="true"></i> <?php _e('AI Assistant', 'wp-mailinglist'); ?> <?php
                                    $badge_text = "";
                                    $serial_validation_status = $isSerialKeyValid;

                                    if (is_array($serial_validation_status) || !$serial_validation_status) {
                                        if(isset($link) && $link) {
                                            $badge_text = '<a target="_blank" href="' . admin_url('admin.php?page=' . $this -> sections -> lite_upgrade) . '" >';
                                        }

                                        $badge_text .= __('(PRO )', 'wp-mailinglist');

                                        if(isset($link) && $link) {
                                            $badge_text .= '</a>';
                                        }
                                    }
                                    echo $badge_text;
                                    ?>
                        </button>
                    </div>
                    <?php endif; ?>
                    <?php if ($ai_rewrite_enabled) : ?>
                    <div id="newsletters-ai-rewrite-wrap">
                        <button type="button" id="newsletters-ai-rewrite" class="button newsletters-has-tooltip<?php echo (!$isSerialKeyValid) ? ' disabled' : ''; ?>" title="<?php esc_attr_e('Rewrite the selected content with AI.', 'wp-mailinglist'); ?>" aria-label="<?php esc_attr_e('Open AI Rewrite', 'wp-mailinglist'); ?>" <?php echo (!$isSerialKeyValid) ? 'disabled="disabled"' : ''; ?>>
                            <i class="fa-solid fa-arrows-rotate fa-fw" aria-hidden="true"></i> <?php _e('AI Rewrite', 'wp-mailinglist'); ?>
                        </button>
                    </div>
                    <?php endif; ?>
                    <?php endif; ?>
                    <div id="usebuilder-wrapper">
                        <button type="button" name="usebuilder" id="usebuilder" class="btn btn-lg btn-success newsletters-has-tooltip <?php echo (!empty($builderon) && $grapeJS_inDB) ? 'active builderon' : 'builderoff'; ?>" title="<?php esc_attr_e('Toggle the Drag & Drop Builder', 'wp-mailinglist'); ?>" aria-label="<?php esc_attr_e('Toggle Drag & Drop Builder', 'wp-mailinglist'); ?>">
                            <i class="fa-solid fa-eye fa-fw" aria-hidden="true"></i> <?php _e('Drag & Drop Builder', 'wp-mailinglist'); ?>
                        </button>

                        <script type="text/javascript">
                        var usebuilder_request = false;

                                                jQuery('#usebuilder').on('click', function(event) {
                                                        var builderbutton = jQuery(this);
                                                        var status = false;
                                                        if (builderbutton.hasClass('builderoff')) {
                                                                jQuery('input#builderon').val('1');
                                jQuery('input#using_grapeJS').val('1');
                                                                builderbutton.removeClass('builderoff').addClass('builderon active');
                                                                jQuery('#postdivrich, #postdiv, #previewdiv, #themesdiv').hide();
                                                                jQuery('#newsletters_builder').show();
                                jQuery('#newsletters-ai-assistant-wrap, #newsletters-ai-rewrite-wrap').fadeOut();
                                                                if (!window.gjsEditor) {
                                                                        startbuilder();
                                                                } else {
                                                                        gjsEditor.refresh();
                                                                }
                                                                status = true;
                                                        } else if (builderbutton.hasClass('builderon')) {
                                                                jQuery('input#builderon').val('');
                                jQuery('input#using_grapeJS').val('0');
                                                                builderbutton.removeClass('builderon active').addClass('builderoff');
                                                                jQuery('#postdivrich, #postdiv, #previewdiv, #themesdiv').show();
                                                                jQuery('#newsletters_builder').hide();
                                jQuery('#newsletters-ai-assistant-wrap, #newsletters-ai-rewrite-wrap').fadeIn();
                                                                status = false;
                                                        }

                            if (usebuilder_request) {
                                usebuilder_request.abort();
                            }

                            usebuilder_request = jQuery.ajax({
                                method: "POST",
                                url: newsletters_ajaxurl + 'action=newsletters_builderon',
                                data: {
                                    status: status
                                }
                            }).done(function(response) {
                                //done
                            }).error(function(response) {
                                //error
                            }).always(function(response) {
                                //always
                            });
                        });
                        </script>
                    </div>

                    <div id="newsletters_builder" style="display:<?php echo (!empty($builderon) && $grapeJS_inDB) ? 'block' : 'none'; ?>;">
                        <p>
                            <select name="newsletters_builder_template" id="newsletters_builder_template">
                                <option value=""><?php _e('- No Template -', 'wp-mailinglist'); ?></option>
                                <?php if ($templates = newsletters_get_templates(array(), false, array('title', 'ASC'), null)) : ?>
                                    <?php foreach ($templates as $template) : ?>
                                        <option value="<?php echo esc_attr(stripslashes($template -> id)); ?>"><?php _e($template -> title); ?></option>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </select>
                            <button type="button" id="updatebuilder" class="btn btn-sm btn-info">
                                <i class="fa-solid fa-paintbrush fa-fw"></i> <?php _e('Load Template', 'wp-mailinglist'); ?>
                                <span id="newsletters_builder_template_loading" style="display:none;">
                                    <i class="fa-solid fa-arrows-rotate fa-spin fa-fw"></i>
                                </span>
                            </button>
                           <!-- <button type="button" id="save_grapejs_content" class="btn btn-sm btn-info">
                                <i class="fa-solid fa-paintbrush fa-fw"></i> <?php _e('Save Drag and Drop Builder design', 'wp-mailinglist'); ?>
                                <span id="newsletters_builder_template_loading_save" style="display:none;">
                                    <i class="fa-solid fa-arrows-rotate fa-spin fa-fw"></i>
                                </span>
                            </button>-->
                        </p>
                        <textarea style="display: none; " name="grapejs_content" id="grapejs_content"><?php echo get_post_meta($post_ID, 'grapejs_content', true) ; ?></textarea>
                        <div id="gjs">
                            <!-- Builder content goes here -->
                            <?php
                                echo $this -> getbodyandcss(get_post_meta($post_ID, 'grapejs_content', true));

                            ?>
                        </div>

                        <?php

                        $assets = array();

                        $args = array(
                            'post_type'             =>  "attachment",
                            'orderby'               =>  "date",
                            'order'                 =>  "DESC",
                            'numberposts'           =>  50,
                        );

                        if ($attachments = get_posts($args)) {
                            foreach ($attachments as $attachment) {
                                $assets[] = array('src' => $attachment -> guid);
                            }
                        }

                        ?>

                        <script type="text/javascript">
            var gjsEditor;
            var newslettersGjsSelection = null;
            var newslettersGjsRte = null;

            var newslettersAiSettings = {
                assistantEnabled: <?php echo $ai_assistant_enabled ? 'true' : 'false'; ?>,
                rewriteEnabled: <?php echo $ai_rewrite_enabled ? 'true' : 'false'; ?>
            };

            var newslettersGjsExtensionsRegistered = false;
            var newslettersGjsColorInputs = {};

            function newslettersCreateGjsIcon(classNames) {
                var icon = document.createElement('i');
                icon.setAttribute('aria-hidden', 'true');

                if (typeof classNames === 'string' && classNames.length) {
                    classNames.split(/\s+/).forEach(function(className) {
                        if (className) {
                            icon.classList.add(className);
                        }
                    });
                }

                return icon;
            }

            function newslettersTriggerGjsAiButton(buttonId, rteInstance) {
                var iframe = document.querySelector('#gjs iframe');
                if (iframe && iframe.contentWindow) {
                    var selection = iframe.contentWindow.getSelection();
                    if (selection && selection.rangeCount && typeof window.newslettersSetGjsSelection === 'function') {
                        window.newslettersSetGjsSelection(selection.getRangeAt(0).cloneRange());
                    }
                }

                newslettersGjsRte = rteInstance;

                var trigger = document.getElementById(buttonId);
                if (trigger) {
                    trigger.click();
                }
            }

            function newslettersEnsureGjsExtensions() {
                if (newslettersGjsExtensionsRegistered) {
                    return;
                }

                newslettersGjsExtensionsRegistered = true;

                grapesjs.plugins.add('newsletters-rte-extensions', function(editor, opts) {
                    var options = Object.assign({
                        aiAssistantEnabled: false,
                        aiRewriteEnabled: false,
                        aiAssistantButtonId: 'newsletters-ai-assistant',
                        aiRewriteButtonId: 'newsletters-ai-rewrite'
                    }, opts || {});

                    var rteManager = editor.RichTextEditor;

                    function getColorInput(key) {
                        if (!newslettersGjsColorInputs[key]) {
                            var input = document.createElement('input');
                            input.type = 'color';
                            input.className = 'newsletters-gjs-color-picker';
                            input.style.position = 'absolute';
                            input.style.left = '-9999px';
                            input.style.opacity = '0';
                            input.style.pointerEvents = 'none';
                            input.setAttribute('aria-hidden', 'true');
                            document.body.appendChild(input);
                            newslettersGjsColorInputs[key] = input;
                        }

                        return newslettersGjsColorInputs[key];
                    }

                    function ensureManagerAction(name, config) {
                        if (!rteManager || typeof rteManager.get !== 'function' || typeof rteManager.add !== 'function') {
                            return;
                        }

                        if (!rteManager.get(name)) {
                            rteManager.add(name, config);
                        }
                    }

                    function buildColorAction(actionId, command, iconClass, label) {
                        return {
                            name: actionId,
                            icon: newslettersCreateGjsIcon(iconClass),
                            attributes: { title: label },
                            result: function(rteInstance) {
                                var input = getColorInput(actionId);
                                input.oninput = function(event) {
                                    rteInstance.exec(command, event.target.value);
                                };
                                input.onchange = function(event) {
                                    rteInstance.exec(command, event.target.value);
                                };
                                input.click();
                            }
                        };
                    }

                    function buildWrapAction() {
                        return {
                            name: 'wrap',
                            icon: newslettersCreateGjsIcon('fa-solid fa-object-group'),
                            attributes: { title: 'Wrap selection' },
                            result: function(rteInstance) {
                                var selection = rteInstance.selection && rteInstance.selection();
                                if (!selection && window.getSelection) {
                                    selection = window.getSelection();
                                }

                                if (!selection || !selection.rangeCount) {
                                    return;
                                }

                                var range = selection.getRangeAt(0);

                                if (range.collapsed) {
                                    return;
                                }

                                var wrapper = document.createElement('span');
                                wrapper.className = 'newsletters-gjs-wrap';

                                try {
                                    range.surroundContents(wrapper);
                                } catch (error) {
                                    var fragment = range.extractContents();
                                    wrapper.appendChild(fragment);
                                    range.insertNode(wrapper);
                                }

                                selection.removeAllRanges();
                                var newRange = document.createRange();
                                newRange.selectNodeContents(wrapper);
                                selection.addRange(newRange);
                            }
                        };
                    }

                    function buildAlignAction(name, command, label, iconClass) {
                        var alignMap = {
                            'justifyLeft': 'left',
                            'justifyCenter': 'center',
                            'justifyRight': 'right',
                            'justifyFull': 'justify'
                        };

                        return {
                            name: name,
                            icon: newslettersCreateGjsIcon(iconClass),
                            attributes: { title: label },
                            state: function(rteInstance, doc) {
                                var alignValue = alignMap[command];

                                if (!gjsEditor) {
                                    return 0;
                                }

                                var selected = gjsEditor.getSelected();
                                if (!selected) {
                                    return 0;
                                }

                                // Get the element to check for alignment
                                var tagName = selected.get('tagName');
                                var elType = selected.get('type');
                                var isButtonElement = (tagName === 'a' || tagName === 'button' || elType === 'link' || elType === 'button');

                                var elementToCheck = selected;
                                if (isButtonElement) {
                                    // For buttons, check parent's text-align
                                    elementToCheck = selected.parent();
                                }

                                if (elementToCheck) {
                                    var style = elementToCheck.getStyle();
                                    if (style && style['text-align'] === alignValue) {
                                        return 1; // active
                                    }
                                }

                                return 0; // inactive
                            },
                            result: function(rteInstance) {
                                var alignValue = alignMap[command];

                                if (!gjsEditor) {
                                    rteInstance.exec(command);
                                    return;
                                }

                                var selected = gjsEditor.getSelected();
                                if (!selected) {
                                    rteInstance.exec(command);
                                    return;
                                }

                                // Get the element to check for alignment
                                var tagName = selected.get('tagName');
                                var elType = selected.get('type');
                                var isButtonElement = (tagName === 'a' || tagName === 'button' || elType === 'link' || elType === 'button');

                                if (isButtonElement) {
                                    // Apply text-align to parent for buttons
                                    var parent = selected.parent();
                                    if (parent) {
                                        parent.addStyle({ 'text-align': alignValue });
                                    }
                                } else {
                                    // Apply text-align directly to the element
                                    selected.addStyle({ 'text-align': alignValue });
                                }
                            }
                        };
                    }

                    function buildAiAction(name, label, iconClass, buttonId) {
                        return {
                            name: name,
                            icon: newslettersCreateGjsIcon(iconClass),
                            attributes: { title: label },
                            result: function(rteInstance) {
                                newslettersTriggerGjsAiButton(buttonId, rteInstance);
                            }
                        };
                    }

                    ensureManagerAction('wrap', buildWrapAction());
                    ensureManagerAction('foreColor', buildColorAction('foreColor', 'foreColor', 'fa-solid fa-font', 'Text colour'));
                    ensureManagerAction('backColor', buildColorAction('backColor', 'hiliteColor', 'fa-solid fa-paintbrush', 'Highlight colour'));
                    ensureManagerAction('removeFormat', {
                        name: 'removeFormat',
                        icon: newslettersCreateGjsIcon('fa-solid fa-eraser'),
                        attributes: { title: 'Remove formatting' },
                        result: function(rteInstance) {
                            rteInstance.exec('removeFormat');
                        }
                    });
                    ensureManagerAction('align-left', buildAlignAction('align-left', 'justifyLeft', 'Align left', 'fa-solid fa-align-left'));
                    ensureManagerAction('align-center', buildAlignAction('align-center', 'justifyCenter', 'Align center', 'fa-solid fa-align-center'));
                    ensureManagerAction('align-right', buildAlignAction('align-right', 'justifyRight', 'Align right', 'fa-solid fa-align-right'));
                    ensureManagerAction('align-justify', buildAlignAction('align-justify', 'justifyFull', 'Align justify', 'fa-solid fa-align-justify'));

                    if (options.aiAssistantEnabled) {
                        ensureManagerAction('aiAssistant', buildAiAction('aiAssistant', 'AI Assistant', 'fa-solid fa-wand-magic-sparkles', options.aiAssistantButtonId));
                    }

                    if (options.aiRewriteEnabled) {
                        ensureManagerAction('aiRewrite', buildAiAction('aiRewrite', 'AI Rewrite', 'fa-solid fa-arrows-rotate', options.aiRewriteButtonId));
                    }

                    function findAction(rteInstance, name) {
                        var actions = typeof rteInstance.getActions === 'function' ? rteInstance.getActions() : [];

                        for (var i = 0; i < actions.length; i++) {
                            if (actions[i] && actions[i].name === name) {
                                return actions[i];
                            }
                        }

                        return null;
                    }

                    function removeAction(rteInstance, name) {
                        var existing = findAction(rteInstance, name);

                        if (!existing) {
                            return;
                        }

                        if (existing.btn && existing.btn.parentNode) {
                            existing.btn.parentNode.removeChild(existing.btn);
                        }

                        var actions = rteInstance.getActions();
                        for (var i = actions.length - 1; i >= 0; i--) {
                            if (actions[i] && actions[i].name === name) {
                                actions.splice(i, 1);
                            }
                        }
                    }

                    function ensureToolbarAction(rteInstance, name, builder) {
                        var existing = findAction(rteInstance, name);
                        if (existing) {
                            return existing;
                        }

                        var action = builder();
                        if (!action) {
                            return null;
                        }

                        // Remove any existing residual button before re-adding
                        removeAction(rteInstance, name);

                        rteInstance.addAction(action, { sync: true });
                        return findAction(rteInstance, name);
                    }

                    function reorderToolbar(rteInstance, order) {
                        var toolbar = typeof rteInstance.actionbarEl === 'function' ? rteInstance.actionbarEl() : null;

                        if (!toolbar) {
                            return;
                        }

                        order.forEach(function(name) {
                            var action = findAction(rteInstance, name);
                            if (action && action.btn && toolbar.contains(action.btn)) {
                                toolbar.appendChild(action.btn);
                            }
                        });
                    }

                    function refreshToolbar(rteInstance) {
                        if (!rteInstance) {
                            return;
                        }

                        ensureToolbarAction(rteInstance, 'wrap', buildWrapAction);
                        ensureToolbarAction(rteInstance, 'foreColor', function() {
                            return buildColorAction('foreColor', 'foreColor', 'fa-solid fa-font', 'Text colour');
                        });
                        ensureToolbarAction(rteInstance, 'backColor', function() {
                            return buildColorAction('backColor', 'hiliteColor', 'fa-solid fa-paintbrush', 'Highlight colour');
                        });
                        ensureToolbarAction(rteInstance, 'removeFormat', function() {
                            return {
                                name: 'removeFormat',
                                icon: newslettersCreateGjsIcon('fa-solid fa-eraser'),
                                attributes: { title: 'Remove formatting' },
                                result: function(innerRte) {
                                    innerRte.exec('removeFormat');
                                }
                            };
                        });
                        ensureToolbarAction(rteInstance, 'align-left', function() {
                            return buildAlignAction('align-left', 'justifyLeft', 'Align left', 'fa-solid fa-align-left');
                        });
                        ensureToolbarAction(rteInstance, 'align-center', function() {
                            return buildAlignAction('align-center', 'justifyCenter', 'Align center', 'fa-solid fa-align-center');
                        });
                        ensureToolbarAction(rteInstance, 'align-right', function() {
                            return buildAlignAction('align-right', 'justifyRight', 'Align right', 'fa-solid fa-align-right');
                        });
                        ensureToolbarAction(rteInstance, 'align-justify', function() {
                            return buildAlignAction('align-justify', 'justifyFull', 'Align justify', 'fa-solid fa-align-justify');
                        });

                        if (options.aiAssistantEnabled) {
                            ensureToolbarAction(rteInstance, 'aiAssistant', function() {
                                return buildAiAction('aiAssistant', 'AI Assistant', 'fa-solid fa-wand-magic-sparkles', options.aiAssistantButtonId);
                            });
                        } else {
                            removeAction(rteInstance, 'aiAssistant');
                        }

                        if (options.aiRewriteEnabled) {
                            ensureToolbarAction(rteInstance, 'aiRewrite', function() {
                                return buildAiAction('aiRewrite', 'AI Rewrite', 'fa-solid fa-arrows-rotate', options.aiRewriteButtonId);
                            });
                        } else {
                            removeAction(rteInstance, 'aiRewrite');
                        }

                        var toolbarOrder = ['bold', 'italic', 'underline', 'strikethrough', 'link', 'wrap', 'foreColor', 'backColor', 'removeFormat'];

                        if (options.aiAssistantEnabled) {
                            toolbarOrder.push('aiAssistant');
                        }

                        if (options.aiRewriteEnabled) {
                            toolbarOrder.push('aiRewrite');
                        }

                        toolbarOrder.push('align-left', 'align-center', 'align-right', 'align-justify');

                        reorderToolbar(rteInstance, toolbarOrder);

                        if (typeof rteInstance.updateActiveActions === 'function') {
                            rteInstance.updateActiveActions();
                        }
                    }

                    editor.on('rte:load', function(rteInstance) {
                        refreshToolbar(rteInstance);
                    });

                    editor.on('rte:enable', function(view, rteInstance) {
                        refreshToolbar(rteInstance);
                    });
                });
            }

            function startbuilder() {
                    if (gjsEditor) {
                            gjsEditor.destroy();
                    }
                    var assets = <?php echo json_encode($assets); ?>;

                    newslettersEnsureGjsExtensions();

                    var newslettersRteActions = ['bold', 'italic', 'underline', 'strikethrough', 'link', 'wrap'];

                    if (newslettersAiSettings.assistantEnabled) {
                    //    newslettersRteActions.push('aiAssistant');
                    }

                    if (newslettersAiSettings.rewriteEnabled) {
                    //    newslettersRteActions.push('aiRewrite');
                    }

                   gjsEditor = grapesjs.init({
                            container : '#gjs',
                                                               clearOnRender: true,
                                                               fromElement: true,
                                                               storageManager: {
                                                                       id: 'newsletters-builder-<?php echo esc_js($_POST['ishistory']); ?>',
                                                                       autosave: true,
                                                                       stepsBeforeSave: 1,
                                                                       type: ''
                                                               },
                                                               assetManager: {
                                                                       assets: assets,
                                                                       upload: newsletters_ajaxurl + "action=newsletters_importmedia",
                                                               },
                                                              // Ensure common RTE actions like alignment, colours and wrap are available
                                                             richTextEditor: {
                                                                    actions: newslettersRteActions
                                                             },
                                                               plugins: ['grapesjs-preset-newsletter', 'gjs-plugin-wordpress', 'newsletters-rte-extensions'],
                                                               pluginsOpts: {
                                                                       'grapesjs-preset-newsletter': {
                                                                               modalTitleImport: 'Import template',
                                                                               // ... other options
                                                                       },
                                                                       'gjs-plugin-wordpress': {
                                                                               // options here...
                                                                       },
                                                                       'newsletters-rte-extensions': {
                                                                                aiAssistantEnabled: newslettersAiSettings.assistantEnabled,
                                                                                aiRewriteEnabled: newslettersAiSettings.rewriteEnabled,
                                                                                aiAssistantButtonId: 'newsletters-ai-assistant',
                                                                                aiRewriteButtonId: 'newsletters-ai-rewrite'
                                                                       }
                                                               }
                                                               });

                                                        gjsEditor.on('load', function(){
                                                                jQuery('#gjs .gjs-frame').attr('id', "gjs-frame");
                                                        });

                                                        jQuery('*[title]').each(function () {
                                var el = $(this);
                                var title = el.attr('title').trim();

                                if(!title)
                                    return;

                                el.attr('data-tooltip', el.attr('title'));
                                                                el.attr('title', '');
                                                    });

                                                        gjsEditor.on('change', function(event) {

                                                                var updatecontent = '<!doctype html><html lang="en"><head><meta charset="utf-8"><style>' + gjsEditor.getCss() + '</style></head><body>' + gjsEditor.getHtml() + '</body></html>';
                                //var doc = new DOMParser().parseFromString(updatecontent, "text/html");
                                var content_final =  gjsEditor.getHtml();
                               // newsletters_tinymce_setcontent(content_final);
                                jQuery('textarea#grapejs_content').text(updatecontent);
                                jQuery('textarea#Theme_builder').text(content_final);

                                
                            });
                                                }



                        function newsletters_tinymce_setcontent(content) {
                            jQuery('.wp-editor-wrap .switch-tmce').trigger('click');
                       //     if (typeof(tinyMCE.activeEditor) == "object" && tinyMCE.activeEditor.setContent != null && typeof(tinyMCE.activeEditor.setContent) == "function") {
                       //         tinyMCE.activeEditor.setContent(content);
                       //         tinyMCE.triggerSave();
                        //    }
//
                            jQuery('textarea#content').html(content);
                            return true;
                        }


                                                jQuery(document).ready(function() {
                                                        <?php if (!empty($builderon) && $grapeJS_inDB) : ?>
                                                                jQuery('#postdivrich, #postdiv, #previewdiv, #themesdiv').hide();
                                                                jQuery('#newsletters_builder').show();
                                                                startbuilder();
                                                        <?php endif; ?>

                                                        if (jQuery('#usebuilder').hasClass('builderon')) {
                                                                jQuery('#newsletters-ai-assistant-wrap, #newsletters-ai-rewrite-wrap').hide();
                                                        }
                                                });

                        jQuery('#updatebuilder').on('click', function(event) {
                            if (!confirm('<?php echo esc_js(stripslashes(__('Current content in the builder will be lost, are you sure?', 'wp-mailinglist'))); ?>')) {
                                return false;
                            }

                            var template_id = jQuery('#newsletters_builder_template').val();
                            if (typeof template_id !== 'undefined' && template_id != '') {
                                jQuery('#newsletters_builder_template_loading').show();
                                jQuery('#updatebuilder').prop('disabled', true);
                                jQuery("input[name=theme_id]").val([template_id]);

                                var buildertemplate_request = jQuery.ajax({
                                    method: "POST",
                                    url: newsletters_ajaxurl + 'action=newsletters_get_template&security=<?php echo wp_create_nonce('newsletters_get_template'); ?>',
                                    data: {
                                        template_id: template_id
                                    }
                                                               }).done(function(response) {
                                                                       if (typeof gjsEditor !== 'undefined' && gjsEditor) {
                                                                               gjsEditor.setComponents(response);
                                                                               gjsEditor.setStyle('');
                                                                       } else {
                                                                               jQuery('#gjs').html(response);
                                                                               startbuilder();
                                                                       }
                                                                       jQuery('textarea#grapejs_content').text(response);
                                                                       //newsletters_tinymce_setcontent(response);
                                                               }).error(function(response) {
                                        var error_text = '';
                                        if (400 == response.status )
                                        {
                                            error_text += "<?php _e("Your webhost security settings do not allow loading HTML content via Ajax." , 'wp-mailinglist' ); ?>";
                                        }
                                        alert( error_text + ' ' +  '<?php _e('Ajax call failed, please try again', 'wp-mailinglist'); ?>');

                                }).always(function(response) {
                                    jQuery('#newsletters_builder_template_loading').hide();
                                    jQuery('#updatebuilder').prop('disabled', false);
                                });
                            }

                            return false;
                        });
                        </script>
                    </div>

                    <?php }
                    else
                        {
                            ?>
                            <?php if($ai_features_enabled) : ?>
                            <?php if ($ai_assistant_enabled) : ?>
                             <div id="newsletters-ai-assistant-wrap">
                                <a type="button" target="_blank"  href="<?php echo admin_url('admin.php?page=' . $this -> sections -> lite_upgrade);   ?>"  type="button" id="newsletters-ai-assistant_PRO" class="button newsletters-has-tooltip" title="<?php esc_attr_e('Upgrade to unlock the AI Assistant button.', 'wp-mailinglist'); ?>" aria-label="<?php esc_attr_e('AI Assistant upgrade information', 'wp-mailinglist'); ?>" >
                                    <i class="fa-solid fa-wand-magic-sparkles fa-fw" aria-hidden="true"></i> <?php _e('AI Assistant', 'wp-mailinglist'); ?> <?php
                                            $badge_text = "";

                                                $badge_text .= __('(PRO )', 'wp-mailinglist');


                                            echo $badge_text;
                                            ?>
                                </a>
                            </div>

                            <?php endif; ?>
                            <?php if ($ai_rewrite_enabled) : ?>
                            <div id="newsletters-ai-rewrite-wrap">
                                <a type="button" target="_blank" href="<?php echo admin_url('admin.php?page=' . $this -> sections -> lite_upgrade);   ?>" id="newsletters-ai-rewrite_PRO" class="button newsletters-has-tooltip" title="<?php esc_attr_e('Upgrade to unlock the AI Rewrite button.', 'wp-mailinglist'); ?>" aria-label="<?php esc_attr_e('AI Rewrite upgrade information', 'wp-mailinglist'); ?>">
                                    <i class="fa-solid fa-arrows-rotate fa-fw" aria-hidden="true"></i> <?php _e('AI Rewrite', 'wp-mailinglist'); ?> <?php
                                            $badge_text = '';
                                            $badge_text .= __('(PRO )', 'wp-mailinglist');
                                            echo $badge_text;
                                    ?>
                                </a>
                            </div>
                            <?php endif; ?>
                            <?php endif; ?>
                            <div id="usebuilder-wrapper" style="min-height: 38px;" >
                                <a type="button"  id="usebuilder" target="_blank" class="btn btn-md btn-success newsletters-has-tooltip" title="<?php esc_attr_e('Upgrade to unlock the Drag & Drop Builder.', 'wp-mailinglist'); ?>" aria-label="<?php esc_attr_e('Drag & Drop Builder upgrade information', 'wp-mailinglist'); ?>" style="text-decoration: none;"  href="<?php echo admin_url('admin.php?page=' . $this -> sections -> lite_upgrade);   ?>">
                                    <i class="fa-solid fa-eye fa-fw" aria-hidden="true"></i> <?php _e('Drag & Drop Builder', 'wp-mailinglist'); ?> <sup>(PRO only)</sup>
                                </a>
                            </div>
                            <?php
                        }
                    }
                    ?>


                    <div id="<?php echo (user_can_richedit()) ? 'postdivrich' : 'postdiv'; ?>" class="postarea edit-form-section" style="position:relative;">
                        <!-- The Editor -->

                        
                        <?php if($ai_features_enabled) : ?>
                        <div id="newsletters-ai-modal">
                            <div class="newsletters-ai-content">
                                <button type="button" class="newsletters-ai-close newsletters-has-tooltip" id="newsletters-ai-close" title="<?php esc_attr_e('Close the AI modal', 'wp-mailinglist'); ?>" aria-label="<?php esc_attr_e('Close modal', 'wp-mailinglist'); ?>">
                                    <span class="screen-reader-text"><?php esc_html_e('Close', 'wp-mailinglist'); ?></span>
                                    <i class="fa-solid fa-xmark" aria-hidden="true"></i>
                                </button>
                                <div class="newsletters-ai-body">
                                    <div class="newsletters-ai-row newsletters-ai-row--header">
                                        <div class="newsletters-ai-label">
                                            <label for="newsletters-ai-model"><?php _e('Choose Model:', 'wp-mailinglist'); ?></label>
                                        </div>
                                        <div class="newsletters-ai-context-toggle">
                                            <label class="newsletters-custom-checkbox" for="newsletters-ai-context">
                                                <input type="checkbox" id="newsletters-ai-context" <?php checked($attach_context_default_enabled, true); ?> />
                                                <span class="check-icon"></span>
                                                <?php _e('Attach context', 'wp-mailinglist'); ?>
                                                <span class="wpmlhelp"><a href="" onclick="return false;" title="<?php _e('Attach the current editor content so the AI can better understand the context.', 'wp-mailinglist'); ?>"><i class="fa-solid fa-circle-question fa-fw"></i></a></span>
                                            </label>
                                        </div>
                                    </div>
                                    <div class="newsletters-ai-row newsletters-ai-row--selects">
                                        <select id="newsletters-ai-model" class="noselect">
                                            <optgroup label="<?php _e('Free Models', 'wp-mailinglist'); ?>">
                                                <option value="gemini-2.5-flash">Gemini 2.5 Flash<?php echo empty($ai_keys['gemini']) ? ' (' . __('Add API Key', 'wp-mailinglist') . ')' : ''; ?></option>
                                            </optgroup>
                                            <optgroup label="<?php _e('Paid Models', 'wp-mailinglist'); ?>">
                                                <option value="gemini-2.5-pro" <?php echo empty($ai_keys['gemini']) ? 'disabled="disabled"' : ''; ?>>Gemini 2.5 Pro<?php echo empty($ai_keys['gemini']) ? ' (' . __('Add API Key', 'wp-mailinglist') . ')' : ''; ?></option>
                                                <option value="chatgpt-pro" <?php echo empty($ai_keys['chatgpt']) ? 'disabled="disabled"' : ''; ?>>ChatGPT Pro<?php echo empty($ai_keys['chatgpt']) ? ' (' . __('Add API Key', 'wp-mailinglist') . ')' : ''; ?></option>
                                                <option value="deepseek-pro" <?php echo empty($ai_keys['deepseek']) ? 'disabled="disabled"' : ''; ?>>Deepseek Pro<?php echo empty($ai_keys['deepseek']) ? ' (' . __('Add API Key', 'wp-mailinglist') . ')' : ''; ?></option>
                                            </optgroup>
                                        </select>

                                        <?php $has_chatgpt_key = !empty($ai_keys['chatgpt']); ?>
                                        <div id="newsletters-chatgpt-model-wrapper" class="newsletters-ai-chatgpt" style="display:none;">
                                            <label for="newsletters-chatgpt-model"><?php _e('ChatGPT Model:', 'wp-mailinglist'); ?></label>
                                            <?php if ($has_chatgpt_key) : ?>
                                                <select id="newsletters-chatgpt-model" class="noselect">
                                                    <option value=""><?php esc_html_e('Loading models…', 'wp-mailinglist'); ?></option>
                                                </select>
                                            <?php endif; ?>
                                            <p class="description" id="newsletters-chatgpt-model-message"<?php echo $has_chatgpt_key ? ' style="display:none;"' : ''; ?>>
                                                <?php if (!$has_chatgpt_key) : ?>
                                                    <?php esc_html_e('Provide a valid ChatGPT API key in the AI settings to load available models.', 'wp-mailinglist'); ?>
                                                <?php endif; ?>
                                            </p>
                                        </div>
                                    </div>

                                    <div class="newsletters-ai-field">
                                        <input type="text" id="newsletters-ai-prompt" value="" placeholder="<?php echo esc_attr(__('Write a short welcome message for the newsletter.', 'wp-mailinglist')); ?>" />
                                    </div>
                                    <div class="newsletters-ai-field">
                                        <div id="newsletters-ai-output" class="newsletters-ai-output" data-placeholder="<?php echo esc_attr(__('Generated text will appear here', 'wp-mailinglist')); ?>"></div>
                                    </div>
                                    <div class="newsletters-ai-actions">
                                        <button type="button" class="button" id="newsletters-ai-generate"><i class="fa-solid fa-wand-magic-sparkles"></i> <?php _e('Generate', 'wp-mailinglist'); ?></button>
                                        <button type="button" class="button button-primary" id="newsletters-ai-insert" disabled="disabled"><?php _e('Insert', 'wp-mailinglist'); ?></button>
                                    </div>
                                    <p class="description newsletters-ai-settings-link">
                                        <?php printf(__('Configure AI settings in %sConfiguration &gt; General &gt; AI Assistant Settings%s.', 'wp-mailinglist'), '<a href="' . admin_url('admin.php?page=' . $this -> sections -> settings . '#aidiv') . '" target="_blank">', '</a>'); ?>
                                    </p>
                                </div>
                            </div>
                        </div>
                        <script type="text/javascript">
                        document.addEventListener('DOMContentLoaded', function(){
                            function newslettersInitAiTooltip() {
                                if (!window.jQuery) {
                                    return;
                                }

                                (function($) {
                                    if (!$.isFunction($.fn.tooltip)) {
                                        return;
                                    }

                                    var selectors = [
                                        '.newsletters-has-tooltip',
                                        '#newsletters-ai-modal .wpmlhelp a'
                                    ];

                                    selectors.forEach(function(selector) {
                                        var $targets = $(selector);
                                        if ($targets.length) {
                                            $targets.each(function() {
                                                var $target = $(this);
                                                var tooltipText = $target.attr('title') || $target.data('tooltip');

                                                if (!tooltipText) {
                                                    return;
                                                }

                                                if (!$target.attr('title')) {
                                                    $target.attr('title', tooltipText);
                                                }

                                                var hasTooltip = $target.data('ui-tooltip') || $target.data('uiTooltip');

                                                if (hasTooltip) {
                                                    $target.tooltip('destroy');
                                                }

                                                $target.tooltip({
                                                    tooltipClass: 'newsletters-ui-tooltip',
                                                    show: { delay: 200 }
                                                });
                                            });
                                        }
                                    });
                                })(window.jQuery);
                            }

                            newslettersInitAiTooltip();
                            var aiButton = document.getElementById('newsletters-ai-assistant');
                            var rewriteButton = document.getElementById('newsletters-ai-rewrite');
                            var modal = document.getElementById('newsletters-ai-modal');
                            if(modal && modal.parentNode !== document.body){
                                modal.style.zIndex = '10';
                                modal.style.position = 'fixed';
                                document.body.appendChild(modal);
                            }
                            var insertBtn = document.getElementById('newsletters-ai-insert');
                            var promptBox = document.getElementById('newsletters-ai-prompt');
                            var outputBox = document.getElementById('newsletters-ai-output');
                            var generateBtn = document.getElementById('newsletters-ai-generate');
                            var modelSelect = document.getElementById('newsletters-ai-model');
                            var chatgptModelWrapper = document.getElementById('newsletters-chatgpt-model-wrapper');
                            var chatgptModelSelect = document.getElementById('newsletters-chatgpt-model');
                            var chatgptModelMessage = document.getElementById('newsletters-chatgpt-model-message');
                            var hasChatgptApiKey = <?php echo !empty($ai_keys['chatgpt']) ? 'true' : 'false'; ?>;
                            var chatgptModelsLoaded = false;
                            var chatgptModelsLoading = false;
                            var contextCheckbox = document.getElementById('newsletters-ai-context');
                            var contextDefaultEnabled = <?php echo $attach_context_default_enabled ? 'true' : 'false'; ?>;
                            if(contextCheckbox){
                                contextCheckbox.checked = !!contextDefaultEnabled;
                            }
                            var defaultPromptPlaceholder = promptBox ? promptBox.placeholder : '';
                            var closeBtn = document.getElementById('newsletters-ai-close');

                            var rewriteMode = false;
                            var savedSelection = null;
                            var savedTextareaSelection = null;
                            var rewriteText = '';
                            var outputReady = false;
                            var lastAiPrompt = '';

                            function openModal(){
                                if(!modal){ return; }
                                modal.classList.add('open');
                                if(contextCheckbox){
                                    contextCheckbox.checked = !!contextDefaultEnabled;
                                }
                            }

                            if(promptBox){
                                promptBox.addEventListener('input', function(){
                                    if(!rewriteMode){
                                        lastAiPrompt = promptBox.value;
                                    }
                                });
                            }

                            function resetModal(clearPrompt = true){
                                if(promptBox && clearPrompt){
                                    promptBox.value = '';
                                    promptBox.placeholder = defaultPromptPlaceholder;
                                }
                                if(outputBox){
                                    outputBox.innerHTML = '';
                                }
                                outputReady = false;
                                if(insertBtn){ insertBtn.disabled = true; }
                            }

                            function showToast(message){
                                var toast = document.createElement('div');
                                toast.className = 'newsletters-ai-toast';
                                toast.textContent = message;
                                document.body.appendChild(toast);
                                setTimeout(function(){ toast.classList.add('show'); }, 10);
                                setTimeout(function(){ toast.classList.remove('show'); setTimeout(function(){ toast.remove(); }, 300); }, 3000);
                            }

                            function closeModal(){
                                modal.classList.remove('open');
                                rewriteMode = false;
                                rewriteText = '';
                                resetModal(false);
                            }

                            function toggleInsert(){
                                insertBtn.disabled = !outputReady || outputBox.textContent.trim() === '';
                            }
                            toggleInsert();

                            if(aiButton){
                                aiButton.addEventListener('click', function(e){
                                    e.preventDefault();
                                    if(aiButton.classList.contains('disabled')){ return; }
                                    newslettersInitAiTooltip();
                                    rewriteMode = false;
                                    rewriteText = '';
                                    if(promptBox){
                                        promptBox.placeholder = defaultPromptPlaceholder;
                                        promptBox.value = lastAiPrompt;
                                    }
                                    resetModal(false);
                                    openModal();
                                    toggleInsert();
                                });
                            }

                            if(rewriteButton){
                                rewriteButton.addEventListener('click', function(e){
                                    e.preventDefault();
                                    if(rewriteButton.classList.contains('disabled')){ return; }
                                    var builderBtn = document.getElementById('usebuilder');
                                    var builderActive = builderBtn && builderBtn.classList.contains('builderon');
                                    newslettersInitAiTooltip();
                                    if(builderActive){
                                        var selectedGjsText = newslettersGjsSelection ? newslettersGjsSelection.toString() : '';
                                        if(selectedGjsText.trim() === ''){
                                            showToast('<?php echo esc_js(__('No text is selected.', 'wp-mailinglist')); ?>');
                                            return;
                                        }
                                        rewriteMode = true;
                                        rewriteText = selectedGjsText;
                                        resetModal();
                                        if(promptBox){
                                            promptBox.value = '<?php echo esc_js(__('Rewrite the selected text', 'wp-mailinglist')); ?>';
                                            promptBox.placeholder = '<?php echo esc_js(__('Rewrite the selected text', 'wp-mailinglist')); ?>';
                                        }
                                        openModal();
                                        toggleInsert();
                                        return;
                                    }
                                    var selectedText = '';
                                    savedSelection = null;
                                    savedTextareaSelection = null;
                                    if(typeof tinymce !== 'undefined' && tinymce.get('content')){
                                        var editor = tinymce.get('content');
                                        selectedText = editor.selection.getContent({format:'text'});
                                        if(selectedText.trim()){
                                            savedSelection = editor.selection.getBookmark(2);
                                        }
                                    } else {
                                        var textarea = document.getElementById('content');
                                        if(textarea){
                                            var start = textarea.selectionStart;
                                            var end = textarea.selectionEnd;
                                            selectedText = textarea.value.substring(start, end);
                                            if(selectedText.trim()){
                                                savedTextareaSelection = {start:start, end:end};
                                            }
                                        }
                                    }
                                    if(selectedText.trim() === ''){
                                        showToast('<?php echo esc_js(__('No text is selected.', 'wp-mailinglist')); ?>');
                                        return;
                                    }
                                    rewriteMode = true;
                                    rewriteText = selectedText;
                                    resetModal();
                                    if(promptBox){
                                        promptBox.value = '<?php echo esc_js(__('Rewrite the selected text', 'wp-mailinglist')); ?>';
                                        promptBox.placeholder = '<?php echo esc_js(__('Rewrite the selected text', 'wp-mailinglist')); ?>';
                                    }
                                    openModal();
                                    toggleInsert();
                                });
                            }

                            function setChatgptModelMessage(message){
                                if(!chatgptModelMessage){ return; }
                                if(message){
                                    chatgptModelMessage.textContent = message;
                                    chatgptModelMessage.style.display = 'block';
                                } else {
                                    chatgptModelMessage.textContent = '';
                                    chatgptModelMessage.style.display = 'none';
                                }
                            }

                            function loadChatgptModels(){
                                if(!hasChatgptApiKey || !chatgptModelSelect || chatgptModelsLoaded || chatgptModelsLoading){
                                    return;
                                }
                                chatgptModelsLoading = true;
                                chatgptModelSelect.disabled = true;
                                chatgptModelSelect.style.display = 'block';
                                chatgptModelSelect.innerHTML = '';
                                var loadingOption = document.createElement('option');
                                loadingOption.value = '';
                                loadingOption.textContent = '<?php echo esc_js(__('Loading models…', 'wp-mailinglist')); ?>';
                                chatgptModelSelect.appendChild(loadingOption);
                                setChatgptModelMessage('');
                                fetch(newsletters_ajaxurl + 'action=newsletters_chatgpt_models', {
                                    method:'POST',
                                    headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
                                    body:''
                                }).then(function(response){
                                    chatgptModelsLoading = false;
                                    chatgptModelSelect.disabled = false;
                                    return response.json();
                                }).then(function(data){
                                    if(data && data.success && Array.isArray(data.models) && data.models.length){
                                        chatgptModelSelect.innerHTML = '';
                                        data.models.forEach(function(modelId, index){
                                            var option = document.createElement('option');
                                            option.value = modelId;
                                            option.textContent = modelId;
                                            if(index === 0){
                                                option.selected = true;
                                            }
                                            chatgptModelSelect.appendChild(option);
                                        });
                                        chatgptModelsLoaded = true;
                                        setChatgptModelMessage('');
                                    } else {
                                        chatgptModelSelect.innerHTML = '';
                                        chatgptModelSelect.style.display = 'none';
                                        var message = (data && data.message) ? data.message : '<?php echo esc_js(__('No ChatGPT models are available. Please verify your API key.', 'wp-mailinglist')); ?>';
                                        setChatgptModelMessage(message);
                                        showToast(message);
                                    }
                                }).catch(function(){
                                    chatgptModelsLoading = false;
                                    if(chatgptModelSelect){
                                        chatgptModelSelect.disabled = false;
                                        chatgptModelSelect.innerHTML = '';
                                        chatgptModelSelect.style.display = 'none';
                                    }
                                    var errorMessage = '<?php echo esc_js(__('Unable to load ChatGPT models. Please check your API key and try again.', 'wp-mailinglist')); ?>';
                                    setChatgptModelMessage(errorMessage);
                                    showToast(errorMessage);
                                });
                            }

                            function toggleChatgptModels(){
                                if(!chatgptModelWrapper){ return; }
                                var current = jQuery(modelSelect).val();
                                var isChatgpt = current && current.indexOf('chatgpt') === 0;
                                if(isChatgpt){
                                    chatgptModelWrapper.style.display = 'flex';
                                    if(hasChatgptApiKey && chatgptModelSelect){
                                        chatgptModelSelect.style.display = 'block';
                                        setChatgptModelMessage('');
                                        loadChatgptModels();
                                    } else {
                                        setChatgptModelMessage('<?php echo esc_js(__('Please add a ChatGPT API key in the settings.', 'wp-mailinglist')); ?>');
                                        showToast('<?php echo esc_js(__('Please add a ChatGPT API key in the settings.', 'wp-mailinglist')); ?>');
                                    }
                                } else {
                                    chatgptModelWrapper.style.display = 'none';
                                    if(chatgptModelSelect){
                                        chatgptModelSelect.style.display = 'block';
                                    }
                                    setChatgptModelMessage('');
                                }
                            }
                            if(modelSelect){
                                jQuery(modelSelect).on('change', toggleChatgptModels);
                                toggleChatgptModels();
                            }

                            if(generateBtn){
                                generateBtn.addEventListener('click', function(){
                                    var prompt = promptBox.value;
                                    var model = jQuery(modelSelect).val();
                                    if(outputBox){
                                        outputBox.innerText = '<?php echo esc_js(__('Generating...', 'wp-mailinglist')); ?>';
                                    }
                                    outputReady = false;

                                    var includeContext = contextCheckbox && contextCheckbox.checked;
                                    var editorText = '';
                                    if(includeContext){
                                        if(typeof tinymce !== 'undefined' && tinymce.get('content')){
                                            editorText = tinymce.get('content').getContent({format:'text'});
                                        } else {
                                            var textarea = document.getElementById('content');
                                            if(textarea){
                                                editorText = textarea.value;
                                            }
                                        }
                                    }
                                    var body = 'model=' + encodeURIComponent(model) + '&prompt=' + encodeURIComponent(prompt);
                                    if(model && model.indexOf('chatgpt') === 0){
                                        if(!hasChatgptApiKey){
                                            outputBox.innerText = '';
                                            outputReady = false;
                                            toggleInsert();
                                            showToast('<?php echo esc_js(__('Please add a ChatGPT API key in the settings.', 'wp-mailinglist')); ?>');
                                            return;
                                        }
                                        if(chatgptModelsLoading){
                                            showToast('<?php echo esc_js(__('ChatGPT models are still loading. Please wait.', 'wp-mailinglist')); ?>');
                                            outputReady = false;
                                            toggleInsert();
                                            return;
                                        }
                                        if(chatgptModelSelect && chatgptModelSelect.value){
                                            body += '&chatgpt_model=' + encodeURIComponent(chatgptModelSelect.value);
                                        } else {
                                            setChatgptModelMessage('<?php echo esc_js(__('Select a ChatGPT model to continue.', 'wp-mailinglist')); ?>');
                                            outputBox.innerText = '';
                                            outputReady = false;
                                            toggleInsert();
                                            return;
                                        }
                                    }
                                    if(includeContext){
                                        body += '&editor=' + encodeURIComponent(editorText);
                                    }
                                    if(rewriteMode){
                                        body += '&rewrite=1&selected=' + encodeURIComponent(rewriteText);
                                    }

                                    fetch(newsletters_ajaxurl + 'action=newsletters_ai_generate', {
                                        method:'POST',
                                        headers:{'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'},
                                        body: body
                                    }).then(function(r){ return r.json(); }).then(function(data){
                                        if(data.text){
                                            outputBox.innerHTML = data.text;
                                            outputReady = true;
                                        } else if(data.message){
                                            outputBox.innerText = data.message;
                                            outputReady = false;
                                        } else {
                                            outputBox.innerText = '';
                                            outputReady = false;
                                        }
                                        toggleInsert();
                                    }).catch(function(){
                                        outputBox.innerText = '<?php echo esc_js(__('Error generating content.', 'wp-mailinglist')); ?>';
                                        outputReady = false;
                                        toggleInsert();
                                    });
                                });
                            }

                            if(insertBtn){
                                insertBtn.addEventListener('click', function(){
                                    var text = outputBox.innerHTML;
                                    var builderBtn = document.getElementById('usebuilder');
                                    var builderActive = builderBtn && builderBtn.classList.contains('builderon');
                                    if(builderActive && newslettersGjsRte){
                                        newslettersRestoreGjsSelection();
                                        var iframe = document.querySelector('#gjs iframe');
                                        if(iframe && iframe.contentWindow){ iframe.contentWindow.focus(); }
                                        newslettersGjsRte.insertHTML(text);
                                    } else if(rewriteMode){
                                        if(typeof tinymce !== 'undefined' && tinymce.get('content')){
                                            var editor = tinymce.get('content');
                                            editor.focus();
                                            if(savedSelection){ editor.selection.moveToBookmark(savedSelection); }
                                            editor.execCommand('mceReplaceContent', false, text);
                                        } else {
                                            var textarea = document.getElementById('content');
                                            if(textarea){
                                                if(savedTextareaSelection){
                                                    var before = textarea.value.substring(0, savedTextareaSelection.start);
                                                    var after = textarea.value.substring(savedTextareaSelection.end);
                                                    textarea.value = before + outputBox.textContent + after;
                                                } else {
                                                    textarea.value += (textarea.value ? '\n' : '') + outputBox.textContent;
                                                }
                                            }
                                        }
                                    } else {
                                        if(typeof tinymce !== 'undefined' && tinymce.get('content')){
                                            tinymce.get('content').execCommand('mceInsertContent', false, text);
                                        } else {
                                            var textarea = document.getElementById('content');
                                            if(textarea){
                                                textarea.value += (textarea.value ? '\n' : '') + outputBox.textContent;
                                            }
                                        }
                                    }
                                    outputBox.innerHTML = "";
                                    outputReady = false;
                                    closeModal();
                                });
                            }

                            if(closeBtn){
                                closeBtn.addEventListener('click', function(e){
                                    e.preventDefault();
                                    closeModal();
                                });
                            }

                            modal.addEventListener('click', function(e){
                                if(e.target === modal){
                                    closeModal();
                                }
                            });
                        });
                        </script>
                        <script type="text/javascript">
                        window.newslettersSetGjsSelection = function(range){
                            newslettersGjsSelection = range;
                        };
                        window.newslettersRestoreGjsSelection = function(){
                            if(newslettersGjsSelection){
                                var iframe = document.querySelector('#gjs iframe');
                                if(iframe && iframe.contentWindow){
                                    var sel = iframe.contentWindow.getSelection();
                                    sel.removeAllRanges();
                                    sel.addRange(newslettersGjsSelection);
                                }
                            }
                        };
                        </script>
                        <?php endif; ?>

                        <?php

                        $setup = "";
                        ob_start();

                        echo "function (ed) {
                            
                            ed.on('change', function(e) {
                                jQuery('#previewiframe').contents().find('html div.newsletters_content').html(ed.getContent());
                            });
                            
                            ed.on('keyup', function(e) {
                                var content = ed.getContent();
                                var div = document.createElement('div');
                                div.innerHTML = content;
                                var preheader = div.textContent || div.innerText || '';
                                preheader = preheader.substr(0,100);
                                jQuery('.newsletters-preview-preheader').text(preheader);
                            });
                        
                            //ed.onKeyDown.add(function (ed, evt) {
                            ed.on('keydown', function(e) {
                                //var content = jQuery('iframe#content_ifr').contents().find('body#tinymce').html();
                                var content = ed.getContent();
                                jQuery('#previewiframe').contents().find('html div.newsletters_content').html(content);
                                
                                var val = jQuery.trim(content),  
                                words = val.replace(/\s+/gi, ' ').split(' ').length,
                                chars = val.length;
                                if(!chars)words=0;
                                
                                jQuery('#word-count').html(words + ' " . __('words and', 'wp-mailinglist') . " ' + chars + ' " . __('characters', 'wp-mailinglist') . "');
                            });
                        }";

                        $setup = ob_get_clean();

                        ?>

                        <?php if (version_compare(get_bloginfo('version'), "3.3") >= 0) : ?>
                            <?php

                            add_action( 'media_buttons',
                            array( $this, 'render_newsletters_media_button' ),
                            20,          // after “Add Media”
                            1 );         // 1 = we want $editor_id
                            wp_enqueue_script(
                                'newsletters-media-button',                                   // handle
                                $this->url() . '/js/newsletters-media-button.js',             // file
                                array( 'jquery', 'editor' ),                                  // deps
                                defined( 'NEWSLETTERS_VERSION' ) ? NEWSLETTERS_VERSION : null,
                                true                                                          // load in footer
                            );

                            wp_editor(
                                isset($_POST['content']) ? $_POST['content'] : '',
                                'content',
                                array(
                                    'drag_drop_upload'    => true,
                                    'tabfocus_elements'   => 'content-html,save-post',
                                    'editor_height'       => 300,
                                    'tinymce'             => array(
                                        'setup'                     =>  $setup,
                                    ),
                                    'tabindex' => "2",
                                )
                            ); ?>
                        <?php else : ?>
                            <?php 
                                
                                add_action( 'media_buttons',
                                array( $this, 'render_newsletters_media_button' ),
                                20,          // after “Add Media”
                                1 );         // 1 = we want $editor_id
                                wp_enqueue_script(
                                    'newsletters-media-button',                                   // handle
                                    $this->url() . '/js/newsletters-media-button.js',             // file
                                    array( 'jquery', 'editor' ),                                  // deps
                                    defined( 'NEWSLETTERS_VERSION' ) ? NEWSLETTERS_VERSION : null,
                                    true                                                          // load in footer
                                );
                                the_editor($_POST['content'], 'content', 'title', true, 2); ?>
                        <?php endif; ?>

                        <table id="post-status-info" cellpadding="0" cellspacing="0">
                            <tbody>
                            <tr>
                                <td id="wp-word-count">
                                    <?php _e('Word Count:', 'wp-mailinglist'); ?>
                                    <span id="word-count">0</span>
                                </td>
                                <td class="autosave-info">
                                        <span id="autosave" style="display:none;">

                                        </span>
                                </td>
                            </tr>
                            </tbody>
                        </table>

                        <?php if (!empty($errors['content'])) : ?>
                            <div class="ui-state-error ui-corner-all">
                                <p><i class="fa-solid fa-triangle-exclamation"></i> <?php echo $errors['content']; ?></p>
                            </div>
                        <?php endif; ?>

                        <p>
                            <button value="1" type="button" class="button button-secondary" id="addcontentarea_button" onclick="addcontentarea(); return false;">
                                <i class="fa-solid fa-circle-plus fa-fw"></i> <?php _e('Add Content Area', 'wp-mailinglist'); ?>
                                <span id="contentarea_loading" style="display:none;"><i class="fa-solid fa-arrows-rotate fa-spin fa-fw"></i></span>
                            </button>
                        </p>
                        <div id="contentareas">
                            <!-- Content Areas Go Here -->
                        </div>
                    </div>
                </div>
                <div id="postbox-container-1" class="postbox-container">
                    <?php do_action('submitpage_box'); ?>
                    <?php do_meta_boxes($page, 'side', $post); ?>
                </div>
                <div id="postbox-container-2" class="postbox-container">
                    <?php do_meta_boxes($page, 'normal', $post); ?>
                    <?php do_meta_boxes($page, 'advanced', $post); ?>
                </div>
            </div>
        </div>
    </form>
</div>

<script type="text/javascript">

    <?php $history_id = (empty($_POST['ishistory'])) ? esc_html(isset($_GET['id']) ? $_GET['id'] : 0) : esc_html($_POST['ishistory']); ?>

    <?php if (!empty($history_id)) : ?>
    var history_id = "<?php echo $history_id; ?>";
    <?php else : ?>
    var history_id = false;
    <?php endif; ?>

    var warnMessage = "<?php echo addslashes(__('You have unsaved changes on this page! All unsaved changes will be lost and it cannot be undone.', 'wp-mailinglist')); ?>";

    function deletecontentarea(number, history_id) {
        if (history_id != "") {
            var data = {number:number, history_id:history_id};
            jQuery.post(newsletters_ajaxurl + 'action=newsletters_deletecontentarea&security=<?php echo wp_create_nonce('deletecontentarea'); ?>', data, function(response) {
                //all good, the request was successful

            });
        } else {
            tinyMCE.execCommand("mceRemoveEditor", false, 'contentarea' + number);
            contentarea--;
        }

        jQuery('#contentareabox' + number).remove();
    }

    function addcontentarea() {
        jQuery('#addcontentarea_button').prop('disabled', true);
        jQuery('#contentarea_loading').show();
        jQuery.post(newsletters_ajaxurl + 'action=newsletters_load_new_editor', {contentarea:contentarea}, function(response) {
            jQuery('#contentareas').append(response);
            jQuery('#addcontentarea_button').prop('disabled', false);

            if (typeof(tinyMCE) == "object" && typeof(tinyMCE.execCommand) == "function") {
                jQuery('#contentarea_loading').hide();
                quicktags({id:'contentarea' + contentarea});
                tinyMCE.execCommand("mceAddEditor", false, 'contentarea' + contentarea);
                wpml_scroll('#contentareabox' + contentarea);
                contentarea++;
            }
        });
    }

    var newsletters_autosave_request = false;

    function newsletters_autosave() {
        if (newsletters_autosave_request) {
            newsletters_autosave_request.abort();
        }

        var content = newsletters_tinymce_content('content');

        if (typeof(tinyMCE) == "object" && typeof(tinyMCE.execCommand) == "function") {
            tinyMCE.triggerSave();
        }

        var formvalues = jQuery('form#post');
       // formvalues['using_grapeJS'] = false;

        <?php if($builderon) { ?>

            // ‼ In newsletters_autosave(), replace the whole PHP-wrapped block
            if ($('#usebuilder').hasClass('builderon')) {
                formvalues['using_grapeJS'] = true;
                formvalues['grapejs_content'] = gjsEditor.Commands.run('gjs-get-inlined-html');
                formvalues['post_id']        = <?php echo $post_ID; ?>;
            } else {
                // make 100 % sure we do NOT accidentally send old builder markup
                formvalues['using_grapeJS']  = false;
                formvalues['grapejs_content']= '';
            }


         //   if (jQuery('#usebuilder').hasClass('builderon'))
         //   {
         //       formvalues['using_grapeJS'] = true;
         //       formvalues['grapejs_content'] = gjsEditor.Commands.run('gjs-get-inlined-html');
         //       formvalues['post_id'] = <?php echo $post_ID ; ?>;
         //   }

        <?php
        }
        ?>

        formvalues = formvalues.serialize();
        newsletters_autosave_running();

        newsletters_autosave_request = jQuery.ajax({
            cache: false,
            data: formvalues,
            dataType: "json",
            url: newsletters_ajaxurl + 'action=newsletters_autosave&security=<?php echo wp_create_nonce('newsletters_autosave'); ?>',
            type: "POST",
            success: function(response) {
                jQuery('#newwindowbutton').removeAttr('disabled').attr('href', response.parts.preview.url);
                jQuery('#ishistory').val(response.history_id);
                jQuery('#p_id').val(response.post_id);
                jQuery('#edit-slug-box').show();
                jQuery('#sample-permalink').html(response.parts.preview.url);
                jQuery('#view-post-btn a').attr('href', response.parts.preview.url);
                jQuery('#shortlink').attr('value', response.parts.preview.url).val(response.parts.preview.url);

                if (typeof window.history.pushState === 'function') {
                    var currentUrl = new URL(window.location.href);
                    currentUrl.searchParams.set('method', 'history');
                    currentUrl.searchParams.set('id', response.history_id);
                    window.history.pushState({}, '', currentUrl);
                }

                // Update the HTML preview
                if (typeof response.parts.preview.html !== 'undefined') { jQuery('#previewiframe').contents().find('html').html(response.parts.preview.html); }
                var iframeheight = jQuery("#previewiframe").contents().find("html").outerHeight();
                jQuery("#previewiframe").height(iframeheight).css({height: iframeheight}).attr("height", iframeheight);

                // Update the TEXT preview
                if (typeof response.parts.preview.text !== 'undefined') { jQuery('#textiframe').contents().find('html').html(response.parts.preview.text); }
                var iframeheight = jQuery("#textiframe").contents().find("html").outerHeight();
                jQuery("#textiframe").height(iframeheight).css({height: iframeheight}).attr("height", iframeheight);

                var date = new Date();
                var year = date.getFullYear();
                var month = ("0" + (date.getMonth() + 1)).slice(-2);
                var day = ("0" + date.getDate()).slice(-2);
                var hours = ("0" + date.getHours()).slice(-2);
                var minutes = ("0" + date.getMinutes()).slice(-2);
                var today = year + '-' + month + '-' + day + ' ' + hours + ':' + minutes;
                var autosavedate = year + '-' + ('0' + (month + 1)).slice(-2) + '-' + day + ' ' + hours + ':' + minutes;
                jQuery('#autosave').html('<?php _e('Draft saved at', 'wp-mailinglist'); ?> ' + autosavedate).show();

                newsletters_autosave_done();
            }
        }).error(function(response) {
            newsletters_autosave_done();
        });

        <?php if($builderon) { ?>
       // newsletters_drag_and_drop_content_save();
        <?php
        }
        ?>


        return true;
    }

    jQuery(document).ready(function(){
        jQuery('body').on('click' , '#save_grapejs_content' , function(e) {
            newsletters_drag_and_drop_content_save();
        });
    });
    function newsletters_drag_and_drop_content_save() {
        newsletters_autosave();
        let formvalues = {};
        formvalues['grapejs_content'] = gjsEditor.Commands.run('gjs-get-inlined-html');
        formvalues['post_id'] = <?php echo $post_ID ; ?>;
        newsletters_autosave_running();

        newsletters_autosave_request = jQuery.ajax({
            cache: false,
            data: formvalues,
            dataType: "json",
            url: newsletters_ajaxurl + 'action=newsletter_drag_and_drop_builder_save&security=<?php echo wp_create_nonce('newsletters_autosave'); ?>',
            type: "POST",
            success: function (response) {
               // alert('success');

            }
        }).error(function (response) {
            newsletters_autosave_done();
        });

        return true;
    }

    function newsletters_autosave_running() {
        jQuery('#sendbutton, #sendbutton2').prop('disabled', true);
        jQuery('iframe#content_ifr').attr('tabindex', "2");
        jQuery('#previewrunnerbutton').attr('disabled', "disabled");
        jQuery('#previewrunnerloading').show();
    }

    function newsletters_autosave_done() {
        jQuery('#sendbutton, #sendbutton2').prop('disabled', false);
        //jQuery('#savedraftbutton, #savedraftbutton2').prop('disabled', false);

        jQuery('#previewrunnerbutton').removeAttr('disabled');
        jQuery('#previewrunnerloading').hide();

        warnMessage = null;
    }

    jQuery(document).ready(function() {

        newsletters_focus('#title');

        jQuery('#title').on('keyup', function(e) {
            jQuery('.newsletters-preview-subject').html(jQuery(this).val());
        });

        jQuery('#fromname').on('change', function(e) {
            jQuery('.newsletters-preview-fromname').html(jQuery(this).val());
        });

        _wpMediaViewsL10n.insertIntoPost = "<?php _e('Insert into Newsletter', 'wp-mailinglist'); ?>";
        _wpMediaViewsL10n.uploadedToThisPost = "<?php _e('Uploaded to this Newsletter', 'wp-mailinglist'); ?>";

        jQuery('iframe#content_ifr').attr('tabindex', "2");

        jQuery('input:not(:button,:submit),textarea,select').change(function() {
            window.onbeforeunload = function () {
                if (warnMessage != null) return warnMessage;
            }
        });

        if (history_id != false) {
            setTimeout(function() {
                newsletters_autosave();
            }, <?php echo ($autosave_interval * 1000); ?>);
        }

        <?php if (empty($disable_autosave)) : ?>
            setTimeout(function() {
                var newsletters_autosave_interval = setInterval(newsletters_autosave, <?php echo ($autosave_interval * 1000); ?>);
            }, <?php echo ($autosave_interval * 1000); ?>);
        <?php endif; ?>

        jQuery(':submit').click(function(e) {
            warnMessage = null;
        });
    });
</script>