document.addEventListener('DOMContentLoaded', function() {
    tinymce.init({
        license_key: 'gpl',
        remove_script_host: false,
        relative_urls: false,  
        entity_encoding: 'raw',
        valid_elements: '*[*]',
        content_css: false,
        force_br_newlines: true,
        entities: '160,nbsp',
        remove_linebreaks: false,
        selector: '.secondary-content',
        encoding: 'UTF-8',
        plugins: 'image link media code table lists',
        toolbar: 'undo redo | styleselect | bold italic | bullist numlist | alignleft aligncenter alignright alignjustify | outdent indent | link image media table | code',
        menubar: 'file edit view insert format tools table help',
        contextmenu: 'table',
        images_upload_url: '/editor/uploads/',
        automatic_uploads: true,
        file_picker_types: 'image',
        images_reuse_filename: true,
        paste_as_text: true,
        setup: function (editor) {
            editor.on('GetContent', function (e) {
                e.content = e.content.replace(/<img([^>]*?)>/g, function(match, attrs) {
                    if (!attrs.includes('loading=')) {
                        return match.replace('>', ' loading="lazy">');
                    }
                    return match;
                });
            });
        },
        table_default_attributes: {
            border: '1',
        },
        table_default_styles: {
            width: '100%',
            borderCollapse: 'collapse',
        },
        file_picker_callback: function(callback, value, meta) {
            if (meta.filetype === 'image') {
                const input = document.createElement('input');
                input.setAttribute('type', 'file');
                input.setAttribute('accept', 'image/*');
                input.onchange = function() {
                    const file = this.files[0];
                    const formData = new FormData();
                    formData.append('file', file);
    
                    fetch('/editor/uploads/', {
                        method: 'POST',
                        body: formData
                    })
                    .then(response => response.json())
                    .then(result => {
                        callback(result.location);
                    })
                    .catch(() => alert('Ошибка при загрузке изображения.'));
                };
                input.click();
            }
        },
        content_style: `
        body { font-family: Arial, sans-serif; font-size: 14px; }
        table { border-collapse: collapse; width: 100%; }
        th, td { border: 1px solid #ddd; padding: 8px; }
        th { background-color: #f2f2f2; text-align: left; }
    `
    });
});

// Color picker functionality
document.addEventListener('DOMContentLoaded', function () {
    const colorPickers = document.querySelectorAll('.inp-color');
    const textInputs = document.querySelectorAll('.inp-color-text');

    colorPickers.forEach(colorPicker => {
        colorPicker.addEventListener('input', function () {
            const textInput = this.nextElementSibling;
            if (textInput && textInput.classList.contains('inp-color-text')) {
                textInput.value = this.value;
            }
        });
    });

    textInputs.forEach(textInput => {
        textInput.addEventListener('input', function () {
            const colorPicker = this.previousElementSibling;
            if (colorPicker && colorPicker.classList.contains('inp-color')) {
                if (/^#([0-9A-F]{3}|[0-9A-F]{6})$/i.test(this.value)) {
                    colorPicker.value = this.value;
                }
            }
        });

        const colorPicker = textInput.previousElementSibling;
        if (colorPicker && colorPicker.classList.contains('inp-color')) {
            if (/^#([0-9A-F]{3}|[0-9A-F]{6})$/i.test(textInput.value)) {
                colorPicker.value = textInput.value;
            }
        }
    });
});

// Casino repeater functionality
function addCasinoItem() {
    const container = document.getElementById('casinoRepeater');
    const tpl = document.getElementById('casinoTemplate').content.cloneNode(true);
    container.appendChild(tpl);
}

function uploadImage(input, wrapper) {
    const file = input.files[0];
    const formData = new FormData();
    formData.append('image', file);

    fetch('upload_repeater_image.php', {
            method: 'POST',
            body: formData
        })
        .then(resp => resp.json())
        .then(data => {
            if (data.success) {
                wrapper.querySelector('.image').value = data.path;
            } else {
                alert('Ошибка загрузки изображения: ' + data.message);
            }
        });
}

function saveRepeater() {
    const items = [];
    document.querySelectorAll('#casinoRepeater .casino-item').forEach((item, index) => {
        items.push({
            id: item.dataset.id || null,
            sort_order: index,
            image: item.querySelector('.image').value,
            alt: item.querySelector('.alt').value,
            title: item.querySelector('.title').value,
            heading: item.querySelector('.heading').value,
            text: item.querySelector('.text').value,
            button: item.querySelector('.button').value,
            keitaro: item.querySelector('.keitaro').value,
        });
    });
    document.getElementById('casinoRepeaterData').value = JSON.stringify(items);
    return true;
}

