document.addEventListener('DOMContentLoaded', function () {
    const uploadForm = document.getElementById('uploadForm');
    const imageInput = document.getElementById('imageInput');
    const doneImgsDiv = document.getElementById('done-imgs');
    const progressContainer = document.getElementById('progress-container');
    const errorMessage = document.getElementById('error-message');

    // Advanced Tab Toggle Functionality
    document.querySelector(".collapsible").addEventListener("click", function () {
        this.classList.toggle("active");
        let content = this.nextElementSibling;
        if (content.style.display === "block") {
            content.style.display = "none";
        } else {
            content.style.display = "block";
        }
    });

    uploadForm.addEventListener('submit', function (event) {
        document.getElementById('download-all').style.display = 'inline-block';
        event.preventDefault();

        const files = imageInput.files;

        if (files.length === 0) {
            alert("Please select at least one image to upload.");
            return;
        } else if (files.length > 10) {
            errorMessage.style.display = 'block';
            return;
        } else {
            errorMessage.style.display = 'none';
        }

        // Clear previous progress bars and images if needed
        progressContainer.innerHTML = '';
        doneImgsDiv.innerHTML = '';

        // Get user inputs
        const color = document.getElementById("color")?.value || "#ffffff";
        const width = document.getElementById("width")?.value || "1080";
        const height = document.getElementById("height")?.value || "1080";
        const minBorder = document.getElementById("min-border")?.value || "16";
        const antiAliasing = document.getElementById("anti-aliasing").checked;

        Array.from(files).forEach((file) => {
            uploadAndProcessImage(file, { color, width, height, minBorder, antiAliasing });
        });
    });

    function uploadAndProcessImage(file, options) {
        const { color, width, height, minBorder, antiAliasing } = options;

        // Create progress bar elements
        const progressWrapper = document.createElement('div');
        progressWrapper.className = 'progress-wrapper';

        const fileNameLabel = document.createElement('div');
        fileNameLabel.className = 'file-name';
        fileNameLabel.textContent = file.name;

        const progressBar = document.createElement('div');
        progressBar.className = 'progress-bar';

        const progressBarFill = document.createElement('div');
        progressBarFill.className = 'progress-bar-fill';

        const progressStatus = document.createElement('div');
        progressStatus.className = 'progress-status';
        progressStatus.textContent = 'Starting upload...';

        progressBar.appendChild(progressBarFill);
        progressWrapper.appendChild(fileNameLabel);
        progressWrapper.appendChild(progressBar);
        progressWrapper.appendChild(progressStatus);
        progressContainer.appendChild(progressWrapper);

        const formData = new FormData();
        formData.append('image', file);

        const xhr = new XMLHttpRequest();

        xhr.open('POST', `https://api.nevets.tech/igformatter/upload?color=${encodeURIComponent(color)}&width=${encodeURIComponent(width)}&height=${encodeURIComponent(height)}&minBorder=${encodeURIComponent(minBorder)}&antiAliasing=${encodeURIComponent(antiAliasing)}`, true);
        xhr.responseType = 'blob';

        // Upload progress event
        xhr.upload.addEventListener('progress', function (e) {
            if (e.lengthComputable) {
                const percentComplete = ((e.loaded / e.total) * 50).toFixed(2); // 0% to 50%
                progressBarFill.style.width = `${percentComplete}%`;
                progressStatus.textContent = `Uploading... ${percentComplete}%`;
            }
        });

        // Download progress event
        xhr.addEventListener('progress', function (e) {
            if (e.lengthComputable) {
                const percentComplete = (50 + ((e.loaded / e.total) * 50)).toFixed(2); // 50% to 100%
                progressBarFill.style.width = `${percentComplete}%`;
                progressStatus.textContent = `Processing... ${percentComplete}%`;
            } else {
                progressStatus.textContent = `Processing...`;
            }
        });

        // On successful completion
        xhr.addEventListener('load', function () {
            if (xhr.status === 200) {
                progressBarFill.style.width = '100%';
                progressStatus.textContent = 'Completed';
                progressWrapper.classList.add('success');

                const blob = xhr.response;
                const imageUrl = URL.createObjectURL(blob);

                const anchor = document.createElement('a');
                anchor.href = imageUrl;
                anchor.className = "card-link";
                anchor.download = `${file.name.replace(/\.[^/.]+$/, "")}_formatted.png`;

                const img = document.createElement('img');
                img.src = imageUrl;
                img.className = "card-img";
                img.alt = "Formatted Image Preview";

                anchor.appendChild(img);
                doneImgsDiv.appendChild(anchor);
            } else {
                handleError(`Processing failed for ${file.name}`, progressWrapper, progressStatus, progressBarFill);
            }
        });

        // On error
        xhr.addEventListener('error', function () {
            handleError(`An error occurred while uploading ${file.name}`, progressWrapper, progressStatus, progressBarFill);
        });

        // On abort
        xhr.addEventListener('abort', function () {
            handleError(`Upload aborted for ${file.name}`, progressWrapper, progressStatus, progressBarFill);
        });

        xhr.send(formData);
    }

    function handleError(message, progressWrapper, progressStatus, progressBarFill) {
        console.error(message);
        progressStatus.textContent = message;
        progressWrapper.classList.add('error');
        progressBarFill.style.width = '100%';
    }
});

// Handle the download all functionality
document.getElementById('download-all').addEventListener('click', function() {
    const links = document.querySelectorAll('#done-imgs .card-link');
    links.forEach(link => {
        link.click();
    });
});
