document.addEventListener('DOMContentLoaded', function () {
    const fileUploadInput = document.getElementById('document-upload');
    const fileUploadLabel = document.querySelector('.custom-file-upload');
    const fileNameDisplay = document.getElementById('file-upload-filename');
    const translateBtn = document.getElementById('translate-btn');
    const processingMessage = document.getElementById('processing-message');
    const previewContainer = document.getElementById('preview-container');
    const imagePreview = document.getElementById('image-preview');
    const startTranslationBtn = document.getElementById('start-translation-btn');
    let uploadedFilePath = '';

    if(fileUploadLabel) {
        fileUploadLabel.addEventListener('click', () => {
            if(fileUploadInput) {
                fileUploadInput.click();
            }
        });
    }

    

    const debugPanel = document.getElementById('debug-panel');
    const debugLog = document.getElementById('debug-log');

    function logToDebug(message) {
        if(debugPanel && debugLog) {
            debugPanel.style.display = 'block';
            debugLog.textContent += message + '\n';
        }
        console.log(message);
    }

    if(fileUploadInput) {
        fileUploadInput.addEventListener('change', () => {
            if (fileUploadInput.files.length > 0) {
                const file = fileUploadInput.files[0];
                logToDebug('File selected: ' + file.name);
                
                const formData = new FormData();
                formData.append('document', file);

                processingMessage.style.display = 'block';
                fileUploadLabel.style.display = 'none';

                fetch('upload.php', {
                    method: 'POST',
                    body: formData
                })
                .then(response => {
                    logToDebug('Received response from server. Status: ' + response.status);
                    return response.json();
                })
                .then(data => {
                    processingMessage.style.display = 'none';

                    if (data.success && data.path) {
                        uploadedFilePath = data.path;
                        const file = fileUploadInput.files[0];
                        
                        const fileExtension = uploadedFilePath.split('.').pop().toLowerCase();
                        const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'tiff', 'bmp', 'webp'];

                        fileUploadLabel.style.display = 'none';
                        fileNameDisplay.textContent = file.name;

                        if (imageExtensions.includes(fileExtension)) {
                            imagePreview.onload = function() {
                                previewContainer.style.display = 'block';
                                imagePreview.style.display = 'block';
                                startTranslationBtn.style.display = 'block';
                            };
                            imagePreview.onerror = function() {
                                alert('Error loading image preview.');
                                fileUploadLabel.style.display = 'block';
                            };
                            imagePreview.src = uploadedFilePath + '?t=' + new Date().getTime();

                        } else if (fileExtension === 'pdf') {
                            const pdfFilename = document.getElementById('pdf-filename');
                            pdfFilename.textContent = file.name;
                            previewContainer.style.display = 'block';
                            document.getElementById('pdf-preview').style.display = 'block';
                            startTranslationBtn.style.display = 'block';
                        } else {
                            alert("Unsupported file type for preview.");
                            fileUploadLabel.style.display = 'block';
                        }

                    } else {
                        throw new Error(data.message || 'File upload failed.');
                    }
                })
                .catch(error => {
                    logToDebug('An error occurred in the upload process: ' + error.message);
                    processingMessage.style.display = 'none';
                    const responseMessageDiv = document.getElementById('response-message');
                    responseMessageDiv.innerHTML = `<div class="alert alert-danger" role="alert">An unexpected error occurred: ${error.message}</div>`;
                    responseMessageDiv.style.display = 'block';
                });

            }
        });
    }
    
    if(startTranslationBtn) {
        startTranslationBtn.addEventListener('click', function(e) {
            e.preventDefault();

            const formData = new FormData();
            formData.append('file_path', uploadedFilePath);
            formData.append('source-lang', document.getElementById('source-lang').value);
            formData.append('target-lang', document.getElementById('target-lang').value);

            const responseMessageDiv = document.getElementById('response-message');

            if(processingMessage) {
                processingMessage.style.display = 'block';
            }
            if(responseMessageDiv){
                responseMessageDiv.innerHTML = '';
                responseMessageDiv.style.display = 'none';
            }

            startTranslationBtn.disabled = true;
            startTranslationBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Translating...';

            fetch('translate.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.message || response.statusText);
                    }).catch(() => {
                        throw new Error(response.statusText);
                    });
                }
                return response.json();
            })
            .then(data => {
                processingMessage.style.display = 'none';

                if (data.status === 'success') {
                    const translatedText = data.data.translatedText;
                    const outputContainer = document.getElementById('translation-output-container');
                    const outputElement = document.getElementById('translation-output');

                    if (outputElement && outputContainer) {
                        outputElement.textContent = translatedText;
                        outputContainer.style.display = 'block';
                    }
                    
                    responseMessageDiv.innerHTML = `<div class="alert alert-success" role="alert">${data.message}</div>`;
                    responseMessageDiv.style.display = 'block';

                } else {
                    responseMessageDiv.innerHTML = `<div class="alert alert-danger" role="alert"><strong>Error:</strong> ${data.message}</div>`;
                    responseMessageDiv.style.display = 'block';
                }
            })
            .catch(error => {
                processingMessage.style.display = 'none';
                responseMessageDiv.innerHTML = `<div class="alert alert-danger" role="alert">An unexpected error occurred: ${error.message}</div>`;
                responseMessageDiv.style.display = 'block';
                console.error('Fetch Error:', error);
            })
            .finally(() => {
                startTranslationBtn.disabled = false;
                startTranslationBtn.innerHTML = '<i class="bi bi-stars"></i> Translate';
            });
        });
    }

    const copyBtn = document.getElementById('copy-btn');
    const downloadBtn = document.getElementById('download-btn');
    const translationOutput = document.getElementById('translation-output');

    if (copyBtn) {
        copyBtn.addEventListener('click', () => {
            if (translationOutput && navigator.clipboard) {
                navigator.clipboard.writeText(translationOutput.textContent).then(() => {
                    const originalText = copyBtn.innerHTML;
                    copyBtn.innerHTML = '<i class="bi bi-check-lg"></i> Copied!';
                    copyBtn.classList.add('btn-success');
                    copyBtn.classList.remove('btn-secondary');
                    setTimeout(() => {
                        copyBtn.innerHTML = originalText;
                        copyBtn.classList.remove('btn-success');
                        copyBtn.classList.add('btn-secondary');
                    }, 2000);
                }).catch(err => {
                    console.error('Failed to copy text: ', err);
                    alert('Failed to copy text. Please try again.');
                });
            }
        });
    }

    if (downloadBtn) {
        downloadBtn.addEventListener('click', () => {
            if (translationOutput && window.jspdf) {
                try {
                    const { jsPDF } = window.jspdf;
                    const doc = new jsPDF();
                    doc.setFont('Helvetica');
                    doc.setFontSize(12);
                    const text = translationOutput.textContent;
                    const lines = doc.splitTextToSize(text, 180);
                    doc.text(lines, 15, 20);
                    doc.save('translation.pdf');
                } catch (error) {
                    console.error('Failed to generate PDF:', error);
                    alert('Failed to generate PDF. An error occurred.');
                }
            } else if (!window.jspdf) {
                alert('The PDF generation library is not loaded.');
            }
        });
    }
});
