Немає опису редагування
мНемає опису редагування
 
(Не показано 38 проміжних версій цього користувача)
Рядок 1: Рядок 1:
// =========================
// ОСНОВНИЙ КОД ДЛЯ ТЕМ, ДОСТУПНОСТІ ТА ЛУПИ
// =========================
$(function () {
$(function () {
     // Теми
     // Теми
Рядок 10: Рядок 13:
         theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
         theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
     }
     }
     if (themes[theme]) mw.loader.load(themes[theme], 'text/css');
   
    // Завантажуємо тему
     if (themes[theme]) {
        mw.loader.load(themes[theme], 'text/css');
    }
 
    // Розмір шрифту
    var fontSize = parseInt(localStorage.getItem('fontSize')) || parseInt($('body').css('font-size')) || 16;


     function createButton(text, bottom, onClick, title) {
     function applyFontSize() {
         var $btn = $('<button>').text(text).attr('title', title).css({
        var content = document.querySelector('.mw-parser-output');
            position: 'fixed',
        if (content) {
            bottom: bottom + 'px',
            content.style.fontSize = fontSize + 'px';
            right: '10px',
        }
            padding: '10px 16px',
    }
            border: 'none',
 
            borderRadius: '25px',
    // Масив для збереження позицій кнопок
            background: '#1a73e8',
    var buttonCount = 0;
            color: '#ffffff',
 
            fontWeight: 'bold',
    // Функція створення кнопки праворуч з автоматичним вертикальним розташуванням
            fontSize: '14px',
    function createButtonRight(text, onClick, title) {
            cursor: 'pointer',
         var btn = document.createElement('button');
            zIndex: 9999,
        btn.innerText = text;
            textAlign: 'center',
        btn.title = title;
            boxShadow: '0 2px 6px rgba(0,0,0,0.3)',
        btn.style.position = 'fixed';
            whiteSpace: 'nowrap'
        btn.style.right = '10px';
         }).click(onClick);
        btn.style.bottom = (10 + buttonCount * 60) + 'px'; // вертикальний відступ між кнопками
         $('body').append($btn);
        btn.style.padding = '10px 16px';
         return $btn;
        btn.style.border = 'none';
        btn.style.borderRadius = '25px';
        btn.style.background = '#1a73e8';
        btn.style.color = '#fff';
        btn.style.fontWeight = 'bold';
        btn.style.fontSize = '14px';
        btn.style.cursor = 'pointer';
        btn.style.zIndex = 9999;
        btn.style.textAlign = 'center';
        btn.style.boxShadow = '0 2px 6px rgba(0,0,0,0.3)';
        btn.style.whiteSpace = 'nowrap';
 
         btn.onclick = onClick;
         document.body.appendChild(btn);
 
        buttonCount++; // збільшуємо лічильник кнопок для наступного bottom
         return btn;
     }
     }


     // Кнопка Темна/Світла тема
     // Кнопка Темна/Світла тема
     var $themeBtn = createButton(
     createButtonRight(
         theme === 'dark' ? 'Світла тема ☀️' : 'Темна тема 🌙',
         theme === 'dark' ? 'Світла тема ☀️' : 'Темна тема 🌙',
        10,
         function () {
         function () {
             var newTheme = theme === 'dark' ? 'light' : 'dark';
             var newTheme = theme === 'dark' ? 'light' : 'dark';
Рядок 45: Рядок 70:
         'Змінити тему'
         'Змінити тему'
     );
     );
    // Змінна для зберігання розміру шрифту
    var fontSize = parseInt($('body').css('font-size'), 10) || 16;
   
    // Функція для застосування розміру шрифту
    function applyFontSize() {
        $('body').css('font-size', fontSize + 'px');
    }


     // Кнопка доступності
     // Кнопка доступності
     var $accessBtn = createButton(
     createButtonRight(
         'Доступність',
         localStorage.getItem('accessibilityMode') === 'on' ? 'Доступність' : 'Доступність',
        70,
         function () {
         function () {
             if (!$('body').hasClass('accessibility-mode')) {
             if (!$('body').hasClass('accessibility-mode')) {
                 $('body').addClass('accessibility-mode');
                 $('body').addClass('accessibility-mode');
                 localStorage.setItem('accessibilityMode', 'on');
                 localStorage.setItem('accessibilityMode', 'on');
                $accessBtn.css('background', '#ff6600');
                $accessBtn.text('Доступність ON');
             } else {
             } else {
                 $('body').removeClass('accessibility-mode');
                 $('body').removeClass('accessibility-mode');
                 localStorage.setItem('accessibilityMode', 'off');
                 localStorage.setItem('accessibilityMode', 'off');
                $accessBtn.css('background', '#1a73e8');
                $accessBtn.text('Доступність OFF');
             }
             }
         },
         },
Рядок 74: Рядок 86:
     );
     );


     // Відновлення стану доступності
     // Кнопки лупи
     if (localStorage.getItem('accessibilityMode') === 'on') {
     createButtonRight('🔍 +', function () {
        $('body').addClass('accessibility-mode');
        $accessBtn.css('background', '#ff6600');
        $accessBtn.text('Доступність ON');
    }
 
    // Лупа
    createButton('🔍 +', 130, function () {
         fontSize += 2;
         fontSize += 2;
         if (fontSize > 30) fontSize = 30;
         if (fontSize > 30) fontSize = 30;
Рядок 89: Рядок 94:
     }, 'Збільшити шрифт');
     }, 'Збільшити шрифт');


     createButton('🔍 -', 170, function () {
     createButtonRight('🔍 -', function () {
         fontSize -= 2;
         fontSize -= 2;
         if (fontSize < 12) fontSize = 12;
         if (fontSize < 12) fontSize = 12;
Рядок 96: Рядок 101:
     }, 'Зменшити шрифт');
     }, 'Зменшити шрифт');


     // Відновлення розміру шрифту
    // Застосовуємо шрифт при завантаженні
     if (localStorage.getItem('fontSize')) {
    applyFontSize();
         fontSize = parseInt(localStorage.getItem('fontSize'), 10);
 
     // Відновлення стану доступності при завантаженні
     if (localStorage.getItem('accessibilityMode') === 'on') {
         $('body').addClass('accessibility-mode');
     }
     }
    applyFontSize();
});
});




