(function() {
    'use strict';

    // --- КОНФИГУРАЦИЯ ---
    var SCRIPT_NAME = 'SidebarWidgets';
    var BTN_CLASS = SCRIPT_NAME + '-btn';
    var PANEL_CLASS = SCRIPT_NAME + '-panel';
    var TARGET_COLUMNS = ['Полезная информация [Remake]', 'колонка 2'];
    var SESSION_KEY = SCRIPT_NAME + '_pendingWidget';
    var LAYOUT_NAME = 'Оформление Remake';
    var DATA_FILE_NAME = 'widgets-data';

    // --- КАТАЛОГ ВИДЖЕТОВ ---
    var WIDGETS = [];

    // --- ДОПРОДАЖИ ---
    var UPSELLS = [
        {
            label: 'Календарь',
            icon: 'fa fa-calendar-check-o',
            url: 'https://remake.space/calendar'
        },
        {
            label: 'Прогресс-бар',
            icon: 'fa fa-tasks',
            url: 'https://remake.space/shop/tproduct/661011665-499397848812-progress-bar'
        },
        {
            label: 'Избранные уроки',
            icon: 'fa fa-bookmark',
            url: 'https://remake.space/shop/tproduct/661011665-419288270592-izbrannie-uroki'
        },
        {
            label: 'Рейтинг участников',
            icon: 'fa fa-trophy',
            url: 'https://remake.space/shop/tproduct/661011665-842662157792-reiting-uchenikov'
        },
        {
            label: 'Допродажа курсов',
            icon: 'fa fa-shopping-cart',
            url: 'https://remake.space/shop/tproduct/661011665-999418985822-doprodazha-kursov'
        },
    ];

    // --- УТИЛИТЫ ---

    function isEditMode() {
        return window.location.search.indexOf('editMode=1') !== -1;
    }

    function getEditModeUrl() {
        var url = window.location.href;
        if (url.indexOf('editMode=1') !== -1) return url;
        var sep = url.indexOf('?') !== -1 ? '&' : '?';
        return url + sep + 'editMode=1';
    }

    function generateXdgetId() {
        return 'r' + Math.random().toString(36).slice(2, 6);
    }

    function sleep(ms) {
        return new Promise(function(resolve) { setTimeout(resolve, ms); });
    }

    // --- УДАЛЁННОЕ ХРАНИЛИЩЕ ВИДЖЕТОВ (GetCourse theme file) ---

    var _cachedLayoutId = null;
    var _cachedFileKey = null;

    async function findLayoutId() {
        if (_cachedLayoutId) return _cachedLayoutId;
        var resp = await fetch('/pl/cms/layout/index');
        var html = await resp.text();
        var $link = $(html).find('table.kv-grid-table td a').filter(function() {
            return $(this).text().trim() === LAYOUT_NAME;
        });
        if (!$link.length) return null;
        var url = $link.attr('href');
        _cachedLayoutId = url.split('id=')[1];
        return _cachedLayoutId;
    }

    async function findFileKey(layoutId) {
        if (_cachedFileKey) return _cachedFileKey;
        var resp = await fetch('/pl/cms/layout/update?id=' + layoutId);
        var html = await resp.text();
        var $rows = $(html).find('.layout-add-content-files__row');
        var fileKey = null;
        $rows.each(function() {
            var name = $(this).find('.layout-add-content-files__filename a').text().trim();
            if (name === DATA_FILE_NAME) {
                fileKey = $(this).find('input[name="fileIndex[]"]').val();
                return false;
            }
        });
        _cachedFileKey = fileKey;
        return _cachedFileKey;
    }

    async function findLayoutAndFile() {
        var layoutId = await findLayoutId();
        if (!layoutId) {
            console.error(SCRIPT_NAME + ': layout "' + LAYOUT_NAME + '" не найден');
            return null;
        }
        var fileKey = await findFileKey(layoutId);
        if (!fileKey) {
            console.error(SCRIPT_NAME + ': файл "' + DATA_FILE_NAME + '" не найден в layout');
            return null;
        }
        return { layoutId: layoutId, fileKey: fileKey };
    }

    async function loadRemoteWidgets() {
        try {
            var info = await findLayoutAndFile();
            if (!info) return [];
            var resp = await fetch('/pl/cms/layout/edit-layout-file?id=' + info.layoutId + '&fileKey=' + info.fileKey);
            var html = await resp.text();
            var $page = $(html);
            var content = $page.find('textarea').first().val() || '[]';
            return JSON.parse(content);
        } catch (e) {
            console.error(SCRIPT_NAME + ': ошибка загрузки виджетов', e);
            return [];
        }
    }

    async function saveRemoteWidgets(widgets) {
        var info = await findLayoutAndFile();
        if (!info) {
            alert('Не удалось найти файл данных виджетов.');
            return false;
        }
        var resp = await fetch('/pl/cms/layout/edit-layout-file?id=' + info.layoutId + '&fileKey=' + info.fileKey);
        var html = await resp.text();
        var $page = $(html);
        var $form = $page.find('form').first();
        var action = $form.attr('action') || ('/pl/cms/layout/edit-layout-file?id=' + info.layoutId + '&fileKey=' + info.fileKey);

        var params = new URLSearchParams();
        $form.find('input[type="hidden"]').each(function() {
            params.append($(this).attr('name'), $(this).val());
        });
        params.append('content', JSON.stringify(widgets, null, 2));

        await fetch(action, {
            method: 'POST',
            headers: { 'content-type': 'application/x-www-form-urlencoded' },
            body: params.toString()
        });
        return true;
    }

    async function addCustomWidget(name, jsonStr) {
        var block;
        try {
            block = JSON.parse(jsonStr);
        } catch (e) {
            alert('Невалидный JSON. Проверьте формат.');
            return false;
        }
        if (!block.type) {
            alert('JSON должен содержать поле "type".');
            return false;
        }
        var customs = await loadRemoteWidgets();
        customs.push({
            label: name || block.type,
            icon: 'fa fa-cube',
            description: block.type,
            block: block
        });
        return await saveRemoteWidgets(customs);
    }

    async function removeCustomWidget(index) {
        var customs = await loadRemoteWidgets();
        customs.splice(index, 1);
        await saveRemoteWidgets(customs);
    }

    // --- СТИЛИ ---

    function injectStyles() {
        if (document.getElementById(SCRIPT_NAME + '-styles')) return;

        var css = [
            '@keyframes sw-panel-in {',
            '  from { opacity: 0; transform: translateY(10px) scale(0.97); }',
            '  to { opacity: 1; transform: translateY(0) scale(1); }',
            '}',
            '@keyframes sw-panel-out {',
            '  from { opacity: 1; transform: translateY(0) scale(1); }',
            '  to { opacity: 0; transform: translateY(10px) scale(0.97); }',
            '}',
            '',
            '.' + BTN_CLASS + ' {',
            '  position: fixed; bottom: 124px; right: 20px; z-index: 100000;',
            '  width: 54px; height: 54px; border-radius: 16px; border: none;',
            '  background: #fff; color: #1a1a2e;',
            '  font-size: 20px; cursor: pointer;',
            '  box-shadow: 0 1px 3px rgba(0,0,0,0.08), 0 8px 24px rgba(0,0,0,0.1);',
            '  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);',
            '  display: flex; align-items: center; justify-content: center;',
            '}',
            '.' + BTN_CLASS + ':hover {',
            '  transform: translateY(-2px);',
            '  box-shadow: 0 2px 6px rgba(0,0,0,0.08), 0 12px 32px rgba(0,0,0,0.14);',
            '}',
            '.' + BTN_CLASS + '.sw-active {',
            '  background: #f0f0f5; border-radius: 16px 16px 4px 16px;',
            '}',
            '',
            '.' + PANEL_CLASS + ' {',
            '  position: fixed; bottom: 188px; right: 20px; z-index: 100001;',
            '  width: 300px; max-height: 520px; overflow-y: auto;',
            '  background: #fff;',
            '  border: 1px solid rgba(0,0,0,0.06);',
            '  border-radius: 18px;',
            '  box-shadow: 0 1px 3px rgba(0,0,0,0.04), 0 16px 48px rgba(0,0,0,0.12);',
            '  animation: sw-panel-in 0.22s cubic-bezier(0.16, 1, 0.3, 1) forwards;',
            '  transform-origin: bottom right;',
            '  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;',
            '}',
            '.' + PANEL_CLASS + '.sw-closing {',
            '  animation: sw-panel-out 0.15s cubic-bezier(0.4, 0, 1, 1) forwards;',
            '}',
            '',
            '.sw-section-label {',
            '  font-size: 11px; font-weight: 600; letter-spacing: 0.06em;',
            '  text-transform: uppercase; color: #a0a0b0; margin: 0;',
            '  padding: 16px 18px 8px;',
            '}',
            '.sw-divider {',
            '  height: 1px; background: #f0f0f4; margin: 4px 0;',
            '}',
            '.sw-panel-list { padding: 4px 8px 8px; }',
            '',
            '.sw-item {',
            '  display: flex; align-items: center; gap: 12px;',
            '  padding: 8px 10px; margin: 1px 0; border-radius: 10px;',
            '  cursor: pointer; transition: all 0.15s ease;',
            '  text-decoration: none !important; color: inherit;',
            '}',
            '.sw-item:hover {',
            '  background: #f5f5fa;',
            '}',
            '.sw-item:active {',
            '  transform: scale(0.98);',
            '  background: #ededf4;',
            '}',
            '.sw-item-icon {',
            '  width: 34px; height: 34px; border-radius: 8px;',
            '  background: #f5f5fa;',
            '  display: flex; align-items: center; justify-content: center;',
            '  font-size: 16px; color: #8888a0; flex-shrink: 0;',
            '  transition: all 0.15s ease;',
            '}',
            '.sw-item:hover .sw-item-icon {',
            '  background: #e8e8f4; color: #5c6bc0;',
            '}',
            '.sw-item-text { min-width: 0; }',
            '.sw-item-label {',
            '  font-size: 14px; font-weight: 500; color: #1a1a2e !important;',
            '  white-space: nowrap; overflow: hidden; text-overflow: ellipsis;',
            '  text-decoration: none !important;',
            '}',
            '.sw-item-desc {',
            '  font-size: 12px; color: #a0a0b0; margin-top: 2px;',
            '  white-space: nowrap; overflow: hidden; text-overflow: ellipsis;',
            '}',
            '',
            '.sw-upsell-icon {',
            '  width: 28px; height: 28px; border-radius: 7px; font-size: 13px;',
            '  background: linear-gradient(135deg, #fff8ef, #fff3e0) !important;',
            '  color: #e6a23c !important;',
            '}',
            '.sw-upsell { padding: 6px 10px; gap: 10px; }',
            '.sw-upsell .sw-item-label { font-size: 13px; }',
            '.sw-item:hover .sw-upsell-icon {',
            '  background: linear-gradient(135deg, #fff3e0, #ffe8c8) !important;',
            '  color: #d48806 !important;',
            '}',
            '.sw-upsell-arrow {',
            '  margin-left: auto; font-size: 13px; color: #c8c8d4;',
            '  transition: all 0.15s ease; flex-shrink: 0;',
            '}',
            '.sw-item:hover .sw-upsell-arrow { color: #e6a23c; transform: translateX(2px); }',
            '',
            '.sw-section-header {',
            '  display: flex; align-items: center; justify-content: space-between;',
            '  padding-right: 14px;',
            '}',
            '.sw-section-header .sw-section-label { flex: 1; }',
            '.sw-add-btn {',
            '  width: 26px; height: 26px; border-radius: 8px; border: 1px solid #e8e8f0;',
            '  background: #fafafa; color: #8888a0; font-size: 12px; cursor: pointer;',
            '  display: flex; align-items: center; justify-content: center;',
            '  transition: all 0.15s ease;',
            '}',
            '.sw-add-btn:hover { background: #f0f0f8; color: #5c6bc0; border-color: #d0d0e0; }',
            '',
            '.sw-add-form {',
            '  padding: 8px 14px 12px; border-bottom: 1px solid #f0f0f4;',
            '}',
            '.sw-add-name, .sw-add-json {',
            '  width: 100%; box-sizing: border-box; border: 1px solid #e0e0ea;',
            '  border-radius: 8px; padding: 8px 10px; font-size: 13px;',
            '  font-family: inherit; resize: vertical; outline: none;',
            '  transition: border-color 0.15s ease;',
            '}',
            '.sw-add-name:focus, .sw-add-json:focus { border-color: #5c6bc0; }',
            '.sw-add-name { margin-bottom: 8px; }',
            '.sw-add-json { min-height: 70px; font-family: monospace; font-size: 12px; }',
            '.sw-add-actions { display: flex; gap: 8px; margin-top: 8px; }',
            '.sw-add-save, .sw-add-cancel {',
            '  flex: 1; padding: 6px 0; border-radius: 8px; border: none;',
            '  font-size: 13px; font-weight: 500; cursor: pointer;',
            '  transition: all 0.15s ease;',
            '}',
            '.sw-add-save {',
            '  background: #5c6bc0; color: #fff;',
            '}',
            '.sw-add-save:hover { background: #4a5ab0; }',
            '.sw-add-cancel {',
            '  background: #f0f0f5; color: #666;',
            '}',
            '.sw-add-cancel:hover { background: #e4e4ee; }',
            '',
            '.sw-delete-btn {',
            '  background: none; border: none; color: #c8c8d4; cursor: pointer;',
            '  padding: 4px 6px; border-radius: 6px; font-size: 13px;',
            '  margin-left: auto; flex-shrink: 0;',
            '  transition: all 0.15s ease;',
            '}',
            '.sw-delete-btn:hover { color: #e55; background: #fff0f0; }',
        ].join('\n');

        var style = document.createElement('style');
        style.id = SCRIPT_NAME + '-styles';
        style.textContent = css;
        document.head.appendChild(style);
    }

    // --- ПЛАВАЮЩАЯ КНОПКА ---

    var panelOpen = false;

    function renderFloatingButton() {
        if ($('.' + BTN_CLASS).length) return;

        var $btn = $('<button class="' + BTN_CLASS + '" title="Каталог виджетов">' +
            '<i class="fa fa-puzzle-piece"></i>' +
            '</button>');

        $btn.on('click', function(e) {
            e.preventDefault();
            e.stopPropagation();
            if (panelOpen) {
                closePanel();
            } else {
                openPanel();
            }
        });

        $('body').append($btn);
    }

    // --- ПАНЕЛЬ-ПОПОВЕР ---

    async function openPanel() {
        if ($('.' + PANEL_CLASS).length) return;
        panelOpen = true;
        $('.' + BTN_CLASS).addClass('sw-active');

        var customWidgets = await loadRemoteWidgets();
        var allWidgets = WIDGETS.concat(customWidgets);

        var html = '<div class="' + PANEL_CLASS + '">';

        // Секция: виджеты
        html += '<div class="sw-section-header">' +
            '<p class="sw-section-label">Ваши виджеты</p>' +
            '<button class="sw-add-btn" title="Добавить виджет"><i class="fa fa-plus"></i></button>' +
            '</div>';

        // Форма добавления (скрыта по умолчанию)
        html += '<div class="sw-add-form" style="display:none;">' +
            '<input class="sw-add-name" type="text" placeholder="Название виджета" />' +
            '<textarea class="sw-add-json" placeholder="Вставьте JSON экспорта виджета..." rows="4">' + '</' + 'textarea>' +
            '<div class="sw-add-actions">' +
            '<button class="sw-add-save">Добавить</button>' +
            '<button class="sw-add-cancel">Отмена</button>' +
            '</div></div>';

        html += '<div class="sw-panel-list">';
        for (var i = 0; i < allWidgets.length; i++) {
            var w = allWidgets[i];
            var isCustom = i >= WIDGETS.length;
            html += '<div class="sw-item" data-index="' + i + '">' +
                '<div class="sw-item-icon"><i class="' + w.icon + '"></i></div>' +
                '<div class="sw-item-text">' +
                '<div class="sw-item-label">' + w.label + '</div>' +
                '<div class="sw-item-desc">' + (w.description || w.block.type) + '</div>' +
                '</div>';
            if (isCustom) {
                html += '<button class="sw-delete-btn" data-custom-index="' + (i - WIDGETS.length) + '" title="Удалить">' +
                    '<i class="fa fa-trash-o"></i></button>';
            }
            html += '</div>';
        }
        html += '</div>';

        // Разделитель + секция: допродажи
        html += '<div class="sw-divider"></div>' +
            '<p class="sw-section-label">Ещё вы можете купить</p>' +
            '<div class="sw-panel-list">';
        for (var j = 0; j < UPSELLS.length; j++) {
            var u = UPSELLS[j];
            html += '<a class="sw-item sw-upsell" href="' + u.url + '" target="_blank">' +
                '<div class="sw-item-icon sw-upsell-icon"><i class="' + u.icon + '"></i></div>' +
                '<div class="sw-item-text">' +
                '<div class="sw-item-label">' + u.label + '</div>' +
                '</div>' +
                '<span class="sw-upsell-arrow"><i class="fa fa-chevron-right"></i></span>' +
                '</a>';
        }
        html += '</div>';

        html += '</div>';

        var $panel = $(html);
        $('body').append($panel);

        // Клик по виджету — импорт
        $panel.find('.sw-item[data-index]').on('click', function(e) {
            if ($(e.target).closest('.sw-delete-btn').length) return;
            var index = parseInt($(this).attr('data-index'), 10);
            closePanel();
            onWidgetSelected(allWidgets[index]);
        });

        // Удаление кастомного виджета
        $panel.find('.sw-delete-btn').on('click', async function(e) {
            e.stopPropagation();
            var ci = parseInt($(this).attr('data-custom-index'), 10);
            var $btn = $(this);
            $btn.find('i').removeClass('fa-trash-o').addClass('fa-spinner fa-spin');
            await removeCustomWidget(ci);
            closePanel();
            setTimeout(openPanel, 200);
        });

        // Кнопка «+» — показать/скрыть форму
        $panel.find('.sw-add-btn').on('click', function(e) {
            e.stopPropagation();
            $panel.find('.sw-add-form').slideToggle(150);
        });

        // Сохранение нового виджета
        $panel.find('.sw-add-save').on('click', async function(e) {
            e.stopPropagation();
            var name = $panel.find('.sw-add-name').val().trim();
            var json = $panel.find('.sw-add-json').val().trim();
            if (!json) { alert('Вставьте JSON виджета.'); return; }
            var $btn = $(this);
            $btn.text('Сохраняю...').prop('disabled', true);
            var ok = await addCustomWidget(name, json);
            if (ok) {
                closePanel();
                setTimeout(openPanel, 200);
            } else {
                $btn.text('Добавить').prop('disabled', false);
            }
        });

        // Отмена
        $panel.find('.sw-add-cancel').on('click', function(e) {
            e.stopPropagation();
            $panel.find('.sw-add-form').slideUp(150);
        });

        // Закрытие по клику вне
        setTimeout(function() {
            $(document).on('click.sw-panel', function(e) {
                if (!$(e.target).closest('.' + PANEL_CLASS + ', .' + BTN_CLASS).length) {
                    closePanel();
                }
            });
        }, 10);
    }

    function closePanel() {
        var $panel = $('.' + PANEL_CLASS);
        if (!$panel.length) { panelOpen = false; return; }

        $panel.addClass('sw-closing');
        $('.' + BTN_CLASS).removeClass('sw-active');
        $(document).off('click.sw-panel');

        setTimeout(function() {
            $panel.remove();
            panelOpen = false;
        }, 150);
    }

    // --- ОБРАБОТКА ВЫБОРА ВИДЖЕТА ---

    function onWidgetSelected(widget) {
        if (!isEditMode()) {
            var blockCopy = JSON.parse(JSON.stringify(widget.block));
            blockCopy.xdgetId = generateXdgetId();
            sessionStorage.setItem(SESSION_KEY, JSON.stringify(blockCopy));
            window.location.href = getEditModeUrl();
            return;
        }

        importWidget(widget.block);
    }

    // --- ИМПОРТ ВИДЖЕТА В КОЛОНКУ ---

    async function importWidget(block) {
        var blockData = JSON.parse(JSON.stringify(block));
        blockData.xdgetId = generateXdgetId();
        var json = JSON.stringify(blockData);

        // 1. Выбрать целевую колонку в <select> (приоритет: Полезная информация [Remake] → колонка 2)
        var $select = $('.global-xdget-editor .element-panel select');
        var $target = null;
        var targetName = '';
        for (var t = 0; t < TARGET_COLUMNS.length; t++) {
            var name = TARGET_COLUMNS[t];
            var $opt = $select.find('option').filter(function() {
                return $(this).text().trim() === name;
            });
            if ($opt.length) {
                $target = $opt;
                targetName = name;
                break;
            }
        }

        if (!$target) {
            alert('Не найдена ни одна из целевых колонок: ' + TARGET_COLUMNS.join(', '));
            return;
        }

        $target.prop('selected', true);
        $select.trigger('change');
        await sleep(300);

        // 2. Открыть дропдаун → клик "Импортировать блок"
        var $dropdownToggle = $('.element-panel .btn-toolbar .btn-group .dropdown-toggle');
        if (!$dropdownToggle.length) {
            alert('Не найдена кнопка дропдауна.');
            return;
        }
        $dropdownToggle.trigger('click');
        await sleep(200);

        var $importLink = $('.element-panel .dropdown-menu a').filter(function() {
            return $(this).text().trim().indexOf('Импортировать') !== -1;
        });

        if (!$importLink.length) {
            alert('Не найдена ссылка "Импортировать блок".');
            return;
        }
        $importLink.trigger('click');
        await sleep(500);

        // 3. Вставить JSON в textarea модального окна
        var $modal = $('.modal.in, .modal.show').last();
        var $textarea = $modal.find('textarea');

        if (!$textarea.length) {
            alert('Не найдена textarea в модальном окне импорта.');
            return;
        }
        $textarea.val(json);
        await sleep(100);

        // 4. Нажать "Импортировать"
        var $importBtn = $modal.find('.btn-import');
        if (!$importBtn.length) {
            alert('Не найдена кнопка "Импортировать".');
            return;
        }
        $importBtn.trigger('click');
        await sleep(500);

        // 5. Сохранить страницу
        var $saveBtn = $('.global-xdget-editor .root-element-panel .btn-save');
        if (!$saveBtn.length) {
            $saveBtn = $('.global-xdget-editor .btn-save').first();
        }

        if ($saveBtn.length) {
            $saveBtn.trigger('click');
        } else {
            alert('Виджет импортирован, но кнопка "Сохранить" не найдена. Сохраните вручную.');
            return;
        }

        await sleep(1000);

        // 6. Выйти из editMode — убираем параметр из URL
        var cleanUrl = window.location.href.replace(/[?&]editMode=1/, '').replace(/\?$/, '');
        window.location.href = cleanUrl;
    }

    // --- АВТОИМПОРТ ПОСЛЕ РЕДИРЕКТА ---

    function checkPendingImport() {
        if (!isEditMode()) return;

        var pending = sessionStorage.getItem(SESSION_KEY);
        if (!pending) return;

        sessionStorage.removeItem(SESSION_KEY);

        try {
            var block = JSON.parse(pending);
            setTimeout(function() {
                importWidget(block);
            }, 2000);
        } catch (e) {
            console.error(SCRIPT_NAME + ': ошибка парсинга pending widget', e);
        }
    }

    // --- ИНИЦИАЛИЗАЦИЯ ---

    $(function() {
        if (!window.userInfo || !window.userInfo.isAdmin) return;
        injectStyles();
        renderFloatingButton();
        checkPendingImport();
    });

})();
