Black Russia Gemini AI (Искусственный интеллект)

AI ассистент (Gemini): Ответы, Суммаризация (в модальном окне, с иконкой), Проверка (автоматическое применение), Вопросы (с UI), TG Бот Отправка (НЕБЕЗОПАСНО!), Быстрая отправка поста в TG, Анализ тона, Расшифровка сленга, Выделение аргументов, Объяснение жаргона, Анализ стиля поста, TL;DR в эмодзи, Быстрые ответы AI

// ==UserScript==
// @name         Black Russia Gemini AI (Искусственный интеллект)
// @namespace    http://tampermonkey.net/
// @version      2.6 // Добавлены быстрые ответы AI и инструкция в настройках
// @description  AI ассистент (Gemini): Ответы, Суммаризация (в модальном окне, с иконкой), Проверка (автоматическое применение), Вопросы (с UI), TG Бот Отправка (НЕБЕЗОПАСНО!), Быстрая отправка поста в TG, Анализ тона, Расшифровка сленга, Выделение аргументов, Объяснение жаргона, Анализ стиля поста, TL;DR в эмодзи, Быстрые ответы AI
// @author       M. Ageev
// @match        *://forum.blackrussia.online/*
// @icon         data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTYgMjU2Ij48cmVjdCB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgZmlsbD0ibm9uZSIvPjxwYXRoIGQ9Ik0xNzkuMDYsMTU1YTMyLDMyLDAsMSwxLTMxLjE4LTMxLjE4IiBmaWxsPSJub25lIiBzdHJva2U9IiM0Mjg1RjQiIHN0cm9rZS1saW5lLWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm9lbmQiIHN0cm9rZS13aWR0aD0iMTYiLz48cGF0aCBkPSJNNTA4LjEyLDEwMWEzMiwyMiwwLDEsMCwzMS4xOCwzMS4xOCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjRUE0MzM1IiBzdHJva2UtbGluZWNhcD0icm9bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIHN0cm9rZS13aWR0aD0iMTYiLz48cGF0aCBkPSJNNzcuODgsMTU1Ljg3YTMyLDMyLDAsMSwwLTMxLjE4LTMxLjE4IiBmaWxsPSJub25lIiBzdHJva2U9IiNGQkJDMDUiIHN0cm9rZS1saW5lLWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIHN0cm9rZS13aWR0aD0iMTYiLz48cGF0aCBkPSJNMTQ3Ljg4LDEwMWEzMiwyMiwwLDEsMCwzMS4xOCwzMS4xOCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMzRBODUzIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIHN0cm9rZS13aWR0aD0iMTYiLz48L3N2Zz4= // Gemini Logo
// @grant        GM_setValue
// @grant        GM_getValue
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// @connect      generativelanguage.googleapis.com
// @connect      api.telegram.org
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // --- Константы и переменные хранения ---
    const SCRIPT_PREFIX = 'BR_GM_Helper_';
    const GEMINI_API_KEY_STORAGE = SCRIPT_PREFIX + 'apiKey';
    const TELEGRAM_BOT_TOKEN_STORAGE = SCRIPT_PREFIX + 'tgBotToken';
    const TELEGRAM_CHAT_ID_STORAGE = SCRIPT_PREFIX + 'tgChatId';

    const GEMINI_MODEL = 'gemini-1.5-flash-latest';
    const GEMINI_ENDPOINT_TEMPLATE = `https://generativelanguage.googleapis.com/v1beta/models/${GEMINI_MODEL}:generateContent?key=`;

    // --- Стили ---
    GM_addStyle(`
        /* ... Базовые стили кнопок ... */
        .br-ai-button { background-color: #4285F4; border: none; color: white; padding: 5px 10px; font-size: 12px; margin: 4px 2px; cursor: pointer; border-radius: 8px; transition: background-color 0.3s ease; display: inline-block; text-align: center; text-decoration: none; vertical-align: middle; }
        .br-ai-button:hover { background-color: #3367D6; }
        .br-ai-button-secondary { background-color: #34A853; } .br-ai-button-secondary:hover { background-color: #2c8f46; }
        .br-ai-button-tertiary { background-color: #FBBC05; color: #333; } .br-ai-button-tertiary:hover { background-color: #F2A604; }
        .br-ai-button-quaternary { background-color: #8ab4f8; color: #202124; } .br-ai-button-quaternary:hover { background-color: #669df6; }
        .br-ai-button-telegram { background-color: #2AABEE; } .br-ai-button-telegram:hover { background-color: #1F9CD6; }
        .br-ai-button-telegram-bot { background-color: #17A2B8; } .br-ai-button-telegram-bot:hover { background-color: #117A8B; }

        /* ... Иконка настроек ... */
        .br-ai-settings-icon { position: fixed; bottom: 20px; right: 20px; background-color: #555; color: white; border-radius: 50%; width: 40px; height: 40px; display: flex; justify-content: center; align-items: center; font-size: 20px; cursor: pointer; z-index: 9999; box-shadow: 2px 2px 5px rgba(0,0,0,0.3); transition: background-color 0.3s ease; } .br-ai-settings-icon:hover { background-color: #777; }

        /* ... Базовые стили модальных окон ... */
        .br-ai-modal { display: none; position: fixed; z-index: 10000; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgba(0,0,0,0.6); }
        .br-ai-modal-content { background-color: #fefefe; margin: 10% auto; padding: 25px; border: 1px solid #888; width: 80%; max-width: 600px; border-radius: 10px; box-shadow: 0 5px 15px rgba(0,0,0,0.3); color: #333; }
        .br-ai-modal-close { color: #aaa; float: right; font-size: 28px; font-weight: bold; cursor: pointer; line-height: 1; } .br-ai-modal-close:hover, .br-ai-modal-close:focus { color: black; text-decoration: none; }
        .br-ai-modal h2 { margin-top: 0;} .br-ai-modal h3 { margin-top: 15px; margin-bottom: 5px;}
        .br-ai-modal label { display: block; margin-bottom: 5px; font-weight: bold; }
        .br-ai-modal input[type="text"], .br-ai-modal input[type="password"], .br-ai-modal textarea { width: calc(100% - 22px); padding: 10px; margin-bottom: 15px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; font-family: inherit; font-size: inherit; }
        .br-ai-modal textarea { min-height: 100px; white-space: pre-wrap; }
        .br-ai-modal button { background-color: #4285F4; color: white; padding: 10px 15px; border: none; border-radius: 5px; cursor: pointer; font-size: 14px; margin-right: 5px; margin-top: 5px; }
        .br-ai-modal button:hover { background-color: #3367D6; }
        .br-ai-modal button.cancel-button { background-color: #aaa; } .br-ai-modal button.cancel-button:hover { background-color: #888; }
        .br-ai-modal .help-text { font-size: 12px; color: #666; margin-top: 5px; margin-bottom: 10px; line-height: 1.4; }
        .br-ai-modal .security-warning { font-size: 13px; color: #D32F2F; font-weight: bold; border: 1px solid #FFCDD2; background-color: #FFEBEE; padding: 10px; margin-top: 5px; margin-bottom: 10px; border-radius: 4px; }

        /* ... Индикатор загрузки ... */
        .br-ai-loading { display: inline-block; margin-left: 10px; border: 3px solid #f3f3f3; border-top: 3px solid #4285F4; border-radius: 50%; width: 15px; height: 15px; animation: spin 1s linear infinite; vertical-align: middle; }
        @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }

        /* ... Стили для блока результата "Кратко" (улучшенные) ... */
        .br-ai-result { border: 1px solid #ccc; background-color: #f0f8ff; color: #111; padding: 10px; margin-top: 10px; border-radius: 5px; white-space: pre-wrap; }
        .br-ai-result-header { font-weight: bold; color: #333; margin-bottom: 5px; display: flex; justify-content: space-between; align-items: center; }
        .br-ai-result p { color: #111; margin: 0; }

        /* ... Контейнер для кнопок поста ... */
        .br-ai-post-actions { display: inline-flex; align-items: center; gap: 5px; margin-left: 5px; flex-wrap: wrap; /* Перенос кнопок на моб */ }

        /* ... Стили для модального окна "Кратко" ... */
        #br-ai-summary-modal .br-ai-modal-content { max-height: 70vh; display: flex; flex-direction: column; }
        #br-ai-summary-modal .br-ai-summary-text-container { flex-grow: 1; overflow-y: auto; border-top: 1px solid #eee; border-bottom: 1px solid #eee; padding: 15px 0; }
        #br-ai-summary-modal .br-ai-summary-text { white-space: pre-wrap; margin-top: 5px; }
    `);

    // --- Модальное окно для Проверки текста ---
    function createCorrectionModal() {
         const modalId = 'br-ai-correction-modal'; if (document.getElementById(modalId)) return; const modal = document.createElement('div'); modal.className = 'br-ai-modal'; modal.id = modalId; modal.innerHTML = ` <div class="br-ai-modal-content"> <span class="br-ai-modal-close">&times;</span> <h2>Проверка текста</h2> <div> <h3>Оригинал:</h3> <textarea id="br-ai-original-text" rows="5" readonly style="background-color:#eee;"></textarea> </div> <div> <h3>Предложенные исправления:</h3> <textarea id="br-ai-corrected-text" rows="8"></textarea> </div> <div id="br-ai-correction-loading" style="display:none; margin-top: 10px;">Загрузка...<span class="br-ai-loading"></span></div> <div style="margin-top: 15px;"> <button id="br-ai-apply-correction">Применить исправления</button> <button id="br-ai-cancel-correction" class="cancel-button">Отмена</button> </div> </div> `; document.body.appendChild(modal); const closeBtn = modal.querySelector('.br-ai-modal-close'); const cancelBtn = modal.querySelector('#br-ai-cancel-correction'); const applyBtn = modal.querySelector('#br-ai-apply-correction'); closeBtn.onclick = cancelBtn.onclick = () => { modal.style.display = 'none'; }; applyBtn.onclick = () => { const correctedText = modal.querySelector('#br-ai-corrected-text').value; const targetTextarea = window.activeCorrectionTextarea; if(targetTextarea) { targetTextarea.value = correctedText; targetTextarea.dispatchEvent(new Event('input', { bubbles: true })); targetTextarea.focus(); } modal.style.display = 'none'; }; modal.addEventListener('click', (event) => { if (event.target === modal) { modal.style.display = 'none'; } });
     }
    createCorrectionModal();

    // --- *** НОВОЕ: Модальное окно для отображения ответов AI *** ---
    function createResponseModal() {
        const modalId = 'br-ai-response-modal';
        if (document.getElementById(modalId)) return;

        const modal = document.createElement('div');
        modal.className = 'br-ai-modal';
        modal.id = modalId;
        modal.innerHTML = `
            <div class="br-ai-modal-content" style="max-height: 80vh; display: flex; flex-direction: column;">
                <span class="br-ai-modal-close">&times;</span>
                <h2 id="br-ai-response-title" style="margin-bottom: 15px;">Ответ AI</h2>
                <div style="flex-grow: 1; overflow-y: auto; border-top: 1px solid #eee; border-bottom: 1px solid #eee; padding: 15px 0;">
                    <div style="margin-bottom: 15px;">
                        <strong>Запрос/Контекст:</strong>
                        <p id="br-ai-response-request" style="white-space: pre-wrap; background-color:#f8f8f8; padding: 8px; border-radius: 3px; margin-top: 5px; max-height: 150px; overflow-y: auto;"></p>
                    </div>
                    <div>
                        <strong>Ответ AI:</strong>
                        <div id="br-ai-response-loading" style="display:none; margin: 10px 0;">Загрузка...<span class="br-ai-loading"></span></div>
                        <p id="br-ai-response-text" style="white-space: pre-wrap; margin-top: 5px;"></p>
                    </div>
                </div>
                 <div style="margin-top: 15px; text-align: right;">
                     <button id="br-ai-response-close" class="cancel-button">Закрыть</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        const closeBtn = modal.querySelector('.br-ai-modal-close');
        const closeBtn2 = modal.querySelector('#br-ai-response-close');

        closeBtn.onclick = closeBtn2.onclick = () => { modal.style.display = 'none'; };
        modal.addEventListener('click', (event) => { if (event.target === modal) { modal.style.display = 'none'; } });
    }
    createResponseModal();

    // --- *** НОВОЕ: Модальное окно для отображения краткого содержания *** ---
    function createSummaryModal() {
        const modalId = 'br-ai-summary-modal';
        if (document.getElementById(modalId)) return;

        const modal = document.createElement('div');
        modal.className = 'br-ai-modal';
        modal.id = modalId;
        modal.innerHTML = `
            <div class="br-ai-modal-content">
                <span class="br-ai-modal-close">&times;</span>
                <h2>Краткое содержание</h2>
                <div class="br-ai-summary-text-container">
                    <p id="br-ai-summary-text" class="br-ai-summary-text"></p>
                    <div id="br-ai-summary-loading" style="display:none; margin-top: 10px;">Загрузка...<span class="br-ai-loading"></span></div>
                </div>
                <div style="margin-top: 15px; text-align: right;">
                    <button id="br-ai-summary-close" class="cancel-button">Закрыть</button>
                </div>
            </div>
        `;
        document.body.appendChild(modal);

        const closeBtn = modal.querySelector('.br-ai-modal-close');
        const closeBtn2 = modal.querySelector('#br-ai-summary-close');

        closeBtn.onclick = closeBtn2.onclick = () => { modal.style.display = 'none'; };
        modal.addEventListener('click', (event) => { if (event.target === modal) { modal.style.display = 'none'; } });
    }
    createSummaryModal();

    // --- *** НОВОЕ: Функция для показа модалки с кратким содержанием *** ---
    function showSummary(summaryText, loadingPromise) {
        const modal = document.getElementById('br-ai-summary-modal');
        if (!modal) return;

        const summaryTextElement = modal.querySelector('#br-ai-summary-text');
        const loadingElement = modal.querySelector('#br-ai-summary-loading');

        summaryTextElement.innerText = '';
        loadingElement.style.display = 'block';
        modal.style.display = 'block';

        loadingPromise.then(text => {
            summaryTextElement.innerText = text;
        }).catch(error => {
            summaryTextElement.innerText = `Произошла ошибка:\n${error.message || error}`;
            summaryTextElement.style.color = 'red';
        }).finally(() => {
            loadingElement.style.display = 'none';
        });
    }

    // --- *** НОВОЕ: Функция для показа модалки с ответом AI *** ---
    function showAIResponse(title, requestText, responsePromise) {
        const modal = document.getElementById('br-ai-response-modal');
        if (!modal) return;

        modal.querySelector('#br-ai-response-title').innerText = title || 'Ответ AI';
        const previewRequestText = (requestText.length > 500) ? requestText.substring(0, 500) + '...' : requestText;
        modal.querySelector('#br-ai-response-request').innerText = previewRequestText || '(Нет текста запроса)';
        const responseElement = modal.querySelector('#br-ai-response-text');
        const loadingElement = modal.querySelector('#br-ai-response-loading');

        responseElement.innerText = '';
        responseElement.style.color = '';
        loadingElement.style.display = 'block';
        modal.style.display = 'block';

        responsePromise.then(responseText => {
            responseElement.innerText = responseText;
        }).catch(error => {
            responseElement.innerText = `Произошла ошибка:\n${error.message || error}`;
            responseElement.style.color = 'red';
        }).finally(() => {
            loadingElement.style.display = 'none';
        });
    }


    // --- Настройки Скрипта (Модальное окно) ---
    const settingsIcon = document.createElement('div'); settingsIcon.innerHTML = '🔑'; settingsIcon.className = 'br-ai-settings-icon'; settingsIcon.title = 'Настроить AI Helper'; document.body.appendChild(settingsIcon);
    const settingsModal = document.createElement('div'); settingsModal.className = 'br-ai-modal'; settingsModal.id = 'br-ai-settings-modal';
    settingsModal.innerHTML = `
        <div class="br-ai-modal-content">
            <span class="br-ai-modal-close">&times;</span>
            <h2>Настройки AI Helper (Gemini + TG Bot)</h2>
            <p><b>Скрипт:</b> Black Russia Forum AI Helper</p>
            <p><b>Версия:</b> ${GM_info.script.version}</p>
            <hr style="margin-top: 10px; margin-bottom: 15px;">
            <h3>Google Gemini</h3>
            <label for="br-ai-gemini-key">Google AI API Ключ:</label>
            <input type="password" id="br-ai-gemini-key" name="geminiApiKey" placeholder="Введите ваш API ключ из Google AI Studio">
            <div class="help-text">Получите ключ в <a href="https://aistudio.google.com/app/apikey" target="_blank">Google AI Studio</a>.</div>
            <h3 style="margin-top: 20px;">Telegram Бот (необязательно)</h3>
            <label for="br-ai-tg-token">Telegram Bot Token:</label>
            <input type="password" id="br-ai-tg-token" name="tgBotToken" placeholder="Введите токен вашего Telegram бота">
            <div class="security-warning">⚠️ **ПРЕДУПРЕЖДЕНИЕ:** Хранить токен бота здесь НЕБЕЗОПАСНО! Любой может его украсть. Используйте только для тестовых ботов!</div>
            <label for="br-ai-tg-chatid" style="margin-top:10px;">Telegram Chat ID:</label>
            <input type="text" id="br-ai-tg-chatid" name="tgChatId" placeholder="Введите ID чата или ваш User ID">
            <div class="help-text">ID чата (для групп начинается с "-") или ваш User ID (узнать можно у ботов типа @userinfobot). Бот должен быть добавлен в чат (если это группа) или вы должны были написать ему /start (если отправка в личку).</div>
            <hr style="margin-top: 20px; margin-bottom: 15px;">
            <h3>Инструкция по использованию</h3>
            <p>После установки скрипта на страницах форума Black Russia появятся дополнительные кнопки и функции:</p>
            <ul>
                <li>🔑 <b>Иконка настроек</b> в правом нижнем углу позволяет ввести ваш Google AI API ключ и (опционально) настройки Telegram бота.</li>
                <li>В каждом посте появятся кнопки:
                    <ul>
                        <li><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M2 2v12h12V2H2zm12-1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h12z"/><path fill-rule="evenodd" d="M3.5 4a.5.5 0 0 1 .5-.5h8a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5H4a.5.5 0 0 1-.5-.5V4zm0 3a.5.5 0 0 1 .5-.5h8a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5H4a.5.5 0 0 1-.5-.5V7zm0 3a.5.5 0 0 1 .5-.5h4a.5.5 0 0 1 0 1H4a.5.5 0 0 1-.5-.5v-1z"/></svg> <b>Кратко (Gemini)</b>: Отображает краткое содержание поста в модальном окне.</li>
                        <li><b>🤔 Стиль поста</b>: Анализирует стиль написания поста (формальный, неформальный и т.д.).</li>
                        <li><b>😂 TL;DR (Emoji)</b>: Делает очень краткое содержание поста в виде нескольких эмодзи.</li>
                        <li><b>💡 Аргументы</b>: Выделяет ключевые аргументы или мысли автора поста.</li>
                        <li><b>❓ AI Вопрос</b>: Позволяет задать вопрос об этом посте и получить ответ от AI.</li>
                        <li><b>🎮 Жаргон</b>: Позволяет ввести игровой термин из поста и получить его объяснение.</li>
                        <li><svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="currentColor" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM8.287 5.906c-.778.324-2.334.994-4.666 2.01-.378.15-.577.298-.595.442-.03.243.275.339.69.47l.175.055c.408.133.958.288 1.243.294.26.006.549-.1.868-.32 2.179-1.471 3.304-2.214 3.374-2.23.05-.012.12-.026.166.016.047.041.042.12.037.141-.03.129-1.227 1.241-1.846 1.817-.193.18-.33.307-.358.336a8.154 8.154 0 0 1-.188.186c-.38.366-.664.64.015 1.088.327.216.589.393.85.571.284.194.568.387.936.629.093.06.183.125.27.187.331.236.63.448.997.414.214-.02.435-.22.547-.82.265-1.417.786-4.486.906-5.751a1.426 1.426 0 0 0-.013-.315.337.337 0 0 0-.114-.217.526.526 0 0 0-.31-.093c-.3.005-.763.166-2.984 1.09z"/></svg> <b>Поделиться в Telegram</b>: Открывает окно для отправки ссылки на пост в Telegram (через клиент).</li>
                        <li><b>🚀 Отпр. весь в TG</b>: Отправляет полный текст поста в ваш Telegram бот (если настроен).</li>
                        <li><b>🤖 Отпр. в TG</b>: Отправляет краткую сводку поста в ваш Telegram бот (если настроен).</li>
                    </ul>
                </li>
                <li>В форме ответа появятся кнопки:
                    <ul>
                        <li><b>🇬 Ответ (Gemini)</b>: Генерирует ответ на основе предыдущих сообщений в теме (или процитированного текста).</li>
                        <li><b>✔️ Проверить текст</b>: Открывает модальное окно с оригинальным текстом и предложенными исправлениями от AI.</li>
                        <li><b>Быстрые ответы AI</b>: Набор кнопок для генерации типовых ответов.</li>
                    </ul>
                </li>
            </ul>
            <button id="br-ai-save-settings">Сохранить Все Настройки</button>
        </div>
    `;
    document.body.appendChild(settingsModal);

    const geminiKeyInput = settingsModal.querySelector('#br-ai-gemini-key'); const tgTokenInput = settingsModal.querySelector('#br-ai-tg-token'); const tgChatIdInput = settingsModal.querySelector('#br-ai-tg-chatid'); const saveSettingsButton = settingsModal.querySelector('#br-ai-save-settings'); const closeSettingsButton = settingsModal.querySelector('.br-ai-modal-close'); settingsIcon.onclick = () => { geminiKeyInput.value = GM_getValue(GEMINI_API_KEY_STORAGE, ''); tgTokenInput.value = GM_getValue(TELEGRAM_BOT_TOKEN_STORAGE, ''); tgChatIdInput.value = GM_getValue(TELEGRAM_CHAT_ID_STORAGE, ''); settingsModal.style.display = 'block'; }; closeSettingsButton.onclick = () => { settingsModal.style.display = 'none'; }; settingsModal.addEventListener('click', (event) => { if (event.target === settingsModal) { settingsModal.style.display = 'none'; } }); saveSettingsButton.onclick = () => { const geminiKey = geminiKeyInput.value.trim(); const tgToken = tgTokenInput.value.trim(); const tgChatId = tgChatIdInput.value.trim(); if (geminiKey) { GM_setValue(GEMINI_API_KEY_STORAGE, geminiKey); } else { GM_deleteValue(GEMINI_API_KEY_STORAGE); } if (tgToken) { GM_setValue(TELEGRAM_BOT_TOKEN_STORAGE, tgToken); } else { GM_deleteValue(TELEGRAM_BOT_TOKEN_STORAGE); } if (tgChatId) { GM_setValue(TELEGRAM_CHAT_ID_STORAGE, tgChatId); } else { GM_deleteValue(TELEGRAM_CHAT_ID_STORAGE); } alert('Настройки сохранены!'); settingsModal.style.display = 'none'; };

    async function callGeminiAPI(prompt, buttonElement) {
        const apiKey = GM_getValue(GEMINI_API_KEY_STORAGE); if (!apiKey) { alert('Пожалуйста, сначала введите ваш Google AI API ключ в настройках (🔑 иконка).'); settingsIcon.click(); return Promise.reject("Нет ключа Gemini"); } let loadingIndicator; if(buttonElement && !buttonElement.closest('.br-ai-modal-content')) { loadingIndicator = document.createElement('span'); loadingIndicator.className = 'br-ai-loading'; buttonElement.parentNode.insertBefore(loadingIndicator, buttonElement.nextSibling); } if(buttonElement) buttonElement.disabled = true; const apiUrl = GEMINI_ENDPOINT_TEMPLATE + apiKey; const requestBody = { contents: [{ parts: [{ text: prompt }] }], }; return new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: 'POST', url: apiUrl, headers: { 'Content-Type': 'application/json' }, data: JSON.stringify(requestBody), responseType: 'json', onload: function(response) { if(loadingIndicator) loadingIndicator.remove(); if(buttonElement) buttonElement.disabled = false; const responseData = response.response; if (response.status === 200) { const candidate = responseData?.candidates?.[0]; const resultText = candidate?.content?.parts?.[0]?.text; if (candidate && candidate.finishReason === 'SAFETY') { console.warn('Gemini response blocked due to safety settings:', candidate.safetyRatings); const msg = 'Ответ был заблокирован из-за настроек безопасности.'; reject(msg); return; } if (!resultText && candidate && candidate.finishReason !== 'STOP') { console.warn('Gemini response finished with reason:', candidate.finishReason, responseData); const msg = `Ошибка: Ответ не получен (причина: ${candidate.finishReason}).`; reject(msg); return; } if (resultText) { resolve(resultText.trim()); } else { console.error('Gemini response error: Invalid structure or no text', responseData); reject('Ошибка: Не удалось извлечь текст из ответа Gemini.'); } } else { console.error('Gemini request failed:', response); let errorMsg = `Ошибка ${response.status}: ${response.statusText}`; if (responseData?.error?.message) { errorMsg += `\n${responseData.error.message}`; } if (response.status === 400 && errorMsg.includes("API key not valid")) { settingsIcon.click(); } else if (response.status === 429) { errorMsg = 'Ошибка 429: Превышен лимит запросов Google AI.'; } reject(errorMsg); } }, onerror: function(response) { if(loadingIndicator) loadingIndicator.remove(); if(buttonElement) buttonElement.disabled = false; console.error('GM_xmlhttpRequest error:', response); reject('Сетевая ошибка при запросе к Google Gemini API.'); } }); });
    }

    function sendToTelegramViaBot(textToSend, buttonElement) {
        const botToken = GM_getValue(TELEGRAM_BOT_TOKEN_STORAGE);
        const chatId = GM_getValue(TELEGRAM_CHAT_ID_STORAGE);
        if (!botToken || !chatId) {
            alert("Telegram Bot Token и Chat ID не настроены. Отправка в Telegram невозможна. Вы можете настроить их в меню настроек (🔑).");
            return Promise.reject("TG Bot не настроен");
        }
        let loadingIndicator;
        if(buttonElement) {
            loadingIndicator = document.createElement('span');
            loadingIndicator.className = 'br-ai-loading';
            buttonElement.parentNode.insertBefore(loadingIndicator, buttonElement.nextSibling);
            buttonElement.disabled = true;
        }
        return new Promise((resolve, reject) => {
            GM_xmlhttpRequest({
                method: 'POST',
                url: `https://api.telegram.org/bot${botToken}/sendMessage`,
                headers: { 'Content-Type': 'application/json' },
                data: JSON.stringify({ chat_id: chatId, text: textToSend, parse_mode: 'HTML' }),
                responseType: 'json',
                onload: function(response) {
                    if(loadingIndicator) loadingIndicator.remove();
                    if(buttonElement) buttonElement.disabled = false;
                    const responseData = response.response;
                    if (response.status === 200 && responseData.ok) {
                        console.log("Сообщение успешно отправлено в Telegram:", responseData);
                        const successMsg = document.createElement('span');
                        successMsg.innerText = '✅ Отправлено';
                        successMsg.style.color = 'green';
                        successMsg.style.fontSize = '10px';
                        successMsg.style.marginLeft = '5px';
                        buttonElement.parentNode.insertBefore(successMsg, buttonElement.nextSibling);
                        setTimeout(() => successMsg.remove(), 2000);
                        resolve(responseData);
                    } else {
                        console.error("Ошибка отправки в Telegram:", response);
                        let errorMsg = `Ошибка TG ${response.status}: ${response.statusText}`;
                        if (responseData && !responseData.ok) {
                            errorMsg += `\n(${responseData.error_code}) ${responseData.description}`;
                        }
                        alert(errorMsg);
                        reject(errorMsg);
                    }
                },
                onerror: function(response) {
                    if(loadingIndicator) loadingIndicator.remove();
                    if(buttonElement) buttonElement.disabled = false;
                    console.error('GM_xmlhttpRequest error (Telegram):', response);
                    alert('Сетевая ошибка при отправке сообщения в Telegram.');
                    reject('Сетевая ошибка TG.');
                }
            });
        });
    }

    function addTelegramShareButton(parentElement, textToShare, buttonClass = 'br-ai-button-telegram') {
        const button = document.createElement('button'); button.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" fill="currentColor" viewBox="0 0 16 16"><path d="M16 8A8 8 0 1 1 0 8a8 8 0 0 1 16 0zM8.287 5.906c-.778.324-2.334.994-4.666 2.01-.378.15-.577.298-.595.442-.03.243.275.339.69.47l.175.055c.408.133.958.288 1.243.294.26.006.549-.1.868-.32 2.179-1.471 3.304-2.214 3.374-2.23.05-.012.12-.026.166.016.047.041.042.12.037.141-.03.129-1.227 1.241-1.846 1.817-.193.18-.33.307-.358.336a8.154 8.154 0 0 1-.188.186c-.38.366-.664.64.015 1.088.327.216.589.393.85.571.284.194.568.387.936.629.093.06.183.125.27.187.331.236.63.448.997.414.214-.02.435-.22.547-.82.265-1.417.786-4.486.906-5.751a1.426 1.426 0 0 0-.013-.315.337.337 0 0 0-.114-.217.526.526 0 0 0-.31-.093c-.3.005-.763.166-2.984 1.09z"/></svg>`; button.title = "Поделиться в Telegram"; button.className = `br-ai-button ${buttonClass}`; button.style.marginLeft = '5px'; button.onclick = (e) => { e.preventDefault(); e.stopPropagation(); const encodedText = encodeURIComponent(textToShare); const telegramUrl = `https://t.me/share/url?text=${encodedText}`; window.open(telegramUrl, '_blank'); }; parentElement.appendChild(button);
     }

    function addReplyButtons() {
        const replyForm = document.querySelector('form.message-response-form, form[action*="add-reply"]'); const textarea = replyForm?.querySelector('textarea[name="message"]'); if (replyForm && textarea) { let buttonContainer = replyForm.querySelector('.br-ai-button-container'); if (!buttonContainer) { buttonContainer = document.createElement('div'); buttonContainer.className = 'br-ai-button-container'; buttonContainer.style.marginTop = '5px'; const submitRow = replyForm.querySelector('.formSubmitRow'); if (submitRow) { submitRow.parentNode.insertBefore(buttonContainer, submitRow); } else { textarea.parentNode.insertBefore(buttonContainer, textarea.nextSibling); } } buttonContainer.innerHTML = ''; const genButton = document.createElement('button'); genButton.innerText = '🇬 Ответ (Gemini)'; genButton.className = 'br-ai-button br-ai-button-reply'; genButton.type = 'button'; genButton.onclick = async (e) => { const currentButton = e.target; let postContent = ''; let threadTitle = document.querySelector('.p-title-value')?.innerText || 'Неизвестная тема'; const quotedPost = textarea.closest('form').querySelector('.bbCodeBlock--quote .bbCodeBlock-content'); if (quotedPost) { postContent = quotedPost.innerText.trim(); } else { const lastPost = Array.from(document.querySelectorAll('.message .message-content')).pop(); if(lastPost) postContent = lastPost.innerText.trim().substring(0, 1000); } let prompt = `Ты - полезный AI ассистент на игровом форуме Black Russia (GTA RP). Тема обсуждения: "${threadTitle}". ${postContent ? `Пользователь отвечает на следующее сообщение:\n"""\n${postContent}\n"""\n` : ''} Напиши подходящий ответ на форум. Будь вежлив, конструктивен и придерживайся темы. Не используй приветствия вроде "Привет!". Пиши только сам текст ответа.`; try { const aiResponse = await callGeminiAPI(prompt, currentButton); if (aiResponse) { textarea.value += (textarea.value ? '\n\n' : '') + aiResponse; textarea.focus(); textarea.dispatchEvent(new Event('input', { bubbles: true })); } } catch (error) { console.error("Ошибка генерации ответа (Gemini):", error); alert(`Ошибка генерации ответа:\n${error}`); } }; buttonContainer.appendChild(genButton); const checkButton = document.createElement('button'); checkButton.innerText = '✔️ Проверить текст'; checkButton.className = 'br-ai-button br-ai-button-tertiary'; checkButton.type = 'button'; checkButton.onclick = async (e) => { const currentButton = e.target; const originalText = textarea.value.trim(); if (!originalText) { alert("Поле ввода пустое. Нечего проверять."); return; } const modal = document.getElementById('br-ai-correction-modal'); const originalTextArea = modal.querySelector('#br-ai-original-text'); const correctedTextArea = modal.querySelector('#br-ai-corrected-text'); const loadingDiv = modal.querySelector('#br-ai-correction-loading'); originalTextArea.value = originalText; correctedTextArea.value = ""; loadingDiv.style.display = 'block'; modal.style.display = 'block'; window.activeCorrectionTextarea = textarea; const prompt = `Проверь и исправь грамматику, орфографию и пунктуацию в следующем тексте, сохраняя основной смысл. Выведи только исправленный текст:\n\n"""${originalText}"""`; try { const aiResponse = await callGeminiAPI(prompt, null); if (aiResponse) { correctedTextArea.value = aiResponse; } else { correctedTextArea.value = "Не удалось получить исправления."; } } catch (error) { console.error("Ошибка проверки текста:", error); correctedTextArea.value = `Ошибка: ${error.message || error}`; } finally { loadingDiv.style.display = 'none'; } }; buttonContainer.appendChild(checkButton);

        // --- Добавляем кнопки быстрых ответов ---
        const quickRepliesContainer = document.createElement('div');
        quickRepliesContainer.style.marginTop = '10px';

        const quickReplyPrompts = [
            { label: '👍 Согласен', prompt: 'Напиши короткое сообщение в стиле "Согласен с тобой", "Поддерживаю", "Отличная идея!" и т.п.' },
            { label: '🤔 Спросить', prompt: 'Задай короткий уточняющий вопрос по теме.' },
            { label: '😊 Спасибо', prompt: 'Напиши короткое благодарственное сообщение.' },
            { label: '😄 Забавно', prompt: 'Напиши короткий комментарий в стиле "Смешно", "Забавно", "Повеселило" и т.п.' },
            { label: '😔 Жаль', prompt: 'Напиши короткое сообщение выражающее сожаление или сочувствие.' },
        ];

        quickReplyPrompts.forEach(reply => {
            const quickReplyButton = document.createElement('button');
            quickReplyButton.innerText = reply.label;
            quickReplyButton.className = 'br-ai-button br-ai-button-quaternary';
            quickReplyButton.style.fontSize = '11px';
            quickReplyButton.style.padding = '4px 8px';
            quickReplyButton.style.marginRight = '5px';
            quickReplyButton.type = 'button';
            quickReplyButton.onclick = async (e) => {
                const currentButton = e.target;
                let threadTitle = document.querySelector('.p-title-value')?.innerText || 'Неизвестная тема';
                let quotedPost = textarea.closest('form').querySelector('.bbCodeBlock--quote .bbCodeBlock-content')?.innerText.trim() || '';
                let context = `Тема: "${threadTitle}". ${quotedPost ? `Процитированное сообщение: "${quotedPost}". ` : ''}`;
                let fullPrompt = `Ты - AI ассистент на форуме Black Russia. ${context} Используй следующий запрос для генерации ответа: "${reply.prompt}". Ответ должен быть коротким, вежливым и соответствовать контексту форума. Не начинай с приветствий.`;
                try {
                    const aiResponse = await callGeminiAPI(fullPrompt, currentButton);
                    if (aiResponse) {
                        textarea.value += (textarea.value ? '\n\n' : '') + aiResponse;
                        textarea.focus();
                        textarea.dispatchEvent(new Event('input', { bubbles: true }));
                    }
                } catch (error) {
                    console.error("Ошибка быстрого ответа (Gemini):", error);
                    alert(`Ошибка генерации быстрого ответа:\n${error}`);
                }
            };
            quickRepliesContainer.appendChild(quickReplyButton);
        });

        buttonContainer.appendChild(quickRepliesContainer);
    }
    }

    function addPostButtons() {
        const posts = document.querySelectorAll('.message:not(.br-ai-processed)');
        posts.forEach(post => {
            const messageContentElement = post.querySelector('.message-content');
            const messageActionBar = post.querySelector('.message-actionBar .actionBar-set--internal');

            if (messageContentElement && messageActionBar) {
                let customActionsContainer = messageActionBar.querySelector('.br-ai-post-actions');
                if (!customActionsContainer) { customActionsContainer = document.createElement('span'); customActionsContainer.className = 'br-ai-post-actions'; const divider = document.createElement('span'); divider.className = 'actionBar-action'; divider.innerHTML = '&middot;'; divider.style.marginLeft = '10px'; messageActionBar.appendChild(divider); messageActionBar.appendChild(customActionsContainer); }
                else { customActionsContainer.innerHTML = ''; }

                // Кнопка "Кратко" (с иконкой и в модальном окне)
                const summarizeButton = document.createElement('button');
                summarizeButton.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M2 2v12h12V2H2zm12-1a1 1 0 0 1 1 1v12a1 1 0 0 1-1 1H2a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h12z"/><path fill-rule="evenodd" d="M3.5 4a.5.5 0 0 1 .5-.5h8a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5H4a.5.5 0 0 1-.5-.5V4zm0 3a.5.5 0 0 1 .5-.5h8a.5.5 0 0 1 .5.5v1a.5.5 0 0 1-.5.5H4a.5.5 0 0 1-.5-.5V7zm0 3a.5.5 0 0 1 .5-.5h4a.5.5 0 0 1 0 1H4a.5.5 0 0 1-.5-.5v-1z"/></svg>`;
                summarizeButton.title = 'Кратко (Gemini)';
                summarizeButton.className = 'br-ai-button br-ai-button-secondary button--link';
                summarizeButton.style.padding = '5px';
                summarizeButton.style.fontSize = '14px';
                summarizeButton.onclick = async (e) => {
                    const currentButton = e.target; const postText = messageContentElement.innerText.trim(); const textWithoutQuotes = postText.replace(/Цитата.*?:\s*[\r\n]+.*?[\r\n]+/gis, ''); if (textWithoutQuotes.length < 100) { alert('Этот пост слишком короткий для краткого изложения.'); return; } const prompt = `Сделай краткое изложение (summary) следующего текста с форума Black Russia. Выдели главную мысль.\n\nТекст:\n"""\n${textWithoutQuotes.substring(0, 2000)}\n"""\n\nКраткое изложение:`;
                    showSummary('', callGeminiAPI(prompt, currentButton));
                };
                customActionsContainer.appendChild(summarizeButton);

                // *** НОВАЯ КНОПКА: Анализ стиля поста ***
                const analyzeStyleButton = document.createElement('button');
                analyzeStyleButton.innerText = '🤔 Стиль поста';
                analyzeStyleButton.title = 'Анализировать стиль написания поста (Gemini)';
                analyzeStyleButton.className = 'br-ai-button br-ai-button-quaternary button--link';
                analyzeStyleButton.onclick = async (e) => {
                    const currentButton = e.target;
                    const postText = messageContentElement.innerText.trim();
                    const prompt = `Определи стиль написания следующего текста с форума Black Russia (например, формальный, неформальный, саркастичный, эмоциональный, агрессивный, вежливый и т.д.). Выведи только одну характеристику стиля.\n\nТекст:\n"""\n${postText.substring(0, 1500)}\n"""\n\nСтиль поста:`;
                    showAIResponse('Стиль поста', postText.substring(0, 500) + '...', callGeminiAPI(prompt, currentButton));
                };
                customActionsContainer.appendChild(analyzeStyleButton);

                // *** НОВАЯ КНОПКА: Краткое содержание в эмодзи ***
                const emojiTLDRButton = document.createElement('button');
                emojiTLDRButton.innerText = '😂 TL;DR (Emoji)';
                emojiTLDRButton.title = 'Сделать краткое содержание поста в виде эмодзи (Gemini)';
                emojiTLDRButton.className = 'br-ai-button br-ai-button-tertiary button--link';
                emojiTLDRButton.onclick = async (e) => {
                    const currentButton = e.target;
                    const postText = messageContentElement.innerText.trim();
                    if (postText.length < 100) {
                        alert('Этот пост слишком короткий для создания TL;DR в эмодзи.');
                        return;
                    }
                    const prompt = `Сделай очень краткое содержание (TL;DR) следующего текста с форума Black Russia, используя только эмодзи (максимум 5-7 эмодзи).\n\nТекст:\n"""\n${postText.substring(0, 1500)}\n"""\n\nTL;DR (Emoji):`;
                    showAIResponse('TL;DR (Emoji)', postText.substring(0, 500) + '...', callGeminiAPI(prompt, currentButton));
                };
                customActionsContainer.appendChild(emojiTLDRButton);

                // Кнопка "Выделение ключевых аргументов/мыслей"
                const findArgumentsButton = document.createElement('button');
                findArgumentsButton.innerText = '💡 Аргументы';
                findArgumentsButton.title = 'Выделить ключевые аргументы/мысли (Gemini)';
                findArgumentsButton.className = 'br-ai-button br-ai-button-quaternary button--link';
                findArgumentsButton.onclick = async (e) => {
                    const currentButton = e.target;
                    const postText = messageContentElement.innerText.trim();
                    const prompt = `Проанализируй следующий текст с форума Black Russia и выдели основные аргументы или ключевые мысли автора. Представь их в виде списка.\n\nТекст:\n"""\n${postText}\n"""\n\nКлючевые аргументы:`;
                    showAIResponse('Ключевые аргументы', postText.substring(0, 500) + '...', callGeminiAPI(prompt, currentButton));
                };
                customActionsContainer.appendChild(findArgumentsButton);

                // Кнопка "AI Вопрос"
                const questionButton = document.createElement('button'); questionButton.innerText = '❓ AI Вопрос'; questionButton.className = 'br-ai-button br-ai-button-quaternary button--link';
                questionButton.onclick = async (e) => {
                    const currentButton = e.target;
                    const userQuestion = window.prompt("Ваш вопрос об этом посте:");
                    if (!userQuestion || !userQuestion.trim()) return;

                    const postText = messageContentElement.innerText.trim();
                    const prompt = `Проанализируй следующий текст с форума:\n"""\n${postText}\n"""\n\nТеперь ответь на вопрос пользователя:\n"""\n${userQuestion}\n"""`;

                    showAIResponse(
                        `Ответ на вопрос: "${userQuestion}"`,
                        `Пост:\n${postText.substring(0, 500)}...\n\nВопрос:\n${userQuestion}`,
                        callGeminiAPI(prompt, currentButton)
                    );
                };
                customActionsContainer.appendChild(questionButton);

                // *** НОВАЯ КНОПКА: Объяснение игрового жаргона/терминов ***
                const explainTermButton = document.createElement('button');
                explainTermButton.innerText = '🎮 Жаргон';
                explainTermButton.title = 'Объяснить игровой жаргон/термин (Gemini)';
                explainTermButton.className = 'br-ai-button br-ai-button-tertiary button--link';
                explainTermButton.onclick = async (e) => {
                    const currentButton = e.target;
                    const postText = messageContentElement.innerText.trim();
                    const termToExplain = window.prompt("Введите игровой жаргон или термин, который вы хотите объяснить из этого поста:");
                    if (!termToExplain || !termToExplain.trim()) return;

                    const prompt = `Объясни значение следующего термина/жаргона "${termToExplain}" в контексте следующего текста с форума Black Russia:\n\nТекст:\n"""\n${postText}\n"""\n\nОбъяснение:`;
                    showAIResponse(`Объяснение термина: "${termToExplain}"`, `Термин: ${termToExplain}\nПост:\n${postText.substring(0, 500)}...`, callGeminiAPI(prompt, currentButton));
                };
                customActionsContainer.appendChild(explainTermButton);

                // Кнопка "Поделиться постом в TG (Клиент)"
                const postTextForTelegram = messageContentElement.innerText.trim();
                addTelegramShareButton(customActionsContainer, `Пост с форума Black Russia:\n\n${postTextForTelegram.substring(0, 1000)}${postTextForTelegram.length > 1000 ? '...' : ''}`);

                // *** НОВАЯ КНОПКА: Быстрая отправка поста в TG (Через Бота) ***
                const sendFullToBotButton = document.createElement('button');
                sendFullToBotButton.innerText = '🚀 Отпр. весь в TG';
                sendFullToBotButton.title = "Отправить весь текст поста в Telegram через бота";
                sendFullToBotButton.className = 'br-ai-button br-ai-button-telegram-bot button--link';
                sendFullToBotButton.onclick = async (e) => {
                    const currentButton = e.target;
                    const postText = messageContentElement.innerText.trim();
                    const threadTitle = document.querySelector('.p-title-value')?.innerText || 'Неизвестная тема';
                    const postUrl = window.location.href.split('#')[0];
                    const messageHtml = `<b>Пост с форума BR</b>\n\n<b>Тема:</b> ${threadTitle}\n\n${postText}\n\n<a href="${postUrl}">Ссылка на пост</a>`;
                    if (!GM_getValue(TELEGRAM_BOT_TOKEN_STORAGE) || !GM_getValue(TELEGRAM_CHAT_ID_STORAGE)) {
                        alert("Telegram Bot Token и Chat ID не настроены. Пожалуйста, настройте их в меню настроек (🔑), чтобы использовать эту функцию.");
                        return;
                    }
                    currentButton.disabled = true;
                    const loading = document.createElement('span');
                    loading.className='br-ai-loading';
                    currentButton.parentNode.insertBefore(loading, currentButton.nextSibling);
                    try {
                        await sendToTelegramViaBot(messageHtml, currentButton);
                    } catch (error) {
                        console.error("Ошибка при отправке полного поста через бота:", error);
                        currentButton.disabled = false;
                    } finally {
                        loading.remove();
                    }
                };
                customActionsContainer.appendChild(sendFullToBotButton);

                // Кнопка "Отправить пост в TG (Через Бота, с краткой сводкой)"
                const sendViaBotButton = document.createElement('button'); sendViaBotButton.innerText = '🤖 Отпр. в TG'; sendViaBotButton.title = "Отправить сводку поста в Telegram через бота"; sendViaBotButton.className = 'br-ai-button br-ai-button-telegram-bot button--link';
                sendViaBotButton.onclick = async (e) => {
                     const currentButton = e.target; const postText = messageContentElement.innerText.trim(); const threadTitle = document.querySelector('.p-title-value')?.innerText || 'Неизвестная тема'; const postUrl = window.location.href.split('#')[0];
                     const prompt = `Сделай очень краткую выжимку (одно-два предложения, до 50 слов) из следующего поста с форума Black Russia для быстрой отправки в Telegram. Укажи главную суть.\n\nТема: ${threadTitle}\nПост:\n"""\n${postText.substring(0, 1500)}\n"""`;
                     if (!GM_getValue(TELEGRAM_BOT_TOKEN_STORAGE) || !GM_getValue(TELEGRAM_CHAT_ID_STORAGE)) {
                        alert("Telegram Bot Token и Chat ID не настроены. Пожалуйста, настройте их в меню настроек (🔑), чтобы использовать эту функцию.");
                        return;
                    }
                     currentButton.disabled = true; const loading = document.createElement('span'); loading.className='br-ai-loading'; currentButton.parentNode.insertBefore(loading, currentButton.nextSibling); try { const summary = await callGeminiAPI(prompt, null); if (summary) { const messageHtml = `<b>Сводка поста с форума BR</b>\n\n<b>Тема:</b> ${threadTitle}\n<b>Суть:</b> ${summary}\n\n<a href="${postUrl}">Ссылка на пост</a>`; await sendToTelegramViaBot(messageHtml, currentButton); } else { await sendToTelegramViaBot(`Не удалось получить сводку.\n<a href="${postUrl}">Ссылка на пост</a>`, currentButton); } } catch (error) { console.error("Ошибка при отправке поста через бота:", error); currentButton.disabled = false; } finally { loading.remove(); }
                 };
                customActionsContainer.appendChild(sendViaBotButton);

                post.classList.add('br-ai-processed');
            }
        });
    }

    // Простая функция для подбора эмодзи (можно улучшить)
    function getEmojiForSection(title) {
        title = title.toLowerCase();
        if (title.includes('обсуждение') || title.includes('разговоры')) return '🗣️';
        if (title.includes('помощь') || title.includes('вопросы')) return '❓';
        if (title.includes('жалобы') || title.includes('нарушения')) return '🚨';
        if (title.includes('предложения') || title.includes('улучшения')) return '💡';
        if (title.includes('новости') || title.includes('обновления')) return '📰';
        if (title.includes('торговля') || title.includes('барахолка')) return '💰';
        if (title.includes('сервер') || title.includes('миры')) return '🌍';
        if (title.includes('кланы') || title.includes('семьи')) return '🏘️';
        if (title.includes('творчество') || title.includes('скриншоты') || title.includes('видео')) return '🎨';
        if (title.includes('архив')) return '📜';
        return '📄'; // Default emoji
    }

    // --- Initialization & MutationObserver ---
    function initializeHelper() { console.log(`Black Russia AI Helper (Gemini v${GM_info.script.version}): Инициализация...`); addReplyButtons(); addPostButtons(); }
    initializeHelper();
    let lastUrl = location.href; let initTimer;
    new MutationObserver(() => { const url = location.href; if (url !== lastUrl) { lastUrl = url; clearTimeout(initTimer); initTimer = setTimeout(initializeHelper, 500); } else { clearTimeout(initTimer); initTimer = setTimeout(() => { addPostButtons(); addReplyButtons(); }, 300); } }).observe(document.body, { subtree: true, childList: true });

    // *** АВТОМАТИЧЕСКОЕ ПРИМЕНЕНИЕ ИСПРАВЛЕНИЙ ***
    const correctionModal = document.getElementById('br-ai-correction-modal');
    if (correctionModal) {
        const applyCorrectionButton = correctionModal.querySelector('#br-ai-apply-correction');
        if (applyCorrectionButton) {
            applyCorrectionButton.onclick = () => {
                const correctedText = correctionModal.querySelector('#br-ai-corrected-text').value;
                const targetTextarea = window.activeCorrectionTextarea;
                if(targetTextarea) {
                    targetTextarea.value = correctedText;
                    targetTextarea.dispatchEvent(new Event('input', { bubbles: true }));
                    targetTextarea.focus();
                }
                correctionModal.style.display = 'none';
            };
        }
    }

})();