//OVERLAY  
// =========================
// ВАШ СТАРИЙ OVERLAY КОД (без змін)
// =========================
(function() {
(function() {
     'use strict';
     'use strict';
      
      
     // Конфигурация в стиле MediaViewer
     // Конфигурація в стилі MediaViewer
     const config = {
     const config = {
        // Стиль оверлею
         overlayBg: 'rgba(0,0,0,0.95)',
         overlayBg: 'rgba(0,0,0,0.95)',
         imageMaxWidth: '90%',
        animationDuration: '0.3s',
         imageMaxHeight: '90%',
       
         closeBtnText: '×',
        // Стиль зображення
         closeBtnStyle: {
         imageMaxWidth: '90vw',
         imageMaxHeight: '80vh',
          
        // Панель інформації
        infoPanel: {
            background: 'rgba(0,0,0,0.8)',
            color: '#fff',
            padding: '15px',
            borderRadius: '8px',
            marginTop: '15px',
            maxWidth: '600px',
            fontSize: '14px'
        },
       
        // Кнопки
         buttons: {
             background: 'rgba(0,0,0,0.7)',
             background: 'rgba(0,0,0,0.7)',
             color: 'white',
             color: '#fff',
             border: 'none',
             size: '40px',
            borderRadius: '50%',
             fontSize: '18px',
            width: '40px',
             borderRadius: '5px',
            height: '40px',
             margin: '5px'
             fontSize: '24px',
             cursor: 'pointer',
            position: 'absolute',
            top: '20px',
             right: '20px'
         },
         },
         zoomBtnStyle: {
          
        // Кнопка закриття
        closeBtn: {
             background: 'rgba(0,0,0,0.7)',
             background: 'rgba(0,0,0,0.7)',
             color: 'white',
             color: '#fff',
             border: 'none',
             size: '40px',
            borderRadius: '50%',
            width: '40px',
            height: '40px',
             fontSize: '20px',
             fontSize: '20px',
             cursor: 'pointer',
             top: '20px',
            position: 'absolute',
             right: '20px'
             right: '20px'
         }
         },
       
        // Винятки
        excludeSelectors: [
            '.no-overlay',
            '[data-no-overlay]',
            '.mw-editsection img',
            '.sprite',
            '.icon',
            '.logo',
            '.nav-icon'
        ]
     };
     };


    let currentOverlay = null;
    let currentImageIndex = 0;
    let imagesInGallery = [];
     let currentScale = 1;
     let currentScale = 1;
     const minScale = 0.5;
     const minScale = 0.5;
Рядок 146: Рядок 178:
     const scaleStep = 0.25;
     const scaleStep = 0.25;


     // Функция для создания оверлея в стиле MediaViewer
     // Повністю відключаємо стандартний MediaViewer
     function showCustomOverlay(url) {
    function disableMediaViewerCompletely() {
        const mediaViewerLinks = document.querySelectorAll('a[href*="/wiki/File:"], a[href*="/w/images/"]');
        mediaViewerLinks.forEach(link => {
            link.removeAttribute('data-mw');
            link.removeAttribute('data-mediatype');
            link.removeAttribute('data-file');
           
            link.addEventListener('click', function(e) {
                const img = this.querySelector('img');
                if (img && shouldOpenInOverlay(img)) {
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    showMediaViewerOverlay(img);
                    return false;
                }
            }, true);
        });
    }
 
    // Створення оверлею в стилі MediaViewer
     function createMediaViewerStyleOverlay() {
         const overlay = document.createElement('div');
         const overlay = document.createElement('div');
         overlay.style.position = 'fixed';
         overlay.className = 'custom-media-viewer';
         overlay.style.top = '0';
         overlay.style.cssText = `
         overlay.style.left = '0';
            position: fixed;
         overlay.style.width = '100%';
            top: 0;
         overlay.style.height = '100%';
            left: 0;
         overlay.style.background = config.overlayBg;
            width: 100%;
        overlay.style.display = 'flex';
            height: 100%;
        overlay.style.justifyContent = 'center';
            background: ${config.overlayBg};
        overlay.style.alignItems = 'center';
            display: none;
         overlay.style.zIndex = '10000';
            justify-content: center;
        overlay.style.cursor = 'default';
            align-items: center;
            z-index: 10000;
            opacity: 0;
            transition: opacity ${config.animationDuration} ease;
            cursor: default;
        `;
 
        // Головний контейнер
        const mainContainer = document.createElement('div');
         mainContainer.style.cssText = `
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
            max-width: 95vw;
            max-height: 95vh;
        `;
 
        // Кнопка закриття ×
        const closeBtn = document.createElement('button');
         closeBtn.innerHTML = '×';
         closeBtn.title = 'Закрити (Esc)';
         closeBtn.style.cssText = `
            width: ${config.closeBtn.size};
            height: ${config.closeBtn.size};
            background: ${config.closeBtn.background};
            color: ${config.closeBtn.color};
            border: none;
            border-radius: 50%;
            font-size: ${config.closeBtn.fontSize};
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            position: absolute;
            top: ${config.closeBtn.top};
            right: ${config.closeBtn.right};
            z-index: 10001;
        `;
 
        // Основний контейнер для зображення та кнопок
        const imageAndControlsContainer = document.createElement('div');
         imageAndControlsContainer.style.cssText = `
            position: relative;
            display: inline-block;
            max-width: ${config.imageMaxWidth};
            max-height: ${config.imageMaxHeight};
            margin-bottom: 10px;
        `;


         // Контейнер для изображения и кнопок
         // Контейнер для зображення
         const container = document.createElement('div');
         const imageContainer = document.createElement('div');
         container.style.position = 'relative';
         imageContainer.style.cssText = `
        container.style.display = 'flex';
            position: relative;
        container.style.justifyContent = 'center';
            display: block;
        container.style.alignItems = 'center';
            max-width: 100%;
        container.style.maxWidth = '95vw';
            max-height: 100%;
         container.style.maxHeight = '95vh';
         `;


        // Изображение
         const img = document.createElement('img');
         const img = document.createElement('img');
         img.src = url;
         img.style.cssText = `
        img.style.maxWidth = config.imageMaxWidth;
            max-width: 100%;
         img.style.maxHeight = config.imageMaxHeight;
            max-height: 100%;
         img.style.objectFit = 'contain';
            object-fit: contain;
         img.style.borderRadius = '8px';
            border-radius: 8px;
         img.style.boxShadow = '0 10px 30px rgba(0,0,0,0.5)';
            box-shadow: 0 10px 30px rgba(0,0,0,0.5);
         img.style.transition = 'transform 0.3s ease';
            cursor: default !important;
         img.style.cursor = 'default'; // Убираем курсор лупы
            transition: transform 0.3s ease;
            display: block;
        `;
 
        // Кнопки навігації (зліва/справа від зображення)
        const prevBtn = createNavButton('‹', 'Попереднє зображення (←)');
        const nextBtn = createNavButton('›', 'Наступне зображення (→)');
         prevBtn.style.cssText += 'left: 10px;';
         nextBtn.style.cssText += 'right: 10px;';
 
         // Контейнер для кнопок масштабування - ПРИКРІПЛЕНИЙ ДО НИЗУ ЗОБРАЖЕННЯ
        const buttonPanel = document.createElement('div');
        buttonPanel.className = 'zoom-controls-panel';
         buttonPanel.style.cssText = `
            position: absolute;
            bottom: 10px;
            left: 50%;
            transform: translateX(-50%);
            display: flex;
            justify-content: center;
            align-items: center;
            gap: 8px;
            background: rgba(0,0,0,0.8);
            padding: 8px 12px;
            border-radius: 8px;
            z-index: 10001;
            min-width: 200px;
            backdrop-filter: blur(5px);
        `;
 
        // Кнопки масштабування
        const zoomOutBtn = createToolButton('−', 'Зменшити (Ctrl + -)');
        const resetZoomBtn = createToolButton('1:1', 'Скинути масштаб (Ctrl + 0)');
        const zoomInBtn = createToolButton('+', 'Збільшити (Ctrl + +)');
        const infoBtn = createToolButton('i', 'Інформація (I)');
 
         // Панель інформації
        const infoPanel = document.createElement('div');
        infoPanel.className = 'image-info-panel';
         infoPanel.style.cssText = `
            background: ${config.infoPanel.background};
            color: ${config.infoPanel.color};
            padding: ${config.infoPanel.padding};
            border-radius: ${config.infoPanel.borderRadius};
            margin-top: 10px;
            max-width: ${config.infoPanel.maxWidth};
            width: 100%;
            text-align: center;
            font-size: ${config.infoPanel.fontSize};
            display: none;
        `;


         // Кнопка закрытия (как в MediaViewer)
         // Функція для оновлення позиції кнопок при зміні розміру зображення
        const closeBtn = document.createElement('button');
        function updateButtonPanelPosition() {
        closeBtn.innerHTML = config.closeBtnText;
            if (!img.parentElement) return;
        closeBtn.title = 'Закрити (Esc)';
           
        closeBtn.style.cssText = Object.entries(config.closeBtnStyle).map(([key, value]) =>
            const imgRect = img.getBoundingClientRect();
             `${key}: ${value};`).join('');
            const containerRect = imageAndControlsContainer.getBoundingClientRect();
        closeBtn.style.zIndex = '10001';
           
            // Позиціонуємо кнопки відносно видимого зображення
             if (imgRect.height > 0) {
                buttonPanel.style.bottom = '10px';
            }
        }


         // Кнопки зума
         // Спостерігач за змінами розміру зображення
         const zoomInBtn = document.createElement('button');
         const resizeObserver = new ResizeObserver(() => {
        zoomInBtn.innerHTML = '+';
             updateButtonPanelPosition();
        zoomInBtn.title = 'Збільшити (Ctrl + +)';
         });
        zoomInBtn.style.cssText = Object.entries(config.zoomBtnStyle).map(([key, value]) =>  
             `${key}: ${value};`).join('');
         zoomInBtn.style.top = '70px';
        zoomInBtn.style.zIndex = '10001';


         const zoomOutBtn = document.createElement('button');
         // Збірка інтерфейсу
         zoomOutBtn.innerHTML = '−';
        imageContainer.appendChild(img);
         zoomOutBtn.title = 'Зменшити (Ctrl + -)';
         imageContainer.appendChild(prevBtn);
         zoomOutBtn.style.cssText = Object.entries(config.zoomBtnStyle).map(([key, value]) =>
         imageContainer.appendChild(nextBtn);
            `${key}: ${value};`).join('');
         imageContainer.appendChild(buttonPanel);
         zoomOutBtn.style.top = '120px';
       
         zoomOutBtn.style.zIndex = '10001';
        imageAndControlsContainer.appendChild(imageContainer);
       
        buttonPanel.appendChild(zoomOutBtn);
        buttonPanel.appendChild(resetZoomBtn);
        buttonPanel.appendChild(zoomInBtn);
        buttonPanel.appendChild(infoBtn);
       
        mainContainer.appendChild(closeBtn);
        mainContainer.appendChild(imageAndControlsContainer);
        mainContainer.appendChild(infoPanel);
          
        overlay.appendChild(mainContainer);
         document.body.appendChild(overlay);


         const resetZoomBtn = document.createElement('button');
         // Спостерігаємо за змінами розміру зображення
         resetZoomBtn.innerHTML = '1:1';
         resizeObserver.observe(img);
        resetZoomBtn.title = 'Скинути масштаб';
        resetZoomBtn.style.cssText = Object.entries(config.zoomBtnStyle).map(([key, value]) =>
            `${key}: ${value};`).join('');
        resetZoomBtn.style.top = '170px';
        resetZoomBtn.style.zIndex = '10001';
        resetZoomBtn.style.fontSize = '16px';


         // Функции зума
         // Функції масштабування
         function zoomImage(scale) {
         function zoomImage(scale) {
             currentScale = Math.max(minScale, Math.min(maxScale, scale));
             currentScale = Math.max(minScale, Math.min(maxScale, scale));
             img.style.transform = `scale(${currentScale})`;
             img.style.transform = `scale(${currentScale})`;
             updateZoomButtons();
             updateZoomButtons();
            // Оновлюємо позицію кнопок після масштабування
            setTimeout(updateButtonPanelPosition, 50);
         }
         }


Рядок 230: Рядок 389:
         }
         }


         // Обработчики зума
         // Обробники подій
         zoomInBtn.addEventListener('click', (e) => {
         function setupEventListeners() {
             e.stopPropagation();
            // Закриття
             zoomImage(currentScale + scaleStep);
            const closeOverlay = () => {
        });
                resizeObserver.disconnect();
                overlay.style.opacity = '0';
                setTimeout(() => {
                    overlay.style.display = 'none';
                    document.body.style.overflow = 'auto';
                    currentOverlay = null;
                    imagesInGallery = [];
                    currentScale = 1;
                }, 300);
            };
 
            closeBtn.addEventListener('click', closeOverlay);
            overlay.addEventListener('click', (e) => {
                if (e.target === overlay) closeOverlay();
            });
 
            // Навігація
            prevBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                navigateImages(-1);
            });
 
            nextBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                navigateImages(1);
            });
 
            // Масштабування
            zoomInBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                zoomImage(currentScale + scaleStep);
             });
 
            zoomOutBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                zoomImage(currentScale - scaleStep);
            });
 
             resetZoomBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                currentScale = 1;
                img.style.transform = 'scale(1)';
                updateZoomButtons();
                setTimeout(updateButtonPanelPosition, 50);
            });
 
            // Інформація
            infoBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                toggleInfoPanel();
            });
 
            // Клавіатура
            const keyHandler = (e) => {
                if (!currentOverlay) return;
               
                switch(e.key) {
                    case 'Escape':
                        closeOverlay();
                        break;
                    case 'ArrowLeft':
                        navigateImages(-1);
                        break;
                    case 'ArrowRight':
                        navigateImages(1);
                        break;
                    case 'i':
                    case 'І':
                        e.preventDefault();
                        toggleInfoPanel();
                        break;
                    case '+':
                    case '=':
                        if (e.ctrlKey) {
                            e.preventDefault();
                            zoomImage(currentScale + scaleStep);
                        }
                        break;
                    case '-':
                        if (e.ctrlKey) {
                            e.preventDefault();
                            zoomImage(currentScale - scaleStep);
                        }
                        break;
                    case '0':
                        if (e.ctrlKey) {
                            e.preventDefault();
                            currentScale = 1;
                            img.style.transform = 'scale(1)';
                            updateZoomButtons();
                            setTimeout(updateButtonPanelPosition, 50);
                        }
                        break;
                }
            };
 
            document.addEventListener('keydown', keyHandler);
 
            // Видаляємо обробник при закритті
            overlay.addEventListener('click', function handler() {
                if (overlay.style.display === 'none') {
                    document.removeEventListener('keydown', keyHandler);
                    overlay.removeEventListener('click', handler);
                }
            });
 
            // Hover ефекти
            [closeBtn, prevBtn, nextBtn, zoomInBtn, zoomOutBtn, resetZoomBtn, infoBtn].forEach(btn => {
                btn.addEventListener('mouseenter', () => {
                    if (!btn.disabled) {
                        btn.style.background = 'rgba(0,0,0,0.9)';
                        btn.style.transform = 'scale(1.1)';
                    }
                });
                btn.addEventListener('mouseleave', () => {
                    btn.style.background = config.buttons.background;
                    btn.style.transform = 'scale(1)';
                });
            });


        zoomOutBtn.addEventListener('click', (e) => {
            // Оновлюємо позицію при завантаженні зображення
            e.stopPropagation();
            img.addEventListener('load', () => {
             zoomImage(currentScale - scaleStep);
                setTimeout(updateButtonPanelPosition, 100);
         });
             });
         }


         resetZoomBtn.addEventListener('click', (e) => {
         setupEventListeners();
            e.stopPropagation();
        updateZoomButtons();
            currentScale = 1;
            img.style.transform = 'scale(1)';
            updateZoomButtons();
        });


         // Закрытие оверлея
         return {  
        const closeOverlay = () => {
             overlay,
             document.body.removeChild(overlay);
            img,
             document.body.style.overflow = 'auto';
            infoPanel,
             currentScale = 1; // Сбрасываем масштаб
            prevBtn,
            nextBtn,
            zoomInBtn,
            zoomOutBtn,
            resetZoomBtn,
            infoBtn,
            buttonPanel,
             updateZoomButtons,
             updateButtonPanelPosition
         };
         };
    }
    // Створення кнопки навігації
    function createNavButton(text, title) {
        const btn = document.createElement('button');
        btn.innerHTML = text;
        btn.title = title;
        btn.style.cssText = `
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            width: ${config.buttons.size};
            height: ${config.buttons.size};
            background: ${config.buttons.background};
            color: ${config.buttons.color};
            border: none;
            border-radius: 50%;
            font-size: ${config.buttons.fontSize};
            cursor: pointer;
            display: none;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            z-index: 10001;
        `;
        return btn;
    }
    // Створення кнопки інструменту
    function createToolButton(text, title) {
        const btn = document.createElement('button');
        btn.innerHTML = text;
        btn.title = title;
        btn.style.cssText = `
            min-width: ${config.buttons.size};
            height: ${config.buttons.size};
            background: ${config.buttons.background};
            color: ${config.buttons.color};
            border: none;
            border-radius: ${config.buttons.borderRadius};
            font-size: ${config.buttons.fontSize};
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            padding: 0 10px;
        `;
        return btn;
    }


         closeBtn.addEventListener('click', closeOverlay);
    // Навігація по зображенням
    function navigateImages(direction) {
         if (imagesInGallery.length <= 1) return;
       
        currentImageIndex += direction;
       
        if (currentImageIndex < 0) {
            currentImageIndex = imagesInGallery.length - 1;
        } else if (currentImageIndex >= imagesInGallery.length) {
            currentImageIndex = 0;
        }
          
          
         // Закрытие по клику на фон (но не на изображение или кнопки)
         showImage(imagesInGallery[currentImageIndex]);
         overlay.addEventListener('click', (e) => {
    }
             if (e.target === overlay) closeOverlay();
 
         });
    // Показ інформації
    function toggleInfoPanel() {
        if (!currentOverlay) return;
        const infoPanel = currentOverlay.infoPanel;
        infoPanel.style.display = infoPanel.style.display === 'none' ? 'block' : 'none';
    }
 
    // Збір всіх зображень на сторінці для галереї
    function collectAllImages(clickedImage) {
         const images = Array.from(document.querySelectorAll('img'))
            .filter(img => shouldOpenInOverlay(img) && !img.closest('.custom-media-viewer'))
            .map(img => ({
                src: img.src,
                alt: img.alt || 'Зображення',
                title: img.title || '',
                width: img.naturalWidth,
                height: img.naturalHeight
             }));
       
        currentImageIndex = images.findIndex(img => img.src === clickedImage.src);
        return images;
    }
 
    // Перевірка, чи повинна картинка відкриватися в оверлеї
    function shouldOpenInOverlay(element) {
        if (config.excludeSelectors.some(selector =>
            element.matches(selector) || element.closest(selector))) {
            return false;
        }
 
        if (element.width < 50 || element.height < 50) {
            return false;
         }
 
        if (element.closest('.gallery, .thumb, .mw-gallery')) {
            return false;
        }
 
        return true;
    }


        // Закрытие по ESC
    // Показ оверлею
        const keyHandler = (e) => {
    function showMediaViewerOverlay(imageElement) {
            if (e.key === 'Escape') {
        if (imageElement.closest('a')) {
                closeOverlay();
            const link = imageElement.closest('a');
                document.removeEventListener('keydown', keyHandler);
             if (link.href && link.href.includes('/wiki/File:')) {
             } else if (e.ctrlKey) {
                 link.addEventListener('click', function(e) {
                 if (e.key === '+' || e.key === '=') {
                     e.preventDefault();
                     e.preventDefault();
                     zoomImage(currentScale + scaleStep);
                     e.stopImmediatePropagation();
                } else if (e.key === '-') {
                 }, true);
                    e.preventDefault();
                    zoomImage(currentScale - scaleStep);
                 } else if (e.key === '0') {
                    e.preventDefault();
                    currentScale = 1;
                    img.style.transform = 'scale(1)';
                    updateZoomButtons();
                }
             }
             }
         };
         }
         document.addEventListener('keydown', keyHandler);
 
         if (!currentOverlay) {
            currentOverlay = createMediaViewerStyleOverlay();
        }


         // Hover эффекты для кнопок
         imagesInGallery = collectAllImages(imageElement);
        [closeBtn, zoomInBtn, zoomOutBtn, resetZoomBtn].forEach(btn => {
       
            btn.addEventListener('mouseenter', () => {
        if (imagesInGallery.length === 0) return;
                btn.style.background = 'rgba(0,0,0,0.9)';
                btn.style.transform = 'scale(1.1)';
            });
            btn.addEventListener('mouseleave', () => {
                btn.style.background = config.zoomBtnStyle.background;
                btn.style.transform = 'scale(1)';
            });
        });


         // Сборка интерфейса
         showImage(imagesInGallery[currentImageIndex]);
        container.appendChild(img);
          
         container.appendChild(closeBtn);
         currentOverlay.overlay.style.display = 'flex';
         container.appendChild(zoomInBtn);
         setTimeout(() => {
         container.appendChild(zoomOutBtn);
            currentOverlay.overlay.style.opacity = '1';
        container.appendChild(resetZoomBtn);
         }, 10);
         overlay.appendChild(container);
          
          
        document.body.appendChild(overlay);
         document.body.style.overflow = 'hidden';
         document.body.style.overflow = 'hidden';
          
          
         // Инициализация кнопок зума
        currentOverlay.prevBtn.style.display = imagesInGallery.length > 1 ? 'flex' : 'none';
         updateZoomButtons();
        currentOverlay.nextBtn.style.display = imagesInGallery.length > 1 ? 'flex' : 'none';
       
        currentScale = 1;
        currentOverlay.img.style.transform = 'scale(1)';
        if (currentOverlay.updateZoomButtons) {
            currentOverlay.updateZoomButtons();
        }
       
         // Оновлюємо позицію кнопок після показу
        setTimeout(() => {
            if (currentOverlay && currentOverlay.updateButtonPanelPosition) {
                currentOverlay.updateButtonPanelPosition();
            }
        }, 200);
    }
 
    // Показ конкретного зображення
    function showImage(imageData) {
        if (!currentOverlay) return;
       
        currentOverlay.img.src = imageData.src;
        currentOverlay.img.alt = imageData.alt;
       
         currentOverlay.infoPanel.innerHTML = `
            <div><strong>${imageData.alt}</strong></div>
            <div>Розмір: ${imageData.width} × ${imageData.height}px</div>
            <div style="margin-top: 10px; opacity: 0.7;">
                ← → для навігації • I для інформації • Ctrl + +-/0 для масштабу • Esc для закриття
            </div>
        `;
       
        currentScale = 1;
        currentOverlay.img.style.transform = 'scale(1)';
        if (currentOverlay.updateZoomButtons) {
            currentOverlay.updateZoomButtons();
        }
       
        // Оновлюємо позицію кнопок після завантаження нового зображення
        currentOverlay.img.onload = () => {
            setTimeout(() => {
                if (currentOverlay && currentOverlay.updateButtonPanelPosition) {
                    currentOverlay.updateButtonPanelPosition();
                }
            }, 100);
        };
     }
     }


     // Перехватываем клики на обычные картинки (без MediaViewer)
     // Обробник кліків
     document.body.addEventListener('click', function(e) {
     document.addEventListener('click', function(e) {
         const target = e.target;
         const target = e.target;


        // Если картинка не часть MediaViewer overlay и нет ссылки на /w/images/
         if (target.closest('.custom-media-viewer')) {
         if (target.tagName === 'IMG' && !target.closest('.mediaViewerOverlay')) {
             return;
             const parentLink = target.closest('a[href*="/w/images/"]');
        }
            if (!parentLink) {
 
                e.preventDefault();
        if (target.tagName === 'IMG' && shouldOpenInOverlay(target)) {
                e.stopPropagation();
            e.preventDefault();
                showCustomOverlay(target.src);
            e.stopImmediatePropagation();
             }
            showMediaViewerOverlay(target);
             return false;
         }
         }


        // Ссылки на файлы, где MediaViewer не срабатывает
         if (target.tagName === 'A' && target.href &&  
         if (target.tagName === 'A' && target.href && target.href.includes('/w/images/')) {
            (target.href.match(/\/wiki\/File:|\.(jpg|jpeg|png|gif|webp)(\?|$)/i))) {
             if (!target.closest('.thumb')) {
             const img = target.querySelector('img');
            if (img && shouldOpenInOverlay(img)) {
                 e.preventDefault();
                 e.preventDefault();
                 e.stopPropagation();
                 e.stopImmediatePropagation();
                 showCustomOverlay(target.href);
                 showMediaViewerOverlay(img);
                return false;
             }
             }
         }
         }
     }, true);
     }, true);


     // Функция добавления кнопки "Закрити" к MediaViewer overlay
     // Повністю відключаємо MediaViewer при завантаженні
     function addCloseButtonToMediaViewer() {
     document.addEventListener('DOMContentLoaded', disableMediaViewerCompletely);
        const overlay = document.querySelector('.mediaViewerOverlay, .mwe-popups');
    setTimeout(disableMediaViewerCompletely, 100);
        if (!overlay || overlay.dataset.closeBtnAdded) return;
        overlay.dataset.closeBtnAdded = true;


        const closeBtn = document.createElement('button');
     // Стилі
        closeBtn.innerText = 'Закрити';
        closeBtn.style.position = 'absolute';
        closeBtn.style.top = '20px';
        closeBtn.style.right = '20px';
        closeBtn.style.padding = '10px 20px';
        closeBtn.style.fontSize = '18px';
        closeBtn.style.cursor = 'pointer';
        closeBtn.style.background = '#f44336';
        closeBtn.style.color = 'white';
        closeBtn.style.border = 'none';
        closeBtn.style.borderRadius = '5px';
        closeBtn.style.zIndex = '10001';
       
        closeBtn.addEventListener('click', () => {
            overlay.style.display = 'none';
        });
 
        overlay.appendChild(closeBtn);
    }
 
    // MutationObserver отслеживает появление overlay MediaViewer
    const observer = new MutationObserver(() => addCloseButtonToMediaViewer());
    observer.observe(document.body, { childList: true, subtree: true });
 
     // Стили для улучшения внешнего вида
     const style = document.createElement('style');
     const style = document.createElement('style');
     style.textContent = `
     style.textContent = `
         button {
         .custom-media-viewer * {
             transition: all 0.2s ease !important;
             box-sizing: border-box;
         }
         }
          
          
         button:hover:not(:disabled) {
         .custom-media-viewer button:hover:not(:disabled) {
             transform: scale(1.1) !important;
             transform: scale(1.1) !important;
             background: rgba(0,0,0,0.9) !important;
             background: rgba(0,0,0,0.9) !important;
         }
         }
          
          
         button:disabled {
         .custom-media-viewer button:disabled {
             cursor: not-allowed !important;
             cursor: not-allowed !important;
            opacity: 0.5 !important;
        }
       
        .custom-media-viewer img {
            transition: transform 0.3s ease !important;
            cursor: default !important;
        }
       
        /* Панель кнопок масштабування - завжди внизу зображення */
        .zoom-controls-panel {
            position: absolute !important;
            bottom: 10px !important;
            left: 50% !important;
            transform: translateX(-50%) !important;
            background: rgba(0,0,0,0.8) !important;
            padding: 8px 12px !important;
            border-radius: 8px !important;
            z-index: 10001 !important;
            min-width: 200px !important;
            backdrop-filter: blur(5px) !important;
        }
       
        /* Контейнер зображення */
        .custom-media-viewer .image-container {
            position: relative !important;
            display: inline-block !important;
        }
       
        /* Повністю ховаємо стандартний MediaViewer */
        .mw-mmv-overlay,
        .mediaViewerOverlay {
            display: none !important;
         }
         }
          
          
         @media (max-width: 768px) {
         @media (max-width: 768px) {
             button {
             .custom-media-viewer button {
                 width: 35px !important;
                 min-width: 35px !important;
                 height: 35px !important;
                 height: 35px !important;
                 font-size: 18px !important;
                 font-size: 16px !important;
                padding: 0 8px !important;
            }
           
            .image-info-panel {
                font-size: 12px !important;
                padding: 10px !important;
                margin-top: 10px !important;
            }
           
            .zoom-controls-panel {
                min-width: 180px !important;
                padding: 6px 10px !important;
                bottom: 8px !important;
            }
        }
       
        @media (max-width: 480px) {
            .custom-media-viewer button {
                min-width: 30px !important;
                height: 30px !important;
                font-size: 14px !important;
                padding: 0 6px !important;
            }
           
            .zoom-controls-panel {
                min-width: 160px !important;
                padding: 5px 8px !important;
                bottom: 5px !important;
                gap: 5px !important;
             }
             }
         }
         }
