function loadFileList(path = '') {
    currentPath = path;
    $("current-path").textContent = "/" + path;
    fetch(`/api/files?username=${username}&path=${encodeURIComponent(path)}`)
        .then(r => r.json())
        .then(data => {
            const list = $("file-list");
            list.innerHTML = '';
            if (path) {
                list.innerHTML += `<li><a class="non-link" href="#" onclick="loadFileList('${path.split('/').slice(0, -1).join('/')}')">⬅️ ..</a></li>`;
            }
            data.sort((a, b) => {
                if (a.is_dir === b.is_dir) {
                    return a.name.localeCompare(b.name);
                }
                return a.is_dir ? -1 : 1;
            });
            data.forEach(entry => {
                const itemPath = path ? `${path}/${entry.name}` : entry.name;
                let html = '';
                if (entry.is_dir) {
                    html = `<li>📁 <a class="non-link" href="#" onclick="loadFileList('${itemPath}')">${entry.name}</a>
                        <a class="non-link action-icon" onclick="deleteItem('${itemPath}')" title="Usuń folder">
                            <i class="fa-solid fa-trash"></i>
                        </a>
                    </li>`;
                } else {
                    const fileExtension = getFileExtension(entry.name);
                    const editableExtensions = ['txt', 'log', 'json', 'yml', 'yaml', 'properties', 'html', 'css', 'js', 'xml', 'py'];
                    const isEditable = editableExtensions.includes(fileExtension.toLowerCase());

                    html = `<li>📄 ${entry.name}
                        ${isEditable ? `
                        <a class="non-link action-icon" onclick="openFileEditor('${itemPath}')" title="Edytuj plik">
                            <i class="fa-solid fa-edit"></i>
                        </a>` : ''}
                        <a class="non-link action-icon" href="/api/files/download?username=${username}&path=${encodeURIComponent(itemPath)}" target="_blank" title="Pobierz plik">
                            <i class="fa-solid fa-download"></i>
                        </a>
                        <a class="non-link action-icon" onclick="deleteItem('${itemPath}')" title="Usuń plik">
                            <i class="fa-solid fa-trash"></i>
                        </a>
                    </li>`;
                }
                list.innerHTML += html;
            });
            closeFileEditor();
        });
}

function deleteItem(path) {
    if (!confirm(`Czy na pewno chcesz usunąć: ${path}?`)) return;

    fetch('/api/files/delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, path })
    })
    .then(res => res.json())
    .then(data => {
        if (data.success) {
            loadFileList(currentPath);
        } else {
            alert("Błąd podczas usuwania: " + (data.error || "Nieznany"));
        }
    })
    .catch(err => {
        console.error(err);
        alert("Błąd połączenia z serwerem.");
    });
}

document.querySelector('[onclick="showTab(\'files\')"]').addEventListener('click', () => {
    loadFileList(); // Load root directory when the tab is opened
});

const dropZone = document.getElementById('drop-zone');
const fileInput = document.getElementById('file-input');
const progressBar = document.getElementById('progress-bar');
const progressWrapper = document.getElementById('upload-progress');

dropZone.addEventListener('click', () => fileInput.click());

dropZone.addEventListener('dragover', e => {
    e.preventDefault();
    dropZone.classList.add('dragover');
});

dropZone.addEventListener('dragleave', e => {
    e.preventDefault();
    dropZone.classList.remove('dragover');
});

dropZone.addEventListener('drop', e => {
    e.preventDefault();
    dropZone.classList.remove('dragover');
    handleFiles(e.dataTransfer.files);
});

fileInput.addEventListener('change', () => {
    handleFiles(fileInput.files);
});

function handleFiles(files) {
    if (!files.length) return;

    const formData = new FormData();
    for (const file of files) {
        formData.append('files', file);
    }
    formData.append('username', username);
    formData.append('path', currentPath);

    progressWrapper.classList.remove('hidden');
    progressBar.style.width = '0%';

    const xhr = new XMLHttpRequest();
    xhr.open('POST', `/api/files/upload?username=${username}&path=${encodeURIComponent(currentPath)}`);

    xhr.upload.addEventListener('progress', e => {
        if (e.lengthComputable) {
            const percent = (e.loaded / e.total) * 100;
            progressBar.style.width = `${percent}%`;
        }
    });

    xhr.onload = () => {
        progressWrapper.classList.add('hidden');
        if (xhr.status === 200) {
            loadFileList(currentPath);
        } else {
            alert("Upload się nie udał.");
        }
    };

    xhr.onerror = () => {
        progressWrapper.classList.add('hidden');
        alert("Upload się nie udał.");
    };

    xhr.send(formData);
}