document.addEventListener("DOMContentLoaded", function () {
    const uploadForm = document.getElementById("upload-form");
    const apkFileInput = document.getElementById("apkFile");
    const fileNameDisplay = document.getElementById("file-name");
    const progressContainer = document.querySelector(".progress-container");
    const progressBar = document.getElementById("progress-bar");
    const progressText = document.getElementById("progress-text");
    const successMessage = document.getElementById("success-message");

    // File input change handler - show selected file name
    if (apkFileInput && fileNameDisplay) {
        apkFileInput.addEventListener("change", function () {
            if (this.files && this.files.length > 0) {
                const fileName = this.files[0].name;
                const fileSize = (this.files[0].size / (1024 * 1024)).toFixed(2);
                fileNameDisplay.innerHTML = `<i class="fas fa-file-archive"></i> ${fileName} (${fileSize} MB)`;
                
                // Clear any previous messages
                successMessage.textContent = "";
                successMessage.className = "message";
            } else {
                fileNameDisplay.innerHTML = `<i class="fas fa-cloud-upload-alt"></i> Choose APK file or drag and drop here`;
            }
        });

        // Drag and drop functionality
        const fileInputWrapper = document.querySelector(".file-input-wrapper");
        
        if (fileInputWrapper) {
            ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
                fileInputWrapper.addEventListener(eventName, preventDefaults, false);
            });

            function preventDefaults(e) {
                e.preventDefault();
                e.stopPropagation();
            }

            ['dragenter', 'dragover'].forEach(eventName => {
                fileInputWrapper.addEventListener(eventName, () => {
                    fileInputWrapper.classList.add('drag-over');
                }, false);
            });

            ['dragleave', 'drop'].forEach(eventName => {
                fileInputWrapper.addEventListener(eventName, () => {
                    fileInputWrapper.classList.remove('drag-over');
                }, false);
            });

            fileInputWrapper.addEventListener('drop', function(e) {
                const dt = e.dataTransfer;
                const files = dt.files;
                
                if (files.length > 0) {
                    apkFileInput.files = files;
                    // Trigger change event
                    const event = new Event('change', { bubbles: true });
                    apkFileInput.dispatchEvent(event);
                }
            });
        }
    }

    if (uploadForm) {
        uploadForm.addEventListener("submit", function (event) {
            event.preventDefault(); // Prevent the default form submission

            if (!apkFileInput || !apkFileInput.files.length) {
                showMessage("Please select an APK file to upload.", "error");
                return;
            }

            const file = apkFileInput.files[0];
            
            // Validate file type
            if (!file.name.toLowerCase().endsWith('.apk')) {
                showMessage("Please select a valid APK file.", "error");
                return;
            }
            
            // Validate file size (50MB max)
            const maxSize = 50 * 1024 * 1024; // 50MB in bytes
            if (file.size > maxSize) {
                showMessage("File is too large. Maximum size is 50MB.", "error");
                return;
            }

            const formData = new FormData(uploadForm);
            const xhr = new XMLHttpRequest();

            // Hide any previous messages
            successMessage.classList.remove('visible', 'success', 'error');
            successMessage.textContent = "";
            
            // Show and reset progress bar
            progressContainer.classList.add('visible');
            progressBar.style.width = "0%";
            progressText.textContent = "0%";

            // Disable submit button during upload
            const submitBtn = uploadForm.querySelector('button[type="submit"]');
            const originalBtnText = submitBtn.innerHTML;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Uploading...';
            submitBtn.disabled = true;

            xhr.open("POST", "upload.php", true);

            // Update progress bar
            xhr.upload.addEventListener("progress", function (e) {
                if (e.lengthComputable) {
                    const percentComplete = Math.round((e.loaded / e.total) * 100);
                    progressBar.style.width = percentComplete + "%";
                    progressText.textContent = percentComplete + "%";
                }
            });

            // Handle upload completion
            xhr.onload = function () {
                // Re-enable submit button
                submitBtn.innerHTML = originalBtnText;
                submitBtn.disabled = false;

                if (xhr.status === 200) {
                    try {
                        const response = JSON.parse(xhr.responseText);
                        console.log("Upload response:", response);
                        
                        if (response.success) {
                            showMessage(response.message || "File uploaded successfully!", "success");
                            uploadForm.reset(); // Clear the form
                            fileNameDisplay.innerHTML = `<i class="fas fa-cloud-upload-alt"></i> Choose APK file or drag and drop here`;
                            
                            // Hide progress bar after success
                            setTimeout(() => {
                                progressContainer.classList.remove('visible');
                            }, 2000);
                        } else {
                            showMessage(response.message || response.error || "Upload failed", "error");
                        }
                    } catch (e) {
                        console.error("JSON parse error:", e);
                        console.log("Response text:", xhr.responseText);
                        showMessage("Upload completed but response format was unexpected.", "warning");
                    }
                } else {
                    console.error("Upload failed with status:", xhr.status);
                    showMessage(`Upload failed with status ${xhr.status}. Please try again.`, "error");
                }
            };

            xhr.onerror = function () {
                submitBtn.innerHTML = originalBtnText;
                submitBtn.disabled = false;
                showMessage("Network error occurred during upload. Please check your connection and try again.", "error");
            };

            xhr.ontimeout = function () {
                submitBtn.innerHTML = originalBtnText;
                submitBtn.disabled = false;
                showMessage("Upload timed out. Please try again.", "error");
            };

            // Set timeout (5 minutes for large files)
            xhr.timeout = 300000;

            xhr.send(formData);
        });
    } else {
        console.error("Upload form not found in the DOM.");
    }

    function showMessage(text, type) {
        // Add icon based on type
        const icon = type === 'success' ? 
            '<i class="fas fa-check-circle"></i>' : 
            '<i class="fas fa-exclamation-circle"></i>';
        
        successMessage.innerHTML = icon + '<span>' + text + '</span>';
        successMessage.className = type + ' visible';
        
        // Auto-hide success messages after 5 seconds
        if (type === "success") {
            setTimeout(() => {
                successMessage.classList.remove('visible');
            }, 5000);
        }
    }
});