MediaWiki:Common.js: відмінності між версіями

Матеріал з darnytsa_hero
Перейти до навігації Перейти до пошуку
Немає опису редагування
Немає опису редагування
Рядок 108: Рядок 108:
     'use strict';
     'use strict';
      
      
     // Конфигурация - легко настраивается
     // Конфигурация в стиле MediaViewer
     const config = {
     const config = {
         overlayBg: 'rgba(0,0,0,0.92)',
        // Стиль оверлея
         maxWidth: '95%',
         overlayBg: 'rgba(0,0,0,0.95)',
         maxHeight: '95%',
         animationDuration: '0.3s',
         closeBtnText: '✕ Закрити',
          
         closeBtnStyle: {
        // Стиль изображения
             background: '#d32f2f',
        imageMaxWidth: '90vw',
            color: 'white',
         imageMaxHeight: '90vh',
            border: 'none',
          
             borderRadius: '4px',
        // Панель информации (как в MediaViewer)
             padding: '12px 24px',
        infoPanel: {
             fontSize: '16px',
             background: 'rgba(0,0,0,0.8)',
            cursor: 'pointer',
             color: '#fff',
             padding: '20px',
             borderRadius: '8px',
             marginTop: '20px',
             marginTop: '20px',
             transition: 'background 0.3s ease'
             maxWidth: '600px',
            fontSize: '14px'
         },
         },
         imageStyle: {
          
             borderRadius: '8px',
        // Кнопки навигации
             boxShadow: '0 4px 20px rgba(0,0,0,0.3)'
        navButtons: {
            background: 'rgba(0,0,0,0.7)',
            color: '#fff',
            size: '50px',
            fontSize: '24px',
             borderRadius: '50%'
        },
       
        // Кнопка закрытия
        closeBtn: {
             background: 'rgba(0,0,0,0.7)',
            color: '#fff',
            size: '40px',
            fontSize: '20px',
            top: '20px',
            right: '20px'
         },
         },
         // Исключения - классы/атрибуты, которые не должны открывать оверлей
       
         // Исключения
         excludeSelectors: [
         excludeSelectors: [
             '.no-overlay',
             '.no-overlay',
Рядок 135: Рядок 154:
             '.mw-editsection img',
             '.mw-editsection img',
             '.sprite',
             '.sprite',
             '.icon'
             '.icon',
            '.logo',
            '.nav-icon'
         ]
         ]
     };
     };


     let currentOverlay = null;
     let currentOverlay = null;
    let currentImageIndex = 0;
    let imagesInGallery = [];


     // Функция создания оверлея
     // Создание оверлея в стиле MediaViewer
     function createOverlay() {
     function createMediaViewerStyleOverlay() {
         const overlay = document.createElement('div');
         const overlay = document.createElement('div');
         overlay.className = 'custom-image-overlay';
         overlay.className = 'custom-media-viewer';
         overlay.style.cssText = `
         overlay.style.cssText = `
             position: fixed;
             position: fixed;
Рядок 155: Рядок 178:
             justify-content: center;
             justify-content: center;
             align-items: center;
             align-items: center;
            z-index: 10000;
            opacity: 0;
            transition: opacity ${config.animationDuration} ease;
        `;
        // Контейнер для содержимого
        const contentContainer = document.createElement('div');
        contentContainer.style.cssText = `
            position: relative;
            max-width: 95vw;
            max-height: 95vh;
            display: flex;
             flex-direction: column;
             flex-direction: column;
             z-index: 10000;
             align-items: center;
        `;
 
        // Верхняя панель с кнопкой закрытия
        const topPanel = document.createElement('div');
        topPanel.style.cssText = `
            width: 100%;
            display: flex;
            justify-content: flex-end;
            margin-bottom: 20px;
        `;
 
        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;
             cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
         `;
         `;


         const imgContainer = document.createElement('div');
        // Контейнер для изображения
         imgContainer.style.cssText = `
         const imageContainer = document.createElement('div');
         imageContainer.style.cssText = `
             position: relative;
             position: relative;
            max-width: ${config.maxWidth};
            max-height: ${config.maxHeight};
             display: flex;
             display: flex;
             justify-content: center;
             justify-content: center;
             align-items: center;
             align-items: center;
            max-width: ${config.imageMaxWidth};
            max-height: ${config.imageMaxHeight};
         `;
         `;


Рядок 175: Рядок 237:
             max-height: 100%;
             max-height: 100%;
             object-fit: contain;
             object-fit: contain;
             ${Object.entries(config.imageStyle).map(([key, value]) =>
             border-radius: 8px;
                `${key.replace(/([A-Z])/g, '-$1').toLowerCase()}: ${value};`).join('')}
            box-shadow: 0 10px 30px rgba(0,0,0,0.5);
            cursor: pointer;
            transition: transform 0.2s ease;
        `;
 
        // Кнопки навигации
        const prevBtn = createNavButton('‹', 'Попереднє зображення (←)');
        const nextBtn = createNavButton('›', 'Наступне зображення (→)');
 
        prevBtn.style.left = '20px';
        nextBtn.style.right = '20px';
 
        // Панель информации
        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: 20px;
            max-width: ${config.infoPanel.maxWidth};
            width: 100%;
            text-align: center;
            font-size: ${config.infoPanel.fontSize};
            display: none;
         `;
         `;


         const closeBtn = document.createElement('button');
         // Сборка интерфейса
         closeBtn.innerHTML = config.closeBtnText;
        topPanel.appendChild(closeBtn);
         closeBtn.style.cssText = Object.entries(config.closeBtnStyle).map(([key, value]) =>
         imageContainer.appendChild(img);
            `${key.replace(/([A-Z])/g, '-$1').toLowerCase()}: ${value};`).join('');
         imageContainer.appendChild(prevBtn);
        imageContainer.appendChild(nextBtn);
          
          
         // Добавляем hover эффект для кнопки
         contentContainer.appendChild(topPanel);
         closeBtn.onmouseover = () => closeBtn.style.background = '#b71c1c';
         contentContainer.appendChild(imageContainer);
         closeBtn.onmouseout = () => closeBtn.style.background = config.closeBtnStyle.background;
        contentContainer.appendChild(infoPanel);
         overlay.appendChild(contentContainer);
 
        document.body.appendChild(overlay);


         imgContainer.appendChild(img);
         // Обработчики событий
        overlay.appendChild(imgContainer);
        function setupEventListeners() {
        overlay.appendChild(closeBtn);
            // Закрытие
            const closeOverlay = () => {
                overlay.style.opacity = '0';
                setTimeout(() => {
                    overlay.style.display = 'none';
                    document.body.style.overflow = 'auto';
                    currentOverlay = null;
                    imagesInGallery = [];
                }, 300);
            };


        // Закрытие по клику на оверлей или кнопку
            closeBtn.addEventListener('click', closeOverlay);
        const closeOverlay = () => {
             overlay.addEventListener('click', (e) => {
             overlay.style.display = 'none';
                if (e.target === overlay) closeOverlay();
            document.body.style.overflow = 'auto';
             });
             currentOverlay = null;
        };


        overlay.addEventListener('click', (e) => {
            // Навигация
            if (e.target === overlay) closeOverlay();
            prevBtn.addEventListener('click', (e) => {
        });
                e.stopPropagation();
                navigateImages(-1);
            });


        closeBtn.addEventListener('click', closeOverlay);
            nextBtn.addEventListener('click', (e) => {
                e.stopPropagation();
                navigateImages(1);
            });


        // Закрытие по ESC
            // Клавиатура
        document.addEventListener('keydown', function escHandler(e) {
            document.addEventListener('keydown', function keyHandler(e) {
            if (e.key === 'Escape' && currentOverlay) {
                if (!currentOverlay) return;
                 closeOverlay();
               
                 document.removeEventListener('keydown', escHandler);
                switch(e.key) {
             }
                    case 'Escape':
         });
                        closeOverlay();
                        break;
                    case 'ArrowLeft':
                        navigateImages(-1);
                        break;
                    case 'ArrowRight':
                        navigateImages(1);
                        break;
                    case 'i':
                        e.preventDefault();
                        toggleInfoPanel();
                        break;
                }
            });
 
            // Zoom по клику на изображение
            img.addEventListener('click', (e) => {
                e.stopPropagation();
                if (img.style.transform === 'scale(1.5)') {
                    img.style.transform = 'scale(1)';
                } else {
                    img.style.transform = 'scale(1.5)';
                }
            });
 
            // Hover эффекты
            [closeBtn, prevBtn, nextBtn].forEach(btn => {
                btn.addEventListener('mouseenter', () => {
                    btn.style.background = 'rgba(0,0,0,0.9)';
                    btn.style.transform = 'scale(1.1)';
                });
                 btn.addEventListener('mouseleave', () => {
                    btn.style.background = config.navButtons.background;
                    btn.style.transform = 'scale(1)';
                 });
            });
        }
 
        setupEventListeners();
 
        return { overlay, img, infoPanel, prevBtn, nextBtn };
    }
 
    // Создание кнопки навигации
    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.navButtons.size};
            height: ${config.navButtons.size};
            background: ${config.navButtons.background};
            color: ${config.navButtons.color};
            border: none;
            border-radius: 50%;
            font-size: ${config.navButtons.fontSize};
            cursor: pointer;
            display: none;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            z-index: 10001;
        `;
        return btn;
    }
 
    // Навигация по изображениям
    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]);
    }
 
    // Показ информации
    function toggleInfoPanel() {
        if (!currentOverlay) return;
        const infoPanel = currentOverlay.infoPanel;
        infoPanel.style.display = infoPanel.style.display === 'none' ? 'block' : 'none';
    }


         document.body.appendChild(overlay);
    // Сбор всех изображений на странице для галереи
        return { overlay, img };
    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) {
     function shouldOpenInOverlay(element) {
        // Проверяем исключения
         if (config.excludeSelectors.some(selector =>  
         if (config.excludeSelectors.some(selector => element.matches(selector) || element.closest(selector))) {
            element.matches(selector) || element.closest(selector))) {
             return false;
             return false;
         }
         }


        // Игнорируем маленькие картинки (иконки)
         if (element.width < 50 || element.height < 50) {
         if (element.width < 50 || element.height < 50) {
             return false;
             return false;
         }
         }


         // Игнорируем картинки внутри ссылок, которые ведут не на изображения
         // Пропускаем изображения из галерей
         const parentLink = element.closest('a');
         if (element.closest('.gallery, .thumb, .mw-gallery')) {
        if (parentLink) {
            return false; // Или можно true, если хотите поддержку галерей
            const href = parentLink.href;
            if (href && !href.match(/\.(jpg|jpeg|png|gif|webp|svg)(\?|$)/i)) {
                return false;
            }
         }
         }


Рядок 241: Рядок 441:
     }
     }


     // Показ кастомного оверлея
     // Показ оверлея
     function showCustomOverlay(url, alt = '') {
     function showMediaViewerOverlay(imageElement) {
         if (!currentOverlay) {
         if (!currentOverlay) {
             currentOverlay = createOverlay();
             currentOverlay = createMediaViewerStyleOverlay();
         }
         }


         currentOverlay.img.src = url;
         // Собираем все изображения для галереи
         currentOverlay.img.alt = alt;
        imagesInGallery = collectAllImages(imageElement);
          
        if (imagesInGallery.length === 0) return;
 
        showImage(imagesInGallery[currentImageIndex]);
       
        // Показываем оверлей с анимацией
         currentOverlay.overlay.style.display = 'flex';
         currentOverlay.overlay.style.display = 'flex';
        setTimeout(() => {
            currentOverlay.overlay.style.opacity = '1';
        }, 10);
          
          
         // Блокируем прокрутку body
         // Блокируем прокрутку
         document.body.style.overflow = 'hidden';
         document.body.style.overflow = 'hidden';
       
        // Показываем/скрываем кнопки навигации
        currentOverlay.prevBtn.style.display = imagesInGallery.length > 1 ? 'flex' : 'none';
        currentOverlay.nextBtn.style.display = imagesInGallery.length > 1 ? 'flex' : 'none';
    }
    // Показ конкретного изображения
    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 для інформації • Esc для закриття
            </div>
        `;
     }
     }


     // Обработчик кликов
     // Обработчик кликов
     document.body.addEventListener('click', function(e) {
     document.addEventListener('click', function(e) {
         const target = e.target;
         const target = e.target;
        // Пропускаем клики внутри оверлея
        if (target.closest('.custom-media-viewer')) {
            return;
        }


         // Клик на картинку
         // Клик на картинку
         if (target.tagName === 'IMG' && shouldOpenInOverlay(target)) {
         if (target.tagName === 'IMG' && shouldOpenInOverlay(target)) {
             // Проверяем, не является ли это частью MediaViewer или других компонентов
             e.preventDefault();
            if (!target.closest('.mediaViewerOverlay, .mwe-popups, .gallery, .thumb')) {
            e.stopPropagation();
                e.preventDefault();
            showMediaViewerOverlay(target);
                e.stopPropagation();
                showCustomOverlay(target.src, target.alt);
            }
         }
         }


         // Клик на ссылку с изображением
         // Клик на ссылку с изображением
         if (target.tagName === 'A' && target.href) {
         if (target.tagName === 'A' && target.href && target.href.match(/\.(jpg|jpeg|png|gif|webp)(\?|$)/i)) {
             const img = target.querySelector('img');
             const img = target.querySelector('img');
             if (img && shouldOpenInOverlay(img)) {
             if (img && shouldOpenInOverlay(img)) {
                 e.preventDefault();
                 e.preventDefault();
                 e.stopPropagation();
                 e.stopPropagation();
                 showCustomOverlay(target.href, img.alt);
                 showMediaViewerOverlay(img);
             }
             }
         }
         }
     }, true);
     });


     // Улучшенный MutationObserver для MediaViewer
     // Стили для плавной анимации
     function enhanceMediaViewer() {
     const style = document.createElement('style');
        const overlay = document.querySelector('.mediaViewerOverlay');
    style.textContent = `
        if (overlay && !overlay.dataset.enhanced) {
        .custom-media-viewer * {
            overlay.dataset.enhanced = true;
            box-sizing: border-box;
 
        }
            const closeBtn = document.createElement('button');
       
            closeBtn.innerHTML = config.closeBtnText;
        .custom-media-viewer button:hover {
            closeBtn.style.cssText = `
             transform: scale(1.1) !important;
                position: absolute;
        }
                top: 20px;
       
                right: 20px;
        .custom-media-viewer img {
                z-index: 10001;
             transition: transform 0.3s ease !important;
                ${Object.entries(config.closeBtnStyle).map(([key, value]) =>
                    `${key.replace(/([A-Z])/g, '-$1').toLowerCase()}: ${value};`).join('')}
             `;
 
            closeBtn.addEventListener('click', () => {
                overlay.style.display = 'none';
            });
 
            overlay.appendChild(closeBtn);
 
             // Добавляем закрытие по ESC для MediaViewer
            overlay.addEventListener('keydown', (e) => {
                if (e.key === 'Escape') {
                    overlay.style.display = 'none';
                }
            });
         }
         }
    }
       
 
         @media (max-width: 768px) {
    // Более эффективный observer
             .custom-media-viewer button {
    const observer = new MutationObserver((mutations) => {
                 width: 40px !important;
         for (const mutation of mutations) {
                height: 40px !important;
             if (mutation.type === 'childList') {
                font-size: 18px !important;
                 for (const node of mutation.addedNodes) {
                    if (node.nodeType === 1) { // Element node
                        if (node.classList && node.classList.contains('mediaViewerOverlay')) {
                            enhanceMediaViewer();
                        } else if (node.querySelector) {
                            const mediaViewer = node.querySelector('.mediaViewerOverlay');
                            if (mediaViewer) enhanceMediaViewer();
                        }
                    }
                }
             }
             }
         }
         }
     });
     `;
 
     document.head.appendChild(style);
     observer.observe(document.body, {
        childList: true,
        subtree: true
    });


     // Инициализация при загрузке DOM
     console.log('Custom MediaViewer loaded successfully');
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', enhanceMediaViewer);
    } else {
        enhanceMediaViewer();
    }


})();
})();

