Замечание: Возможно, после публикации вам придётся очистить кэш своего браузера, чтобы увидеть изменения.

  • Firefox / Safari: Удерживая клавишу Shift, нажмите на панели инструментов Обновить либо нажмите Ctrl+F5 или Ctrl+R (⌘+R на Mac)
  • Google Chrome: Нажмите Ctrl+Shift+R (⌘+Shift+R на Mac)
  • Edge: Удерживая Ctrl, нажмите Обновить либо нажмите Ctrl+F5
  • Opera: Нажмите Ctrl+F5.
/**
 * Gadget: Blame Finder
 * Версия 2.0 с поддержкой ночного режима и петаскиванием кнопки
 * Назначение: поиск автора любого текста в статье
 * Локализация под wiki.peresvet.artushak.ru, лицензия: CC BY-SA 4.0
 * Использование:
  1. Нажимаете кнопку «Кто автор?» в правом нижнем углу
  2. Выделяете любой текст на странице (минимум 20 символов)
  3. Кликайте по появившейся в центре кнопке таймера (20 секунд на всё)
  4. Гаджет анализирует последние 1000 правок страницы
  5. Находит первое появление этого текста в истории
  6. Показывает:
   · Имя автора
   · Дату правки
   · Комментарий к правке
   · Ссылки на версию и diff
 * Что может:
  · Искать авторов фрагментов текста в статьях
  · Расчитан на работу в пространствах статей и форума
  · Поддерживает мышь и сенсорный экран
  · Показывает панель логов с отладкой
 */

