$(document).ready(function() {

    function addTabSupport(selector) {
        $(selector).summernote({
            lang: 'ru-RU',
            placeholder: '',
            height: 280,
            dialogsInBody: true,
            toolbar: [
                ['style', ['style']],
                ['font', ['bold', 'italic', 'underline', 'clear']],
                ['fontname', ['fontname']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['table', ['table']],
                ['insert', ['link', 'picture', 'video']],
                ['view', ['fullscreen', 'codeview']]
            ],
            callbacks: {
                onImageUpload: function(files) {
                    var editor = $(this);
                    var formData = new FormData();
                    formData.append('image', files[0]);

                    $.ajax({
                        url: '/engine/mods/summernote_image.php&folder=' + $('#folder').val() + '&p_id=' + $('#p_id').val(),
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function(imageUrl) {
                            editor.summernote('insertImage', imageUrl);
                        },
                        error: function(xhr, status, error) {
                            console.error(xhr.responseText);
                        }
                    });
                },
                onKeydown: function(e) {
                    if (e.key === "Tab") {
                        e.preventDefault();
                        var selection = window.getSelection();
                        if (!selection.rangeCount) return;

                        var range = selection.getRangeAt(0);
                        var startNode = range.startContainer;
                        var startOffset = range.startOffset;

                        // Shift+Tab = remove 4 spaces if present before cursor
                        if (e.shiftKey) {
                            if (startNode.nodeType === 3) { // Text node
                                var text = startNode.textContent;
                                var beforeCursor = text.slice(0, startOffset);
                                if (beforeCursor.endsWith("    ")) {
                                    startNode.textContent = text.slice(0, startOffset - 4) + text.slice(startOffset);
                                    range.setStart(startNode, startOffset - 4);
                                    range.setEnd(startNode, startOffset - 4);
                                    selection.removeAllRanges();
                                    selection.addRange(range);
                                }
                            }
                        } else {
                            // Tab = insert 4 spaces
                            var tabNode = document.createTextNode("    ");
                            range.insertNode(tabNode);
                            range.setStartAfter(tabNode);
                            range.setEndAfter(tabNode);
                            selection.removeAllRanges();
                            selection.addRange(range);
                        }
                    }

                    // Backspace works normally
                }
            }
        });
    }

    addTabSupport('#short_desc');
    addTabSupport('#full_desc');

    $(document).on('drop dragover', function(e) {
        e.preventDefault();
    });
});
