$(document).ready(function() {

    var section = document.getElementById('toolsSection');
    section.classList.add('active');
    var block = document.getElementById('tools');
    block.classList.add('show');
    var currentLink = document.getElementById('locationsControl');
    currentLink.classList.add('active');
    let selectedLang;

    let locationCounter = 1;

    $('#add-root-btn').click(function() {
        const locationName = $.trim($('#root-location-input').val() || '');
        if (locationName) {
            addLocation(null, locationName);
            selectedLang = $.trim($('#language-select').val() || '');
            saveLocations();

            $('#root-location-input').val('');
            $('.empty-state').remove();
        } else {
            showAlert('Пожалуйста, введите название локации', 'danger');
        }
    });

    function showAlert(message, type) {
        const tpl = document.getElementById('alert-template');
        const el = tpl.content.cloneNode(true).children[0];

        el.classList.add(`alert-${type}`);
        el.querySelector('.alert-message').textContent = message;
        document.querySelector('.locations-block').prepend(el);

        setTimeout(() => {
            $(el).alert('close');
        }, 3000);
    }


    function createLocationElement({id, name, slug, type, level}) {
        const tpl = document.getElementById('location-template');
        const el = tpl.content.cloneNode(true).children[0];

        el.dataset.id = id;
        el.dataset.name = name;
        el.dataset.level = level ?? 0;
        el.dataset.type = type ?? "";
        el.dataset.slug = slug ?? "";

        el.querySelector('.location-name').textContent =
            slug ? `${name} | ${slug}` : name;

        initLocationHandlers($(el));

        return el;
    }


    function addLocation(parentElement, name, type, slug) {
        const locationId = `loc-${locationCounter++}`;
        const level = parentElement
            ? (parseInt(parentElement.closest('.location-item').attr('data-level') || 0) + 1)
            : 0;

        const locEl = createLocationElement({
            id: locationId,
            name,
            slug,
            type,
            level
        });

        if (parentElement) {
            parentElement.find('.location-container').first().append(locEl);
        } else {
            $('#locations-container').append(locEl);
        }
    }

    function initLocationHandlers(locationElement) {
        locationElement.find('.add-btn').click(function() {
            const parentElement = $(this).closest('.location-item');
            $('#addLocationModal').data('parentElement', parentElement);

            $('#modal-location-name').val('');
            $('#modal-location-type').val('');
            $('#modal-location-slug').val('');

            const modal = new bootstrap.Modal(document.getElementById('addLocationModal'));
            modal.show();
        });

        locationElement.find('.add-lang').click(function() {
            const parentElement = $(this).closest('.location-item');
            $('#addLangModal').data('parentElement', parentElement);

            $('#modal-lang-name').val('');

            const modal = new bootstrap.Modal(document.getElementById('addLangModal'));
            modal.show();
        });


        locationElement.find('.remove-btn').click(function() {
            const locEl = $(this).closest('.location-item');
            const locId = locEl.attr('data-id');

            if (confirm('Удалить эту локацию и все дочерние элементы?')) {
                $.ajax({
                    url: '/engine/ajax/lib/locationsControl/deleteLocation.php',
                    method: 'POST',
                    dataType: 'json',
                    data: { id: locId },
                    success: function(data) {
                        if (data.status === 'success') {
                            locEl.remove();
                            if ($('#locations-container').children().length === 0) {
                                showEmptyState();
                            }
                        } else {
                            showAlert('Ошибка при удалении локации: ' + data.message, 'danger');
                        }
                    },
                    error: function() {
                        showAlert('Ошибка при удалении локации на сервере', 'danger');
                    }
                });
            }
        });


        locationElement.find('.toggle-btn').click(function() {
            $(this).closest('.location-item').toggleClass('collapsed');
        });
    }

    function showEmptyState() {
        const tpl = document.getElementById('empty-state-template');
        const el = tpl.content.cloneNode(true).children[0];
        $('#locations-container').html(el);
    }

    $('#modal-add-btn').click(function() {
        const name = $('#modal-location-name').val().trim();
        const type = $('#modal-location-type').val().trim();
        const slug = $('#modal-location-slug').val().trim();

        if (!name || !type) {
            alert('Заполните все поля!');
            return;
        }

        const parentElement = $('#addLocationModal').data('parentElement');
        addLocation(parentElement, name, type, slug);
        selectedLang = $.trim($('#language-select').val() || '');

        saveLocations();

        const modalEl = document.getElementById('addLocationModal');
        const modal = bootstrap.Modal.getInstance(modalEl);
        modal.hide();
    });

    $('#modal-lang-add-btn').click(function() {
        const name = $('#modal-lang-name').val().trim();
        const lang = $('#modal-lang-language-select').val().trim();

        const parentElement = $('#addLangModal').data('parentElement');
        const id = parseInt(parentElement.closest('.location-item').attr('data-id'));
        if (!name || !lang) {
            alert('Заполните все поля!');
            return;
        }

        $.ajax({
            url: '/engine/ajax/lib/locationsControl/saveLocationLang.php',
            method: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify({
                "lang": lang,
                "name": name,
                "id": id
            }),
            success: function(data) {
                loadLocationsFromDB();
                showAlert('Данные успешно сохранены', 'success');
            },
            error: function(xhr, status, error) {
                console.error(xhr.responseText);
                showAlert('Ошибка при сохранении данных', 'danger');
            }
        });

        const modalEl = document.getElementById('addLangModal');
        const modal = bootstrap.Modal.getInstance(modalEl);
        modal.hide();
    });

    function saveLocations() {
        const locationsTree = buildLocationData($('#locations-container'));
        if (locationsTree.length === 0) {
            showAlert('Нет данных для экспорта. Добавьте хотя бы одну локацию.', 'warning');
            return;
        }

        const flatLocations = flattenLocations(locationsTree);

        $.ajax({
            url: '/engine/ajax/lib/locationsControl/saveLocations.php',
            method: 'POST',
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(flatLocations),
            success: function(data) {
                const mapNewIds = data.mapNewIds;
                $('.location-item').each(function() {
                    const el = $(this);
                    const id = el.data('id');
                    if (mapNewIds[id]) {
                        el.attr('data-id', mapNewIds[id]);
                    }
                });
                showAlert('Данные успешно сохранены', 'success');
            },
            error: function(xhr, status, error) {
                console.error(xhr.responseText);
                showAlert('Ошибка при сохранении данных', 'danger');
            }
        });
    }


    function flattenLocations(locations, result = []) {
        locations.forEach(loc => {
            const { children, ...locData } = loc;
            result.push(locData);
            if (children && children.length > 0) {
                flattenLocations(children, result);
            }
        });
        return result;
    }

    function buildLocationData(container, parentId = null) {
        const locations = [];

        container.children('.location-item').each(function() {
            const locationElement = $(this);
            const locationId = locationElement.attr('data-id');
            const type = locationElement.attr('data-type');
            const slug = locationElement.attr('data-slug');
            const name = locationElement.attr('data-name');
            const lang = locationElement.attr('data-lang');

            const location = {
                id: locationId,
                name: name,
                level: parseInt(locationElement.attr('data-level')),
                parent_id: parentId,
                slug: slug,
                type: type,
                lang: selectedLang

            };

            const childrenContainer = locationElement.find('.location-container').first();
            if (childrenContainer.children().length > 0) {
                location.children = buildLocationData(childrenContainer, locationId);
            }

            locations.push(location);
        });

        return locations;
    }

    $('#expand-all-btn').click(function() {
        $('.location-item').removeClass('collapsed');
    });

    $('#collapse-all-btn').click(function() {
        $('.location-item').addClass('collapsed');
    });

    loadLocationsFromDB();
    function loadLocationsFromDB() {
         $.ajax({
             url: '/engine/ajax/lib/locationsControl/getLocations.php',
             method: 'GET',
             dataType: 'json',
             success: function(data) {
                 $('#locations-container').empty();
                 const tree = buildTree(data.locations);
                 renderTree(tree, $('#locations-container'));

                 $('.location-item').addClass('collapsed');

             },
             error: function() {
                 showAlert('Ошибка при загрузке данных из БД', 'danger');
             }
         });


    }

    function buildTree(data) {
        const map = {};
        const roots = [];

        data.forEach(item => {
            item.children = [];
            map[item.id] = item;
        });

        data.forEach(item => {
            if (item.parent_id) {
                if (item.parent_id && map[item.parent_id]) {
                    map[item.parent_id].children.push(item);
                }
            } else {
                roots.push(item);
            }
        });

        return roots;
    }

    function renderTree(tree, container) {
        tree.forEach(item => {
            const locEl = createLocationElement({
                id: item.id,
                name: item.name,
                slug: item.slug,
                type: item.type,
                level: item.level || 0,
            });

            container.append(locEl);

            if (item.children && item.children.length > 0) {
                renderTree(item.children, $(locEl).find('.location-container').first());
            }
        });
    }


});