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

  • 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 с поддержкой ночного режима и перетаскиванием кнопки
 * Назначение: поиск автора любого текста в статье
 * Универсальный вики-портируемый код.
 * Лицензия: MIT (opensource.org/license/mit); источник: absurdopedia.wiki
 * Использование:
  1.   Нажимаете кнопку «Кто автор?» (изначально она — в правом нижнем углу)
  2.   Выделяете любой текст на странице (минимум 20 символов)
  3.1. В скинах Monobook и Vector-10: 
       · кликайте по появившейся в центре кнопке таймера (20 секунд на всё)
  3.2  В скине Vector-22:
       · кликайте по кнопке «Кто автор?» (20 секунд на всё)
  4.   Гаджет анализирует последние 1000 правок страницы
  5.   Находит первое появление этого текста в истории
  6.   Показывает:
       · Имя автора
       · Дату правки
       · Комментарий к правке
       · Ссылки на версию и diff
 * Что может:
  · Искать авторов фрагментов текста в статьях
  · Расчитан на работу в пространствах статей и форума
  · Поддерживает мышь и сенсорный экран
  · Показывает панель логов с отладкой
 */

(function() {
    'use strict';

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

    // ===== КОНСТАНТЫ =====
    var SCRIPT_PATH_FALLBACK = '/w';
    var BUTTON_STORAGE_KEY = 'blameFinderButtonPos';
    var LOG_WIDTH = 380;
    var LOG_MAX_HEIGHT_CSS = 'min(300px, 50vh)';
    var LOG_MAX_ENTRIES = 30;
    var SELECTION_MIN_LENGTH = 20;
    var SELECTION_TIMEOUT_MS = 20000;
    var DRAG_MOVE_THRESHOLD = 5;
    var API_REQUEST_TIMEOUT_MS = 20000;
    var GLOBAL_TIMEOUT_MS = 120000;
    var MAX_REVISIONS = 1000;
    var REVISIONS_PER_BATCH = 50;
    var MAX_VERIFICATION_RETRIES = 5;

    var COLORS = {
        primary: '#36c',
        primaryHover: '#447ff5',
        danger: '#f00',
        warning: '#ff0',
        success: '#0f0',
        logBg: 'rgba(0,0,0,0.9)'
    };

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

    // ===== ЭКРАНИРОВАНИЕ =====
    function escapeText(text) {
        if (text === undefined || text === null) return '';
        return String(text)
            .replace(/&/g, '&')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#039;');
    }

    function sanitizeUrl(url) {
        if (!url || typeof url !== 'string') return null;
        var trimmed = url.trim();
        if (trimmed === '') return null;
        if (trimmed.charAt(0) === '#') return trimmed;
        if (trimmed.charAt(0) === '/' && trimmed.charAt(1) !== '/') 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 !== undefined && options.text !== null) {
            element.textContent = options.text;
        }

        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, String(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 || 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;
    }

    // ===== ТЕМА =====
    var cachedDarkTheme = null;
    function isDarkTheme() {
        if (cachedDarkTheme !== null) return cachedDarkTheme;
        var result = false;
        try {
            var html = document.documentElement;
            var body = document.body;
            if (html.classList.contains('skin-theme-clientpref-night')) result = true;
            else if (html.classList.contains('skin-theme-clientpref-day')) result = false;
            else if (html.classList.contains('skin-theme-clientpref-os')) {
                result = !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches);
            } else {
                var dataTheme = (html.getAttribute('data-theme') || '') + ' ' +
                                (body ? (body.getAttribute('data-theme') || '') : '');
                if (/dark|night/i.test(dataTheme)) result = true;
                else if (/light|day/i.test(dataTheme)) result = false;
                else 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);
                        result = (0.299 * r + 0.587 * g + 0.114 * b) < 128;
                    }
                }
            }
        } catch (e) {}
        cachedDarkTheme = result;
        return result;
    }

    // ===== ИНФОРМАЦИЯ О СТРАНИЦЕ =====
    var cachedPageInfo = null;
    function getPageInfo() {
        if (cachedPageInfo) return cachedPageInfo;
        cachedPageInfo = computePageInfo();
        return cachedPageInfo;
    }

    function computePageInfo() {
        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 };
    }

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

        var queryString = Object.keys(params).map(function(key) {
            var value = params[key];
            return encodeURIComponent(key) + '=' + encodeURIComponent(value === undefined ? '' : value);
        }).join('&');

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

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

        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');
                        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: COLORS.logBg, color: COLORS.success,
                fontFamily: 'monospace', fontSize: '12px',
                padding: '10px', borderRadius: '5px', zIndex: '9999',
                border: '2px solid ' + COLORS.primary,
                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 ' + COLORS.primary
            }
        });

        var titleSpan = createSafeElement('span', {
            text: 'Логи BlameFinder',
            css: { color: COLORS.primary, fontWeight: 'bold' }
        });

        var buttonContainer = createSafeElement('div');

        var clearButton = createSafeElement('button', {
            id: 'blame-clear', text: 'Очистить',
            css: {
                background: 'none', border: '1px solid ' + COLORS.primary,
                color: COLORS.primary, marginRight: '5px',
                cursor: 'pointer', padding: '5px'
            }
        });

        var toggleButton = createSafeElement('button', {
            id: 'blame-toggle', text: 'Скрыть',
            css: {
                background: 'none', border: '1px solid ' + COLORS.primary,
                color: COLORS.primary, cursor: 'pointer', padding: '5px'
            }
        });

        ['color', 'border-color'].forEach(function(prop) {
            clearButton.style.setProperty(prop, COLORS.primary, 'important');
            toggleButton.style.setProperty(prop, COLORS.primary, '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';
            syncLogToggleLabel();
        };

        logPanel.style.display = 'none';
    }

    function showLogPanel() {
        if (!logPanel || 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 = COLORS.success;
        if (type === 'error') color = COLORS.danger;
        else if (type === 'warning') color = COLORS.warning;

        logEntries.unshift({ time: timestamp, text: String(message), color: color });
        if (logEntries.length > LOG_MAX_ENTRIES) 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 для ' + window.location.host, 'info');

        var button = createSafeElement('div', {
            id: 'blame-finder-button',
            text: 'Кто автор?',
            attrs: { role: 'button', tabindex: '0', 'aria-label': 'Найти автора выделенного текста' },
            css: {
                position: 'fixed', right: '20px', bottom: '20px',
                background: COLORS.primary, 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;

        function onPointerDown(e) {
            if (e.pointerType === 'mouse' && 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) > DRAG_MOVE_THRESHOLD || Math.abs(dy) > DRAG_MOVE_THRESHOLD)) {
                moved = true;
            }
            if (!moved) return;

            var rect = button.getBoundingClientRect();
            var newLeft = clamp(startLeft + dx, 0, window.innerWidth - rect.width);
            var newTop  = clamp(startTop + dy, 0, window.innerHeight - rect.height);
            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 = COLORS.primaryHover;
        });
        button.addEventListener('mouseleave', function() {
            if (!button.dataset.dragging) button.style.background = COLORS.primary;
        });

        function handleActivate(e) {
            if (moved) {
                moved = false;
                if (e) { e.preventDefault(); e.stopPropagation(); }
                return;
            }
            if (e) { e.preventDefault(); e.stopPropagation(); }
            showLogPanel();
            activateSelectionMode();
        }

        button.addEventListener('click', handleActivate);
        button.addEventListener('keydown', function(e) {
            if (e.key === 'Enter' || e.key === ' ') handleActivate(e);
        });

        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;
    var selectionCountdown = 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: COLORS.primary, 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: COLORS.warning } });
        small.appendChild(document.createTextNode('осталось '));

        var timerSpan = createSafeElement('span', {
            id: 'blame-timer', text: String(SELECTION_TIMEOUT_MS / 1000),
            css: { color: COLORS.warning }
        });
        small.appendChild(timerSpan);
        small.appendChild(document.createTextNode(' секунд'));
        tooltip.appendChild(small);
        document.body.appendChild(tooltip);

        var secondsLeft = SELECTION_TIMEOUT_MS / 1000;
        selectionCountdown = setInterval(function() {
            secondsLeft--;
            var timerSpanEl = document.getElementById('blame-timer');
            if (timerSpanEl) timerSpanEl.textContent = String(secondsLeft);
            if (secondsLeft <= 0) {
                if (selectionCountdown) { clearInterval(selectionCountdown); selectionCountdown = null; }
            }
        }, 1000);

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

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

            if (selectionCountdown) { clearInterval(selectionCountdown); selectionCountdown = 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();
        }

        var touchDebounceTimer = null;
        function touchHandler() {
            if (!selectionActive) return;
            if (touchDebounceTimer) clearTimeout(touchDebounceTimer);
            touchDebounceTimer = setTimeout(function() {
                touchDebounceTimer = null;
                handleSelection();
            }, 150);
        }

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

            if (selectedText.length >= SELECTION_MIN_LENGTH) {
                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 +
                       ' символов, нужно минимум ' + SELECTION_MIN_LENGTH + ')', 'warning');
            }
        }

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

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

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

        addLog('Начинаем поиск для страницы: ' + title, 'info');
        addLog('Ищем текст: "' + text.substring(0, 100) + (text.length > 100 ? '..."' : '"'), 'info');

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

        var finished = false;
        function finish() {
            if (finished) return;
            finished = true;
            hideLoading(loadingDiv);
        }

        var globalTimeout = setTimeout(function() {
            if (finished) return;
            addLog('Глобальный таймаут (' + (GLOBAL_TIMEOUT_MS / 1000) +
                   ' с): сервер не отвечает или история слишком велика', 'error');
            finish();
        }, GLOBAL_TIMEOUT_MS);

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

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

            addLog('Начинаем поиск первого появления текста...', 'info');
            addLog('Верификация включена (макс. попыток: ' + MAX_VERIFICATION_RETRIES + ')', 'info');

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

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

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

            absApiRequest(params, function(data) {
                if (data.error) {
                    addLog('Ошибка API: ' + 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 + '/' + MAX_REVISIONS, 'info');
                } else {
                    addLog('У страницы нет истории правок', 'warning');
                    callback(revisions);
                    return;
                }

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

        fetchRevisions();
    }

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

        var rejectedRevisions = new Set();
        var lastCandidate = null;
        var retries = 0;

        var i = count - 1;

        while (i >= 0 && retries <= MAX_VERIFICATION_RETRIES) {
            var rev = revisions[i];
            var content = rev.content || '';

            if (rejectedRevisions.has(rev.revid)) {
                i--;
                continue;
            }

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

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

            if (i === count - 1) {
                addLog('Текст есть в самой первой ревизии страницы', 'info');
                callback({ rev: rev, title: title });
                return;
            }

            var previousContent = (revisions[i + 1] && revisions[i + 1].content) || '';
            var appearsInCurrent = content.indexOf(text) !== -1;
            var appearsInPrevious = previousContent.indexOf(text) !== -1;

            if (appearsInCurrent && !appearsInPrevious) {
                addLog('Верификация пройдена: текст появился именно в этой правке', 'success');
                callback({ rev: rev, title: title });
                return;
            }

            lastCandidate = rev;
            rejectedRevisions.add(rev.revid);
            retries++;

            addLog(
                'Верификация не пройдена (текст был и в предыдущей правке). ' +
                'Попытка ' + retries + '/' + MAX_VERIFICATION_RETRIES + ', продолжаем поиск...',
                'warning'
            );

            i--;
        }

        if (lastCandidate) {
            addLog(
                'Достигнут лимит попыток верификации. Возвращаю последнего кандидата: ' +
                lastCandidate.revid,
                'warning'
            );
            callback({ rev: lastCandidate, title: title });
            return;
        }

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

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

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

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

        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',
            attrs: { role: 'dialog', 'aria-modal': 'true', 'aria-labelledby': 'blame-modal-title' },
            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'
            }
        });

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

        var userP = createSafeElement('p');
        userP.appendChild(createSafeElement('strong', { text: 'Участник:' }));
        userP.appendChild(document.createTextNode(' ' + rev.user));
        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(' "' + rev.comment + '"'));
        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=' + encodeURIComponent(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=' + encodeURIComponent(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);
            document.removeEventListener('keydown', escHandler);
        }

        function escHandler(e) {
            if (e.key === 'Escape') closeModal();
        }
        document.addEventListener('keydown', escHandler);

        closeButton.onclick = closeModal;
        overlay.onclick = closeModal;
        try { closeButton.focus(); } catch (e) {}
    }

    function showLoading(message) {
        var existing = document.getElementById('blame-loading');
        if (existing && existing.parentNode) existing.parentNode.removeChild(existing);

        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: не основное пространство имён, гаджет не активирован');
    }
})();