document.addEventListener("DOMContentLoaded", function() {
    console.log('🔥 Script.js loaded!');
    
    // Theme management
    initializeTheme();
    
    const dropArea = document.getElementById('dropArea');
    const fileInput = document.getElementById('fileInput');
    const progressContainer = document.getElementById('progressContainer');
    const progressBar = document.getElementById('progressBar');
    const progressText = document.getElementById('progressText');
    const result = document.getElementById('result');
    
    const fileModeButton = document.getElementById('fileMode');
    const pasteModeButton = document.getElementById('pasteMode');
    const urlModeButton = document.getElementById('urlMode');
    const faqButton = document.getElementById('faqButton');

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

    const pasteContent = document.getElementById('pasteContent');
    const submitPasteButton = document.getElementById('submitPaste');
    const pasteResult = document.getElementById('pasteResult');
    
    // URL Shortener elements
    const urlInput = document.getElementById('urlInput');
    const customCode = document.getElementById('customCode');
    const urlExpiry = document.getElementById('urlExpiry');
    const shortenUrlButton = document.getElementById('shortenUrl');
    const urlResult = document.getElementById('urlResult');
    const urlPreviewContainer = document.getElementById('urlPreviewContainer');
    
    // Mobile clipboard elements
    const mobileClipboardSection = document.getElementById('mobileClipboardSection');
    const mobilePasteButton = document.getElementById('mobilePasteButton');
    
    let filesToUpload = [];
    let currentMode = 'file'; // Track current mode: 'file', 'paste', or 'faq'

    // Expiry elements
    const expirySelect = document.getElementById('expirySelect');
    const customExpiry = document.getElementById('customExpiry');
    const pasteExpirySelect = document.getElementById('pasteExpirySelect');
    const customPasteExpiry = document.getElementById('customPasteExpiry');

    // Helper function to check if file is an image
    function isImageFile(file) {
        const imageTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml', 'image/bmp'];
        return imageTypes.includes(file.type.toLowerCase());
    }

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

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

    urlModeButton.addEventListener('click', () => {
        currentMode = 'url';
        showSection(urlShortenerSection);
        hideSection(fileSharingSection);
        hideSection(pastebinSection);
        hideSection(faqSection);
        activateButton(urlModeButton);
        
        // Initialize URL shortener after section is visible
        initializeUrlShortener();
    });

    faqButton.addEventListener('click', () => {
        currentMode = 'faq';
        showSection(faqSection);
        hideSection(fileSharingSection);
        hideSection(pastebinSection);
        hideSection(urlShortenerSection);
        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, urlModeButton, faqButton];
        buttons.forEach(btn => btn.classList.remove('active'));
        button.classList.add('active');
    }

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

    // Expiry selection handlers
    if (expirySelect) {
        expirySelect.addEventListener('change', (e) => {
            if (e.target.value === 'custom') {
                customExpiry.style.display = 'block';
                customExpiry.focus();
            } else {
                customExpiry.style.display = 'none';
            }
        });
    }

    if (pasteExpirySelect) {
        pasteExpirySelect.addEventListener('change', (e) => {
            if (e.target.value === 'custom') {
                customPasteExpiry.style.display = 'block';
                customPasteExpiry.focus();
            } else {
                customPasteExpiry.style.display = 'none';
            }
        });
    }

    // Helper function to calculate expiry datetime
    function calculateExpiryTime(expiryValue, customValue = null) {
        if (expiryValue === 'never') return null;
        if (expiryValue === 'custom' && customValue) {
            return new Date(customValue).toISOString();
        }

        const now = new Date();
        switch (expiryValue) {
            case '1h': return new Date(now.getTime() + 60 * 60 * 1000).toISOString();
            case '24h': return new Date(now.getTime() + 24 * 60 * 60 * 1000).toISOString();
            case '7d': return new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000).toISOString();
            case '30d': return new Date(now.getTime() + 30 * 24 * 60 * 60 * 1000).toISOString();
            case '90d': return new Date(now.getTime() + 90 * 24 * 60 * 60 * 1000).toISOString();
            default: return null;
        }
    }

    // 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);
    });

    // Reusable clipboard paste function
    async function handleClipboardPaste() {
        console.log('📱 Clipboard paste triggered');
        
        try {
            // Try to read from clipboard using the Clipboard API
            if (navigator.clipboard && navigator.clipboard.read) {
                showToast('📋 Checking clipboard...', 'info', 2000);
                
                const clipboardItems = await navigator.clipboard.read();
                const files = [];
                let hasText = false;
                let textContent = '';

                for (const clipboardItem of clipboardItems) {
                    for (const type of clipboardItem.types) {
                        if (type.startsWith('image/')) {
                            const blob = await clipboardItem.getType(type);
                            // Create a file from the blob
                            const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
                            const fileExtension = type.split('/')[1] || 'png';
                            const file = new File([blob], `clipboard-image-${timestamp}.${fileExtension}`, { type });
                            files.push(file);
                        } else if (type === 'text/plain') {
                            hasText = true;
                            textContent = await clipboardItem.getType(type).then(blob => blob.text());
                        }
                    }
                }

                if (files.length > 0) {
                    console.log(`📋 Found ${files.length} image(s) in clipboard`);
                    showToast(`📋 Uploading ${files.length} image(s) from clipboard...`, 'success');
                    filesToUpload = files;
                    displaySelectedFiles(files);
                    handleFileUpload(files);
                } else if (hasText && textContent.trim()) {
                    // If no images but there's text, suggest switching to paste mode
                    const shouldSwitchToPaste = confirm(
                        `📋 Found text in clipboard: "${textContent.slice(0, 100)}${textContent.length > 100 ? '...' : ''}"\n\nWould you like to switch to Paste mode to upload this text?`
                    );
                    
                    if (shouldSwitchToPaste) {
                        pasteModeButton.click();
                        pasteContent.value = textContent;
                        pasteContent.focus();
                        pasteContent.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        showToast('📋 Text pasted successfully!', 'success');
                    }
                } else {
                    showToast('📋 No supported content found in clipboard. Try copying an image or text first.', 'warning', 4000);
                }
            } else {
                // Fallback for browsers that don't support Clipboard API
                showToast('📋 Please use your browser\'s paste function (long-press and select "Paste")', 'info', 4000);
            }
        } catch (error) {
            console.error('📋 Clipboard access error:', error);
            if (error.name === 'NotAllowedError') {
                showToast('📋 Clipboard access denied. Please allow clipboard permissions and try again.', 'warning', 4000);
            } else {
                showToast('📋 Unable to access clipboard. Try copying something first, or use long-press and "Paste".', 'warning', 4000);
            }
        }
    }

    // Mobile paste button handler
    if (mobilePasteButton) {
        mobilePasteButton.addEventListener('click', handleClipboardPaste);
    }

    // Clipboard paste functionality
    document.addEventListener('paste', async (event) => {
        console.log('📋 Paste event triggered');
        console.log('📋 Current mode:', currentMode);
        console.log('📋 Event target:', event.target.tagName);
        console.log('📋 User agent:', navigator.userAgent.includes('Mobile') ? 'Mobile' : 'Desktop');
        
        // Only handle paste when in file mode and not typing in textarea
        if (currentMode !== 'file' || event.target.tagName === 'TEXTAREA' || event.target.tagName === 'INPUT') {
            console.log('📋 Paste ignored - wrong mode or target');
            return;
        }

        event.preventDefault();
        console.log('📋 Paste event detected and processing...');

        const clipboardItems = event.clipboardData.items;
        console.log('📋 Clipboard items:', clipboardItems.length);
        
        const files = [];
        let hasText = false;
        let textContent = '';

        // Process clipboard items
        for (let item of clipboardItems) {
            console.log('📋 Processing item type:', item.type);
            if (item.type.indexOf('image') !== -1) {
                // Handle image from clipboard
                const file = item.getAsFile();
                if (file) {
                    // Create a more descriptive filename with timestamp
                    const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);
                    const fileExtension = file.type.split('/')[1] || 'png';
                    Object.defineProperty(file, 'name', {
                        writable: true,
                        value: `clipboard-image-${timestamp}.${fileExtension}`
                    });
                    files.push(file);
                }
            } else if (item.type === 'text/plain') {
                hasText = true;
                textContent = event.clipboardData.getData('text/plain');
            }
        }

        if (files.length > 0) {
            // Upload images from clipboard
            console.log(`📋 Found ${files.length} image(s) in clipboard`);
            showToast(`📋 Uploading ${files.length} image(s) from clipboard...`, 'info');
            result.innerHTML = '<p>📋 Uploading image from clipboard...</p>';
            filesToUpload = files;
            displaySelectedFiles(files);
            handleFileUpload(files);
        } else if (hasText && textContent.trim()) {
            // If no images but there's text, suggest switching to paste mode
            const shouldSwitchToPaste = confirm(
                `📋 Found text in clipboard: "${textContent.slice(0, 100)}${textContent.length > 100 ? '...' : ''}"\n\nWould you like to switch to Paste mode to upload this text?`
            );
            
            if (shouldSwitchToPaste) {
                // Switch to paste mode and fill the textarea
                pasteModeButton.click();
                pasteContent.value = textContent;
                pasteContent.focus();
                // Auto-scroll to textarea
                pasteContent.scrollIntoView({ behavior: 'smooth', block: 'center' });
                showToast('📋 Text pasted successfully!', 'success');
            } else {
                showToast('📋 Clipboard paste cancelled', 'info', 2000);
            }
        } else {
            // Show a helpful message with mobile-specific guidance
            const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
            if (isMobile) {
                showToast('📋 No content found. On mobile: long-press and select "Paste" or copy an image first.', 'warning', 4000);
            } else {
                showToast('📋 No supported content found in clipboard. Try copying an image or text.', 'warning');
            }
        }
    });

    // Add visual feedback for clipboard functionality
    document.addEventListener('keydown', (event) => {
        if ((event.ctrlKey || event.metaKey) && event.key === 'v' && currentMode === 'file') {
            // Only show hint if not focused on input/textarea
            if (event.target.tagName !== 'TEXTAREA' && event.target.tagName !== 'INPUT') {
                dropArea.style.transform = 'scale(1.02)';
                dropArea.style.borderColor = '#4CAF50';
                setTimeout(() => {
                    dropArea.style.transform = '';
                    dropArea.style.borderColor = '';
                }, 200);
            }
        }
    });

    // Mobile long-press visual feedback
    const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || 
                     ('ontouchstart' in window) || 
                     (navigator.maxTouchPoints > 0);
    
    // Update instructions based on device type
    const desktopInstructions = document.getElementById('desktopInstructions');
    const mobileInstructions = document.getElementById('mobileInstructions');
    
    if (isMobile) {
        if (desktopInstructions) desktopInstructions.style.display = 'none';
        if (mobileInstructions) mobileInstructions.style.display = 'block';
        
        // Show mobile-specific content
        document.querySelectorAll('.mobile-only').forEach(el => el.style.display = 'block');
        document.querySelectorAll('.desktop-only').forEach(el => el.style.display = 'none');
    } else {
        if (desktopInstructions) desktopInstructions.style.display = 'block';
        if (mobileInstructions) mobileInstructions.style.display = 'none';
        
        // Show desktop-specific content
        document.querySelectorAll('.mobile-only').forEach(el => el.style.display = 'none');
        document.querySelectorAll('.desktop-only').forEach(el => el.style.display = 'block');
    }
    
    // Show mobile hints if on mobile
    if (isMobile) {
        // Show mobile hints
        const mobileHints = document.querySelectorAll('.mobile-hint');
        mobileHints.forEach(hint => hint.style.display = 'block');
    }
    
    // Context menu elements
    const contextMenu = document.getElementById('contextMenu');
    const contextPasteButton = document.getElementById('contextPasteButton');
    const contextSelectButton = document.getElementById('contextSelectButton');
    
    let longPressTimer = null;
    let contextMenuVisible = false;
    
    // Hide context menu when clicking elsewhere
    document.addEventListener('click', (event) => {
        if (contextMenuVisible && !contextMenu.contains(event.target)) {
            hideContextMenu();
        }
    });
    
    function showContextMenu(x, y) {
        contextMenu.style.left = x + 'px';
        contextMenu.style.top = y + 'px';
        contextMenu.style.display = 'block';
        contextMenuVisible = true;
        
        // Adjust position if menu goes off-screen
        const rect = contextMenu.getBoundingClientRect();
        if (rect.right > window.innerWidth) {
            contextMenu.style.left = (x - rect.width) + 'px';
        }
        if (rect.bottom > window.innerHeight) {
            contextMenu.style.top = (y - rect.height) + 'px';
        }
    }
    
    function hideContextMenu() {
        contextMenu.style.display = 'none';
        contextMenuVisible = false;
    }
    
    if (isMobile) {
        dropArea.addEventListener('touchstart', (event) => {
            if (currentMode === 'file') {
                longPressTimer = setTimeout(() => {
                    // Add visual feedback for long press
                    dropArea.style.backgroundColor = '#e3f2fd';
                    dropArea.style.borderColor = '#2196F3';
                    
                    // Show context menu at touch position
                    const touch = event.touches[0];
                    showContextMenu(touch.clientX, touch.clientY);
                    
                    // Haptic feedback if available
                    if (navigator.vibrate) {
                        navigator.vibrate(50);
                    }
                }, 500); // 500ms for long press
            }
        });

        dropArea.addEventListener('touchend', () => {
            clearTimeout(longPressTimer);
            // Reset visual feedback
            setTimeout(() => {
                dropArea.style.backgroundColor = '';
                dropArea.style.borderColor = '';
            }, 200);
        });

        dropArea.addEventListener('touchmove', () => {
            clearTimeout(longPressTimer);
        });
    }
    
    // Context menu paste button
    if (contextPasteButton) {
        contextPasteButton.addEventListener('click', async () => {
            hideContextMenu();
            await handleClipboardPaste();
        });
    }
    
    // Context menu select files button
    if (contextSelectButton) {
        contextSelectButton.addEventListener('click', () => {
            hideContextMenu();
            fileInput.click();
        });
    }

    // 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 {
            
            progressText.textContent = 'Preparing upload...'; 
            progressBar.style.width = '0%'; 
 
            const results = []; 
            for (let i = 0; i < files.length; i++) { 
                const file = files[i]; 
                console.log(`📤 Starting upload ${i + 1}/${files.length}: ${file.name}`); 
                
                // Show starting state for this file
                progressText.textContent = `Starting upload: ${file.name} (${i + 1}/${files.length})`;
                
                try { 
                    const result = await uploadFileWithProgress(file, i, files.length); 
                    results.push(result); 
                    
                    // Don't manually update progress here - let the final completion handle it
                    console.log(`✅ File ${i + 1}/${files.length} completed: ${file.name}`);
                    
                } catch (error) { 
                    console.error(`❌ Failed to upload ${file.name}:`, error); 
                    throw error; 
                } 
            } 
 
            // Show upload completion but indicate we're still processing
            progressBar.style.width = '100%'; 
            progressText.textContent = '📊 Processing uploaded files...';
            
            // Brief delay to show processing state
            await new Promise(resolve => setTimeout(resolve, 500));
            
            // Display results
            displayUploadedFiles(results);
            
            // Final completion state
            progressText.textContent = '✅ Upload complete!';
            
        } catch (error) {
            console.error('❌ Upload process failed:', error);
            result.innerHTML = `<div class="error">Upload failed: ${error.message}</div>`;
        } finally {
            // Don't reset progress bar - keep it at completion state
            // The page will redirect or reload anyway
            console.log('📊 Upload process finished (finally block)');
        }
    }

    // Upload single file with progress tracking
    function uploadFileWithProgress(file, fileIndex, totalFiles) {
        return new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            const formData = new FormData();
            formData.append('files[]', file);
            
            // Add expiry information
            const expiryValue = expirySelect?.value || 'never';
            const customExpiryValue = customExpiry?.value;
            const expiryTime = calculateExpiryTime(expiryValue, customExpiryValue);
            
            if (expiryTime) {
                formData.append('expires_at', expiryTime);
            }
            
            // Track upload progress
            xhr.upload.addEventListener('progress', (event) => {
                if (event.lengthComputable) {
                    // Calculate progress for this file (0-100%)
                    const fileProgress = (event.loaded / event.total) * 100;
                    
                    // Calculate overall progress more conservatively
                    // Each file gets an equal portion of the total progress
                    const baseProgress = (fileIndex / totalFiles) * 100;
                    const currentFileContribution = (fileProgress / totalFiles);
                    const overallProgress = Math.min(99, baseProgress + currentFileContribution); // Cap at 99% until all done
                    
                    // Update progress bar and text
                    progressBar.style.width = `${Math.round(overallProgress)}%`;
                    progressText.textContent = `Uploading ${file.name}... ${Math.round(fileProgress)}% (${fileIndex + 1}/${totalFiles})`;
                }
            });
            
            // Handle upload completion
            xhr.addEventListener('load', () => {
                if (xhr.status >= 200 && xhr.status < 300) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        console.log('📤 Upload response:', response);
                        
                        resolve({
                            url: response.urls[0],
                            file: file,
                            originalSize: file.size
                        });
                    } catch (error) {
                        reject(new Error('Invalid response from server'));
                    }
                } else {
                    reject(new Error(`Upload failed: ${xhr.statusText || 'Unknown error'}`));
                }
            });
            
            // Handle upload errors
            xhr.addEventListener('error', () => {
                reject(new Error('Network error during upload'));
            });
            
            // Handle upload timeout
            xhr.addEventListener('timeout', () => {
                reject(new Error('Upload timed out'));
            });
            
            // Start the upload
            xhr.open('POST', '/api/upload');
            xhr.send(formData);
        });
    }

    // 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.className = 'file-result-bar';
            
            // Create file info section
            const fileInfo = document.createElement('div');
            fileInfo.className = 'file-info-section';
            
            const fileName = document.createElement('div');
            fileName.className = 'file-name';
            fileName.innerHTML = `📄 ${fileResult.file.name}`;
            fileInfo.appendChild(fileName);
            
            const fileSize = document.createElement('div');
            fileSize.className = 'file-size';
            fileSize.innerHTML = `📊 ${(fileResult.originalSize / 1024).toFixed(1)} KB`;
            fileInfo.appendChild(fileSize);
            
            fileContainer.appendChild(fileInfo);
            
            const buttonContainer = document.createElement('div');
            buttonContainer.className = 'file-buttons-section';
            
            // 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);
            
            // Add image thumbnail if it's an image
            if (isImageFile(fileResult.file)) {
                const thumbnail = document.createElement('img');
                thumbnail.src = fileResult.url;
                thumbnail.alt = fileResult.file.name;
                thumbnail.className = 'file-thumbnail';
                
                thumbnail.onerror = () => {
                    thumbnail.style.display = 'none';
                };
                
                fileContainer.appendChild(thumbnail);
            }
            
            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>';
            
            // Calculate paste expiry
            const expiryValue = pasteExpirySelect?.value || 'never';
            const customExpiryValue = customPasteExpiry?.value;
            const expiryTime = calculateExpiryTime(expiryValue, customExpiryValue);
            
            // Prepare request body
            const requestBody = { content: content };
            if (expiryTime) {
                requestBody.expires_at = expiryTime;
            }
            
            // Upload paste
            const response = await fetch('/api/paste', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestBody)
            });
            
            if (!response.ok) {
                throw new Error(`Upload failed: ${response.statusText}`);
            }
            
            const pasteResponse = await response.json();
            const url = pasteResponse.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.setAttribute('data-theme', 'light');
        }
    }

    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);
        }
    };
}


