/**
 * PDF Viewer with Auto-Rotation
 * Features: Random shuffle, auto-advance every 3 seconds, thumbnail navigation
 */

class PDFViewer {
    constructor(containerId, options = {}) {
        this.container = document.getElementById(containerId);
        this.options = {
            autoRotate: true,
            rotateInterval: 3000, // 3 seconds
            randomShuffle: true,
            pdfFile: options.pdfFile || 'pdf.pdf',
            ...options
        };
        
        this.pages = [];
        this.currentPage = 0;
        this.shuffledOrder = [];
        this.autoRotateTimer = null;
        this.isLoading = true;
        
        this.init();
    }
    
    async init() {
        await this.loadPDF();
        this.renderViewer();
        this.setupEventListeners();
        
        if (this.options.randomShuffle) {
            this.createShuffledOrder();
        }
        
        if (this.options.autoRotate) {
            this.startAutoRotate();
        }
    }
    
    async loadPDF() {
        try {
            // First, try to get cached images
            const response = await fetch(`pdf_converter.php?action=get&pdf=${this.options.pdfFile}`);
            const data = await response.json();
            
            if (data.error || !data.images || data.images.length === 0) {
                // Not cached, convert now
                const convertResponse = await fetch(`pdf_converter.php?action=convert&pdf=${this.options.pdfFile}`);
                const convertData = await convertResponse.json();
                
                if (convertData.error) {
                    throw new Error(convertData.error);
                }
                
                this.pages = convertData.images;
            } else {
                this.pages = data.images;
            }
            
            this.isLoading = false;
        } catch (error) {
            console.error('Error loading PDF:', error);
            this.showError('Failed to load PDF');
        }
    }
    
    createShuffledOrder() {
        // Create array of page indices
        this.shuffledOrder = this.pages.map((_, i) => i);
        
        // Fisher-Yates shuffle
        for (let i = this.shuffledOrder.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [this.shuffledOrder[i], this.shuffledOrder[j]] = [this.shuffledOrder[j], this.shuffledOrder[i]];
        }
    }
    
    renderViewer() {
        this.container.innerHTML = `
            <div class="pdf-viewer">
                <!-- Top Toolbar -->
                <div class="pdf-toolbar">
                    <div class="pdf-toolbar-left">
                        <button class="pdf-btn" id="pdf-menu-btn">☰</button>
                        <span class="pdf-filename">${this.options.pdfFile}</span>
                    </div>
                    <div class="pdf-toolbar-center">
                        <button class="pdf-btn" id="pdf-prev-btn">←</button>
                        <span class="pdf-page-info">
                            <input type="number" id="pdf-current-page" value="1" min="1" max="${this.pages.length}"> / ${this.pages.length}
                        </span>
                        <button class="pdf-btn" id="pdf-next-btn">→</button>
                    </div>
                    <div class="pdf-toolbar-right">
                        <button class="pdf-btn" id="pdf-zoom-out">−</button>
                        <span class="pdf-zoom-level">100%</span>
                        <button class="pdf-btn" id="pdf-zoom-in">+</button>
                        <button class="pdf-btn" id="pdf-rotate-toggle" title="Toggle Auto-Rotate">⟳</button>
                        <button class="pdf-btn" id="pdf-close" title="Close Viewer">✕</button>
                    </div>
                </div>
                
                <!-- Main Content Area -->
                <div class="pdf-content">
                    <!-- Sidebar with Thumbnails -->
                    <div class="pdf-sidebar" id="pdf-sidebar">
                        <div class="pdf-thumbnails" id="pdf-thumbnails">
                            ${this.renderThumbnails()}
                        </div>
                    </div>
                    
                    <!-- Main Viewer -->
                    <div class="pdf-main-viewer">
                        <div class="pdf-page-container" id="pdf-page-container">
                            <img id="pdf-main-image" class="pdf-main-image" src="" alt="PDF Page">
                        </div>
                    </div>
                </div>
                
                <!-- Loading Indicator -->
                <div class="pdf-loading" id="pdf-loading" style="display: ${this.isLoading ? 'flex' : 'none'}">
                    <div class="pdf-spinner"></div>
                    <p>Loading PDF...</p>
                </div>
            </div>
        `;
        
        // Load first page
        this.goToPage(0);
    }
    
    renderThumbnails() {
        return this.pages.map((page, index) => `
            <div class="pdf-thumbnail ${index === 0 ? 'active' : ''}" data-page="${index}">
                <img src="${page.url}" alt="Page ${page.page}" loading="lazy">
                <div class="pdf-thumbnail-number">${page.page}</div>
            </div>
        `).join('');
    }
    