// Drag and Drop functionality for casino items
document.addEventListener('DOMContentLoaded', function() {
    const container = document.getElementById('casinoRepeater');
    if (!container) return;

    let draggedElement = null;
    let placeholder = null;

    function updateOrderNumbers() {
        const items = container.querySelectorAll('.casino-item');
        items.forEach((item, index) => {
            const numberElement = item.querySelector('.casino-order-number');
            if (numberElement) {
                numberElement.textContent = index + 1;
            }
        });
    }

    function createPlaceholder() {
        const div = document.createElement('div');
        div.className = 'drag-placeholder';
        div.style.cssText = 'height: 60px; margin: 10px 0; border: 2px dashed #007bff; background: #f0f8ff; opacity: 0.5;';
        return div;
    }

    function initAccordion() {
        const items = container.querySelectorAll('.casino-item');

        items.forEach(item => {
            const header = item.querySelector('.casino-item-header');
            const toggleBtn = item.querySelector('.toggle-accordion');
            const content = item.querySelector('.casino-item-content');
            const dragHandle = item.querySelector('.drag-handle');

            if (!header || !toggleBtn || !content) return;

            const toggleAccordion = (e) => {
                if (e.target.closest('.drag-handle')) {
                    return;
                }

                const isOpen = content.style.display !== 'none' && content.style.display !== '';

                if (isOpen) {
                    content.style.display = 'none';
                    toggleBtn.textContent = '▼';
                } else {
                    content.style.display = 'flex';
                    toggleBtn.textContent = '▲';
                }
            };

            header.addEventListener('click', toggleAccordion);

            header.addEventListener('mousedown', (e) => {
                if (!e.target.closest('.drag-handle')) {
                    item.setAttribute('draggable', 'false');
                }
            });

            header.addEventListener('mouseup', () => {
                item.setAttribute('draggable', 'true');
            });

            dragHandle.addEventListener('mousedown', (e) => {
                e.stopPropagation();
                item.setAttribute('draggable', 'true');
            });

            const headingInput = item.querySelector('.heading');
            if (headingInput) {
                headingInput.addEventListener('input', function() {
                    const titleElement = item.querySelector('.casino-item-title');
                    if (titleElement) {
                        titleElement.textContent = this.value || 'New Casino Item';
                    }
                });
            }
        });
    }

    function initDragAndDrop() {
        const items = container.querySelectorAll('.casino-item');

        items.forEach(item => {
            item.setAttribute('draggable', 'true');

            const dragHandle = item.querySelector('.drag-handle');

            dragHandle.addEventListener('mousedown', function(e) {
                item.setAttribute('draggable', 'true');
            });

            item.addEventListener('dragstart', function(e) {
                if (!e.target.querySelector('.drag-handle')) {
                    e.preventDefault();
                    return;
                }

                draggedElement = this;
                this.classList.add('dragging');
                e.dataTransfer.effectAllowed = 'move';
                e.dataTransfer.setData('text/html', '');

                setTimeout(() => {
                    this.style.display = 'none';
                }, 0);
            });

            item.addEventListener('dragend', function(e) {
                this.style.display = '';
                this.classList.remove('dragging');

                if (placeholder && placeholder.parentNode) {
                    placeholder.parentNode.removeChild(placeholder);
                }
                placeholder = null;
                draggedElement = null;

                updateOrderNumbers();
            });
        });
    }

    container.addEventListener('dragover', function(e) {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';

        if (!draggedElement) return;

        const afterElement = getDragAfterElement(container, e.clientY);
        const currentItems = [...container.querySelectorAll('.casino-item:not(.dragging)')];

        if (!placeholder) {
            placeholder = createPlaceholder();
        }

        if (afterElement == null) {
            container.appendChild(placeholder);
        } else {
            container.insertBefore(placeholder, afterElement);
        }
    });

    container.addEventListener('drop', function(e) {
        e.preventDefault();

        if (!draggedElement || !placeholder) return;

        if (placeholder.parentNode) {
            placeholder.parentNode.insertBefore(draggedElement, placeholder);
            placeholder.parentNode.removeChild(placeholder);
        }

        draggedElement.style.display = '';
        placeholder = null;
    });

    function getDragAfterElement(container, y) {
        const draggableElements = [...container.querySelectorAll('.casino-item:not(.dragging)')];

        return draggableElements.reduce((closest, child) => {
            const box = child.getBoundingClientRect();
            const offset = y - box.top - box.height / 2;

            if (offset < 0 && offset > closest.offset) {
                return { offset: offset, element: child };
            } else {
                return closest;
            }
        }, { offset: Number.NEGATIVE_INFINITY }).element;
    }

    initAccordion();
    initDragAndDrop();
    updateOrderNumbers();

    container.addEventListener('itemRemoved', function() {
        updateOrderNumbers();
    });

    window.originalAddCasinoItem = window.addCasinoItem;
    window.addCasinoItem = function() {
        if (window.originalAddCasinoItem) {
            window.originalAddCasinoItem();
        } else {
            const container = document.getElementById('casinoRepeater');
            const tpl = document.getElementById('casinoTemplate').content.cloneNode(true);
            container.appendChild(tpl);
        }
        setTimeout(() => {
            initAccordion();
            initDragAndDrop();
            updateOrderNumbers();
        }, 10);
    };
});