// Toast notification function
function showToast(message, type = "success", duration = 3000) {
    const toast = document.createElement("div");
    toast.className = "clipboard-toast";
    toast.textContent = message;
    
    if (type === "info") {
        toast.style.background = "#2196F3";
    } else if (type === "warning") {
        toast.style.background = "#1d1b18ff";
    } else if (type === "error") {
        toast.style.background = "#f44336";
    }
    
    document.body.appendChild(toast);
    
    // Auto remove after duration
    setTimeout(() => {
        if (document.body.contains(toast)) {
            toast.style.animation = "slideInToast 0.3s ease-out reverse";
            setTimeout(() => {
                if (document.body.contains(toast)) {
                    document.body.removeChild(toast);
                }
            }, 300);
        }
    }, duration);
}

// URL Shortener initialization function
function initializeUrlShortener() {
    console.log('🔗 Initializing URL shortener...');
    
    // Re-query elements now that section is visible
    const urlInput = document.getElementById('urlInput');
    const customCode = document.getElementById('customCode');
    const urlExpiry = document.getElementById('urlExpiry');
    const shortenUrlButton = document.getElementById('shortenUrl');
    const urlResult = document.getElementById('urlResult');
    const urlPreviewContainer = document.getElementById('urlPreviewContainer');
    
    console.log('URL shortener elements:', {
        urlInput: !!urlInput,
        customCode: !!customCode,
        urlExpiry: !!urlExpiry,
        shortenUrlButton: !!shortenUrlButton,
        urlResult: !!urlResult,
        urlPreviewContainer: !!urlPreviewContainer
    });
    
    if (shortenUrlButton && urlInput && urlResult) {
        console.log('✅ URL shortener elements found, adding event listeners');
        
        // Remove any existing listeners to avoid duplicates
        shortenUrlButton.replaceWith(shortenUrlButton.cloneNode(true));
        const newShortenButton = document.getElementById('shortenUrl');
        
        newShortenButton.addEventListener('click', () => shortenUrl(urlInput, customCode, urlExpiry, urlResult, urlPreviewContainer, newShortenButton));
        
        // Enter key support for URL input
        urlInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                shortenUrl(urlInput, customCode, urlExpiry, urlResult, urlPreviewContainer, newShortenButton);
            }
        });
        
        // Copy button functionality
        document.addEventListener('click', (e) => {
            if (e.target && e.target.id === 'copyUrlButton') {
                const shortUrlInput = document.getElementById('shortUrlInput');
                if (shortUrlInput) {
                    shortUrlInput.select();
                    shortUrlInput.setSelectionRange(0, 99999); // For mobile
                    
                    navigator.clipboard.writeText(shortUrlInput.value).then(() => {
                        showToast('Short URL copied to clipboard! 📋', 'success');
                    }).catch(() => {
                        // Fallback for older browsers
                        document.execCommand('copy');
                        showToast('Short URL copied to clipboard! �', 'success');
                    });
                }
            }
        });
    } else {
        console.log('❌ URL shortener elements not found');
    }
}

