document.addEventListener('DOMContentLoaded', function () {
    // Function to handle file preview
    window.previewFile = function(filename) {
        const modal = document.getElementById('modal');
        const content = modal.querySelector('.content');
        modal.style.display = 'block';

        // Directly specify the directory path
        const filePath = 'a/' + filename;  // Assuming 'a' is the directory

        console.log("Attempting to preview file at path:", filePath);  // Debug output

        // Check file type and adjust content accordingly
        if (/\.(mp4)$/i.test(filename)) {
            content.innerHTML = '<video width="100%" controls><source src="' + filePath + '" type="video/mp4">Your browser does not support the video tag.</video>';
        } else if (/\.(jpg|jpeg|png)$/i.test(filename)) {
            content.innerHTML = '<img src="' + filePath + '" style="width:100%;">';
        }
    };

    window.deleteFile = function(filename) {
        const password = prompt("Enter the password to delete the file:");
        if (password !== null) {
            const form = document.createElement('form');
            form.method = 'post';
            form.action = '';
            form.innerHTML = '<input type="hidden" name="filename" value="' + filename + '">' + // No further encoding needed
                             '<input type="hidden" name="action" value="delete">' +
                             '<input type="hidden" name="password" value="' + password + '">';
            document.body.appendChild(form);
            form.submit();
        }
    };

    window.archiveFile = function(filename) {
        const password = prompt("Enter the password to archive the file:");
         if (password !== null) {
             const form = document.createElement('form');
             form.method = 'post';
             form.action = '';
             form.innerHTML = '<input type="hidden" name="filename" value="' + filename + '">' +
                              '<input type="hidden" name="action" value="archive">' +
                             '<input type="hidden" name="password" value="' + password + '">';
            document.body.appendChild(form);
            form.submit();
         }
     };

    // Close modal on clicking the 'close' button
    document.querySelector('.modal .close').addEventListener('click', function() {
        document.getElementById('modal').style.display = "none";
    });

    // Close modal when clicking outside of it
    window.onclick = function(event) {
        const modal = document.getElementById('modal');
        if (event.target == modal) {
            modal.style.display = "none";
        }
    };
});