document.addEventListener("DOMContentLoaded", function() {
    console.log('🔥 Script.js loaded!');
    
    // Theme management
    initializeTheme();
    
    const dropArea = document.getElementById('drop-area');
    const fileInput = document.getElementById('fileInput');
    const progressContainer = document.getElementById('progressContainer');
    const    function updateThemeButton(themeSetting) {
        const themeToggle = document.getElementById('themeToggle');
        if (themeToggle) {
            if (themeSetting === 'light') {
                themeToggle.textContent = '🌙';
                themeToggle.title = 'Switch to dark mode';
            } else {
                themeToggle.textContent = '☀️';
                themeToggle.title = 'Switch to light mode';
            }
        }
    } = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    const result = document.getElementById('result');
    
    const fileModeButton = document.getElementById('fileMode');
    const pasteModeButton = document.getElementById('pasteMode');
    const faqButton = document.getElementById('faqButton');

    const fileSharingSection = document.getElementById('fileSharingSection');
    const pastebinSection = document.getElementById('pastebinSection');
    const faqSection = document.getElementById('faqSection');

    const pasteContent = document.getElementById('pasteContent');
    const submitPasteButton = document.getElementById('submitPaste');
    const pasteResult = document.getElementById('pasteResult');
    
    let filesToUpload = [];

    // Toggle between file sharing, pastebin, and FAQ sections
    fileModeButton.addEventListener('click', () => {
        showSection(fileSharingSection);
        hideSection(pastebinSection);
        hideSection(faqSection);
        activateButton(fileModeButton);
    });

    pasteModeButton.addEventListener('click', () => {
        showSection(pastebinSection);
        hideSection(fileSharingSection);
        hideSection(faqSection);
        activateButton(pasteModeButton);
    });

    faqButton.addEventListener('click', () => {
        showSection(faqSection);
        hideSection(fileSharingSection);
        hideSection(pastebinSection);
        activateButton(faqButton);
    });

    // Helper function to show a section
    function showSection(section) {
        section.style.display = 'block';
    }

    // Helper function to hide a section
    function hideSection(section) {
        section.style.display = 'none';
    }

    // Helper function to activate a button
    function activateButton(button) {
        const buttons = [fileModeButton, pasteModeButton, faqButton];
        buttons.forEach(btn => btn.classList.remove('active'));
        button.classList.add('active');
    }

    // Make drop area clickable
    dropArea.addEventListener('click', () => {
        fileInput.click();
    });

    // Drag-and-drop events
    dropArea.addEventListener('dragover', (event) => {
        event.preventDefault();
        dropArea.classList.add('dragging');
    });

    dropArea.addEventListener('dragleave', () => {
        dropArea.classList.remove('dragging');
    });

    dropArea.addEventListener('drop', (event) => {
        event.preventDefault();
        dropArea.classList.remove('dragging');
        
        filesToUpload = event.dataTransfer.files;
        displaySelectedFiles(filesToUpload);
        handleFileUpload(filesToUpload);
    });

    // Handle file input selection
    fileInput.addEventListener('change', (event) => {
        filesToUpload = event.target.files;
        displaySelectedFiles(filesToUpload);
        handleFileUpload(filesToUpload);
    });

    // Helper function to display selected files
    function displaySelectedFiles(files) {
        result.innerHTML = '<p>� Uploading files...</p>';
    }

    // Handle file upload (simplified, no encryption)
    async function handleFileUpload(files) {
        console.log('� Starting file upload...');
        
        // Check file sizes first (default 100MB)
        const maxSizeMB = 100;
        for (let file of files) {
            if (file.size > maxSizeMB * 1024 * 1024) {
                result.innerHTML = `<div class="error">File too large: ${file.name} (${(file.size/1024/1024).toFixed(2)}MB). Max allowed: ${maxSizeMB}MB.</div>`;
                return;
            }
        }
        
        try {
            progressContainer.style.display = 'block';
            progressText.textContent = 'Uploading files...';
            
            const uploadPromises = Array.from(files).map(async (file, index) => {
                try {
                    console.log(`� Uploading file: ${file.name}`);
                    
                    // Create form data with file
                    const formData = new FormData();
                    formData.append('file', file);
                    
                    // Upload file
                    const response = await fetch('/api/upload', {
                        method: 'POST',
                        body: formData
                    });
                    
                    if (!response.ok) {
                        throw new Error(`Upload failed: ${response.statusText}`);
                    }
                    
                    const result = await response.json();
                    console.log('📤 Upload response:', result);
                    
                    return {
                        url: result.urls[0],
                        file: file,
                        originalSize: file.size
                    };
                    
                } catch (error) {
                    console.error(`❌ Failed to upload ${file.name}:`, error);
                    throw error;
                }
            });
            
            // Wait for all uploads to complete
            const results = await Promise.all(uploadPromises);
            
            // Update progress
            progressBar.style.width = '100%';
            progressText.textContent = '100%';
            
            // Display results
            displayUploadedFiles(results);
            
        } catch (error) {
            console.error('❌ Upload process failed:', error);
            result.innerHTML = `<div class="error">Upload failed: ${error.message}</div>`;
        } finally {
            // Hide progress after a short delay
            setTimeout(() => {
                progressContainer.style.display = 'none';
                progressBar.style.width = '0%';
                progressText.textContent = '0%';
            }, 2000);
        }
    }

    // Display uploaded files
    function displayUploadedFiles(results) {
        console.log('� Displaying file results:', results);
        
        result.innerHTML = '';
        
        const header = document.createElement('div');
        header.innerHTML = '<h3>� Files Uploaded</h3>';
        result.appendChild(header);
        
        results.forEach((fileResult, index) => {
            const fileContainer = document.createElement('div');
            fileContainer.style.marginBottom = '15px';
            fileContainer.style.padding = '15px';
            fileContainer.style.border = '2px solid #4CAF50';
            fileContainer.style.borderRadius = '8px';
            fileContainer.style.backgroundColor = '#f0f8f0';
            
            const fileName = document.createElement('div');
            fileName.innerHTML = `<strong>📄 ${fileResult.file.name}</strong>`;
            fileName.style.marginBottom = '10px';
            fileContainer.appendChild(fileName);
            
            const fileSize = document.createElement('div');
            fileSize.innerHTML = `� Size: ${(fileResult.originalSize / 1024).toFixed(1)} KB`;
            fileSize.style.marginBottom = '10px';
            fileSize.style.fontSize = '14px';
            fileContainer.appendChild(fileSize);
            
            const buttonContainer = document.createElement('div');
            buttonContainer.style.display = 'flex';
            buttonContainer.style.gap = '10px';
            buttonContainer.style.flexWrap = 'wrap';
            
            // Share button
            const shareButton = document.createElement('button');
            shareButton.textContent = '🔗 Copy Link';
            shareButton.className = 'share-button';
            shareButton.addEventListener('click', () => {
                navigator.clipboard.writeText(fileResult.url).then(() => {
                    shareButton.textContent = '✅ Copied!';
                    setTimeout(() => {
                        shareButton.textContent = '🔗 Copy Link';
                    }, 2000);
                });
            });
            buttonContainer.appendChild(shareButton);
            
            // View button
            const viewButton = document.createElement('button');
            viewButton.textContent = '👁️ View';
            viewButton.className = 'view-button';
            viewButton.addEventListener('click', () => {
                window.open(fileResult.url, '_blank');
            });
            buttonContainer.appendChild(viewButton);
            
            // QR Code button
            const qrButton = document.createElement('button');
            qrButton.textContent = '📱 QR Code';
            qrButton.className = 'qr-button';
            qrButton.style.backgroundColor = '#9C27B0';
            qrButton.style.color = 'white';
            qrButton.addEventListener('click', () => {
                console.log('🔍 QR button clicked for file:', fileResult.file.name);
                showQRCode(fileResult.url, fileResult.file.name);
            });
            buttonContainer.appendChild(qrButton);
            
            fileContainer.appendChild(buttonContainer);
            
            result.appendChild(fileContainer);
        });
    }

    // Handle paste submission (simplified, no encryption)
    submitPasteButton.addEventListener('click', async () => {
        const content = pasteContent.value.trim();
        
        if (!content) {
            pasteResult.innerHTML = '<p class="error">Please enter some content</p>';
            return;
        }
        
        try {
            pasteResult.innerHTML = '<p>� Uploading paste...</p>';
            
            // Upload paste
            const response = await fetch('/api/paste', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    content: content
                })
            });
            
            if (!response.ok) {
                throw new Error(`Upload failed: ${response.statusText}`);
            }
            
            const result = await response.json();
            const url = result.url;
            
            // Display result
            displayPasteResult(url, content.length);
            
            // Clear the textarea
            pasteContent.value = '';
            
        } catch (error) {
            console.error('❌ Paste upload failed:', error);
            pasteResult.innerHTML = `<div class="error">Paste upload failed: ${error.message}</div>`;
        }
    });

    // Display paste result
    function displayPasteResult(url, originalLength) {
        pasteResult.innerHTML = `
            <div style="border: 2px solid #4CAF50; border-radius: 8px; padding: 15px; background: #f0f8f0; margin-top: 15px;">
                <h3>� Paste Uploaded</h3>
                <p>📝 Content: ${originalLength} characters</p>
                <div style="display: flex; gap: 10px; margin-top: 10px;">
                    <button class="share-button" onclick="navigator.clipboard.writeText('${url}').then(() => { this.textContent = '✅ Copied!'; setTimeout(() => this.textContent = '🔗 Copy Link', 2000); })">🔗 Copy Link</button>
                    <button class="view-button" onclick="window.open('${url}', '_blank')">👁️ View</button>
                    <button class="qr-button" style="background-color: #9C27B0; color: white;" onclick="showQRCode('${url}', 'Paste (${originalLength} chars)')">📱 QR Code</button>
                </div>
            </div>
        `;
    }

    // Theme management functions
    function initializeTheme() {
        // Get saved theme from cookie or default to light
        const savedTheme = getCookie('sharey-theme') || 'light';
        
        // Apply the theme
        applyTheme(savedTheme);
        
        // Set up theme toggle button
        const themeToggle = document.getElementById('themeToggle');
        console.log('🔍 Theme toggle button found:', themeToggle ? 'YES' : 'NO');
        if (themeToggle) {
            console.log('🎯 Adding click listener to theme button');
            themeToggle.addEventListener('click', toggleTheme);
            // Show the current theme setting on button
            updateThemeButton(savedTheme);
        } else {
            console.log('⚠️ Theme toggle button not found on this page');
        }
    }

    function toggleTheme() {
        console.log('🎨 Theme toggle button clicked!');
        const currentTheme = getCookie('sharey-theme') || 'light';
        console.log('🎨 Current theme:', currentTheme);
        let newTheme;
        
        // Toggle between light and dark only
        if (currentTheme === 'light') {
            newTheme = 'dark';
        } else {
            newTheme = 'light';
        }
        
        console.log('🎨 Switching to theme:', newTheme);
        applyTheme(newTheme);
        setCookie('sharey-theme', newTheme, 365); // Save for 1 year
        updateThemeButton(newTheme);
        
        console.log(`🎨 Theme switched to: ${newTheme}`);
    }

    function applyTheme(themeSetting) {
        if (themeSetting === 'dark') {
            document.documentElement.setAttribute('data-theme', 'dark');
        } else {
            document.documentElement.removeAttribute('data-theme');
        }
    }

    function getSystemTheme() {
        return window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    }

    function updateThemeButton(themeSetting) {
        const themeToggle = document.getElementById('themeToggle');
        if (themeToggle) {
            if (themeSetting === 'light') {
                themeToggle.textContent = '�';
                themeToggle.title = 'Switch to dark mode';
            } else {
                themeToggle.textContent = '☀️';
                themeToggle.title = 'Switch to light mode';
            }
        }
    }

    // Cookie management functions
    function setCookie(name, value, days) {
        const expires = new Date();
        expires.setTime(expires.getTime() + (days * 24 * 60 * 60 * 1000));
        document.cookie = `${name}=${value};expires=${expires.toUTCString()};path=/;SameSite=Lax`;
    }

    function getCookie(name) {
        const nameEQ = name + "=";
        const ca = document.cookie.split(';');
        for (let i = 0; i < ca.length; i++) {
            let c = ca[i];
            while (c.charAt(0) === ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

});

// QR Code functionality (global function for inline onclick handlers)
function showQRCode(url, title) {
    console.log('🔍 QR Code button clicked!', url, title);
    
    // Check if QRCode library is available
    if (typeof QRCode === 'undefined') {
        console.warn('QRCode library not available, using fallback');
        showQRCodeFallback(url, title);
        return;
    }
    
    // Create modal overlay
    const modal = document.createElement('div');
    modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 10000;
    `;
    
    // Create modal content
    const modalContent = document.createElement('div');
    modalContent.style.cssText = `
        background: white;
        padding: 30px;
        border-radius: 10px;
        text-align: center;
        max-width: 400px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
    `;
    
    // Add title
    const titleEl = document.createElement('h3');
    titleEl.textContent = `📱 QR Code for ${title}`;
    titleEl.style.marginBottom = '20px';
    modalContent.appendChild(titleEl);
    
    // Create QR code canvas
    const canvas = document.createElement('canvas');
    modalContent.appendChild(canvas);
    
    // Generate QR code
    QRCode.toCanvas(canvas, url, {
        width: 256,
        margin: 2,
        color: {
            dark: '#000000',
            light: '#FFFFFF'
        }
    }, function(error) {
        if (error) {
            console.error('QR Code generation failed:', error);
            modalContent.innerHTML = '<p>❌ Failed to generate QR code</p>';
        }
    });
    
    // Add close button
    const closeButton = document.createElement('button');
    closeButton.textContent = '✕ Close';
    closeButton.style.cssText = `
        margin-top: 20px;
        padding: 10px 20px;
        background: #f44336;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 16px;
    `;
    closeButton.onclick = () => document.body.removeChild(modal);
    modalContent.appendChild(closeButton);
    
    // Add URL text (truncated)
    const urlText = document.createElement('p');
    urlText.textContent = url.length > 50 ? url.substring(0, 50) + '...' : url;
    urlText.style.cssText = `
        font-size: 12px;
        color: #666;
        margin-top: 15px;
        word-break: break-all;
    `;
    modalContent.appendChild(urlText);
    
    modal.appendChild(modalContent);
    document.body.appendChild(modal);
    
    // Close on click outside
    modal.onclick = (e) => {
        if (e.target === modal) {
            document.body.removeChild(modal);
        }
    };
}

// Fallback QR code function using online API
function showQRCodeFallback(url, title) {
    console.log('🔍 Using QR code fallback for:', title);
    
    // Create modal overlay
    const modal = document.createElement('div');
    modal.style.cssText = `
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: rgba(0, 0, 0, 0.8);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 10000;
    `;
    
    // Create modal content
    const modalContent = document.createElement('div');
    modalContent.style.cssText = `
        background: white;
        padding: 30px;
        border-radius: 10px;
        text-align: center;
        max-width: 400px;
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
    `;
    
    // Add title
    const titleEl = document.createElement('h3');
    titleEl.textContent = `📱 QR Code for ${title}`;
    titleEl.style.marginBottom = '20px';
    modalContent.appendChild(titleEl);
    
    // Create QR code using API service
    const qrImg = document.createElement('img');
    const encodedUrl = encodeURIComponent(url);
    qrImg.src = `https://api.qrserver.com/v1/create-qr-code/?size=256x256&data=${encodedUrl}`;
    qrImg.style.cssText = `
        width: 256px;
        height: 256px;
        border: 2px solid #ddd;
        border-radius: 8px;
    `;
    qrImg.onerror = () => {
        qrImg.style.display = 'none';
        const errorMsg = document.createElement('p');
        errorMsg.textContent = '❌ Failed to generate QR code. You can copy the link instead.';
        errorMsg.style.color = 'red';
        modalContent.appendChild(errorMsg);
    };
    modalContent.appendChild(qrImg);
    
    // Add close button
    const closeButton = document.createElement('button');
    closeButton.textContent = '✕ Close';
    closeButton.style.cssText = `
        margin-top: 20px;
        padding: 10px 20px;
        background: #f44336;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 16px;
    `;
    closeButton.onclick = () => document.body.removeChild(modal);
    modalContent.appendChild(closeButton);
    
    // Add copy button
    const copyButton = document.createElement('button');
    copyButton.textContent = '📋 Copy Link';
    copyButton.style.cssText = `
        margin-top: 10px;
        margin-left: 10px;
        padding: 10px 20px;
        background: #4CAF50;
        color: white;
        border: none;
        border-radius: 5px;
        cursor: pointer;
        font-size: 16px;
    `;
    copyButton.onclick = () => {
        navigator.clipboard.writeText(url).then(() => {
            copyButton.textContent = '✅ Copied!';
            setTimeout(() => copyButton.textContent = '📋 Copy Link', 2000);
        });
    };
    modalContent.appendChild(copyButton);
    
    // Add URL text (truncated)
    const urlText = document.createElement('p');
    urlText.textContent = url.length > 50 ? url.substring(0, 50) + '...' : url;
    urlText.style.cssText = `
        font-size: 12px;
        color: #666;
        margin-top: 15px;
        word-break: break-all;
    `;
    modalContent.appendChild(urlText);
    
    modal.appendChild(modalContent);
    document.body.appendChild(modal);
    
    // Close on click outside
    modal.onclick = (e) => {
        if (e.target === modal) {
            document.body.removeChild(modal);
        }
    };
}