// URL Shortener functionality
console.log('�🔗 Setting up URL shortener...');
console.log('shortenUrlButton:', shortenUrlButton);
console.log('urlInput:', urlInput);
console.log('urlResult:', urlResult);

if (shortenUrlButton && urlInput && urlResult) {
    console.log('✅ URL shortener elements found, adding event listeners');
    shortenUrlButton.addEventListener('click', shortenUrl);
    
    // Enter key support for URL input
    urlInput.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            shortenUrl();
        }
    });
    
    // Copy button functionality
    document.addEventListener('click', (e) => {
        if (e.target && e.target.id === 'copyUrlButton') {
            const shortUrlInput = document.getElementById('shortUrlInput');
            if (shortUrlInput) {
                shortUrlInput.select();
                shortUrlInput.setSelectionRange(0, 99999); // For mobile
                
                navigator.clipboard.writeText(shortUrlInput.value).then(() => {
                    showToast('Short URL copied to clipboard! 📋', 'success');
                }).catch(() => {
                    // Fallback for older browsers
                    document.execCommand('copy');
                    showToast('Short URL copied to clipboard! 📋', 'success');
                });
            }
        }
    });
} else {
    console.log('❌ URL shortener elements not found');
    console.log('Missing elements:', {
        shortenUrlButton: !shortenUrlButton,
        urlInput: !urlInput, 
        urlResult: !urlResult
    });
}