    setupEventListeners() {
        // Navigation buttons
        document.getElementById('pdf-prev-btn').addEventListener('click', () => this.previousPage());
        document.getElementById('pdf-next-btn').addEventListener('click', () => this.nextPage());
        
        // Page input
        document.getElementById('pdf-current-page').addEventListener('change', (e) => {
            const pageNum = parseInt(e.target.value) - 1;
            if (pageNum >= 0 && pageNum < this.pages.length) {
                this.goToPage(pageNum);
            }
        });
        
        // Auto-rotate toggle
        document.getElementById('pdf-rotate-toggle').addEventListener('click', () => this.toggleAutoRotate());
        
        // Close button
        document.getElementById('pdf-close').addEventListener('click', () => this.close());
        
        // Sidebar toggle
        document.getElementById('pdf-menu-btn').addEventListener('click', () => this.toggleSidebar());
        
        // Thumbnail clicks
        document.querySelectorAll('.pdf-thumbnail').forEach(thumb => {
            thumb.addEventListener('click', () => {
                const pageIndex = parseInt(thumb.getAttribute('data-page'));
                this.goToPage(pageIndex);
                this.stopAutoRotate(); // Stop auto-rotate when user manually navigates
            });
        });
        
        // Keyboard navigation
        document.addEventListener('keydown', (e) => {
            if (e.key === 'ArrowLeft') this.previousPage();
            if (e.key === 'ArrowRight') this.nextPage();
            if (e.key === ' ') {
                e.preventDefault();
                this.toggleAutoRotate();
            }
        });
        
        // Preload next image
        this.preloadNextImage();
    }
    
    goToPage(index) {
        if (index < 0 || index >= this.pages.length) return;
        
        this.currentPage = index;
        const page = this.pages[index];
        
        // Update main image
        const mainImage = document.getElementById('pdf-main-image');
        mainImage.src = page.url;
        
        // Update page number
        document.getElementById('pdf-current-page').value = page.page;
        
        // Update active thumbnail
        document.querySelectorAll('.pdf-thumbnail').forEach(thumb => {
            thumb.classList.remove('active');
        });
        document.querySelector(`.pdf-thumbnail[data-page="${index}"]`)?.classList.add('active');
        
        // Scroll thumbnail into view
        const activeThumbnail = document.querySelector(`.pdf-thumbnail[data-page="${index}"]`);
        if (activeThumbnail) {
            activeThumbnail.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
        }
        
        // Preload next image
        this.preloadNextImage();
    }
    
    nextPage() {
        if (this.options.randomShuffle && this.shuffledOrder.length > 0) {
            const currentShuffledIndex = this.shuffledOrder.indexOf(this.currentPage);
            const nextShuffledIndex = (currentShuffledIndex + 1) % this.shuffledOrder.length;
            this.goToPage(this.shuffledOrder[nextShuffledIndex]);
        } else {
            const nextPage = (this.currentPage + 1) % this.pages.length;
            this.goToPage(nextPage);
        }
    }
    
    previousPage() {
        if (this.options.randomShuffle && this.shuffledOrder.length > 0) {
            const currentShuffledIndex = this.shuffledOrder.indexOf(this.currentPage);
            const prevShuffledIndex = (currentShuffledIndex - 1 + this.shuffledOrder.length) % this.shuffledOrder.length;
            this.goToPage(this.shuffledOrder[prevShuffledIndex]);
        } else {
            const prevPage = (this.currentPage - 1 + this.pages.length) % this.pages.length;
            this.goToPage(prevPage);
        }
    }
    
    startAutoRotate() {
        this.stopAutoRotate();
        this.autoRotateTimer = setInterval(() => {
            this.nextPage();
        }, this.options.rotateInterval);
        
        document.getElementById('pdf-rotate-toggle')?.classList.add('active');
    }
    
    stopAutoRotate() {
        if (this.autoRotateTimer) {
            clearInterval(this.autoRotateTimer);
            this.autoRotateTimer = null;
        }
        document.getElementById('pdf-rotate-toggle')?.classList.remove('active');
    }
    
    toggleAutoRotate() {
        if (this.autoRotateTimer) {
            this.stopAutoRotate();
        } else {
            this.startAutoRotate();
        }
    }
    
    toggleSidebar() {
        const sidebar = document.getElementById('pdf-sidebar');
        sidebar.classList.toggle('collapsed');
    }
    
    close() {
        // Stop auto-rotate
        this.stopAutoRotate();
        
        // Hide PDF viewer
        this.container.style.display = 'none';
        
        // Show main content again
        const mainContent = document.getElementById('main-content');
        if (mainContent) {
            mainContent.style.display = 'block';
        }
    }
    
    preloadNextImage() {
        const nextIndex = (this.currentPage + 1) % this.pages.length;
        const nextPage = this.pages[nextIndex];
        
        // Preload next image
        const img = new Image();
        img.src = nextPage.url;
    }
    
    showError(message) {
        this.container.innerHTML = `
            <div class="pdf-error">
                <h2>Error</h2>
                <p>${message}</p>
            </div>
        `;
    }
}

// PDF Viewer is now initialized on button click from index.php
// No auto-initialization needed here