Версія за 16:14, 24 вересня 2025

$(function () {
    // Теми
    var themes = {
        light: '/w/index.php?title=MediaWiki:Light.css&action=raw&ctype=text/css',
        dark: '/w/index.php?title=MediaWiki:Dark.css&action=raw&ctype=text/css'
    };

    var theme = localStorage.getItem('selectedTheme');
    if (!theme) {
        theme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    }
    if (themes[theme]) mw.loader.load(themes[theme], 'text/css');

    function createButton(text, bottom, onClick, title) {
        var $btn = $('<button>').text(text).attr('title', title).css({
            position: 'fixed',
            bottom: bottom + 'px',
            right: '10px',
            padding: '10px 16px',
            border: 'none',
            borderRadius: '25px',
            background: '#1a73e8',
            color: '#ffffff',
            fontWeight: 'bold',
            fontSize: '14px',
            cursor: 'pointer',
            zIndex: 9999,
            textAlign: 'center',
            boxShadow: '0 2px 6px rgba(0,0,0,0.3)',
            whiteSpace: 'nowrap'
        }).click(onClick);
        $('body').append($btn);
        return $btn;
    }

    // Кнопка Темна/Світла тема
    var $themeBtn = createButton(
        theme === 'dark' ? 'Світла тема ☀️' : 'Темна тема 🌙',
        10,
        function () {
            var newTheme = theme === 'dark' ? 'light' : 'dark';
            localStorage.setItem('selectedTheme', newTheme);
            location.reload();
        },
        'Змінити тему'
    );

    // Змінна для зберігання розміру шрифту
    var fontSize = parseInt($('body').css('font-size'), 10) || 16;
    
    // Функція для застосування розміру шрифту
    function applyFontSize() {
        $('body').css('font-size', fontSize + 'px');
    }

    // Кнопка доступності
    var $accessBtn = createButton(
        'Доступність',
        70,
        function () {
            if (!$('body').hasClass('accessibility-mode')) {
                $('body').addClass('accessibility-mode');
                localStorage.setItem('accessibilityMode', 'on');
                $accessBtn.css('background', '#ff6600');
                $accessBtn.text('Доступність ON');
            } else {
                $('body').removeClass('accessibility-mode');
                localStorage.setItem('accessibilityMode', 'off');
                $accessBtn.css('background', '#1a73e8');
                $accessBtn.text('Доступність OFF');
            }
        },
        'Увімкнути/вимкнути режим доступності'
    );

    // Відновлення стану доступності
    if (localStorage.getItem('accessibilityMode') === 'on') {
        $('body').addClass('accessibility-mode');
        $accessBtn.css('background', '#ff6600');
        $accessBtn.text('Доступність ON');
    }

    // Лупа
    createButton('🔍 +', 130, function () {
        fontSize += 2;
        if (fontSize > 30) fontSize = 30;
        localStorage.setItem('fontSize', fontSize);
        applyFontSize();
    }, 'Збільшити шрифт');

    createButton('🔍 -', 170, function () {
        fontSize -= 2;
        if (fontSize < 12) fontSize = 12;
        localStorage.setItem('fontSize', fontSize);
        applyFontSize();
    }, 'Зменшити шрифт');

    // Відновлення розміру шрифту
    if (localStorage.getItem('fontSize')) {
        fontSize = parseInt(localStorage.getItem('fontSize'), 10);
    }
    applyFontSize();
});