Рядок 393: Рядок 839:


})();
})();
// =========================
// КНОПКА ВИПАДКОВА СТОРІНКА (вище)
// =========================
function createRandomButton() {
    if (document.getElementById('float-random-btn')) return;
    if (!document.body.classList.contains('skin-minerva')) return;
   
    const btn = document.createElement('button');
    btn.id = 'float-random-btn';
    btn.innerHTML = '🎲 Випадкова cторінка';
    btn.title = 'Випадкова сторінка';
    btn.style.cssText = `
        position: fixed;
        bottom: 240px; 
        left: 15px;
        z-index: 9998;
        background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
        color: white;
        border: none;
        padding: 12px 18px;
        border-radius: 25px;
        font-size: 16px;
        font-weight: bold;
        cursor: pointer;
        box-shadow: 0 4px 15px rgba(0,0,0,0.3);
        display: flex;
        align-items: center;
        gap: 8px;
        transition: all 0.3s ease;
        white-space: nowrap;
    `;
   
    btn.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        btn.innerHTML = '⏳ Завантаження...';
        btn.style.opacity = '0.7';
        btn.disabled = true;
        setTimeout(() => {
            window.location.href = '/w/index.php/Спеціальна:Випадкова_сторінка';
        }, 100);
    });
   
    btn.addEventListener('mouseenter', function() {
        if (!this.disabled) {
            this.style.transform = 'scale(1.05)';
            this.style.boxShadow = '0 6px 20px rgba(0,0,0,0.4)';
        }
    });
   
    btn.addEventListener('mouseleave', function() {
        this.style.transform = 'scale(1)';
        this.style.boxShadow = '0 4px 15px rgba(0,0,0,0.3)';
    });
   
    document.body.appendChild(btn);
}
// =========================
// КНОПКА "ЯК ЦЕ ПРАЦЮЄ?" (виправлена версія)
// =========================
function createHowItWorksButton() {
    if (document.getElementById('how-it-works-btn')) return;
   
    const btn = document.createElement('button');
    btn.id = 'how-it-works-btn';
    btn.innerHTML = '?';
    btn.title = 'Як це працює?';
    btn.style.cssText = `
        position: fixed;
        bottom: 140px;
        left: 15px;
        z-index: 9998;
        background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
        color: white;
        border: none;
        width: 60px;
        height: 60px;
        border-radius: 50%;
        font-size: 24px;
        font-weight: bold;
        cursor: pointer;
        box-shadow: 0 4px 15px rgba(0,0,0,0.3);
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
        line-height: 1;
    `;
   
    btn.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        window.location.href = '/w/index.php/FAQ';
    });
   
    btn.addEventListener('mouseenter', function() {
        this.style.transform = 'scale(1.05)';
        this.style.boxShadow = '0 6px 20px rgba(0,0,0,0.4)';
    });
   
    btn.addEventListener('mouseleave', function() {
        this.style.transform = 'scale(1)';
        this.style.boxShadow = '0 4px 15px rgba(0,0,0,0.3)';
    });
   
    document.body.appendChild(btn);
}
// =========================
// ВИПРАВЛЕНА ІНІЦІАЛІЗАЦІЯ (замінити тільки цю частину)
// =========================
// Видаляємо всі старі ініціалізатори і замінюємо на цей простий код:
let buttonsInitialized = false;
function initializeLeftButtons() {
    if (buttonsInitialized) return;
    buttonsInitialized = true;
   
    // Кнопка "Як це працює?" для всіх тем
    createHowItWorksButton();
   
    // Кнопка "Випадкова сторінка" тільки для Minerva
    if (document.body.classList.contains('skin-minerva')) {
        createRandomButton();
    }
}
// Тільки один спосіб ініціалізації
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeLeftButtons);
} else {
    setTimeout(initializeLeftButtons, 100);
}
// Тільки один резервний таймер
setTimeout(initializeLeftButtons, 1000);