export function initFileInputs() {
    document.querySelectorAll(".file-input").forEach(input => {
        const dropArea = input.closest(".drop-area");
        const preview = dropArea.nextElementSibling;

        input.addEventListener("change", () => handleFiles(input, preview));
        dropArea.addEventListener("dragover", (e) => e.preventDefault());
        dropArea.addEventListener("drop", (e) => {
            e.preventDefault();
            input.files = e.dataTransfer.files;
            handleFiles(input, preview);
        });
    });
}

function handleFiles(input, preview) {
    preview.innerHTML = "";
    const files = Array.from(input.files);
    files.forEach((file) => {
        if (file.type.startsWith("image/")) {
            const reader = new FileReader();
            reader.onload = (e) => {
                const imgHTML = `<div class="image-preview-box" data-file-name="${file.name}">
                                    <i class="bx bx-trash" onclick="app.removeImage('${file.name}')"></i>
                                    <img src="${e.target.result}" />
                                </div>`;
                preview.insertAdjacentHTML('beforeend', imgHTML);
            };
            reader.readAsDataURL(file);
        }
    });
}

// Function to remove a file by its name
export function removeImage(fileName) {
    const previewBox = document.querySelector(`.image-preview-box[data-file-name='${fileName}']`);
    if (previewBox) {
        previewBox.remove();
    }

    // Update file input to remove the selected file
    const input = document.querySelector(".file-input");
    let files = Array.from(input.files).filter(file => file.name !== fileName);

    // Create a new DataTransfer object to update input.files
    let dataTransfer = new DataTransfer();
    files.forEach(file => dataTransfer.items.add(file));
    input.files = dataTransfer.files;
}