(function() {
    'use strict';

    if (window.self !== window.top) {
        console.log('BlameFinder: не запускаемся в iframe по соображениям безопасности');
        return;
    }

    var scriptPath = '/w';
    try {
        if (typeof mw !== 'undefined' && mw.config && mw.config.get) {
            scriptPath = mw.config.get('wgScriptPath') || '/w';
        }
    } catch (e) {
        scriptPath = '/w';
    }

    var BUTTON_STORAGE_KEY = 'blameFinderButtonPos';
    var LOG_WIDTH = 380;
    var LOG_MAX_HEIGHT_CSS = 'min(300px, 50vh)';

    function escapeText(text, escapeSlash) {
        if (text === undefined || text === null) return '';
        var s = String(text)
            .replace(/&/g, '&')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
        if (escapeSlash) {
            s = s.replace(/\//g, '&#x2F;');
        }
        return s;
    }

    function escapeHtml(text) {
        return escapeText(text, true);
    }

    function escapeForLog(text) {
        return escapeText(text, false);
    }

    function sanitizeUrl(url) {
        if (!url || typeof url !== 'string') return null;
        var trimmed = url.trim();
        if (trimmed === '') return null;
        if (trimmed.charAt(0) === '/' || trimmed.charAt(0) === '#') {
            return trimmed;
        }
        try {
            var parsed = new URL(trimmed, window.location.origin);
            if (parsed.protocol === 'https:' || parsed.protocol === 'http:') {
                return trimmed;
            }
        } catch (e) {}
        return null;
    }

    function createSafeElement(tag, options) {
        var element = document.createElement(tag);
        if (!options) return element;
        if (options.className) element.className = options.className;
        if (options.id) element.id = options.id;
        if (options.text) element.textContent = options.text;
        if (options.html) element.textContent = options.html;

        if (options.css) {
            Object.keys(options.css).forEach(function(prop) {
                element.style[prop] = options.css[prop];
            });
        }

        if (options.attrs) {
            Object.keys(options.attrs).forEach(function(key) {
                if (key === 'href' || key === 'src') {
                    var safe = sanitizeUrl(options.attrs[key]);
                    if (safe !== null) element.setAttribute(key, safe);
                } else {
                    element.setAttribute(key, options.attrs[key]);
                }
            });
        }
        return element;
    }

    function createSafeLink(url, text, title) {
        var safeUrl = sanitizeUrl(url) || '#';
        return createSafeElement('a', {
            text: text,
            attrs: {
                href: safeUrl,
                target: '_blank',
                rel: 'noopener noreferrer',
                title: title ? escapeHtml(title) : escapeHtml(text)
            }
        });
    }

    function validateTitle(title) {
        if (!title || typeof title !== 'string') return null;
        var cleaned = title.replace(/[\x00-\x1F\x7F<>"']/g, '').trim();
        return cleaned.length > 0 ? cleaned : null;
    }

    function isDarkTheme() {
        try {
            var html = document.documentElement;
            var body = document.body;
            if (html.classList.contains('skin-theme-clientpref-night')) return true;
            if (html.classList.contains('skin-theme-clientpref-day')) return false;
            if (html.classList.contains('skin-theme-clientpref-os')) {
                return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
            }
            var dataTheme = (html.getAttribute('data-theme') || '') + ' ' +
                            (body ? (body.getAttribute('data-theme') || '') : '');
            if (/dark|night/i.test(dataTheme)) return true;
            if (/light|day/i.test(dataTheme)) return false;
            if (body) {
                var bg = window.getComputedStyle(body).backgroundColor;
                var m = bg.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/i);
                if (m) {
                    var r = parseInt(m[1], 10);
                    var g = parseInt(m[2], 10);
                    var b = parseInt(m[3], 10);
                    var luminance = (0.299 * r + 0.587 * g + 0.114 * b);
                    if (luminance < 128) return true;
                    if (luminance >= 128) return false;
                }
            }
        } catch (e) {}
        return false;
    }

    function getPageInfo() {
        var title = null;
        var namespace = 0;
        var isSpecial = false;
        var pathname = window.location.pathname || '';
        var search = window.location.search || '';

        var excludedNamespaces = [
            'обсуждение', 'talk', 'участник', 'user', 'user_talk',
            'обсуждение_участника', 'файл', 'file', 'file_talk',
            'обсуждение_файла', 'mediawiki', 'mediawiki_talk',
            'обсуждение_mediawiki', 'шаблон', 'template',
            'template_talk', 'обсуждение_шаблона', 'справка',
            'help', 'help_talk', 'обсуждение_справки', 'категория',
            'category', 'category_talk', 'обсуждение_категории',
            'портал', 'portal', 'portal_talk', 'обсуждение_портала',
            'special', 'служебная'
        ];

        function classifyTitle(candidate) {
            if (!candidate) return;
            if (candidate.indexOf(':') !== -1) {
                var prefix = candidate.split(':')[0].toLowerCase();
                if (excludedNamespaces.indexOf(prefix) !== -1) namespace = 1;
                if (prefix === 'special' || prefix === 'служебная') isSpecial = true;
            }
        }

        try {
            var urlParams = new URLSearchParams(search);
            var paramTitle = urlParams.get('title');
            if (paramTitle) {
                paramTitle = validateTitle(paramTitle);
                if (paramTitle) {
                    classifyTitle(paramTitle);
                    title = paramTitle;
                }
            }

            if (!title) {
                if (/special:|служебная:/i.test(pathname)) isSpecial = true;

                if (pathname.indexOf('/wiki/') !== -1) {
                    var pathTitle = pathname.split('/wiki/')[1];
                    if (pathTitle) {
                        try { pathTitle = decodeURIComponent(pathTitle); } catch (e) {}
                        pathTitle = pathTitle.split('?')[0].split('#')[0];
                        classifyTitle(pathTitle);
                        title = validateTitle(pathTitle);
                    }
                } else {
                    var segments = pathname.split('/').filter(function(s) { return s.length > 0; });
                    if (segments.length > 0) {
                        var rootTitle = segments[segments.length - 1];
                        try { rootTitle = decodeURIComponent(rootTitle); } catch (e) {}
                        rootTitle = rootTitle.split('?')[0].split('#')[0];
                        classifyTitle(rootTitle);
                        title = validateTitle(rootTitle);
                    }
                }
            }

            if (!title) {
                var h1 = document.querySelector('h1.firstHeading, .firstHeading, #firstHeading');
                if (h1 && h1.textContent) title = validateTitle(h1.textContent.trim());
            }
        } catch (e) {
            console.log('BlameFinder: ошибка получения информации о странице', e);
        }

        return { title: title || 'Main_Page', isArticle: namespace === 0 && !isSpecial };
    }

    function absApiRequest(params, callback, errorCallback) {
        var apiUrl = scriptPath + '/api.php';
        params.format = 'json';

        var safeParams = {};
        Object.keys(params).forEach(function(key) {
            var value = params[key];
            if (typeof value === 'string') {
                safeParams[key] = value.replace(/[<>"']/g, '');
            } else {
                safeParams[key] = value;
            }
        });

        var queryString = Object.keys(safeParams).map(function(key) {
            return encodeURIComponent(key) + '=' + encodeURIComponent(safeParams[key]);
        }).join('&');

        var url = apiUrl + '?' + queryString;
        var xhr = new XMLHttpRequest();
        var timeoutId = null;
        var completed = false;

        timeoutId = setTimeout(function() {
            if (!completed) {
                completed = true;
                xhr.abort();
                addLog('Таймаут API: сервер не отвечает', 'error');
                if (errorCallback) errorCallback('timeout');
            }
        }, 15000);

        xhr.open('GET', url, true);
        xhr.setRequestHeader('Api-User-Agent', 'BlameFinder/2.0');

        xhr.onreadystatechange = function() {
            if (completed) return;
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    var contentType = xhr.getResponseHeader('Content-Type') || '';
                    if (contentType.indexOf('application/json') === -1 &&
                        contentType.indexOf('text/javascript') === -1) {
                        clearTimeout(timeoutId);
                        completed = true;
                        addLog('Неверный Content-Type ответа API', 'error');
                        if (errorCallback) errorCallback('invalid_content_type');
                        return;
                    }
                    try {
                        var data = JSON.parse(xhr.responseText);
                        if (!data || typeof data !== 'object') throw new Error('Invalid response format');
                        clearTimeout(timeoutId);
                        completed = true;
                        callback(data);
                    } catch (e) {
                        clearTimeout(timeoutId);
                        completed = true;
                        addLog('Ошибка парсинга ответа API', 'error');
                        if (errorCallback) errorCallback('parse_error');
                    }
                } else {
                    clearTimeout(timeoutId);
                    completed = true;
                    addLog('Ошибка HTTP: ' + xhr.status, 'error');
                    if (errorCallback) errorCallback('http_' + xhr.status);
                }
            }
        };

        xhr.onerror = function() {
            if (!completed) {
                clearTimeout(timeoutId);
                completed = true;
                addLog('Ошибка сети при запросе к API', 'error');
                if (errorCallback) errorCallback('network_error');
            }
        };

        xhr.send();
    }

    // ===== ЛОГ-ПАНЕЛЬ =====
    var logPanel = null;
    var logEntries = [];
    var logVisible = false;

    function createLogPanel() {
        if (logPanel) return;

        logPanel = createSafeElement('div', {
            id: 'blame-log-panel',
            css: {
                position: 'fixed',
                bottom: '80px',
                right: '20px',
                width: LOG_WIDTH + 'px',
                maxHeight: LOG_MAX_HEIGHT_CSS,
                overflowY: 'auto',
                background: 'rgba(0,0,0,0.9)',
                color: '#0f0',
                fontFamily: 'monospace',
                fontSize: '12px',
                padding: '10px',
                borderRadius: '5px',
                zIndex: '9999',
                border: '2px solid #36c',
                boxShadow: '0 0 20px rgba(0,0,0,0.5)',
                display: 'none'
            }
        });

        var header = createSafeElement('div', {
            css: {
                display: 'flex',
                justifyContent: 'space-between',
                marginBottom: '10px',
                paddingBottom: '5px',
                borderBottom: '2px solid #36c'
            }
        });

        var titleSpan = createSafeElement('span', {
            text: 'Логи BlameFinder',
            css: { color: '#36c', fontWeight: 'bold' }
        });

        var buttonContainer = createSafeElement('div');

        var clearButton = createSafeElement('button', {
            id: 'blame-clear',
            className: 'blame-log-btn',
            text: 'Очистить',
            css: {
                background: 'none',
                border: '1px solid #36c',
                color: '#36c',
                marginRight: '5px',
                cursor: 'pointer',
                padding: '5px'
            }
        });

        var toggleButton = createSafeElement('button', {
            id: 'blame-toggle',
            className: 'blame-log-btn',
            text: 'Скрыть',
            css: {
                background: 'none',
                border: '1px solid #36c',
                color: '#36c',
                cursor: 'pointer',
                padding: '5px'
            }
        });

        ['color', 'border-color'].forEach(function(prop) {
            clearButton.style.setProperty(prop, '#36c', 'important');
            toggleButton.style.setProperty(prop, '#36c', 'important');
        });
        clearButton.style.setProperty('background', 'none', 'important');
        toggleButton.style.setProperty('background', 'none', 'important');

        buttonContainer.appendChild(clearButton);
        buttonContainer.appendChild(toggleButton);
        header.appendChild(titleSpan);
        header.appendChild(buttonContainer);

        var content = createSafeElement('div', {
            id: 'blame-log-content',
            css: { wordBreak: 'break-word' }
        });

        logPanel.appendChild(header);
        logPanel.appendChild(content);
        document.body.appendChild(logPanel);

        clearButton.onclick = function(e) {
            e.stopPropagation();
            logEntries = [];
            updateLogDisplay();
        };

        toggleButton.onclick = function(e) {
            e.stopPropagation();
            logVisible = !logVisible;
            logPanel.style.display = logVisible ? 'block' : 'none';
            toggleButton.textContent = logVisible ? 'Скрыть' : 'Показать';
            syncLogToggleLabel();
        };

        logPanel.style.display = 'none';
    }

    function showLogPanel() {
        if (!logPanel) return;
        if (logVisible) return;
        logVisible = true;
        logPanel.style.display = 'block';
        syncLogToggleLabel();
        positionLogPanelNearButton();
    }

    function syncLogToggleLabel() {
        var toggle = document.getElementById('blame-toggle');
        if (toggle) toggle.textContent = logVisible ? 'Скрыть' : 'Показать';
    }

    function positionLogPanelNearButton() {
        if (!logPanel) return;
        var btn = document.getElementById('blame-finder-button');
        if (!btn) return;

        var r = btn.getBoundingClientRect();
        var panelW = Math.min(LOG_WIDTH, window.innerWidth - 20);
        var panelH = Math.min(300, window.innerHeight * 0.5);

        var left = r.left;
        if (left + panelW > window.innerWidth - 10) {
            left = Math.max(10, window.innerWidth - panelW - 10);
        }

        var top = r.top - panelH - 10;
        if (top < 10) {
            top = Math.min(r.bottom + 10, window.innerHeight - panelH - 10);
        }

        logPanel.style.left = left + 'px';
        logPanel.style.top = top + 'px';
        logPanel.style.right = 'auto';
        logPanel.style.bottom = 'auto';
        logPanel.style.width = panelW + 'px';
    }

    function addLog(message, type) {
        var timestamp = new Date().toLocaleTimeString('ru', { timeZoneName: 'short' });
        var color = '#0f0';
        if (type === 'error') color = '#f00';
        if (type === 'warning') color = '#ff0';
        if (type === 'success') color = '#0f0';

        var safeMessage = escapeForLog(String(message));
        logEntries.unshift({ time: timestamp, text: safeMessage, color: color });
        if (logEntries.length > 30) logEntries.pop();
        updateLogDisplay();
    }

    function updateLogDisplay() {
        var content = document.getElementById('blame-log-content');
        if (!content) return;
        while (content.firstChild) content.removeChild(content.firstChild);

        logEntries.forEach(function(entry) {
            var entryDiv = createSafeElement('div', {
                css: { color: entry.color, marginBottom: '3px' }
            });
            entryDiv.textContent = '[' + entry.time + '] ' + entry.text;
            content.appendChild(entryDiv);
        });
    }

    // ===== КНОПКА + DRAG =====
    function clamp(v, min, max) {
        return Math.max(min, Math.min(max, v));
    }

    function addButton() {
        if (document.getElementById('blame-finder-button')) return;

        addLog('Инициализация BlameFinder для absurdopedia.wiki', 'info');

        var button = createSafeElement('div', {
            id: 'blame-finder-button',
            text: 'Кто автор?',
            css: {
                position: 'fixed',
                right: '20px',
                bottom: '20px',
                background: '#36c',
                color: 'white',
                padding: '10px 20px',
                borderRadius: '5px',
                cursor: 'grab',
                zIndex: '9999',
                fontFamily: 'sans-serif',
                fontSize: '14px',
                boxShadow: '0 2px 10px rgba(0,0,0,0.3)',
                userSelect: 'none',
                webkitUserSelect: 'none',
                touchAction: 'none',
                transition: 'background 0.15s'
            }
        });

        document.body.appendChild(button);
        createLogPanel();
        restoreButtonPosition(button);
        makeButtonDraggable(button);

        addLog('Кнопка добавлена', 'success');
    }

    function restoreButtonPosition(button) {
        var saved = null;
        try {
            saved = JSON.parse(localStorage.getItem(BUTTON_STORAGE_KEY) || 'null');
        } catch (e) {
            saved = null;
        }
        if (!saved || typeof saved.left !== 'number' || typeof saved.top !== 'number') return;

        var rect = button.getBoundingClientRect();
        var w = rect.width || 120;
        var h = rect.height || 40;
        var left = clamp(saved.left, 0, window.innerWidth - w);
        var top  = clamp(saved.top, 0, window.innerHeight - h);

        button.style.right = 'auto';
        button.style.bottom = 'auto';
        button.style.left = left + 'px';
        button.style.top = top + 'px';
    }

    function saveButtonPosition(button) {
        var rect = button.getBoundingClientRect();
        try {
            localStorage.setItem(BUTTON_STORAGE_KEY, JSON.stringify({
                left: Math.round(rect.left),
                top: Math.round(rect.top)
            }));
        } catch (e) {}
    }

    function makeButtonDraggable(button) {
        var startX = 0, startY = 0, startLeft = 0, startTop = 0;
        var pointerId = null;
        var moved = false;
        var MOVE_THRESHOLD = 5;

        function onPointerDown(e) {
            if (e.button !== undefined && e.button !== 0) return;
            pointerId = e.pointerId;
            moved = false;

            var rect = button.getBoundingClientRect();
            startLeft = rect.left;
            startTop = rect.top;
            startX = e.clientX;
            startY = e.clientY;

            button.style.right = 'auto';
            button.style.bottom = 'auto';
            button.style.left = startLeft + 'px';
            button.style.top = startTop + 'px';
            button.style.cursor = 'grabbing';
            button.dataset.dragging = '1';

            try { button.setPointerCapture(pointerId); } catch (err) {}

            button.addEventListener('pointermove', onPointerMove);
            button.addEventListener('pointerup', onPointerUp);
            button.addEventListener('pointercancel', onPointerUp);
        }

        function onPointerMove(e) {
            if (e.pointerId !== pointerId) return;
            var dx = e.clientX - startX;
            var dy = e.clientY - startY;
            if (!moved && (Math.abs(dx) > MOVE_THRESHOLD || Math.abs(dy) > MOVE_THRESHOLD)) {
                moved = true;
            }
            if (!moved) return;

            var rect = button.getBoundingClientRect();
            var w = rect.width, h = rect.height;
            var newLeft = clamp(startLeft + dx, 0, window.innerWidth - w);
            var newTop  = clamp(startTop + dy, 0, window.innerHeight - h);
            button.style.left = newLeft + 'px';
            button.style.top = newTop + 'px';

            if (logVisible) positionLogPanelNearButton();
            e.preventDefault();
        }

        function onPointerUp(e) {
            if (e.pointerId !== pointerId) return;
            try { button.releasePointerCapture(pointerId); } catch (err) {}
            button.removeEventListener('pointermove', onPointerMove);
            button.removeEventListener('pointerup', onPointerUp);
            button.removeEventListener('pointercancel', onPointerUp);
            button.style.cursor = 'grab';
            delete button.dataset.dragging;
            if (moved) saveButtonPosition(button);
            pointerId = null;
        }

        button.addEventListener('pointerdown', onPointerDown);

        button.addEventListener('mouseenter', function() {
            if (!button.dataset.dragging) button.style.background = '#447ff5';
        });
        button.addEventListener('mouseleave', function() {
            if (!button.dataset.dragging) button.style.background = '#36c';
        });

        button.addEventListener('click', function(e) {
            if (moved) {
                moved = false;
                e.preventDefault();
                e.stopPropagation();
                return;
            }
            e.preventDefault();
            showLogPanel();
            activateSelectionMode();
        });

        button.addEventListener('dblclick', function(e) {
            e.preventDefault();
            e.stopPropagation();
            try { localStorage.removeItem(BUTTON_STORAGE_KEY); } catch (err) {}
            button.style.left = 'auto';
            button.style.top = 'auto';
            button.style.right = '20px';
            button.style.bottom = '20px';
            if (logVisible) positionLogPanelNearButton();
        });

        window.addEventListener('resize', function() {
            var rect = button.getBoundingClientRect();
            if (rect.left + rect.width > window.innerWidth ||
                rect.top + rect.height > window.innerHeight) {
                button.style.left = clamp(rect.left, 0, window.innerWidth - rect.width) + 'px';
                button.style.top  = clamp(rect.top, 0, window.innerHeight - rect.height) + 'px';
            }
            if (logVisible) positionLogPanelNearButton();
        });
    }

    // ===== РЕЖИМ ВЫДЕЛЕНИЯ =====
    var selectionActive = false;
    var selectionTimer = null;

    function activateSelectionMode() {
        if (selectionActive) {
            addLog('Режим выделения уже активен', 'warning');
            return;
        }

        selectionActive = true;
        addLog('Режим выделения активирован', 'info');
        addLog('Выделите текст (мышью или касанием)', 'info');

        var tooltip = createSafeElement('div', {
            id: 'blame-tooltip',
            css: {
                position: 'fixed',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                background: '#36c',
                color: 'white',
                padding: '20px 40px',
                borderRadius: '10px',
                zIndex: '10000',
                fontFamily: 'sans-serif',
                fontSize: '18px',
                textAlign: 'center',
                boxShadow: '0 0 30px rgba(0,0,0,0.5)'
            }
        });

        tooltip.appendChild(document.createTextNode('Выделите текст'));
        tooltip.appendChild(document.createElement('br'));

        var small = createSafeElement('small', { css: { color: '#ff0' } });
        small.appendChild(document.createTextNode('осталось '));

        var timerSpan = createSafeElement('span', {
            id: 'blame-timer',
            text: '20',
            css: { color: '#ff0' }
        });
        small.appendChild(timerSpan);
        small.appendChild(document.createTextNode(' секунд'));
        tooltip.appendChild(small);
        document.body.appendChild(tooltip);

        var seconds = 20;
        var timer = setInterval(function() {
            seconds--;
            var timerSpanEl = document.getElementById('blame-timer');
            if (timerSpanEl) timerSpanEl.textContent = seconds;
        }, 1000);

        function cleanup() {
            if (!selectionActive) return;
            selectionActive = false;

            document.removeEventListener('mouseup', mouseHandler);
            document.removeEventListener('touchend', touchHandler);

            if (timer) { clearInterval(timer); timer = null; }
            if (selectionTimer) { clearTimeout(selectionTimer); selectionTimer = null; }

            var tip = document.getElementById('blame-tooltip');
            if (tip && tip.parentNode) tip.parentNode.removeChild(tip);

            addLog('Режим выделения отключён', 'info');
        }

        function mouseHandler() {
            if (!selectionActive) return;
            handleSelection();
        }

        function touchHandler() {
            if (!selectionActive) return;
            setTimeout(handleSelection, 100);
        }

        function handleSelection() {
            if (!selectionActive) return;
            var selection = window.getSelection();
            var selectedText = selection.toString().trim();

            if (selectedText.length >= 20) {
                var logText = 'Выделен текст (' + selectedText.length + ' символов): "' +
                             selectedText.substring(0, 50) +
                             (selectedText.length > 50 ? '..."' : '"');
                addLog(logText, 'success');
                cleanup();
                findAuthor(selectedText);
            } else if (selectedText.length > 0) {
                addLog('Слишком короткий текст (' + selectedText.length + ' символов, нужно минимум 20)', 'warning');
            }
        }

        document.addEventListener('mouseup', mouseHandler);
        document.addEventListener('touchend', touchHandler);

        selectionTimer = setTimeout(function() {
            if (selectionActive) {
                addLog('Время вышло', 'warning');
                cleanup();
            }
        }, 20000);
    }

    // ===== ПОИСК АВТОРА =====
    function findAuthor(text) {
        var pageInfo = getPageInfo();
        var title = pageInfo.title;

        addLog('Начинаем поиск для страницы: ' + escapeForLog(title), 'info');

        var logText = 'Ищем текст: "' + text.substring(0, 100) + (text.length > 100 ? '..."' : '"');
        addLog(logText, 'info');

        var loadingDiv = showLoading('Анализирую историю правок...');
        addLog('Запрашиваем историю правок через API', 'info');

        var globalTimeout = setTimeout(function() {
            hideLoading(loadingDiv);
            addLog('Глобальный таймаут: сервер не отвечает', 'error');
        }, 15000);

        getRevisions(title, function(revisions) {
            clearTimeout(globalTimeout);
            addLog('Получено ревизий: ' + revisions.length, 'info');

            if (revisions.length === 0) {
                addLog('Не удалось загрузить историю правок', 'error');
                hideLoading(loadingDiv);
                return;
            }

            addLog('Начинаем поиск первого появления текста...', 'info');

            findTextAppearance(revisions, text, title, function(result) {
                hideLoading(loadingDiv);
                if (result) {
                    addLog('Текст найден! Автор: ' + escapeForLog(result.rev.user), 'success');
                    showResult(result);
                } else {
                    addLog('Текст не найден в истории', 'error');
                }
            });
        }, function(error) {
            clearTimeout(globalTimeout);
            hideLoading(loadingDiv);
            addLog('Ошибка при запросе к API: ' + error, 'error');
        });
    }

    function getRevisions(title, callback, errorCallback) {
        var revisions = [];
        var continueParam = {};
        var totalFetched = 0;
        var maxRevisions = 1000;

        function fetchRevisions() {
            var params = {
                action: 'query',
                prop: 'revisions',
                titles: title,
                rvprop: 'ids|timestamp|user|comment|content',
                rvlimit: 50,
                rvdir: 'older',
                rvslots: 'main',
                formatversion: 2
            };

            if (continueParam.rvcontinue) {
                if (typeof continueParam.rvcontinue === 'string') {
                    params.rvcontinue = continueParam.rvcontinue.replace(/[<>"']/g, '');
                }
            }

            absApiRequest(params, function(data) {
                if (data.error) {
                    addLog('Ошибка API: ' + escapeForLog(data.error.info), 'error');
                    if (errorCallback) errorCallback(data.error.info);
                    return;
                }
                if (!data.query || !data.query.pages || !data.query.pages[0]) {
                    addLog('Странный ответ от API', 'error');
                    if (errorCallback) errorCallback('invalid_response');
                    return;
                }

                var page = data.query.pages[0];
                if (page.missing) {
                    addLog('Страница не найдена в API', 'error');
                    if (errorCallback) errorCallback('page_missing');
                    return;
                }

                if (page.revisions && page.revisions.length > 0) {
                    page.revisions.forEach(function(rev) {
                        revisions.push({
                            revid: rev.revid || 0,
                            timestamp: rev.timestamp || '',
                            user: (rev.user && typeof rev.user === 'string') ? rev.user : 'Аноним',
                            comment: (rev.comment && typeof rev.comment === 'string') ? rev.comment : '—',
                            content: (rev.slots && rev.slots.main && rev.slots.main.content) ?
                                    rev.slots.main.content : ''
                        });
                    });
                    totalFetched += page.revisions.length;
                    addLog('Загружено ревизий: ' + totalFetched + '/' + maxRevisions, 'info');
                } else {
                    addLog('У страницы нет истории правок', 'warning');
                    callback(revisions);
                    return;
                }

                if (data.continue && totalFetched < maxRevisions) {
                    continueParam = { rvcontinue: data.continue.rvcontinue };
                    fetchRevisions();
                } else {
                    if (totalFetched >= maxRevisions) {
                        addLog('Достигнут лимит загрузки (' + maxRevisions + ' ревизий)', 'warning');
                    }
                    callback(revisions);
                }
            }, errorCallback);
        }

        fetchRevisions();
    }

    function findTextAppearance(revisions, text, title, callback) {
        var oldestFirst = revisions.slice().reverse();
        addLog('Анализируем ' + oldestFirst.length + ' ревизий от старых к новым', 'info');

        var foundRev = null;
        var checkedCount = 0;

        for (var i = 0; i < oldestFirst.length; i++) {
            var rev = oldestFirst[i];
            var content = rev.content || '';
            checkedCount++;

            if (checkedCount % 50 === 0) {
                addLog('Проверено ' + checkedCount + '/' + oldestFirst.length + ' ревизий...', 'info');
            }

            if (content.indexOf(text) === -1) continue;

            addLog('Текст найден в ревизии от ' + rev.timestamp + ' (id: ' + rev.revid + ')', 'info');

            if (i === 0) {
                foundRev = rev;
                addLog('Текст есть в самой первой ревизии страницы', 'info');
                break;
            }

            var previousContent = oldestFirst[i - 1].content || '';
            if (previousContent.indexOf(text) === -1) {
                foundRev = rev;
                addLog('Найдено первое появление! Ревизия: ' + rev.revid, 'success');
                break;
            }

            addLog('Текст был и в предыдущей ревизии, продолжаем поиск...', 'info');
        }

        if (!foundRev) {
            addLog('Текст не найден ни в одной ревизии', 'error');
            callback(null);
            return;
        }

        callback({ rev: foundRev, title: title });
    }

    function showResult(result) {
        var rev = result.rev;
        var title = result.title;

        var date = new Date(rev.timestamp);
        var formattedDate = date.toLocaleString('ru', {
            year: 'numeric',
            month: 'long',
            day: 'numeric',
            hour: '2-digit',
            minute: '2-digit',
            timeZone: 'UTC'
        }) + ' (UTC)';

        addLog('Результат: автор ' + escapeForLog(rev.user) + ', дата ' + formattedDate, 'success');

        var safeUser = escapeHtml(rev.user);
        var safeComment = escapeHtml(rev.comment);
        var dark = isDarkTheme();

        var colors = dark ? {
            bg: '#3a3d42', fg: '#ffffff', border: '#72777d',
            accent: '#8fb3ff', subtle: '#54595d', btnText: '#1a1a1a'
        } : {
            bg: '#ffffff', fg: '#202122', border: '#a2a9b1',
            accent: '#3366cc', subtle: '#eaecf0', btnText: '#ffffff'
        };

        var overlay = createSafeElement('div', {
            id: 'blame-overlay',
            css: {
                position: 'fixed', top: '0', left: '0', right: '0', bottom: '0',
                background: 'rgba(0,0,0,0.5)', zIndex: '9999'
            }
        });

        var modal = createSafeElement('div', {
            id: 'blame-result-modal',
            css: {
                position: 'fixed', top: '50%', left: '50%',
                transform: 'translate(-50%, -50%)',
                background: colors.bg, color: colors.fg,
                border: '2px solid ' + colors.border,
                borderRadius: '8px', padding: '20px',
                zIndex: '10000', maxWidth: '500px',
                boxShadow: '0 5px 20px rgba(0,0,0,0.3)',
                fontFamily: 'sans-serif'
            }
        });

        modal.appendChild(createSafeElement('h3', {
            text: 'Найден автор текста',
            css: { marginTop: '0', color: colors.fg }
        }));

        var userP = createSafeElement('p');
        userP.appendChild(createSafeElement('strong', { text: 'Участник:' }));
        userP.appendChild(document.createTextNode(' ' + safeUser));
        modal.appendChild(userP);

        var dateP = createSafeElement('p');
        dateP.appendChild(createSafeElement('strong', { text: 'Дата правки:' }));
        dateP.appendChild(document.createTextNode(' ' + formattedDate));
        modal.appendChild(dateP);

        var commentP = createSafeElement('p');
        commentP.appendChild(createSafeElement('strong', { text: 'Комментарий:' }));
        commentP.appendChild(document.createTextNode(' "' + safeComment + '"'));
        modal.appendChild(commentP);

        var versionP = createSafeElement('p');
        versionP.appendChild(createSafeElement('strong', { text: 'Версия:' }));
        versionP.appendChild(document.createTextNode(' '));
        var versionUrl = scriptPath + '/index.php?title=' + encodeURIComponent(title) + '&oldid=' + rev.revid;
        var versionLink = createSafeLink(versionUrl, 'посмотреть эту версию');
        versionLink.style.setProperty('color', colors.accent, 'important');
        versionLink.style.setProperty('text-decoration', 'underline', 'important');
        versionP.appendChild(versionLink);
        modal.appendChild(versionP);

        var diffP = createSafeElement('p');
        diffP.appendChild(createSafeElement('strong', { text: 'Дифф:' }));
        diffP.appendChild(document.createTextNode(' '));
        var diffUrl = scriptPath + '/index.php?title=' + encodeURIComponent(title) + '&diff=prev&oldid=' + rev.revid;
        var diffLink = createSafeLink(diffUrl, 'посмотреть изменения');
        diffLink.style.setProperty('color', colors.accent, 'important');
        diffLink.style.setProperty('text-decoration', 'underline', 'important');
        diffP.appendChild(diffLink);
        modal.appendChild(diffP);

        modal.appendChild(createSafeElement('hr', {
            css: { border: 'none', borderTop: '1px solid ' + colors.subtle }
        }));

        var closeButton = createSafeElement('button', {
            id: 'blame-close',
            text: 'Закрыть',
            css: {
                background: colors.accent, color: colors.btnText,
                border: 'none', padding: '8px 16px',
                borderRadius: '4px', cursor: 'pointer'
            }
        });
        modal.appendChild(closeButton);

        document.body.appendChild(overlay);
        document.body.appendChild(modal);

        function closeModal() {
            var m = document.getElementById('blame-result-modal');
            var o = document.getElementById('blame-overlay');
            if (m && m.parentNode) m.parentNode.removeChild(m);
            if (o && o.parentNode) o.parentNode.removeChild(o);
        }

        closeButton.onclick = closeModal;
        overlay.onclick = closeModal;
    }

    function showLoading(message) {
        var dark = isDarkTheme();
        var bg = dark ? '#3a3d42' : '#f8f9fa';
        var fg = dark ? '#ffffff' : '#202122';
        var border = dark ? '#72777d' : '#a2a9b1';

        var div = createSafeElement('div', {
            id: 'blame-loading',
            text: message || 'Загрузка...',
            css: {
                position: 'fixed', top: '20px', right: '20px',
                background: bg, color: fg,
                border: '1px solid ' + border,
                padding: '10px 20px', borderRadius: '4px',
                zIndex: '10000', fontFamily: 'sans-serif',
                boxShadow: '0 2px 10px rgba(0,0,0,0.1)'
            }
        });
        document.body.appendChild(div);
        return div;
    }

    function hideLoading(div) {
        if (div && div.parentNode) div.parentNode.removeChild(div);
    }

    // ===== ЗАПУСК =====
    var pageInfo = getPageInfo();
    if (pageInfo.isArticle) {
        if (document.readyState === 'complete') {
            addButton();
        } else {
            window.addEventListener('load', addButton);
        }
    } else {
        console.log('BlameFinder: не основное пространство имён, гаджет не активирован');
    }
})();