- Improve this whole script further and Make it significantly better. 
- Makesure that script can be saved as a bookmarklet in my browser and when executed on any webpage or website it should extract all of the image urls present in that particular webpage and display all of the image urls as images in imageviewer.
- improve ui and ux too.
- modern and visually appealing ui.
- don't use framework.
- fix all of the possible edge cases, errors, bottlenecks, loopholes, leaks, etc..
- use only free and lightweight resources.
- make sure I can use it as bookmarklet in my browser and execute on any webpage to extract all of the images from the webpage and display all of images seamlessly..
- optimise it fully but only for mobile browser in any circumstances possible.
- always consider all of the possible consequences of your modification before modifying.
- make it smooth and fast as possible.
- Send the fully working full improved code.
think step by step.
--
(function(){
    try {
        // Enhanced Configuration
        const CONFIG = {
            MAX_IMAGES: 100,                    // Increased maximum number of images
            CORS_PROXIES: [                     // Multiple fallback proxies
                'https://corsproxy.io/?',
                'https://api.allorigins.win/raw?url=',
                'https://api.codetabs.com/v1/proxy?quest='
            ],
            ZOOM: {
                MIN: 0.5,                       // Minimum zoom level
                MAX: 10,                        // Maximum zoom level
                STEP: 0.1                       // Zoom step increment
            },
            SLIDESHOW: {
                MIN_INTERVAL: 0.5,              // Minimum slideshow interval in seconds
                MAX_INTERVAL: 60,               // Maximum slideshow interval
                DEFAULT_INTERVAL: 3             // Default interval
            },
            PRELOAD: {
                ADJACENT: 2,                    // Number of adjacent images to preload
                CHUNK_SIZE: 5                   // Number of images to load in each chunk
            },
            ANIMATION: {
                DURATION: 300,                  // Animation duration in milliseconds
                EASING: 'cubic-bezier(0.4, 0, 0.2, 1)' // Smooth easing function
            }
        };

        // Prevent multiple instances
        if (window.ultimateHighslideViewer) {
            window.ultimateHighslideViewer.focus();
            return;
        }

        // Enhanced image source gathering
        function gatherImageSources() {
            const sources = new Set();
            
            // Query multiple potential image selectors
            const selectors = [
                'img.highslide-image',
                'img[data-highslide]',
                'a.highslide img',
                'img[data-large-src]',
                'img[data-full-src]'
            ];

            selectors.forEach(selector => {
                document.querySelectorAll(selector).forEach(img => {
                    // Try multiple possible source attributes
                    ['src', 'data-src', 'data-large-src', 'data-full-src', 'href'].forEach(attr => {
                        const src = img.getAttribute(attr) || img.closest('a')?.href;
                        if (src) sources.add(sanitizeURL(src));
                    });
                });
            });

            return Array.from(sources).slice(0, CONFIG.MAX_IMAGES);
        }

        // Enhanced URL sanitization with additional security checks
        function sanitizeURL(url) {
            try {
                const sanitized = new URL(url, window.location.href);
                // Ensure URL is either from same origin or uses https
                if (sanitized.protocol !== 'https:' && sanitized.origin !== window.location.origin) {
                    return '';
                }
                return sanitized.href;
            } catch(e) {
                return '';
            }
        }

        // Gather images with enhanced detection
        const images = gatherImageSources();

        if(images.length === 0) {
            alert('No compatible images found on this page.');
            return;
        }

        // Create viewer window with improved features
        const viewer = window.open('', '_blank', 'width=1200,height=800,scrollbars=no,resizable=yes');

        if(!viewer) {
            alert('Popup blocked! Please allow popups for this website to use the image viewer.');
            return;
        }

        window.ultimateHighslideViewer = viewer;

        // Enhanced HTML content with additional features
        const htmlContent = `
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Enhanced Ultra-Robust Image Viewer</title>
            <style>
                /* Base Styles */
                :root {
                    --primary-color: #2196F3;
                    --secondary-color: #333;
                    --background-color: #000;
                    --text-color: #fff;
                    --overlay-color: rgba(0, 0, 0, 0.75);
                    --transition-duration: 300ms;
                }

                * {
                    margin: 0;
                    padding: 0;
                    box-sizing: border-box;
                }

                body {
                    margin: 0;
                    background-color: var(--background-color);
                    color: var(--text-color);
                    font-family: system-ui, -apple-system, sans-serif;
                    overflow: hidden;
                    position: relative;
                    height: 100vh;
                    display: grid;
                    grid-template-rows: auto 1fr auto;
                }

                /* Enhanced Controls */
                .controls {
                    position: fixed;
                    z-index: 100;
                    padding: 1rem;
                    display: flex;
                    gap: 1rem;
                    background: var(--overlay-color);
                    border-radius: 8px;
                    backdrop-filter: blur(10px);
                    transition: opacity var(--transition-duration);
                }

                .controls-top {
                    top: 1rem;
                    right: 1rem;
                }

                .controls-bottom {
                    bottom: 1rem;
                    left: 50%;
                    transform: translateX(-50%);
                }

                /* Enhanced Buttons */
                .button {
                    background: var(--primary-color);
                    color: var(--text-color);
                    border: none;
                    padding: 0.75rem 1.25rem;
                    border-radius: 6px;
                    cursor: pointer;
                    font-size: 0.9rem;
                    font-weight: 500;
                    transition: all var(--transition-duration);
                    display: flex;
                    align-items: center;
                    gap: 0.5rem;
                }

                .button:hover {
                    background: color-mix(in srgb, var(--primary-color) 80%, white);
                    transform: translateY(-1px);
                }

                .button:active {
                    transform: translateY(0);
                }

                /* Enhanced Image Container */
                .image-container {
                    position: relative;
                    width: 100%;
                    height: 100%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    overflow: hidden;
                }

                .main-image {
                    max-width: 100%;
                    max-height: 100%;
                    object-fit: contain;
                    transition: transform var(--transition-duration) var(--animation-easing);
                    will-change: transform;
                }

                /* Enhanced Thumbnails */
                .thumbnails {
                    position: fixed;
                    bottom: 5rem;
                    left: 50%;
                    transform: translateX(-50%);
                    display: flex;
                    gap: 0.5rem;
                    padding: 1rem;
                    background: var(--overlay-color);
                    border-radius: 8px;
                    backdrop-filter: blur(10px);
                    max-width: 90vw;
                    overflow-x: auto;
                    scrollbar-width: thin;
                    scrollbar-color: var(--primary-color) transparent;
                }

                .thumbnail {
                    height: 80px;
                    border: 2px solid transparent;
                    border-radius: 4px;
                    transition: all var(--transition-duration);
                    cursor: pointer;
                    opacity: 0.7;
                }

                .thumbnail:hover {
                    opacity: 0.9;
                    transform: translateY(-2px);
                }

                .thumbnail.active {
                    border-color: var(--primary-color);
                    opacity: 1;
                }

                /* Enhanced Loading States */
                .loader {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                }

                .loader::after {
                    content: '';
                    display: block;
                    width: 40px;
                    height: 40px;
                    border-radius: 50%;
                    border: 4px solid var(--text-color);
                    border-top-color: var(--primary-color);
                    animation: spin 1s linear infinite;
                }

                @keyframes spin {
                    to { transform: rotate(360deg); }
                }

                /* Enhanced Error States */
                .error {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                    background: var(--overlay-color);
                    padding: 2rem;
                    border-radius: 8px;
                    text-align: center;
                    max-width: 80%;
                }

                /* Enhanced Navigation */
                .nav-button {
                    position: fixed;
                    top: 50%;
                    transform: translateY(-50%);
                    background: var(--overlay-color);
                    color: var(--text-color);
                    border: none;
                    width: 48px;
                    height: 48px;
                    border-radius: 50%;
                    cursor: pointer;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    transition: all var(--transition-duration);
                    z-index: 90;
                }

                .nav-button:hover {
                    background: var(--primary-color);
                    transform: translateY(-50%) scale(1.1);
                }

                .nav-prev { left: 1rem; }
                .nav-next { right: 1rem; }

                /* Enhanced Tooltips */
                [data-tooltip] {
                    position: relative;
                }

                [data-tooltip]::before {
                    content: attr(data-tooltip);
                    position: absolute;
                    bottom: 100%;
                    left: 50%;
                    transform: translateX(-50%);
                    padding: 0.5rem;
                    background: var(--overlay-color);
                    border-radius: 4px;
                    font-size: 0.8rem;
                    white-space: nowrap;
                    opacity: 0;
                    pointer-events: none;
                    transition: all var(--transition-duration);
                }

                [data-tooltip]:hover::before {
                    opacity: 1;
                    transform: translateX(-50%) translateY(-0.5rem);
                }

                /* Enhanced Responsive Design */
                @media (max-width: 768px) {
                    .controls {
                        padding: 0.75rem;
                        gap: 0.5rem;
                    }

                    .button {
                        padding: 0.5rem 1rem;
                        font-size: 0.8rem;
                    }

                    .thumbnail {
                        height: 60px;
                    }

                    .nav-button {
                        width: 40px;
                        height: 40px;
                    }
                }

                /* Enhanced Accessibility */
                @media (prefers-reduced-motion: reduce) {
                    * {
                        animation-duration: 0.01ms !important;
                        animation-iteration-count: 1 !important;
                        transition-duration: 0.01ms !important;
                        scroll-behavior: auto !important;
                    }
                }

                .sr-only {
                    position: absolute;
                    width: 1px;
                    height: 1px;
                    padding: 0;
                    margin: -1px;
                    overflow: hidden;
                    clip: rect(0, 0, 0, 0);
                    white-space: nowrap;
                    border: 0;
                }
            </style>
        </head>
        <body>
            <div class="controls controls-top">
                <button class="button" id="proxyToggle" data-tooltip="Toggle CORS Proxy">
                    <span class="proxy-status">Direct</span>
                </button>
                <button class="button" id="downloadBtn" data-tooltip="Download Image">
                    Download
                </button>
                <button class="button" id="fullscreenBtn" data-tooltip="Toggle Fullscreen">
                    Fullscreen
                </button>
            </div>

            <div class="image-container" id="imageContainer">
                <img class="main-image" id="mainImage" alt="Main view" loading="lazy">
                <div class="loader" id="loader"></div>
                <div class="error" id="error" style="display: none">
                    <h3>Failed to load image</h3>
                    <p>Try enabling the proxy or check your connection.</p>
                </div>
            </div>

            <button class="nav-button nav-prev" id="prevBtn" aria-label="Previous image">←</button>
            <button class="nav-button nav-next" id="nextBtn" aria-label="Next image">→</button>

            <div class="controls controls-bottom">
                <button class="button" id="slideshowBtn">Start Slideshow</button>
                <input type="number" id="slideshowInterval" value="3" min="0.5" max="60" step="0.5"
                    style="width: 60px; padding: 0.5rem; border-radius: 4px; border: none;">
                <button class="button" id="resetBtn" data-tooltip="Reset View">Reset</button>
            </div>

            <div class="thumbnails" id="thumbnails"></div>

            <script>
                (function() {
                    // Enhanced State Management
                    const state = {
                        images: ${JSON.stringify(images)},
                        currentIndex: 0,
                        proxyIndex: 0,
                        scale: 1,
                        rotation: 0,
                        translateX: 0,
                        translateY: 0,
                        isMoving: false,
                        loadedImages: new Set(),
                        slideshowInterval: null,
                        gestureStart: { x: 0, y: 0, distance: 0 },
                        imageCache: new Map(),
                        errorCount: new Map(),
                    };

                    // Enhanced Element References
                    const elements = {
                        container: document.getElementById('imageContainer'),
                        image: document.getElementById('mainImage'),
                        loader: document.getElementById('loader'),
                        error: document.getElementById('error'),
                        prevBtn: document.getElementById('prevBtn'),
                        nextBtn: document.getElementById('nextBtn'),
                        proxyBtn: document.getElementById('proxyToggle'),
                        downloadBtn: document.getElementById('downloadBtn'),
                        fullscreenBtn: document.getElementById('fullscreenBtn'),
                        slideshowBtn: document.getElementById('slideshowBtn'),
                        intervalInput: document.getElementById('slideshowInterval'),
                        resetBtn: document.getElementById('resetBtn'),
                        thumbnails: document.getElementById('thumbnails'),
                    };

                    // Enhanced Image Loading System
                    class ImageLoader {
                        constructor() {
                            this.cache = new Map();
                            this.loading = new Map();
                            this.errors = new Map();
                        }

                        async load(url, useProxy = false) {
                            const cacheKey = useProxy ? `proxy-${url}` : url;
                            
                            // Check cache first
                            // Check cache first
                            if (this.cache.has(cacheKey)) {
                                return this.cache.get(cacheKey);
                            }

                            // Handle concurrent loading requests
                            if (this.loading.has(cacheKey)) {
                                return this.loading.get(cacheKey);
                            }

                            const loadPromise = new Promise(async (resolve, reject) => {
                                try {
                                    const finalUrl = useProxy ? 
                                        CONFIG.CORS_PROXIES[state.proxyIndex] + encodeURIComponent(url) : 
                                        url;

                                    const img = new Image();
                                    img.crossOrigin = 'anonymous';

                                    img.onload = () => {
                                        this.cache.set(cacheKey, img);
                                        this.loading.delete(cacheKey);
                                        resolve(img);
                                    };

                                    img.onerror = () => {
                                        this.errors.set(cacheKey, (this.errors.get(cacheKey) || 0) + 1);
                                        this.loading.delete(cacheKey);
                                        reject(new Error(`Failed to load image: ${url}`));
                                    };

                                    img.src = finalUrl;
                                } catch (error) {
                                    this.loading.delete(cacheKey);
                                    reject(error);
                                }
                            });

                            this.loading.set(cacheKey, loadPromise);
                            return loadPromise;
                        }

                        preloadAdjacent(currentIndex) {
                            const indices = [];
                            for (let i = 1; i <= CONFIG.PRELOAD.ADJACENT; i++) {
                                indices.push((currentIndex + i) % state.images.length);
                                indices.push((currentIndex - i + state.images.length) % state.images.length);
                            }

                            indices.forEach(index => {
                                const url = state.images[index];
                                if (!this.cache.has(url)) {
                                    this.load(url, state.proxyIndex > 0).catch(() => {});
                                }
                            });
                        }
                    }

                    const imageLoader = new ImageLoader();

                    // Enhanced Image Display Controller
                    class ImageDisplayController {
                        constructor() {
                            this.bindEvents();
                            this.setupIntersectionObserver();
                        }

                        async showImage(index, transition = true) {
                            if (index < 0 || index >= state.images.length) return;

                            const url = state.images[index];
                            elements.loader.style.display = 'block';
                            elements.error.style.display = 'none';
                            elements.image.style.opacity = transition ? '0' : '1';

                            try {
                                const img = await imageLoader.load(url, state.proxyIndex > 0);
                                
                                if (transition) {
                                    await this.fadeOut(elements.image);
                                }

                                elements.image.src = img.src;
                                state.currentIndex = index;
                                this.updateThumbnails();
                                this.resetView();

                                if (transition) {
                                    await this.fadeIn(elements.image);
                                }

                                imageLoader.preloadAdjacent(index);
                            } catch (error) {
                                this.handleLoadError(url);
                            } finally {
                                elements.loader.style.display = 'none';
                            }
                        }

                        async fadeOut(element) {
                            return new Promise(resolve => {
                                element.style.transition = `opacity ${CONFIG.ANIMATION.DURATION}ms ${CONFIG.ANIMATION.EASING}`;
                                element.style.opacity = '0';
                                setTimeout(resolve, CONFIG.ANIMATION.DURATION);
                            });
                        }

                        async fadeIn(element) {
                            return new Promise(resolve => {
                                element.style.transition = `opacity ${CONFIG.ANIMATION.DURATION}ms ${CONFIG.ANIMATION.EASING}`;
                                element.style.opacity = '1';
                                setTimeout(resolve, CONFIG.ANIMATION.DURATION);
                            });
                        }

                        handleLoadError(url) {
                            const errorCount = imageLoader.errors.get(url) || 0;
                            
                            if (errorCount === 1 && state.proxyIndex === 0) {
                                state.proxyIndex = 1;
                                elements.proxyBtn.querySelector('.proxy-status').textContent = 'Proxy 1';
                                this.showImage(state.currentIndex, false);
                            } else if (state.proxyIndex < CONFIG.CORS_PROXIES.length - 1) {
                                state.proxyIndex++;
                                elements.proxyBtn.querySelector('.proxy-status').textContent = `Proxy ${state.proxyIndex}`;
                                this.showImage(state.currentIndex, false);
                            } else {
                                elements.error.style.display = 'block';
                            }
                        }

                        resetView() {
                            state.scale = 1;
                            state.rotation = 0;
                            state.translateX = 0;
                            state.translateY = 0;
                            this.updateTransform();
                        }

                        updateTransform() {
                            elements.image.style.transform = `
                                translate(${state.translateX}px, ${state.translateY}px)
                                rotate(${state.rotation}deg)
                                scale(${state.scale})
                            `;
                        }

                        updateThumbnails() {
                            const thumbnails = elements.thumbnails.querySelectorAll('.thumbnail');
                            thumbnails.forEach((thumb, index) => {
                                thumb.classList.toggle('active', index === state.currentIndex);
                                if (index === state.currentIndex) {
                                    thumb.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'center' });
                                }
                            });
                        }

                        setupIntersectionObserver() {
                            const options = {
                                root: elements.thumbnails,
                                rootMargin: '20px',
                                threshold: 0.1
                            };

                            const observer = new IntersectionObserver((entries) => {
                                entries.forEach(entry => {
                                    if (entry.isIntersecting) {
                                        const img = entry.target;
                                        if (!img.src && img.dataset.src) {
                                            img.src = img.dataset.src;
                                            observer.unobserve(img);
                                        }
                                    }
                                });
                            }, options);

                            // Observe all thumbnails
                            elements.thumbnails.querySelectorAll('.thumbnail').forEach(thumb => {
                                observer.observe(thumb);
                            });
                        }

                        bindEvents() {
                            // Navigation Controls
                            elements.prevBtn.addEventListener('click', () => {
                                this.showImage((state.currentIndex - 1 + state.images.length) % state.images.length);
                            });

                            elements.nextBtn.addEventListener('click', () => {
                                this.showImage((state.currentIndex + 1) % state.images.length);
                            });

                            // Proxy Toggle
                            elements.proxyBtn.addEventListener('click', () => {
                                state.proxyIndex = (state.proxyIndex + 1) % (CONFIG.CORS_PROXIES.length + 1);
                                elements.proxyBtn.querySelector('.proxy-status').textContent = 
                                    state.proxyIndex === 0 ? 'Direct' : `Proxy ${state.proxyIndex}`;
                                this.showImage(state.currentIndex, false);
                            });

                            // Slideshow Controls
                            elements.slideshowBtn.addEventListener('click', () => {
                                if (state.slideshowInterval) {
                                    clearInterval(state.slideshowInterval);
                                    state.slideshowInterval = null;
                                    elements.slideshowBtn.textContent = 'Start Slideshow';
                                } else {
                                    const interval = Math.max(
                                        CONFIG.SLIDESHOW.MIN_INTERVAL,
                                        Math.min(CONFIG.SLIDESHOW.MAX_INTERVAL,
                                        parseFloat(elements.intervalInput.value))
                                    ) * 1000;

                                    state.slideshowInterval = setInterval(() => {
                                        this.showImage((state.currentIndex + 1) % state.images.length);
                                    }, interval);
                                    elements.slideshowBtn.textContent = 'Stop Slideshow';
                                }
                            });

                            // Fullscreen Toggle
                            elements.fullscreenBtn.addEventListener('click', () => {
                                if (!document.fullscreenElement) {
                                    document.documentElement.requestFullscreen();
                                    elements.fullscreenBtn.textContent = 'Exit Fullscreen';
                                } else {
                                    document.exitFullscreen();
                                    elements.fullscreenBtn.textContent = 'Fullscreen';
                                }
                            });

                            // Download Button
                            elements.downloadBtn.addEventListener('click', () => {
                                const link = document.createElement('a');
                                link.href = elements.image.src;
                                link.download = `image_${state.currentIndex + 1}`;
                                link.click();
                            });

                            // Keyboard Navigation
                            document.addEventListener('keydown', (e) => {
                                switch(e.key) {
                                    case 'ArrowLeft': elements.prevBtn.click(); break;
                                    case 'ArrowRight': elements.nextBtn.click(); break;
                                    case 'Escape': window.close(); break;
                                }
                            });

                            // Touch and Mouse Controls for Pan/Zoom
                            this.setupTouchControls();
                            this.setupMouseControls();
                        }

                        setupTouchControls() {
                            let initialTouchDistance = 0;
                            let initialScale = 1;

                            elements.container.addEventListener('touchstart', (e) => {
                                if (e.touches.length === 2) {
                                    initialTouchDistance = Math.hypot(
                                        e.touches[0].clientX - e.touches[1].clientX,
                                        e.touches[0].clientY - e.touches[1].clientY
                                    );
                                    initialScale = state.scale;
                                    e.preventDefault();
                                }
                            });

                            elements.container.addEventListener('touchmove', (e) => {
                                if (e.touches.length === 2) {
                                    const currentDistance = Math.hypot(
                                        e.touches[0].clientX - e.touches[1].clientX,
                                        e.touches[0].clientY - e.touches[1].clientY
                                    );
                                    
                                    const scaleFactor = currentDistance / initialTouchDistance;
                                    state.scale = Math.min(
                                        Math.max(initialScale * scaleFactor, CONFIG.ZOOM.MIN),
                                        CONFIG.ZOOM.MAX
                                    );
                                    
                                    this.updateTransform();
                                    e.preventDefault();
                                }
                            });
                        }

                        setupMouseControls() {
                            let isDragging = false;
                            let startX, startY;
                            let initialTranslateX, initialTranslateY;

                            elements.container.addEventListener('mousedown', (e) => {
                                if (e.button === 0) {
                                    isDragging = true;
                                    startX = e.clientX;
                                    startY = e.clientY;
                                    initialTranslateX = state.translateX;
                                    initialTranslateY = state.translateY;
                                    elements.container.style.cursor = 'grabbing';
                                }
                            });

                            elements.container.addEventListener('mousemove', (e) => {
                                if (isDragging) {
                                    state.translateX = initialTranslateX + (e.clientX - startX);
                                    state.translateY = initialTranslateY + (e.clientY - startY);
                                    this.updateTransform();
                                }
                            });

                            elements.container.addEventListener('mouseup', () => {
                                isDragging = false;
                                elements.container.style.cursor = 'grab';
                            });

                            elements.container.addEventListener('mouseleave', () => {
                                isDragging = false;
                                elements.container.style.cursor = 'grab';
                            });

                            elements.container.addEventListener('wheel', (e) => {
                                e.preventDefault();
                                const rect = elements.image.getBoundingClientRect();
                                const mouseX = e.clientX - rect.left;
                                const mouseY = e.clientY - rect.top;

                                const scaleFactor = e.deltaY < 0 ? 1.1 : 0.9;
                                const newScale = Math.min(
                                    Math.max(state.scale * scaleFactor, CONFIG.ZOOM.MIN),
                                    CONFIG.ZOOM.MAX
                                );

                                // Zoom towards mouse position
                                if (newScale !== state.scale) {
                                    const scaleRatio = newScale / state.scale;
                                    state.scale = newScale;
                                    state.translateX = mouseX - (mouseX - state.translateX) * scaleRatio;
                                    state.translateY = mouseY - (mouseY - state.translateY) * scaleRatio;
                                    this.updateTransform();
                                }
                            });
                        }
                    }

                    // Initialize the viewer
                    const displayController = new ImageDisplayController();

                    // Create thumbnails
                    state.images.forEach((src, index) => {
                        const thumb = document.createElement('img');
                        thumb.className = 'thumbnail';
                        thumb.dataset.src = src; // For lazy loading
                        thumb.alt = `Thumbnail ${index + 1}`;
                        thumb.addEventListener('click', () => {
                            displayController.showImage(index);
                        });
                        elements.thumbnails.appendChild(thumb);
                    });

                    // Start with first image
                    displayController.showImage(0, false);

                    // Cleanup on window close
                    window.addEventListener('beforeunload', () => {
                        if (state.slideshowInterval) {
                            clearInterval(state.slideshowInterval);
                        }
                        window.ultimateHighslideViewer = null;
                    });
                })();
            </script>
        </body>
        </html>
        `;

        // Write the HTML content to the new window
        viewer.document.open();
        viewer.document.write(htmlContent);
        viewer.document.close();

    } catch (error) {
        console.error('Enhanced Ultra-Robust Image Viewer Error:', error);
        alert('An error occurred while launching the image viewer. Please try again.');
    }
})();