async function shortenUrl(urlInputEl, customCodeEl, urlExpiryEl, urlResultEl, urlPreviewContainerEl, shortenButtonEl) {
    // Use passed elements or fallback to global ones
    const urlInput = urlInputEl || document.getElementById('urlInput');
    const customCode = customCodeEl || document.getElementById('customCode');
    const urlExpiry = urlExpiryEl || document.getElementById('urlExpiry');
    const urlResult = urlResultEl || document.getElementById('urlResult');
    const urlPreviewContainer = urlPreviewContainerEl || document.getElementById('urlPreviewContainer');
    const shortenUrlButton = shortenButtonEl || document.getElementById('shortenUrl');
    
    console.log('🔗 shortenUrl function called');
    
    const url = urlInput.value.trim();
    const code = customCode.value.trim();
    const expiryHours = urlExpiry.value === 'never' ? null : parseInt(urlExpiry.value);
    
    console.log('URL:', url, 'Code:', code, 'Expiry:', expiryHours);
    
    if (!url) {
        showError('Please enter a URL to shorten', urlResult);
        return;
    }
    
    // Basic URL validation
    try {
        new URL(url);
    } catch (e) {
        showError('Please enter a valid URL (include http:// or https://)', urlResult);
        return;
    }
    
    // Show loading state
    shortenUrlButton.disabled = true;
    shortenUrlButton.textContent = '⏳ Shortening...';
    showInfo('Creating short URL...', urlResult);
    
    try {
        const payload = {
            url: url
        };
        
        if (code) {
            payload.code = code;
        }
        
        if (expiryHours) {
            payload.expires_in_hours = expiryHours;
        }
        
        const response = await fetch('/api/shorten', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(payload)
        });
        
        const data = await response.json();
        
        if (response.ok) {
            showUrlSuccess(data, urlResult, urlPreviewContainer, urlInput, customCode, urlExpiry);
        } else {
            showError(data.error || 'Failed to create short URL', urlResult);
        }
    } catch (error) {
        console.error('URL shortening error:', error);
        showError('Failed to create short URL. Please try again.', urlResult);
    } finally {
        // Reset button state
        shortenUrlButton.disabled = false;
        shortenUrlButton.textContent = '✨ Shorten URL';
    }
}

function showUrlSuccess(data, urlResult, urlPreviewContainer, urlInput, customCode, urlExpiry) {
    urlResult.className = 'result-message success';
    urlResult.textContent = '✅ Short URL created successfully!';
    
    // Show preview container
    urlPreviewContainer.style.display = 'block';
    
    // Update preview elements
    const shortUrlInput = document.getElementById('shortUrlInput');
    const targetUrl = document.getElementById('targetUrl');
    const clickCount = document.getElementById('clickCount');
    const expiryInfo = document.getElementById('expiryInfo');
    const expiryDate = document.getElementById('expiryDate');
    
    if (shortUrlInput) {
        shortUrlInput.value = data.short_url;
    }
    
    if (targetUrl) {
        targetUrl.textContent = data.target_url;
    }
    
    if (clickCount) {
        clickCount.textContent = '0';
    }
    
    if (data.expires_at && expiryInfo && expiryDate) {
        expiryDate.textContent = new Date(data.expires_at).toLocaleString();
        expiryInfo.style.display = 'block';
    } else if (expiryInfo) {
        expiryInfo.style.display = 'none';
    }
    
    // Clear form
    urlInput.value = '';
    customCode.value = '';
    urlExpiry.value = '24';
}
