/**
 * WP Bootstrap Studio — Editor
 * Handles CodeMirror initialization and editor enhancements
 */
(function($) {
    'use strict';
    
    // Initialize CodeMirror on the code editor textarea when toggled
    let codeMirrorInstance = null;
    
    $(document).on('click', '#wpbs-toggle-code', function() {
        const $wrapper = $('#wpbs-code-editor-wrapper');
        
        if ($wrapper.is(':visible') && !codeMirrorInstance) {
            // Initialize CodeMirror
            if (typeof wp !== 'undefined' && wp.codeEditor) {
                const settings = wp.codeEditor.defaultSettings ? 
                    _.clone(wp.codeEditor.defaultSettings) : {};
                settings.codemirror = $.extend({}, settings.codemirror, {
                    mode: 'htmlmixed',
                    lineNumbers: true,
                    lineWrapping: true,
                    indentUnit: 2,
                    tabSize: 2,
                });
                
                const editor = wp.codeEditor.initialize($('#wpbs-code-editor'), settings);
                codeMirrorInstance = editor.codemirror;
                
                // Sync changes back to textarea
                codeMirrorInstance.on('change', function() {
                    codeMirrorInstance.save();
                });
            }
        }
    });
    
})(jQuery);
