(function($) {
    'use strict';
    window.WTC = window.WTC || {};
    WTC.AdminContracts = {
        init: function() {
            this.initializeEditors();
            this.bindEvents();
        },
        initializeEditors: function() {
            if (typeof tinymce !== 'undefined') {
                tinymce.on('AddEditor', function(e) {
                    var editor = e.editor;
                    editor.on('change', function() {
                        editor.save(); 
                    });
                });
            }
        },
        bindEvents: function() {
            $('.template-variables .button').on('click', function() {
                const variable = $(this).data('variable');
                let activeEditorId;
                if (tinymce.activeEditor) {
                    activeEditorId = tinymce.activeEditor.id;
                } else {
                    activeEditorId = $('.wp-editor-area:visible').first().attr('id');
                }
                if (activeEditorId) {
                    WTC.AdminContracts.insertVariable(activeEditorId, variable);
                }
            });
            $(document).on('click', '.wp-switch-editor', function() {
                const editorId = $(this).closest('.wp-editor-wrap').find('.wp-editor-area').attr('id');
                if (editorId && tinymce.get(editorId)) {
                    tinymce.get(editorId).focus();
                }
            });
        },
        insertVariable: function(editorId, variable) {
            if (typeof tinymce !== 'undefined' && tinymce.get(editorId)) {
                const editor = tinymce.get(editorId);
                editor.focus();
                editor.insertContent(variable);
                editor.save();
            } else {
                const $textarea = $('#' + editorId);
                const currentPos = $textarea.prop('selectionStart');
                const text = $textarea.val() || '';
                const before = text.substring(0, currentPos);
                const after = text.substring(currentPos, text.length);
                $textarea.val(before + variable + after);
                $textarea.trigger('change');
            }
        }
    };
    $(document).ready(function() {
        WTC.AdminContracts.init();
    });
})(jQuery); 