<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CloudXM Plugins</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        @keyframes spin { to { transform: rotate(360deg); } }
        .animate-spin { animation: spin 1s linear infinite; }
        .scroll-animate { opacity: 0; transform: translateY(30px); transition: opacity 0.6s ease-out, transform 0.6s ease-out; }
        .scroll-animate.visible { opacity: 1; transform: translateY(0); }

        /* Lightbox styles */
        .lightbox {
            display: none;
            position: fixed;
            z-index: 9999;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.9);
            justify-content: center;
            align-items: center;
        }
        .lightbox.active {
            display: flex;
        }
        .lightbox-content {
            max-width: 90%;
            max-height: 90%;
            object-fit: contain;
        }
        .lightbox-close {
            position: absolute;
            top: 20px;
            right: 30px;
            color: #fff;
            font-size: 40px;
            cursor: pointer;
            user-select: none;
        }
        .lightbox-nav {
            position: absolute;
            top: 50%;
            transform: translateY(-50%);
            color: #fff;
            font-size: 50px;
            cursor: pointer;
            user-select: none;
            padding: 20px;
            transition: color 0.2s;
        }
        .lightbox-nav:hover {
            color: #3b82f6;
        }
        .lightbox-prev {
            left: 20px;
        }
        .lightbox-next {
            right: 20px;
        }
        .lightbox-counter {
            position: absolute;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            color: #fff;
            font-size: 16px;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 py-8 lg:py-12">

        <nav class="flex justify-end gap-2 mb-4">
            <a href="/stable" class="inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-lg border border-green-300 text-green-700 hover:bg-green-50 transition-all duration-200">
                Stable
            </a>
            <a href="/dev" class="inline-flex items-center px-3 py-1.5 text-sm font-medium rounded-lg border border-yellow-400 text-yellow-700 hover:bg-yellow-50 transition-all duration-200">
                Development
            </a>
        </nav>

        <header class="text-center mb-10">
            <h1 class="text-3xl lg:text-4xl font-bold text-gray-900 mb-3">
                CloudXM Plugins
                <span id="env-badge" class="ml-2 px-2.5 py-0.5 text-xs font-semibold rounded-full text-white"></span>
            </h1>
            <p class="text-lg text-gray-600 max-w-2xl mx-auto">
                Official plugins for CloudXM NFE Server - automate electronic invoice emission on your platform
            </p>
        </header>

        <div id="content">
            <div class="flex flex-col items-center justify-center py-20 text-gray-500">
                <div class="w-8 h-8 border-3 border-gray-200 border-t-blue-600 rounded-full animate-spin mb-4" style="border-width:3px"></div>
                <p>Loading plugin catalog...</p>
            </div>
        </div>

    </div>

    <!-- Lightbox modal -->
    <div id="lightbox" class="lightbox">
        <span class="lightbox-close">&times;</span>
        <span class="lightbox-nav lightbox-prev">&#10094;</span>
        <img src="" alt="" class="lightbox-content" id="lightbox-img">
        <span class="lightbox-nav lightbox-next">&#10095;</span>
        <div class="lightbox-counter" id="lightbox-counter"></div>
    </div>

    <footer class="mt-16 pt-8 border-t border-gray-200">
        <div class="max-w-5xl mx-auto text-center text-sm text-gray-600">
            <p>&copy; {{CURRENT_YEAR}} CloudXM. Plugins for automated electronic invoice emission.</p>
        </div>
    </footer>

    <script>
        (function() {
            var envConfig = {
                environment: '{{ENVIRONMENT}}',
                environmentClass: '{{ENVIRONMENT_CLASS}}'
            };

            var badge = document.getElementById('env-badge');
            if (envConfig.environmentClass === 'dev') {
                badge.textContent = envConfig.environment;
                badge.className = badge.className + ' bg-yellow-500';
            } else {
                badge.textContent = envConfig.environment;
                badge.className = badge.className + ' bg-green-600';
            }

            async function loadPlugins() {
                try {
                    var pluginsUrl = '{{PLUGINS_URL}}';
                    var response = await fetch(pluginsUrl);
                    var data = await response.json();
                    var content = document.getElementById('content');

                    if (!data.plugins || Object.keys(data.plugins).length === 0) {
                        content.innerHTML = '<div class="text-center py-12 text-gray-500">No plugins available at the moment.</div>';
                        return;
                    }

                    var pluginsHtml = Object.entries(data.plugins).map(function(entry) {
                        var key = entry[0];
                        var plugin = entry[1];
                        var iconLetter = plugin.name.charAt(0).toUpperCase();
                        var downloadFilename = plugin.downloadUrl.split('/').pop();

                        // Fetch screenshots for this plugin from its latest.json
                        // We'll render a placeholder and fill it in asynchronously
                        var cardId = 'card-' + key.replace(/[^a-z0-9]/gi, '-');

                        return '<div id="' + cardId + '" class="scroll-animate bg-white rounded-2xl shadow-lg hover:shadow-2xl transition-all duration-300 border border-gray-100 overflow-hidden">' +
                            '<div class="p-8">' +
                                '<div class="flex flex-col lg:flex-row lg:items-start gap-6">' +
                                    '<div class="flex-shrink-0 w-16 h-16 bg-gradient-to-br from-purple-600 to-indigo-700 rounded-xl flex items-center justify-center">' +
                                        '<span class="text-2xl font-bold text-white">' + iconLetter + '</span>' +
                                    '</div>' +
                                    '<div class="flex-1 min-w-0">' +
                                        '<div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 mb-3">' +
                                            '<h3 class="text-xl font-bold text-gray-900">' + plugin.name + '</h3>' +
                                            '<span class="inline-flex items-center px-3 py-1 rounded-full text-xs font-semibold bg-green-100 text-green-800 self-start">v' + plugin.currentVersion + '</span>' +
                                        '</div>' +
                                        '<p class="text-gray-600 mb-5">' + (plugin.description || 'CloudXM WordPress Plugin') + '</p>' +
                                        '<div class="flex flex-col sm:flex-row gap-3">' +
                                            '<a href="' + plugin.downloadUrl + '" download="' + downloadFilename + '" class="inline-flex items-center justify-center gap-2 bg-blue-600 hover:bg-blue-700 text-white font-semibold py-2.5 px-5 rounded-lg transition duration-200 shadow-md hover:shadow-lg">' +
                                                '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>' +
                                                'Download ZIP' +
                                            '</a>' +
                                            '<a href="' + plugin.distributionUrl + '" class="inline-flex items-center justify-center gap-2 bg-gray-100 hover:bg-gray-200 text-gray-700 font-semibold py-2.5 px-5 rounded-lg transition duration-200">' +
                                                '<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"></path></svg>' +
                                                'View Details' +
                                            '</a>' +
                                        '</div>' +
                                    '</div>' +
                                '</div>' +
                            '</div>' +
                            // Screenshot strip (hidden until loaded) - now AFTER the card content
                            '<div class="screenshot-strip hidden bg-gray-50 border-t border-gray-100" data-plugin="' + key + '">' +
                                '<div class="p-4">' +
                                    '<h4 class="text-sm font-semibold text-gray-700 mb-3">Screenshots</h4>' +
                                    '<div class="flex gap-3 overflow-x-auto pb-2"></div>' +
                                '</div>' +
                            '</div>' +
                        '</div>';
                    }).join('');

                    // After rendering cards, load screenshots for each plugin
                    setTimeout(function() {
                        content.querySelectorAll('.screenshot-strip[data-plugin]').forEach(function(strip) {
                            var pluginKey = strip.getAttribute('data-plugin');
                            var infoUrl = data.plugins[pluginKey] && data.plugins[pluginKey].infoUrl;
                            if (!infoUrl) return;

                            fetch(infoUrl)
                                .then(function(r) { return r.json(); })
                                .then(function(info) {
                                    if (!info.screenshots || info.screenshots.length === 0) return;
                                    var inner = strip.querySelector('.flex.gap-3');
                                    inner.innerHTML = info.screenshots.map(function(url, i) {
                                        return '<a href="' + url + '" data-screenshot-index="' + i + '" class="flex-shrink-0 screenshot-link" data-plugin="' + pluginKey + '">' +
                                            '<img src="' + url + '" alt="Screenshot ' + (i+1) + '" loading="lazy" ' +
                                            'class="h-28 w-auto rounded-lg border border-gray-200 shadow-sm hover:shadow-md hover:scale-105 transition-all duration-200 object-cover cursor-pointer">' +
                                        '</a>';
                                    }).join('');

                                    // Store screenshots array on the strip for navigation
                                    strip.screenshots = info.screenshots;
                                    strip.classList.remove('hidden');

                                    // Add click handlers for lightbox
                                    inner.querySelectorAll('.screenshot-link').forEach(function(link) {
                                        link.addEventListener('click', function(e) {
                                            e.preventDefault();
                                            openLightbox(strip.screenshots, parseInt(this.getAttribute('data-screenshot-index')));
                                        });
                                    });
                                })
                                .catch(function() { /* no screenshots, keep hidden */ });
                        });
                    }, 0);

                    content.innerHTML = '<div class="grid gap-6 max-w-4xl mx-auto">' + pluginsHtml + '</div>';

                    var observer = new IntersectionObserver(function(entries) {
                        entries.forEach(function(entry) {
                            if (entry.isIntersecting) {
                                entry.target.classList.add('visible');
                                observer.unobserve(entry.target);
                            }
                        });
                    }, { threshold: 0.1 });
                    content.querySelectorAll('.scroll-animate').forEach(function(el) { observer.observe(el); });

                    // Lightbox functionality
                    var lightbox = document.getElementById('lightbox');
                    var lightboxImg = document.getElementById('lightbox-img');
                    var lightboxCounter = document.getElementById('lightbox-counter');
                    var currentScreenshots = [];
                    var currentIndex = 0;

                    function openLightbox(screenshots, index) {
                        currentScreenshots = screenshots;
                        currentIndex = index;
                        updateLightboxImage();
                        lightbox.classList.add('active');
                        document.body.style.overflow = 'hidden';
                    }

                    function updateLightboxImage() {
                        lightboxImg.src = currentScreenshots[currentIndex];
                        lightboxCounter.textContent = (currentIndex + 1) + ' / ' + currentScreenshots.length;
                    }

                    function closeLightbox() {
                        lightbox.classList.remove('active');
                        document.body.style.overflow = '';
                        currentScreenshots = [];
                        currentIndex = 0;
                    }

                    function nextImage() {
                        currentIndex = (currentIndex + 1) % currentScreenshots.length;
                        updateLightboxImage();
                    }

                    function prevImage() {
                        currentIndex = (currentIndex - 1 + currentScreenshots.length) % currentScreenshots.length;
                        updateLightboxImage();
                    }

                    // Close button
                    lightbox.querySelector('.lightbox-close').addEventListener('click', closeLightbox);

                    // Navigation buttons
                    lightbox.querySelector('.lightbox-next').addEventListener('click', nextImage);
                    lightbox.querySelector('.lightbox-prev').addEventListener('click', prevImage);

                    // Click outside image to close
                    lightbox.addEventListener('click', function(e) {
                        if (e.target === lightbox) {
                            closeLightbox();
                        }
                    });

                    // Keyboard navigation
                    document.addEventListener('keydown', function(e) {
                        if (!lightbox.classList.contains('active')) return;

                        if (e.key === 'Escape') {
                            closeLightbox();
                        } else if (e.key === 'ArrowRight') {
                            nextImage();
                        } else if (e.key === 'ArrowLeft') {
                            prevImage();
                        }
                    });

                } catch (error) {
                    console.error('Error loading plugins:', error);
                    document.getElementById('content').innerHTML =
                        '<div class="text-center py-12 text-red-500">Failed to load plugin catalog. Please try again later.</div>';
                }
            }

            loadPlugins();
        })();
    </script>
</body>
</html>
