TEST SCRIPT

Скрипт для КА ЕКБ

Fra og med 29.05.2026. Se den nyeste version.

You will need to install an extension such as Tampermonkey, Greasemonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install an extension such as Tampermonkey or Violentmonkey to install this script.

You will need to install an extension such as Tampermonkey or Userscripts to install this script.

You will need to install an extension such as Tampermonkey to install this script.

You will need to install a user script manager extension to install this script.

(I already have a user script manager, let me install it!)

Advertisement:

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(I already have a user style manager, let me install it!)

Advertisement:

// ==UserScript==
// @name         TEST SCRIPT
// @namespace    http://tampermonkey.net/
// @version      3
// @description  Скрипт для КА ЕКБ
// @author       Flora
// @match        https://forum.ragerussia.online/*
// @include      https://forum.ragerussia.online/
// @icon         https://www.google.com/s2/favicons?sz=64&domain=ragerussia.online
// @grant        none
// @license      none
// ==/UserScript==

(async function () {
    `use strict`;
    const UNACCEPT_PREFIX = 3;
    const ACCEPT_PREFIX = 2;
    const CLOSED_PREFIX = 4;
    const PIN_PREFIX = 10;

    const STORAGE_KEY = 'forum_script_custom_templates';
    const SCRIPTSETTINGS_KEY = 'forum_script_settings';
    const QUICKREPLY_KEY = 'forum_script_quick_replies';
    const STATS_KEY = 'forum_script_stats';

    // Загрузка настроек скрипта
    function loadSettings() {
        const saved = localStorage.getItem(SCRIPTSETTINGS_KEY);
        if (saved) {
            try {
                return JSON.parse(saved);
            } catch(e) {
                return { topBarEnabled: true, theme: 'dark', quickActions: true, autoReload: false, quickRepliesEnabled: true, showStats: true, autoSaveDrafts: true };
            }
        }
        return { topBarEnabled: true, theme: 'dark', quickActions: true, autoReload: false, quickRepliesEnabled: true, showStats: true, autoSaveDrafts: true };
    }

    function saveSettings(settings) {
        localStorage.setItem(SCRIPTSETTINGS_KEY, JSON.stringify(settings));
    }

    function loadCustomTemplates() {
        const saved = localStorage.getItem(STORAGE_KEY);
        if (saved) {
            try {
                return JSON.parse(saved);
            } catch(e) {
                return [];
            }
        }
        return [];
    }

    function saveCustomTemplates(templates) {
        localStorage.setItem(STORAGE_KEY, JSON.stringify(templates));
    }

    // Загрузка быстрых ответов
    function loadQuickReplies() {
        const saved = localStorage.getItem(QUICKREPLY_KEY);
        if (saved) {
            try {
                return JSON.parse(saved);
            } catch(e) {
                return [];
            }
        }
        return [];
    }

    function saveQuickReplies(replies) {
        localStorage.setItem(QUICKREPLY_KEY, JSON.stringify(replies));
    }

    // Статистика использования
    function updateStats(templateName) {
        const stats = loadStats();
        const today = new Date().toDateString();

        if (!stats[today]) {
            stats[today] = { total: 0, templates: {} };
        }

        stats[today].total++;
        stats[today].templates[templateName] = (stats[today].templates[templateName] || 0) + 1;

        // Очищаем статистику старше 30 дней
        const dates = Object.keys(stats);
        const cutoff = new Date();
        cutoff.setDate(cutoff.getDate() - 30);

        dates.forEach(date => {
            if (new Date(date) < cutoff) {
                delete stats[date];
            }
        });

        saveStats(stats);
    }

    function loadStats() {
        const saved = localStorage.getItem(STATS_KEY);
        if (saved) {
            try {
                return JSON.parse(saved);
            } catch(e) {
                return {};
            }
        }
        return {};
    }

    function saveStats(stats) {
        localStorage.setItem(STATS_KEY, JSON.stringify(stats));
    }

    // Сохранение черновика
    function saveDraft(content) {
        const threadId = window.location.pathname.split('/').pop();
        localStorage.setItem(`draft_${threadId}`, content);
        showNotification('💾 Черновик сохранён', 'success');
    }

    function loadDraft() {
        const threadId = window.location.pathname.split('/').pop();
        return localStorage.getItem(`draft_${threadId}`);
    }

    function clearDraft() {
        const threadId = window.location.pathname.split('/').pop();
        localStorage.removeItem(`draft_${threadId}`);
    }

    // Показ уведомлений
    function showNotification(message, type = 'info') {
        const colors = {
            success: '#2ecc71',
            error: '#e74c3c',
            info: '#3498db',
            warning: '#f39c12'
        };

        const notification = $(`
            <div style="position:fixed;bottom:80px;right:20px;background:${colors[type]};color:white;padding:10px 16px;border-radius:8px;z-index:10002;font-size:13px;box-shadow:0 4px 12px rgba(0,0,0,0.3);animation:slideIn 0.3s ease;">
                ${message}
            </div>
        `);

        $('body').append(notification);
        setTimeout(() => {
            notification.fadeOut(300, () => notification.remove());
        }, 2000);
    }

    // Копирование текста с уведомлением
    function copyToClipboard(text, successMessage = '✅ Скопировано!') {
        navigator.clipboard.writeText(text);
        showNotification(successMessage, 'success');
    }

    function addCustomTemplate(title, content, prefix = 3, close = false, category = 'complaints') {
        const templates = loadCustomTemplates();
        templates.push({
            title: title,
            content: content,
            prefix: prefix,
            status: false,
            close: close,
            category: category,
            isCustom: true,
            createdAt: Date.now()
        });
        saveCustomTemplates(templates);
        return templates;
    }

    function deleteCustomTemplate(index) {
        const templates = loadCustomTemplates();
        templates.splice(index, 1);
        saveCustomTemplates(templates);
        return templates;
    }

    function updateCustomTemplate(index, title, content, prefix, close, category) {
        const templates = loadCustomTemplates();
        if (templates[index]) {
            templates[index] = {
                ...templates[index],
                title: title,
                content: content,
                prefix: prefix,
                close: close,
                category: category
            };
            saveCustomTemplates(templates);
        }
        return templates;
    }

    const data = await getThreadData();
    const user = data.user;

    // ВСТРОЕННЫЕ ШАБЛОНЫ
    const complaintButtons = [
        {
    "title": "❌ Отказано",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(147, 112, 219)][SIZE=5]Отказано.[/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "отказано", "closed", "deny"]
  },
  {
    "title": "✅ Наказание выдано верно",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Проверив доказательства администратора, было принято решение, что наказание было выдано верно. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "наказание верно", "closed", "deny"]
  },
  {
    "title": "❌ Не подлежит обж",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(147, 112, 219)][SIZE=5] Ваш аккаунт не подлежит обжалованию. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "не обжалуется", "closed", "ban appeal"]
  },
  {
    "title": "⏳ На рассмотрении",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE][/I]\n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Ваша жалоба взята на рассмотрение. \n Не нужно создавать копии этой жалобы, ожидайте ответа в этой теме.[/SIZE][/COLOR][/FONT]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Ожидайте ответа.[/FONT][/COLOR][/SIZE][/I][/CENTER]",
    "prefix": 4,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["рассмотрение", "ожидание", "review", "pending"]
  },
  {
    "title": "⚠️ Беседа с адм",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Ваша жалоба была одобрена и будет проведена строгая беседа с администратором. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приятной игры на сервере [/FONT][COLOR=rgb(106, 90, 205)][FONT=arial]Екатеринбург [/FONT][/COLOR][/COLOR][/SIZE][/I][/SIZE][/FONT][/SIZE][/I][/CENTER]",
    "prefix": 2,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["одобрено", "беседа с админом", "approved", "admin talk"]
  },
  {
    "title": "🔄 Передано ГА",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Ваша жалоба передана Главному администратору [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Ожидайте ответа [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 4,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["передано", "главный администратор", "transfer", "GA"]
  },
  {
    "title": "❌ Нету доказательств",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]В вашей жалобе отсутствуют доказательства. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "нет доказательств", "evidence", "closed"]
  },
  {
    "title": "❌ Не рабочие доказательства",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]В вашей жалобе не работают доказательства. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "битые ссылки", "broken link", "invalid"]
  },
  {
    "title": "❌ Недостаточно доказательств",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]В вашей жалобе недостаточно доказательств . [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "мало доков", "insufficient", "evidence"]
  },
  {
    "title": "✅ Игрок будет наказан",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE][/I]\n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Ваша жалоба рассмотрена. Игрок будет наказан.[/SIZE][/COLOR][/FONT]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приятной игры![/FONT][/COLOR][/SIZE][/I][/CENTER]",
    "prefix": 2,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["одобрено", "наказание игроку", "approved", "player punish"]
  },
  {
    "title": "❌ Нету тайм-кода",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]В предоставленных доказательствах отсутствует /time. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "таймкод", "time", "closed"]
  },
  {
    "title": "⚠️ Админ получит наказание",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Ваша жалоба была одобрена и администратор получит наказание. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приятной игры на сервере [/FONT][COLOR=rgb(106, 90, 205)][FONT=arial]Екатеринбург  [/FONT][/COLOR][/COLOR][/SIZE][/I][/SIZE][/FONT][/SIZE][/I][/CENTER]",
    "prefix": 2,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["одобрено", "наказание админу", "admin punish", "approved"]
  },
  {
    "title": "❌ В тех раздел",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Вы ошиблись разделом.\nОбратитесь в Технический раздел - [URL=https://forum.ragerussia.online/forums/3//]*Тык*[/URL]. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 2,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "не тот раздел", "tech", "wrong section"]
  },
  {
    "title": "❌ Жалоба не по форме",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Ваша жалоба составлена не по форме.\nУбедительная просьба ознакомиться с правилами подачи жалоб на администрацию - [URL=https://forum.ragerussia.online/threads/8660/]*Тык*[/URL] [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "не по форме", "form", "rules"]
  },
  {
    "title": "✅ Наказание будет снято",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Ваше наказание будет снято в ближайшее время.[/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приятной игры на сервере [/FONT][COLOR=rgb(106, 90, 205)][FONT=arial]Екатеринбург [/FONT][/COLOR][/COLOR][/SIZE][/I][/SIZE][/FONT][/SIZE][/I][/CENTER]",
    "prefix": 2,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["одобрено", "снятие бана", "unban", "approved"]
  },
  {
    "title": "🔄 Передано ЗГА",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Ваша жалоба передана Заместителю главного администратора [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Ожидайте ответа [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 4,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["передано", "зам глава", "deputy", "transfer"]
  },
  {
    "title": "❌ Уже не адм",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Данный игрок был снят с поста администратора. [/SIZE][/COLOR][/FONT][/I]\n[url=https://postimages.org/][img]https://i.postimg.cc/TY3TpPFL/9914e97b895811f4cb5f5aafcdebc98f7a9b20a3r1-320-146-hq.gif[/img][/url]\n\n[SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приятной игры на сервере [/FONT][COLOR=rgb(106, 90, 205)][FONT=arial]Екатеринбург  [/FONT][/COLOR][/COLOR][/SIZE][/I][/SIZE][/FONT][/SIZE][/I][/CENTER]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "экс-админ", "ex admin", "dismissed"]
  },
  {
    "title": "⏳ Запрошу доки",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Запрошу доказательства у администратора. \n Ожидайте, пожалуйста, ответа от администрации и не нужно создавать копии этой темы. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Ожидайте ответа. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 4,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["ожидание", "запрос доков", "evidence request", "pending"]
  },
  {
    "title": "❌ От 3-го лица",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Жалобы, написанные от 3-го лица рассмотрению не подлежат.[/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто.[/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "третье лицо", "third party", "closed"]
  },
  {
    "title": "⚠️ Беседа с лидером",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Ваша жалоба была одобрена и будет проведена строгая беседа с лидером. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приятной игры на сервере [/FONT][COLOR=rgb(106, 90, 205)][FONT=arial]Екатеринбург [/FONT][/COLOR][/COLOR][/SIZE][/I][/SIZE][/FONT][/SIZE][/I][/CENTER]",
    "prefix": 2,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["одобрено", "беседа с лидером", "leader talk", "approved"]
  },
  {
    "title": "⚠️ Лидер получит наказание",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Ваша жалоба была одобрена и лидер получит наказание. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приятной игры на сервере [/FONT][COLOR=rgb(106, 90, 205)][FONT=arial]Екатеринбург  [/FONT][/COLOR][/COLOR][/SIZE][/I][/SIZE][/FONT][/SIZE][/I][/CENTER]",
    "prefix": 2,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["одобрено", "наказание лидеру", "leader punish", "approved"]
  },
  {
    "title": "❌ Нет нарушений от лд",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}.  [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Проверив ваши доказательства, нарушения со стороны лидера не выявлено. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приятной игры на сервере [/FONT][COLOR=rgb(106, 90, 205)][FONT=arial]Екатеринбург  [/FONT][/COLOR][/COLOR][/SIZE][/I][/SIZE][/FONT][/SIZE][/I][/CENTER]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "нет нарушений", "no violation", "leader", "closed"]
  },
  {
    "title": "❌ В нрп обман",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый  ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Вы ошиблись разделом.\nОбратитесь в раздел жалоб на NonRP разводы - [URL=https://forum.ragerussia.online/forums/105/]*Тык*[/URL]. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "не тот раздел", "nonrp", "scam", "wrong section"]
  },
  {
    "title": "❌ Не лидер",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый  ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Данный игрок не является лидером. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приятной игры на сервере [/FONT][COLOR=rgb(106, 90, 205)][FONT=arial]Екатеринбург  [/FONT][/COLOR][/COLOR][/SIZE][/I][/SIZE][/FONT][/SIZE][/I][/CENTER]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "не лидер", "not leader", "closed"]
  },
  {
    "title": "❌ Нету условий сделки",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Отсутствуют условия сделки. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "условия сделки", "terms", "deal", "closed"]
  },
  {
    "title": "❌ Ошиблись сервером",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Вы ошиблись сервером. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "не тот сервер", "wrong server", "closed"]
  },
  {
    "title": "❌ Нарушений не найдено",
    "content": "[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] \n\n[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Просмотрев ваши доказательства, нарушений найдено не было. [/SIZE][/COLOR][/FONT][/I]\n[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]\n\n[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]",
    "prefix": 3,
    "status": false,
    "close": false,
    "category": "complaints",
    "tags": ["отказ", "нарушений нет", "no violation", "closed"]
  }

    ];

    const requestButtons = [
        {
            title: `📌 Ответ в прошлой теме`,
            content: `[CENTER][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Приветствую, уважаемый ${user.name}. [/FONT][/COLOR][/SIZE] <br><br>[FONT=times new roman][COLOR=rgb(146, 58, 255)][SIZE=5]Ответ был дан в прошлой теме. [/SIZE][/COLOR][/FONT][/I]<br>[URL=https://postimages.org/][IMG]https://i.postimg.cc/6pRdXXKx/20240615-022705.png[/IMG][/URL]<br><br>[I][SIZE=5][FONT=times new roman][SIZE=5][I][I][SIZE=4][COLOR=rgb(147, 112, 219)][FONT=arial]Закрыто. [/CENTER][/FONT][/COLOR][/SIZE][/I][/I][/SIZE][/FONT][/SIZE]`,
            prefix: 3, status: false, close: false, category: 'requests', tags: ['прошлая тема', 'дубль', 'old']
        },
    ];

    
    let isWindowOpen = false;
    let currentSearchQuery = '';

    function toggleCompactWindow() {
        if (isWindowOpen) {
            $('#compactScriptWindow').remove();
            isWindowOpen = false;
        } else {
            showCompactWindow();
        }
    }

    function filterTemplates() {
        const search = $('#templateSearchInput').val().toLowerCase();
        currentSearchQuery = search;

       
        $('.template-item-btn[data-template-type="builtin"]').each(function() {
            const title = $(this).text().toLowerCase();
            const tags = $(this).data('tags') || '';
            const matches = title.includes(search) || (tags && tags.toLowerCase().includes(search));
            $(this).toggle(matches);
        });

       
        $('.custom-template-item').each(function() {
            const title = $(this).find('.custom-title').text().toLowerCase();
            const matches = title.includes(search);
            $(this).toggle(matches);
        });

      
        const visibleBuiltin = $('.template-item-btn[data-template-type="builtin"]:visible').length;
        const visibleCustom = $('.custom-template-item:visible').length;
        const activeTab = $('.tab-btn.active').data('tab');

        if (activeTab === 'builtin' && visibleBuiltin === 0 && search) {
            if (!$('#noResultsMsg').length) {
                $('#builtinTab').append('<div id="noResultsMsg" style="text-align:center;padding:20px;color:#aaa;">🔍 Ничего не найдено</div>');
            }
        } else {
            $('#noResultsMsg').remove();
        }

        if (activeTab === 'custom' && visibleCustom === 0 && search) {
            if (!$('#noCustomResultsMsg').length) {
                $('#customTab').append('<div id="noCustomResultsMsg" style="text-align:center;padding:20px;color:#aaa;">🔍 Нет своих шаблонов по запросу</div>');
            }
        } else {
            $('#noCustomResultsMsg').remove();
        }
    }

    function showCompactWindow() {
        const customTemplates = loadCustomTemplates();
        const quickReplies = loadQuickReplies();
        const settings = loadSettings();
        const stats = loadStats();
        const todayStats = stats[new Date().toDateString()] || { total: 0, templates: {} };

        const windowHtml = `
            <div id="compactScriptWindow" style="position:fixed;top:50px;right:20px;width:420px;max-height:85vh;background:linear-gradient(135deg, #1a1a2e, #16213e);border-radius:16px;box-shadow:0 8px 32px rgba(0,0,0,0.4),0 0 0 1px rgba(155,89,182,0.3);z-index:10000;display:flex;flex-direction:column;overflow:hidden;backdrop-filter:blur(10px);">
                <!-- Заголовок окна -->
                <div style="display:flex;justify-content:space-between;align-items:center;padding:12px 16px;background:linear-gradient(135deg, #9b59b6, #6a3ad5);cursor:move;" id="windowHeader">
                    <div style="display:flex;align-items:center;gap:8px;">
                        <span style="font-size:20px;">✨</span>
                        <span style="font-weight:bold;color:white;">Script by Flora</span>
                        <span style="font-size:11px;background:rgba(255,255,255,0.2);padding:2px 8px;border-radius:20px;">v7</span>
                    </div>
                    <div style="display:flex;gap:8px;">
                        <button id="minimizeWindowBtn" style="background:none;border:none;color:white;font-size:18px;cursor:pointer;width:28px;height:28px;display:flex;align-items:center;justify-content:center;border-radius:6px;transition:all 0.2s;">➖</button>
                        <button id="closeWindowBtn" style="background:none;border:none;color:white;font-size:18px;cursor:pointer;width:28px;height:28px;display:flex;align-items:center;justify-content:center;border-radius:6px;transition:all 0.2s;">✖️</button>
                    </div>
                </div>

                <!-- Содержимое окна -->
                <div style="padding:12px;overflow-y:auto;flex:1;max-height:calc(85vh - 50px);">
                    <!-- Быстрые действия -->
                    <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:16px;">
                        <button id="quickClosedBtn" style="padding:10px;border-radius:10px;border:none;background:linear-gradient(135deg,#e74c3c,#c0392b);color:white;cursor:pointer;font-weight:bold;transition:all 0.2s;">🔒 Закрыть</button>
                        <button id="quickUnacceptBtn" style="padding:10px;border-radius:10px;border:none;background:linear-gradient(135deg,#f39c12,#e67e22);color:white;cursor:pointer;font-weight:bold;transition:all 0.2s;">❌ Отказать</button>
                        <button id="quickConsiderBtn" style="padding:10px;border-radius:10px;border:none;background:linear-gradient(135deg,#3498db,#2980b9);color:white;cursor:pointer;font-weight:bold;transition:all 0.2s;">📋 На рассм.</button>
                    </div>

                    <!-- Дополнительные быстрые кнопки -->
                    <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:8px;margin-bottom:16px;">
                        <button id="quickAcceptBtn" style="padding:8px;border-radius:8px;border:none;background:linear-gradient(135deg,#27ae60,#2ecc71);color:white;cursor:pointer;font-size:12px;">✅ Принять</button>
                        <button id="quickCopyLinkBtn" style="padding:8px;border-radius:8px;border:none;background:linear-gradient(135deg,#3498db,#2980b9);color:white;cursor:pointer;font-size:12px;">🔗 Копировать ссылку</button>
                        <button id="quickMentionBtn" style="padding:8px;border-radius:8px;border:none;background:linear-gradient(135deg,#9b59b6,#6a3ad5);color:white;cursor:pointer;font-size:12px;">@ Упомянуть</button>
                    </div>

                    <!-- Улучшенный поиск шаблонов -->
                    <div style="margin-bottom:12px;">
                        <div style="position:relative;">
                            <input type="text" id="templateSearchInput" placeholder="🔍 Поиск шаблонов (название, теги)..." style="width:100%;padding:10px 35px 10px 12px;border-radius:10px;border:1px solid #9b59b6;background:#0f0f1a;color:white;box-sizing:border-box;">
                            <span id="searchClearBtn" style="position:absolute;right:10px;top:50%;transform:translateY(-50%);cursor:pointer;color:#aaa;display:none;">✖️</span>
                        </div>
                        <div id="searchStats" style="font-size:10px;color:#aaa;margin-top:4px;text-align:right;"></div>
                    </div>

                    <!-- Вкладки -->
                    <div style="display:flex;gap:4px;margin-bottom:12px;border-bottom:1px solid rgba(155,89,182,0.3);flex-wrap:wrap;">
                        <button class="tab-btn active" data-tab="builtin" style="padding:8px 12px;background:none;border:none;color:white;cursor:pointer;border-bottom:2px solid #9b59b6;">📦 Встроенные</button>
                        <button class="tab-btn" data-tab="custom" style="padding:8px 12px;background:none;border:none;color:#aaa;cursor:pointer;">⭐ Мои (${customTemplates.length})</button>
                        <button class="tab-btn" data-tab="quick" style="padding:8px 12px;background:none;border:none;color:#aaa;cursor:pointer;">⚡ Быстрые ответы (${quickReplies.length})</button>
                        <button class="tab-btn" data-tab="stats" style="padding:8px 12px;background:none;border:none;color:#aaa;cursor:pointer;">📊 Статистика</button>
                        <button class="tab-btn" data-tab="settings" style="padding:8px 12px;background:none;border:none;color:#aaa;cursor:pointer;">⚙️ Настройки</button>
                    </div>

                    <!-- Список встроенных шаблонов -->
                    <div id="builtinTab" class="tab-content" style="display:block;">
                        <div style="margin-bottom:8px;font-size:11px;color:#aaa;">📋 ЖАЛОБЫ (${complaintButtons.length})</div>
                        ${complaintButtons.map((btn, idx) => `
                            <button class="template-item-btn" data-template-type="builtin" data-template-index="${idx}" data-is-request="false" data-tags="${btn.tags.join(' ')}" style="display:block;width:100%;text-align:left;padding:8px 12px;margin:4px 0;border-radius:8px;border:none;background:#0f0f1a;color:#ecf0f1;cursor:pointer;transition:all 0.2s;">${btn.title}</button>
                        `).join('')}
                        <div style="margin:12px 0 8px 0;font-size:11px;color:#aaa;">📨 ЗАПРОСЫ (${requestButtons.length})</div>
                        ${requestButtons.map((btn, idx) => `
                            <button class="template-item-btn" data-template-type="builtin" data-template-index="${idx}" data-is-request="true" data-tags="${btn.tags.join(' ')}" style="display:block;width:100%;text-align:left;padding:8px 12px;margin:4px 0;border-radius:8px;border:none;background:#0f0f1a;color:#ecf0f1;cursor:pointer;transition:all 0.2s;">${btn.title}</button>
                        `).join('')}
                    </div>

                    <!-- Список своих шаблонов -->
                    <div id="customTab" class="tab-content" style="display:none;">
                        <button id="createTemplateBtn" style="width:100%;padding:10px;border-radius:10px;border:none;background:#2ecc71;color:white;cursor:pointer;margin-bottom:12px;font-weight:bold;">➕ Создать шаблон</button>
                        <div id="customTemplatesList">
                            ${customTemplates.length === 0 ? '<div style="text-align:center;padding:20px;color:#aaa;">Нет своих шаблонов<br>Нажмите "Создать шаблон"</div>' : ''}
                            ${customTemplates.map((tpl, idx) => `
                                <div class="custom-template-item" data-template-index="${idx}" style="background:#0f0f1a;border-radius:8px;margin-bottom:8px;padding:8px;">
                                    <div style="display:flex;justify-content:space-between;align-items:center;">
                                        <span class="custom-title" style="font-weight:bold;color:#9b59b6;">${escapeHtml(tpl.title)}</span>
                                        <div>
                                            <button class="edit-custom-btn" data-index="${idx}" style="background:#f39c12;border:none;padding:4px 8px;border-radius:4px;color:white;cursor:pointer;margin-right:4px;">✏️</button>
                                            <button class="delete-custom-btn" data-index="${idx}" style="background:#e74c3c;border:none;padding:4px 8px;border-radius:4px;color:white;cursor:pointer;">🗑️</button>
                                        </div>
                                    </div>
                                    <div style="font-size:10px;color:#aaa;margin:4px 0;">Префикс: ${tpl.prefix === 2 ? 'Принято' : (tpl.prefix === 3 ? 'Отказано' : 'На рассмотрении')}</div>
                                    <button class="use-custom-btn" data-index="${idx}" style="width:100%;margin-top:6px;padding:6px;border-radius:6px;border:none;background:#3498db;color:white;cursor:pointer;">Использовать</button>
                                </div>
                            `).join('')}
                        </div>
                    </div>

                    <!-- Быстрые ответы -->
                    <div id="quickTab" class="tab-content" style="display:none;">
                        <button id="addQuickReplyBtn" style="width:100%;padding:10px;border-radius:10px;border:none;background:#9b59b6;color:white;cursor:pointer;margin-bottom:12px;font-weight:bold;">➕ Добавить быстрый ответ</button>
                        <div id="quickRepliesList">
                            ${quickReplies.length === 0 ? '<div style="text-align:center;padding:20px;color:#aaa;">Нет быстрых ответов<br>Нажмите "Добавить быстрый ответ"</div>' : ''}
                            ${quickReplies.map((reply, idx) => `
                                <div class="quick-reply-item" data-reply-index="${idx}" style="background:#0f0f1a;border-radius:8px;margin-bottom:8px;padding:8px;">
                                    <div style="display:flex;justify-content:space-between;align-items:center;">
                                        <span style="font-weight:bold;color:#2ecc71;">⚡ ${escapeHtml(reply.title)}</span>
                                        <div>
                                            <button class="edit-quick-reply" data-index="${idx}" style="background:#f39c12;border:none;padding:4px 8px;border-radius:4px;color:white;cursor:pointer;margin-right:4px;">✏️</button>
                                            <button class="delete-quick-reply" data-index="${idx}" style="background:#e74c3c;border:none;padding:4px 8px;border-radius:4px;color:white;cursor:pointer;">🗑️</button>
                                        </div>
                                    </div>
                                    <div style="font-size:11px;color:#aaa;margin-top:4px;">${escapeHtml(reply.content.substring(0, 50))}...</div>
                                    <button class="use-quick-reply" data-index="${idx}" style="width:100%;margin-top:6px;padding:6px;border-radius:6px;border:none;background:#27ae60;color:white;cursor:pointer;">📝 Вставить ответ</button>
                                </div>
                            `).join('')}
                        </div>
                    </div>

                    <!-- Статистика -->
                    <div id="statsTab" class="tab-content" style="display:none;">
                        <div style="background:#0f0f1a;border-radius:8px;padding:12px;">
                            <div style="text-align:center;margin-bottom:12px;">
                                <span style="font-size:24px;">📊</span>
                                <h4 style="margin:5px 0;color:white;">Статистика за сегодня</h4>
                                <div style="font-size:28px;color:#9b59b6;font-weight:bold;">${todayStats.total}</div>
                                <div style="font-size:11px;color:#aaa;">всего ответов</div>
                            </div>
                            ${Object.keys(todayStats.templates).length > 0 ? `
                                <div style="margin-top:12px;">
                                    <div style="font-size:12px;color:#aaa;margin-bottom:8px;">Использованные шаблоны:</div>
                                    ${Object.entries(todayStats.templates).map(([name, count]) => `
                                        <div style="display:flex;justify-content:space-between;margin-bottom:4px;">
                                            <span style="font-size:11px;">${name}</span>
                                            <span style="color:#9b59b6;">${count} раз</span>
                                        </div>
                                    `).join('')}
                                </div>
                            ` : '<div style="text-align:center;padding:20px;color:#aaa;">Нет статистики за сегодня</div>'}
                            <button id="resetStatsBtn" style="width:100%;margin-top:12px;padding:8px;border-radius:6px;border:none;background:#e74c3c;color:white;cursor:pointer;">🗑️ Сбросить статистику</button>
                        </div>
                    </div>

                    <!-- Настройки -->
                    <div id="settingsTab" class="tab-content" style="display:none;">
                        <div style="background:#0f0f1a;border-radius:8px;padding:12px;">
                            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                                <span>🎨 Верхняя панель</span>
                                <label class="switch">
                                    <input type="checkbox" id="topBarToggle" ${settings.topBarEnabled ? 'checked' : ''}>
                                    <span class="slider"></span>
                                </label>
                            </div>
                            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                                <span>🌙 Тёмная тема</span>
                                <label class="switch">
                                    <input type="checkbox" id="themeToggle" ${settings.theme === 'dark' ? 'checked' : ''}>
                                    <span class="slider"></span>
                                </label>
                            </div>
                            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                                <span>⚡ Быстрые действия</span>
                                <label class="switch">
                                    <input type="checkbox" id="quickActionsToggle" ${settings.quickActions !== false ? 'checked' : ''}>
                                    <span class="slider"></span>
                                </label>
                            </div>
                            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                                <span>🔄 Авто-перезагрузка</span>
                                <label class="switch">
                                    <input type="checkbox" id="autoReloadToggle" ${settings.autoReload ? 'checked' : ''}>
                                    <span class="slider"></span>
                                </label>
                            </div>
                            <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
                                <span>💾 Авто-сохранение черновиков</span>
                                <label class="switch">
                                    <input type="checkbox" id="autoSaveToggle" ${settings.autoSaveDrafts !== false ? 'checked' : ''}>
                                    <span class="slider"></span>
                                </label>
                            </div>
                            <button id="loadDraftBtn" style="width:100%;padding:8px;border-radius:6px;border:none;background:#3498db;color:white;cursor:pointer;margin-top:8px;">📂 Загрузить черновик</button>
                            <button id="clearDraftBtn" style="width:100%;padding:8px;border-radius:6px;border:none;background:#e74c3c;color:white;cursor:pointer;margin-top:8px;">🗑️ Очистить черновик</button>
                            <button id="resetTemplatesBtn" style="width:100%;padding:10px;border-radius:8px;border:1px solid #e74c3c;background:none;color:#e74c3c;cursor:pointer;margin-top:12px;">🗑️ Сбросить свои шаблоны</button>
                            <button id="exportTemplatesBtn" style="width:100%;padding:10px;border-radius:8px;border:1px solid #3498db;background:none;color:#3498db;cursor:pointer;margin-top:8px;">💾 Экспорт шаблонов</button>
                            <button id="importTemplatesBtn" style="width:100%;padding:10px;border-radius:8px;border:1px solid #2ecc71;background:none;color:#2ecc71;cursor:pointer;margin-top:8px;">📥 Импорт шаблонов</button>
                        </div>
                    </div>
                </div>
            </div>
        `;

        $('body').append(windowHtml);
        isWindowOpen = true;

        
        let isDragging = false;
        let dragOffsetX, dragOffsetY;

        $('#windowHeader').on('mousedown', function(e) {
            if (e.target.closest('#minimizeWindowBtn') || e.target.closest('#closeWindowBtn')) return;
            isDragging = true;
            dragOffsetX = e.clientX - $('#compactScriptWindow').offset().left;
            dragOffsetY = e.clientY - $('#compactScriptWindow').offset().top;
            $('#compactScriptWindow').css('cursor', 'grabbing');
        });

        $(document).on('mousemove', function(e) {
            if (!isDragging) return;
            let newLeft = e.clientX - dragOffsetX;
            let newTop = e.clientY - dragOffsetY;
            newLeft = Math.max(0, Math.min(newLeft, $(window).width() - $('#compactScriptWindow').outerWidth()));
            newTop = Math.max(0, Math.min(newTop, $(window).height() - $('#compactScriptWindow').outerHeight()));
            $('#compactScriptWindow').css({ left: newLeft, right: 'auto', top: newTop });
        });

        $(document).on('mouseup', function() {
            isDragging = false;
            $('#compactScriptWindow').css('cursor', '');
        });

       
        $('#closeWindowBtn').click(() => toggleCompactWindow());

       
        let isMinimized = false;
        $('#minimizeWindowBtn').click(function() {
            if (!isMinimized) {
                $('#compactScriptWindow .tab-content, #compactScriptWindow > div:not(#windowHeader)').hide();
                $('#compactScriptWindow').css({ width: 'auto', minWidth: '200px' });
                $(this).text('🔽');
                isMinimized = true;
            } else {
                $('#compactScriptWindow .tab-content, #compactScriptWindow > div:not(#windowHeader)').show();
                $('#compactScriptWindow').css({ width: '420px', minWidth: '' });
                $(this).text('➖');
                isMinimized = false;
            }
        });

        
        $('.tab-btn').click(function() {
            $('.tab-btn').removeClass('active').css({ color: '#aaa', borderBottom: 'none' });
            $(this).addClass('active').css({ color: 'white', borderBottom: '2px solid #9b59b6' });

            const tab = $(this).data('tab');
            $('.tab-content').hide();
            if (tab === 'builtin') {
                $('#builtinTab').show();
                filterTemplates();
            } else if (tab === 'custom') {
                $('#customTab').show();
                filterTemplates();
            } else if (tab === 'quick') {
                $('#quickTab').show();
            } else if (tab === 'stats') {
                $('#statsTab').show();
            } else if (tab === 'settings') $('#settingsTab').show();
        });

       
        const $searchInput = $('#templateSearchInput');
        const $searchClearBtn = $('#searchClearBtn');

        $searchInput.on('input', function() {
            const val = $(this).val();
            $searchClearBtn.toggle(val.length > 0);
            filterTemplates();

            const visibleCount = $('.template-item-btn[data-template-type="builtin"]:visible, .custom-template-item:visible').length;
            $('#searchStats').text(`Найдено: ${visibleCount}`);
        });

        $searchClearBtn.click(function() {
            $searchInput.val('');
            $searchClearBtn.hide();
            filterTemplates();
            $('#searchStats').text('');
        });

       
        $('#quickClosedBtn').click(() => editThreadDataAndReload(PIN_PREFIX, true, false));
        $('#quickUnacceptBtn').click(() => editThreadDataAndReload(UNACCEPT_PREFIX, false, false));
        $('#quickConsiderBtn').click(() => editThreadDataAndReload(CLOSED_PREFIX, false, false));
        $('#quickAcceptBtn').click(() => editThreadDataAndReload(ACCEPT_PREFIX, false, false));

        $('#quickCopyLinkBtn').click(() => copyToClipboard(window.location.href, '✅ Ссылка скопирована!'));

        $('#quickMentionBtn').click(() => {
            const mention = `${user.mention}`;
            pasteContent(mention);
            showNotification('👤 Упоминание добавлено', 'success');
        });

       
        $('.template-item-btn').click(async function() {
            const type = $(this).data('template-type');
            const idx = $(this).data('template-index');
            const isRequest = $(this).data('is-request');

            let template;
            if (type === 'builtin') {
                const list = isRequest ? requestButtons : complaintButtons;
                template = list[idx];
            }

            if (template) {
                updateStats(template.title);
                pasteContent(template.content);
                if (template.prefix !== undefined) await editThreadDataAsync(template.prefix, template.status);
                if (template.close) await closeThreadAsync();
                setTimeout(() => $('.button--icon.button--icon--reply.rippleButton').trigger('click'), 500);

                const autoReload = loadSettings().autoReload;
                if (autoReload) {
                    setTimeout(() => location.reload(), 1000);
                } else {
                    toggleCompactWindow();
                }
            }
        });

        
        $('#createTemplateBtn').click(() => {
            toggleCompactWindow();
            showTemplateEditor();
        });

        
        $('.edit-custom-btn').click(function() {
            const idx = $(this).data('index');
            const templates = loadCustomTemplates();
            toggleCompactWindow();
            showTemplateEditor(templates[idx], idx);
        });

        $('.delete-custom-btn').click(function() {
            const idx = $(this).data('index');
            if (confirm('Удалить шаблон?')) {
                deleteCustomTemplate(idx);
                toggleCompactWindow();
                showCompactWindow();
            }
        });

        $('.use-custom-btn').click(async function() {
            const idx = $(this).data('index');
            const templates = loadCustomTemplates();
            const template = templates[idx];
            if (template) {
                updateStats(template.title);
                pasteContent(template.content);
                if (template.prefix !== undefined) await editThreadDataAsync(template.prefix, template.status);
                if (template.close) await closeThreadAsync();
                setTimeout(() => $('.button--icon.button--icon--reply.rippleButton').trigger('click'), 500);

                const autoReload = loadSettings().autoReload;
                if (autoReload) {
                    setTimeout(() => location.reload(), 1000);
                } else {
                    toggleCompactWindow();
                }
            }
        });

        
        $('#addQuickReplyBtn').click(() => {
            toggleCompactWindow();
            showQuickReplyEditor();
        });

        $('.edit-quick-reply').click(function() {
            const idx = $(this).data('index');
            const replies = loadQuickReplies();
            toggleCompactWindow();
            showQuickReplyEditor(replies[idx], idx);
        });

        $('.delete-quick-reply').click(function() {
            const idx = $(this).data('index');
            if (confirm('Удалить быстрый ответ?')) {
                const replies = loadQuickReplies();
                replies.splice(idx, 1);
                saveQuickReplies(replies);
                toggleCompactWindow();
                showCompactWindow();
            }
        });

        $('.use-quick-reply').click(function() {
            const idx = $(this).data('index');
            const replies = loadQuickReplies();
            const reply = replies[idx];
            if (reply) {
                pasteContent(reply.content);
                showNotification(`⚡ Быстрый ответ "${reply.title}" вставлен`, 'success');
                toggleCompactWindow();
            }
        });

      
        $('#resetStatsBtn').click(() => {
            if (confirm('Сбросить всю статистику?')) {
                saveStats({});
                toggleCompactWindow();
                showCompactWindow();
            }
        });

       
        $('#topBarToggle').change(function() {
            const settings = loadSettings();
            settings.topBarEnabled = $(this).is(':checked');
            saveSettings(settings);
            if (settings.topBarEnabled) showTopBar(); else $('#topBarScript').remove();
        });

        $('#themeToggle').change(function() {
            const settings = loadSettings();
            settings.theme = $(this).is(':checked') ? 'dark' : 'light';
            saveSettings(settings);
            applyTheme(settings.theme);
        });

        $('#quickActionsToggle').change(function() {
            const settings = loadSettings();
            settings.quickActions = $(this).is(':checked');
            saveSettings(settings);
            if (!settings.quickActions) {
                $('.quick-actions-row').hide();
            } else {
                $('.quick-actions-row').show();
            }
        });

        $('#autoReloadToggle').change(function() {
            const settings = loadSettings();
            settings.autoReload = $(this).is(':checked');
            saveSettings(settings);
        });

        $('#autoSaveToggle').change(function() {
            const settings = loadSettings();
            settings.autoSaveDrafts = $(this).is(':checked');
            saveSettings(settings);
        });

        $('#loadDraftBtn').click(() => {
            const draft = loadDraft();
            if (draft) {
                pasteContent(draft);
                showNotification('📂 Черновик загружен', 'success');
                toggleCompactWindow();
            } else {
                showNotification('❌ Нет сохранённого черновика', 'error');
            }
        });

        $('#clearDraftBtn').click(() => {
            clearDraft();
            showNotification('🗑️ Черновик очищен', 'success');
        });

        $('#resetTemplatesBtn').click(() => {
            if (confirm('Удалить все свои шаблоны? Это действие нельзя отменить.')) {
                saveCustomTemplates([]);
                toggleCompactWindow();
                showCompactWindow();
            }
        });

        $('#exportTemplatesBtn').click(() => {
            const templates = loadCustomTemplates();
            const dataStr = JSON.stringify(templates, null, 2);
            const blob = new Blob([dataStr], {type: 'application/json'});
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `templates_backup_${Date.now()}.json`;
            a.click();
            URL.revokeObjectURL(url);
            showNotification('💾 Шаблоны экспортированы', 'success');
        });

        $('#importTemplatesBtn').click(() => {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'application/json';
            input.onchange = (e) => {
                const file = e.target.files[0];
                const reader = new FileReader();
                reader.onload = (event) => {
                    try {
                        const imported = JSON.parse(event.target.result);
                        if (Array.isArray(imported)) {
                            const existing = loadCustomTemplates();
                            saveCustomTemplates([...existing, ...imported]);
                            showNotification(`✅ Импортировано ${imported.length} шаблонов`, 'success');
                            toggleCompactWindow();
                            showCompactWindow();
                        } else {
                            showNotification('❌ Неверный формат файла', 'error');
                        }
                    } catch(e) {
                        showNotification('❌ Ошибка при импорте', 'error');
                    }
                };
                reader.readAsText(file);
            };
            input.click();
        });

       
        filterTemplates();

        
        if (!settings.quickActions) {
            $('.quick-actions-row').hide();
        }
    }

    
    function showQuickReplyEditor(reply = null, index = -1) {
        const isEdit = reply !== null;
        const modalHtml = `
            <div class="quick-reply-editor-overlay" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.85);z-index:10001;display:flex;align-items:center;justify-content:center;">
                <div style="background:#1a1a2e;border-radius:16px;width:90%;max-width:500px;padding:20px;border:1px solid #9b59b6;">
                    <h3 style="margin:0 0 15px 0;color:white;">${isEdit ? '✏️ Редактировать быстрый ответ' : '➕ Добавить быстрый ответ'}</h3>
                    <input type="text" id="quickReplyTitle" placeholder="Название" value="${isEdit ? escapeHtml(reply.title) : ''}" style="width:100%;padding:10px;margin-bottom:12px;border-radius:8px;border:1px solid #9b59b6;background:#0f0f1a;color:white;box-sizing:border-box;">
                    <textarea id="quickReplyContent" placeholder="Содержание (BB-код)" rows="6" style="width:100%;padding:10px;margin-bottom:12px;border-radius:8px;border:1px solid #9b59b6;background:#0f0f1a;color:white;box-sizing:border-box;font-family:monospace;">${isEdit ? escapeHtml(reply.content) : ''}</textarea>
                    <div style="display:flex;gap:10px;justify-content:flex-end;">
                        <button id="cancelQuickReplyBtn" style="padding:8px 20px;border-radius:8px;border:none;background:#7f8c8d;color:white;cursor:pointer;">Отмена</button>
                        <button id="saveQuickReplyBtn" style="padding:8px 20px;border-radius:8px;border:none;background:#9b59b6;color:white;cursor:pointer;">${isEdit ? 'Сохранить' : 'Добавить'}</button>
                    </div>
                </div>
            </div>
        `;

        $('body').append(modalHtml);
        const $overlay = $('.quick-reply-editor-overlay');

        $('#cancelQuickReplyBtn').click(() => $overlay.remove());
        $('#saveQuickReplyBtn').click(() => {
            const title = $('#quickReplyTitle').val().trim();
            const content = $('#quickReplyContent').val();

            if (!title) { alert('Введите название!'); return; }
            if (!content) { alert('Введите содержание!'); return; }

            const replies = loadQuickReplies();
            if (isEdit) {
                replies[index] = { title, content };
            } else {
                replies.push({ title, content });
            }
            saveQuickReplies(replies);
            $overlay.remove();
            showCompactWindow();
        });

        $overlay.click((e) => { if ($(e.target).is('.quick-reply-editor-overlay')) $overlay.remove(); });
    }

    function applyTheme(theme) {
        if (theme === 'dark') {
            $('#compactScriptWindow').css('background', 'linear-gradient(135deg, #1a1a2e, #16213e)');
        } else {
            $('#compactScriptWindow').css('background', 'linear-gradient(135deg, #f5f5f5, #e0e0e0)');
        }
    }

    
    function showTopBar() {
        if ($('#topBarScript').length) return;

        const topBarHtml = `
            <div id="topBarScript" style="position:fixed;top:0;left:0;right:0;height:36px;background:linear-gradient(90deg, #1a1a2e, #16213e, #1a1a2e);border-bottom:2px solid #9b59b6;z-index:9999;display:flex;align-items:center;justify-content:space-between;padding:0 16px;box-shadow:0 2px 10px rgba(0,0,0,0.3);">
                <div style="display:flex;align-items:center;gap:8px;">
                    <span style="font-size:18px;">✨</span>
                    <span style="color:white;font-weight:bold;font-size:13px;">Forum Script EKB</span>
                    <span style="font-size:10px;background:#9b59b6;padding:2px 6px;border-radius:20px;">by Flora</span>
                </div>
                <div style="display:flex;gap:6px;">
                    <button id="topBarOpenBtn" style="background:linear-gradient(135deg,#9b59b6,#6a3ad5);border:none;padding:4px 12px;border-radius:16px;color:white;cursor:pointer;font-size:11px;font-weight:bold;">📋 Открыть</button>
                    <button id="topBarCloseBtn" style="background:rgba(231,76,60,0.8);border:none;padding:4px 12px;border-radius:16px;color:white;cursor:pointer;font-size:11px;">🔒 Закрыть</button>
                    <button id="topBarUnacceptBtn" style="background:rgba(243,156,18,0.8);border:none;padding:4px 12px;border-radius:16px;color:white;cursor:pointer;font-size:11px;">❌ Отказать</button>
                    <button id="topBarAcceptBtn" style="background:rgba(46,204,113,0.8);border:none;padding:4px 12px;border-radius:16px;color:white;cursor:pointer;font-size:11px;">✅ Принять</button>
                    <button id="topBarCopyLink" style="background:rgba(52,152,219,0.8);border:none;padding:4px 12px;border-radius:16px;color:white;cursor:pointer;font-size:11px;">🔗 Копировать ссылку</button>
                </div>
            </div>
        `;

        $('body').append(topBarHtml);

        $('#topBarOpenBtn').click(() => showCompactWindow());
        $('#topBarCloseBtn').click(() => editThreadDataAndReload(PIN_PREFIX, true, false));
        $('#topBarUnacceptBtn').click(() => editThreadDataAndReload(UNACCEPT_PREFIX, false, false));
        $('#topBarAcceptBtn').click(() => editThreadDataAndReload(ACCEPT_PREFIX, false, false));
        $('#topBarCopyLink').click(() => copyToClipboard(window.location.href, '✅ Ссылка скопирована!'));

        
        $('body').css('padding-top', '36px');
    }

    
    function showTemplateEditor(template = null, index = -1) {
        const isEdit = template !== null;
        const modalHtml = `
            <div class="template-editor-overlay" style="position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.85);z-index:10001;display:flex;align-items:center;justify-content:center;">
                <div style="background:#1a1a2e;border-radius:16px;width:90%;max-width:500px;padding:20px;border:1px solid #9b59b6;">
                    <h3 style="margin:0 0 15px 0;color:white;">${isEdit ? '✏️ Редактировать шаблон' : '➕ Создать шаблон'}</h3>
                    <input type="text" id="editorTitle" placeholder="Название" value="${isEdit ? escapeHtml(template.title) : ''}" style="width:100%;padding:10px;margin-bottom:12px;border-radius:8px;border:1px solid #9b59b6;background:#0f0f1a;color:white;box-sizing:border-box;">
                    <textarea id="editorContent" placeholder="Содержание (BB-код)" rows="6" style="width:100%;padding:10px;margin-bottom:12px;border-radius:8px;border:1px solid #9b59b6;background:#0f0f1a;color:white;box-sizing:border-box;font-family:monospace;">${isEdit ? escapeHtml(template.content) : ''}</textarea>
                    <select id="editorPrefix" style="width:100%;padding:10px;margin-bottom:12px;border-radius:8px;border:1px solid #9b59b6;background:#0f0f1a;color:white;">
                        <option value="2" ${isEdit && template.prefix == 2 ? 'selected' : ''}>Префикс: Принято (2)</option>
                        <option value="3" ${isEdit && template.prefix == 3 ? 'selected' : ''}>Префикс: Отказано (3)</option>
                        <option value="4" ${isEdit && template.prefix == 4 ? 'selected' : ''}>Префикс: На рассмотрении (4)</option>
                    </select>
                    <label style="display:flex;align-items:center;gap:8px;margin-bottom:12px;color:white;">
                        <input type="checkbox" id="editorClose" ${isEdit && template.close ? 'checked' : ''}> Закрыть тему после ответа
                    </label>
                    <div style="display:flex;gap:10px;justify-content:flex-end;">
                        <button id="cancelEditorBtn" style="padding:8px 20px;border-radius:8px;border:none;background:#7f8c8d;color:white;cursor:pointer;">Отмена</button>
                        <button id="saveEditorBtn" style="padding:8px 20px;border-radius:8px;border:none;background:#9b59b6;color:white;cursor:pointer;">${isEdit ? 'Сохранить' : 'Создать'}</button>
                    </div>
                </div>
            </div>
        `;

        $('body').append(modalHtml);
        const $overlay = $('.template-editor-overlay');

        $('#cancelEditorBtn').click(() => $overlay.remove());
        $('#saveEditorBtn').click(() => {
            const title = $('#editorTitle').val().trim();
            const content = $('#editorContent').val();
            const prefix = parseInt($('#editorPrefix').val());
            const close = $('#editorClose').is(':checked');

            if (!title) { alert('Введите название!'); return; }
            if (!content) { alert('Введите содержание!'); return; }

            if (isEdit) {
                updateCustomTemplate(index, title, content, prefix, close, 'complaints');
            } else {
                addCustomTemplate(title, content, prefix, close, 'complaints');
            }
            $overlay.remove();
            showCompactWindow();
        });

        $overlay.click((e) => { if ($(e.target).is('.template-editor-overlay')) $overlay.remove(); });
    }

    function escapeHtml(str) {
        if (!str) return '';
        return str.replace(/[&<>]/g, function(m) {
            if (m === '&') return '&amp;';
            if (m === '<') return '&lt;';
            if (m === '>') return '&gt;';
            return m;
        });
    }

    function pasteContent(content) {
        const editor = $('div.fr-element.fr-view');
        const placeholder = $('span.fr-placeholder');
        placeholder.empty();
        const currentContent = editor.html();
        if (currentContent === '' || currentContent === '<p><br></p>' || currentContent === '<p></p>') {
            editor.html(content);
        } else {
            editor.append(`<p><br></p><p><br></p>`);
            editor.append(content);
        }

       
        const settings = loadSettings();
        if (settings.autoSaveDrafts !== false) {
            saveDraft(content);
        }
    }

    async function getThreadData() {
        const $username = $('a.username');
        if (!$username.length || !$username[0].attributes['data-user-id']) {
            return { user: { id: 0, name: 'Игрок', mention: '[USER]Игрок[/USER]' } };
        }
        const authorID = $username[0].attributes['data-user-id'].nodeValue;
        const authorName = $username.html();
        return { user: { id: authorID, name: authorName, mention: `[USER=${authorID}]${authorName}[/USER]` } };
    }

    function closeThreadAsync() {
        return new Promise((resolve, reject) => {
            const formData = new FormData();
            formData.append('_xfToken', XF.config.csrf);
            formData.append('_xfRequestUri', location.pathname + location.search);
            formData.append('_xfWithData', '1');
            formData.append('_xfResponseType', 'json');
            fetch(location.href + 'close', { method: 'POST', body: formData })
                .then(r => r.json())
                .then(data => data.status === 'ok' ? resolve(data) : reject(data))
                .catch(e => reject(e));
        });
    }

    function editThreadDataAsync(prefix, closed = false) {
        return new Promise((resolve, reject) => {
            const $titleValue = $('.p-title-value');
            if (!$titleValue.length) { reject('Элемент заголовка не найден'); return; }
            let threadTitle = $titleValue[0].lastChild ? $titleValue[0].lastChild.textContent : $titleValue.text();
            if (!threadTitle || threadTitle.trim() === '') threadTitle = 'Тема';
            const formData = new FormData();
            formData.append('prefix_id', prefix);
            formData.append('title', threadTitle);
            formData.append('_xfToken', XF.config.csrf);
            formData.append('_xfRequestUri', location.pathname + location.search);
            formData.append('_xfWithData', '1');
            formData.append('_xfResponseType', 'json');
            if (closed) formData.append('sticky', '1');
            fetch(location.href + 'edit', { method: 'POST', body: formData })
                .then(r => r.json())
                .then(data => data.status === 'ok' ? resolve(data) : reject(data))
                .catch(e => reject(e));
        });
    }

    function editThreadDataAndReload(prefix, closed, close) {
        editThreadDataAsync(prefix, closed).then(async () => {
            if (close) await closeThreadAsync();
            location.reload();
        }).catch(err => console.error('Ошибка:', err));
    }

    
    $(document).ready(() => {
        
        $('head').append(`
            <style>
                .switch {
                    position: relative;
                    display: inline-block;
                    width: 50px;
                    height: 24px;
                }
                .switch input {
                    opacity: 0;
                    width: 0;
                    height: 0;
                }
                .slider {
                    position: absolute;
                    cursor: pointer;
                    top: 0;
                    left: 0;
                    right: 0;
                    bottom: 0;
                    background-color: #ccc;
                    transition: 0.3s;
                    border-radius: 24px;
                }
                .slider:before {
                    position: absolute;
                    content: "";
                    height: 18px;
                    width: 18px;
                    left: 3px;
                    bottom: 3px;
                    background-color: white;
                    transition: 0.3s;
                    border-radius: 50%;
                }
                input:checked + .slider {
                    background-color: #9b59b6;
                }
                input:checked + .slider:before {
                    transform: translateX(26px);
                }
                .template-item-btn:hover, .use-custom-btn:hover, #quickClosedBtn:hover, #quickUnacceptBtn:hover, #quickConsiderBtn:hover {
                    transform: scale(1.02);
                    filter: brightness(1.1);
                }
                #topBarOpenBtn:hover, #topBarCloseBtn:hover, #topBarUnacceptBtn:hover, #topBarAcceptBtn:hover, #topBarCopyLink:hover {
                    transform: scale(1.05);
                    filter: brightness(1.1);
                }
                .custom-template-item, .quick-reply-item {
                    transition: all 0.2s;
                }
                .custom-template-item:hover, .quick-reply-item:hover {
                    transform: translateX(2px);
                }
                @keyframes slideIn {
                    from {
                        transform: translateX(100%);
                        opacity: 0;
                    }
                    to {
                        transform: translateX(0);
                        opacity: 1;
                    }
                }
            </style>
        `);

      
        if (loadSettings().topBarEnabled) {
            showTopBar();
        }

       
        $('body').append(`
            <div id="floatingScriptBtn" style="position:fixed;bottom:20px;right:20px;width:45px;height:45px;border-radius:50%;background:linear-gradient(135deg,#9b59b6,#6a3ad5);border:2px solid rgba(255,255,255,0.3);color:white;font-size:22px;cursor:pointer;z-index:9998;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 15px rgba(0,0,0,0.3);transition:all 0.3s;">
                ✨
            </div>
        `);

        $('#floatingScriptBtn').click(() => showCompactWindow());
        $('#floatingScriptBtn').hover(
            function() { $(this).css({ transform: 'scale(1.1)', boxShadow: '0 6px 20px rgba(155,89,182,0.5)' }); },
            function() { $(this).css({ transform: 'scale(1)', boxShadow: '0 4px 15px rgba(0,0,0,0.3)' }); }
        );

       
        const draft = loadDraft();
        if (draft && loadSettings().autoSaveDrafts !== false) {
            setTimeout(() => {
                if (confirm('📝 Найден сохранённый черновик. Загрузить его?')) {
                    pasteContent(draft);
                    showNotification('📂 Черновик загружен', 'success');
                }
            }, 1000);
        }
    });
})();