//OVERLAY 
(function() {
    'use strict';
    
    // Конфигурация в стиле MediaViewer
    const config = {
        // Стиль оверлея
        overlayBg: 'rgba(0,0,0,0.95)',
        animationDuration: '0.3s',
        
        // Стиль изображения
        imageMaxWidth: '90vw',
        imageMaxHeight: '90vh',
        
        // Панель информации (как в MediaViewer)
        infoPanel: {
            background: 'rgba(0,0,0,0.8)',
            color: '#fff',
            padding: '20px',
            borderRadius: '8px',
            marginTop: '20px',
            maxWidth: '600px',
            fontSize: '14px'
        },
        
        // Кнопки навигации
        navButtons: {
            background: 'rgba(0,0,0,0.7)',
            color: '#fff',
            size: '50px',
            fontSize: '24px',
            borderRadius: '50%'
        },
        
        // Кнопка закрытия
        closeBtn: {
            background: 'rgba(0,0,0,0.7)',
            color: '#fff',
            size: '40px',
            fontSize: '20px',
            top: '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 = [];

    // Создание оверлея в стиле MediaViewer
    function createMediaViewerStyleOverlay() {
        const overlay = document.createElement('div');
        overlay.className = 'custom-media-viewer';
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: ${config.overlayBg};
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 10000;
            opacity: 0;
            transition: opacity ${config.animationDuration} ease;
        `;

        // Контейнер для содержимого
        const contentContainer = document.createElement('div');
        contentContainer.style.cssText = `
            position: relative;
            max-width: 95vw;
            max-height: 95vh;
            display: flex;
            flex-direction: column;
            align-items: center;
        `;

        // Верхняя панель с кнопкой закрытия
        const topPanel = document.createElement('div');
        topPanel.style.cssText = `
            width: 100%;
            display: flex;
            justify-content: flex-end;
            margin-bottom: 20px;
        `;

        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;
        `;

        // Контейнер для изображения
        const imageContainer = document.createElement('div');
        imageContainer.style.cssText = `
            position: relative;
            display: flex;
            justify-content: center;
            align-items: center;
            max-width: ${config.imageMaxWidth};
            max-height: ${config.imageMaxHeight};
        `;

        const img = document.createElement('img');
        img.style.cssText = `
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
            border-radius: 8px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.5);
            cursor: pointer;
            transition: transform 0.2s ease;
        `;

        // Кнопки навигации
        const prevBtn = createNavButton('‹', 'Попереднє зображення (←)');
        const nextBtn = createNavButton('›', 'Наступне зображення (→)');

        prevBtn.style.left = '20px';
        nextBtn.style.right = '20px';

        // Панель информации
        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: 20px;
            max-width: ${config.infoPanel.maxWidth};
            width: 100%;
            text-align: center;
            font-size: ${config.infoPanel.fontSize};
            display: none;
        `;

        // Сборка интерфейса
        topPanel.appendChild(closeBtn);
        imageContainer.appendChild(img);
        imageContainer.appendChild(prevBtn);
        imageContainer.appendChild(nextBtn);
        
        contentContainer.appendChild(topPanel);
        contentContainer.appendChild(imageContainer);
        contentContainer.appendChild(infoPanel);
        overlay.appendChild(contentContainer);

        document.body.appendChild(overlay);

        // Обработчики событий
        function setupEventListeners() {
            // Закрытие
            const closeOverlay = () => {
                overlay.style.opacity = '0';
                setTimeout(() => {
                    overlay.style.display = 'none';
                    document.body.style.overflow = 'auto';
                    currentOverlay = null;
                    imagesInGallery = [];
                }, 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);
            });

            // Клавиатура
            document.addEventListener('keydown', function keyHandler(e) {
                if (!currentOverlay) return;
                
                switch(e.key) {
                    case 'Escape':
                        closeOverlay();
                        break;
                    case 'ArrowLeft':
                        navigateImages(-1);
                        break;
                    case 'ArrowRight':
                        navigateImages(1);
                        break;
                    case 'i':
                        e.preventDefault();
                        toggleInfoPanel();
                        break;
                }
            });

            // Zoom по клику на изображение
            img.addEventListener('click', (e) => {
                e.stopPropagation();
                if (img.style.transform === 'scale(1.5)') {
                    img.style.transform = 'scale(1)';
                } else {
                    img.style.transform = 'scale(1.5)';
                }
            });

            // Hover эффекты
            [closeBtn, prevBtn, nextBtn].forEach(btn => {
                btn.addEventListener('mouseenter', () => {
                    btn.style.background = 'rgba(0,0,0,0.9)';
                    btn.style.transform = 'scale(1.1)';
                });
                btn.addEventListener('mouseleave', () => {
                    btn.style.background = config.navButtons.background;
                    btn.style.transform = 'scale(1)';
                });
            });
        }

        setupEventListeners();

        return { overlay, img, infoPanel, prevBtn, nextBtn };
    }

    // Создание кнопки навигации
    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.navButtons.size};
            height: ${config.navButtons.size};
            background: ${config.navButtons.background};
            color: ${config.navButtons.color};
            border: none;
            border-radius: 50%;
            font-size: ${config.navButtons.fontSize};
            cursor: pointer;
            display: none;
            align-items: center;
            justify-content: center;
            transition: all 0.2s ease;
            z-index: 10001;
        `;
        return btn;
    }

    // Навигация по изображениям
    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]);
    }

    // Показ информации
    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; // Или можно true, если хотите поддержку галерей
        }

        return true;
    }

    // Показ оверлея
    function showMediaViewerOverlay(imageElement) {
        if (!currentOverlay) {
            currentOverlay = createMediaViewerStyleOverlay();
        }

        // Собираем все изображения для галереи
        imagesInGallery = collectAllImages(imageElement);
        
        if (imagesInGallery.length === 0) return;

        showImage(imagesInGallery[currentImageIndex]);
        
        // Показываем оверлей с анимацией
        currentOverlay.overlay.style.display = 'flex';
        setTimeout(() => {
            currentOverlay.overlay.style.opacity = '1';
        }, 10);
        
        // Блокируем прокрутку
        document.body.style.overflow = 'hidden';
        
        // Показываем/скрываем кнопки навигации
        currentOverlay.prevBtn.style.display = imagesInGallery.length > 1 ? 'flex' : 'none';
        currentOverlay.nextBtn.style.display = imagesInGallery.length > 1 ? 'flex' : 'none';
    }

    // Показ конкретного изображения
    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 для інформації • Esc для закриття
            </div>
        `;
    }

    // Обработчик кликов
    document.addEventListener('click', function(e) {
        const target = e.target;

        // Пропускаем клики внутри оверлея
        if (target.closest('.custom-media-viewer')) {
            return;
        }

        // Клик на картинку
        if (target.tagName === 'IMG' && shouldOpenInOverlay(target)) {
            e.preventDefault();
            e.stopPropagation();
            showMediaViewerOverlay(target);
        }

        // Клик на ссылку с изображением
        if (target.tagName === 'A' && target.href && target.href.match(/\.(jpg|jpeg|png|gif|webp)(\?|$)/i)) {
            const img = target.querySelector('img');
            if (img && shouldOpenInOverlay(img)) {
                e.preventDefault();
                e.stopPropagation();
                showMediaViewerOverlay(img);
            }
        }
    });

    // Стили для плавной анимации
    const style = document.createElement('style');
    style.textContent = `
        .custom-media-viewer * {
            box-sizing: border-box;
        }
        
        .custom-media-viewer button:hover {
            transform: scale(1.1) !important;
        }
        
        .custom-media-viewer img {
            transition: transform 0.3s ease !important;
        }
        
        @media (max-width: 768px) {
            .custom-media-viewer button {
                width: 40px !important;
                height: 40px !important;
                font-size: 18px !important;
            }
        }
    `;
    document.head.appendChild(style);

    console.log('Custom MediaViewer loaded successfully');

})();