var HuSNS = window.HuSNS || {};
HuSNS.ImageViewer = {
    _viewer: null,
    _images: [],
    _currentIndex: 0,
    
    init: function() {
        if (!this._viewer) {
            this._createViewer();
        }
    },
    
    _createViewer: function() {
        this._viewer = document.createElement('div');
        this._viewer.id = 'image-viewer';
        this._viewer.className = 'image-viewer';
        this._viewer.innerHTML = `
            <div class="viewer-header">
                <span class="viewer-counter"></span>
                <span class="viewer-close" onclick="HuSNS.ImageViewer.close()">&times;</span>
            </div>
            <div class="viewer-body">
                <img src="" alt="">
                <div class="viewer-prev" onclick="HuSNS.ImageViewer.prev()"></div>
                <div class="viewer-next" onclick="HuSNS.ImageViewer.next()"></div>
            </div>
            <div class="viewer-footer">
                <span class="viewer-download" onclick="HuSNS.ImageViewer.download()">下载</span>
            </div>
        `;
        document.body.appendChild(this._viewer);
        
        this._viewer.addEventListener('click', function(e) {
            if (e.target === this) {
                HuSNS.ImageViewer.close();
            }
        });
    },
    
    show: function(images, index) {
        this.init();
        this._images = images;
        this._currentIndex = index || 0;
        this._updateViewer();
        this._viewer.style.display = 'flex';
        document.body.style.overflow = 'hidden';
    },
    
    close: function() {
        if (this._viewer) {
            this._viewer.style.display = 'none';
            document.body.style.overflow = '';
        }
    },
    
    prev: function() {
        if (this._currentIndex > 0) {
            this._currentIndex--;
            this._updateViewer();
        }
    },
    
    next: function() {
        if (this._currentIndex < this._images.length - 1) {
            this._currentIndex++;
            this._updateViewer();
        }
    },
    
    _updateViewer: function() {
        var img = this._viewer.querySelector('.viewer-body img');
        var counter = this._viewer.querySelector('.viewer-counter');
        
        if (img) {
            img.src = this._images[this._currentIndex];
        }
        
        if (counter) {
            counter.textContent = (this._currentIndex + 1) + ' / ' + this._images.length;
        }
    },
    
    download: function() {
        var currentImage = this._images[this._currentIndex];
        if (!currentImage) return;
        
        var link = document.createElement('a');
        link.href = currentImage;
        link.download = 'image_' + Date.now() + '.jpg';
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    }
};

if (typeof module !== 'undefined' && module.exports) {
    module.exports = HuSNS.ImageViewer;
}