function formatSize(bytes) {
    if (bytes === 0) return '0 byte';
    const k = 1024;
    const sizes = ['bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

function renderItems(itemList) {
    const container = document.getElementById('filesList');
    if (!itemList.length) {
        container.innerHTML = '<div class="no-results">❌ هیچ موردی یافت نشد</div>';
        document.getElementById('visibleCount').innerText = '0';
        document.getElementById('totalCount').innerText = itemList.length;
        return;
    }

    let html = '';
    for (let item of itemList) {
        const sizeFormatted = formatSize(item.size);
        const downloadText = item.is_dir 
            ? `📥 دانلود کل پوشه: ${item.total_dir_downloads || 0}` 
            : `⬇️ دانلود: ${item.downloads || 0}`;
        
        const sizeLabel = item.is_dir ? `📦 حجم کل: ${sizeFormatted}` : `📄 حجم: ${sizeFormatted}`;
        
        if (item.is_dir) {
            html += `
                <div class="file-item" data-name="${item.name.toLowerCase()}">
                    <div class="file-info">
                        <div class="file-name">
                            <span class="icon">📁</span>
                            <a href="?path=${encodeURIComponent(item.path)}" class="folder-link">${item.name}</a>
                        </div>
                        <div class="file-details">
                            <span>${sizeLabel}</span>
                            <span>${downloadText}</span>
                        </div>
                    </div>
                    <div class="file-actions">
                        <span style="font-size:1.5rem;">📂</span>
                    </div>
                </div>
            `;
        } else {
            const downloadLink = `download.php?file=${encodeURIComponent(item.path)}`;
            html += `
                <div class="file-item" data-name="${item.name.toLowerCase()}">
                    <div class="file-info">
                        <div class="file-name">
                            <span class="icon">📄</span>
                            ${item.name}
                        </div>
                        <div class="file-details">
                            <span>${sizeLabel}</span>
                            <span>${downloadText}</span>
                        </div>
                    </div>
                    <div class="file-actions">
                        <a href="${downloadLink}" class="download-btn">⬇️ دانلود</a>
                    </div>
                </div>
            `;
        }
    }
    container.innerHTML = html;
    document.getElementById('totalCount').innerText = itemList.length;
    document.getElementById('visibleCount').innerText = itemList.length;
}

function searchInItems(query, itemsArray) {
    if (!query.trim()) return itemsArray;
    const q = query.trim().toLowerCase();
    return itemsArray.filter(item => item.name.toLowerCase().includes(q));
}

document.addEventListener('DOMContentLoaded', () => {
    const searchInput = document.getElementById('searchInput');
    const resetBtn = document.getElementById('resetSearch');
    let allItems = items; // از php آمده

    function updateSearch() {
        const filtered = searchInItems(searchInput.value, allItems);
        renderItems(filtered);
    }

    searchInput.addEventListener('input', updateSearch);
    resetBtn.addEventListener('click', () => {
        searchInput.value = '';
        updateSearch();
    });

    renderItems(allItems);
});