<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>PyBrowser - {{ hostname }}</title>
    <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='0.9em' font-size='90'>🐍</text></svg>">
    <style>
        body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: #f0f2f5; margin: 0; padding: 20px; }
        .container { max-width: 900px; margin: auto; background: white; border-radius: 12px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); position: relative; }
        
        /* Header */
        .header { padding: 15px 20px; background: #2c3e50; color: white; display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0; z-index: 100; }
        .header-title { display: flex; align-items: center; gap: 10px; font-weight: bold; }
        .hostname { font-weight: normal; font-size: 0.85rem; opacity: 0.7; background: rgba(255,255,255,0.1); padding: 2px 8px; border-radius: 4px; }
        
        .header-actions { display: flex; align-items: center; gap: 12px; }
        
        /* Download Button */
        .download-btn { display: none; padding: 8px 16px; background: #27ae60; color: white; border: 2px solid white; border-radius: 20px; cursor: pointer; font-size: 0.9rem; font-weight: bold; transition: all 0.2s; }
        .download-btn:hover { background: #229954; transform: scale(1.05); }
        .download-btn.show { display: inline-block; }
        
        /* Breadcrumb */
        .breadcrumb { padding: 10px 20px; background: #ecf0f1; border-bottom: 1px solid #bdc3c7; font-size: 0.9rem; position: sticky; top: 68px; z-index: 99; }
        .breadcrumb a { color: #3498db; text-decoration: none; }
        .breadcrumb a:hover { text-decoration: underline; }
        .breadcrumb span { color: #7f8c8d; margin: 0 5px; }
        
        /* Search and Sort Bar */
        .search-sort-bar { padding: 15px 20px; background: #fff; border-bottom: 1px solid #e0e0e0; display: flex; gap: 10px; align-items: center; position: sticky; top: 108px; z-index: 98; }
        .search-box { flex-grow: 1; position: relative; }
        .search-box input { width: 100%; padding: 10px 40px 10px 15px; border: 2px solid #cbd5e0; border-radius: 8px; font-size: 0.95rem; box-sizing: border-box; }
        .search-box input:focus { outline: none; border-color: #3498db; }
        .search-icon { position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: #7f8c8d; }
        .sort-buttons { display: flex; gap: 5px; }
        .sort-btn { padding: 8px 15px; background: #ecf0f1; border: 2px solid #cbd5e0; border-radius: 6px; cursor: pointer; font-size: 0.85rem; transition: all 0.2s; color: #333; text-decoration: none; display: inline-block; }
        .sort-btn:hover { background: #cbd5e0; }
        .sort-btn.active { background: #3498db; color: white; border-color: #3498db; }
        
        /* Botões Circulares: Fundo Escuro, Ícone Branco */
        .circle-btn { 
            width: 40px; height: 40px; background: #2c3e50; border-radius: 50%; 
            display: flex; align-items: center; justify-content: center; 
            text-decoration: none; border: 2px solid white; cursor: pointer; 
            transition: transform 0.2s, opacity 0.2s; padding: 0; flex-shrink: 0;
        }
        .circle-btn:hover { transform: scale(1.1); opacity: 0.9; }
        .circle-btn svg { fill: white; width: 18px; height: 18px; }

        /* Itens da Lista */
        .item { display: flex; align-items: center; padding: 12px 20px; border-bottom: 1px solid #eee; gap: 15px; }
        .item:hover { background: #f8f9fa; }
        .item-checkbox { width: 20px; height: 20px; cursor: pointer; flex-shrink: 0; }
        .item-info { flex-grow: 1; text-decoration: none; color: #333; display: flex; align-items: center; min-width: 0; }
        .icon-type { margin-right: 15px; font-size: 1.2rem; flex-shrink: 0; }
        .item-name { flex-grow: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .item-date { color: #7f8c8d; font-size: 0.85rem; min-width: 130px; text-align: right; flex-shrink: 0; }
        .item .circle-btn { border: none; box-shadow: 0 2px 4px rgba(0,0,0,0.2); flex-shrink: 0; }

        /* Modal */
        .modal { display: none; position: fixed; z-index: 1000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.6); align-items: center; justify-content: center; }
        .modal-content { background: white; padding: 30px; border-radius: 12px; width: 90%; max-width: 400px; text-align: center; color: #333; }
        .upload-option { display: block; border: 2px dashed #cbd5e0; padding: 20px; margin: 15px 0; border-radius: 8px; cursor: pointer; }
        .upload-option:hover { border-color: #2c3e50; background: #f8f9fa; }
        input[type="file"] { display: none; }
        
        /* Upload File List */
        .file-list-container { margin-top: 15px; max-height: 300px; overflow-y: auto; background: #f8f9fa; border-radius: 8px; padding: 10px; }
        .file-list-table { width: 100%; border-collapse: collapse; font-size: 0.9rem; }
        .file-list-table th { background: #2c3e50; color: white; padding: 8px; text-align: left; font-weight: bold; position: sticky; top: 0; }
        .file-list-table td { padding: 8px; border-bottom: 1px solid #e0e0e0; }
        .file-list-table tr:hover { background: #fff; }
        .file-size { color: #7f8c8d; font-size: 0.85rem; }
        .file-more { color: #7f8c8d; font-style: italic; text-align: center; padding: 12px; }
        
        /* Search Modal */
        .search-modal-content { max-width: 1000px; width: 95%; max-height: 85vh; display: flex; flex-direction: column; padding: 40px; }
        .search-input-container { display: flex; gap: 12px; margin-bottom: 25px; }
        .search-input-container input { flex: 1; padding: 15px 20px; border: 2px solid #e0e0e0; border-radius: 10px; font-size: 1.05rem; transition: all 0.2s; }
        .search-input-container input:focus { outline: none; border-color: #3498db; box-shadow: 0 0 0 3px rgba(52, 152, 219, 0.1); }
        .search-input-container button { padding: 15px 30px; background: #3498db; color: white; border: none; border-radius: 10px; cursor: pointer; font-weight: bold; font-size: 1rem; transition: all 0.2s; }
        .search-input-container button:hover { background: #2980b9; transform: translateY(-1px); box-shadow: 0 4px 8px rgba(0,0,0,0.15); }
        .search-results { flex: 1; overflow-y: auto; max-height: 500px; border-radius: 10px; background: #fafafa; padding: 10px; }
        .search-result-item { display: flex; align-items: center; padding: 16px 20px; border: 1px solid #e8e8e8; gap: 15px; background: white; margin-bottom: 8px; border-radius: 8px; transition: all 0.2s; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
        .search-result-item:hover { background: #f8f9fa; border-color: #3498db; transform: translateX(4px); box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
        .search-result-icon { font-size: 1.5rem; flex-shrink: 0; }
        .search-result-info { flex: 1; min-width: 0; }
        .search-result-name { font-weight: 600; color: #2c3e50; font-size: 1rem; margin-bottom: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .search-result-path { font-size: 0.875rem; color: #95a5a6; display: flex; align-items: center; gap: 6px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .search-navigate-btn { padding: 10px 20px; background: #27ae60; color: white; border: none; border-radius: 8px; cursor: pointer; font-size: 0.9rem; font-weight: 600; white-space: nowrap; transition: all 0.2s; flex-shrink: 0; }
        .search-navigate-btn:hover { background: #229954; transform: translateY(-1px); box-shadow: 0 4px 8px rgba(39, 174, 96, 0.3); }
        .search-loading { text-align: center; padding: 60px 20px; color: #7f8c8d; font-size: 1.1rem; }
        .search-empty { text-align: center; padding: 60px 20px; color: #95a5a6; font-size: 1.05rem; }
        
        /* Item Highlight */
        .item.highlight { background: #fff3cd !important; border: 2px solid #ffc107; animation: highlight-pulse 1.5s ease-in-out; }
        @keyframes highlight-pulse { 0%, 100% { background: #fff3cd; } 50% { background: #ffe69c; } }
        
        /* Viewer Modal */
        .viewer-modal { display: none; position: fixed; z-index: 2000; left: 0; top: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); align-items: center; justify-content: center; }
        .viewer-content { background: white; border-radius: 12px; width: 90%; height: 90%; max-width: 1200px; max-height: 90vh; display: flex; flex-direction: column; overflow: hidden; }
        .viewer-header { padding: 15px 20px; background: #2c3e50; color: white; display: flex; justify-content: space-between; align-items: center; border-radius: 12px 12px 0 0; }
        .viewer-title { font-weight: bold; font-size: 1.1rem; }
        .viewer-close { background: #e74c3c; color: white; border: none; border-radius: 50%; width: 35px; height: 35px; cursor: pointer; font-size: 1.2rem; display: flex; align-items: center; justify-content: center; }
        .viewer-close:hover { background: #c0392b; }
        .viewer-body { flex-grow: 1; overflow: auto; padding: 0; display: flex; align-items: center; justify-content: center; background: #f8f9fa; }
        .viewer-body img { max-width: 100%; max-height: 100%; object-fit: contain; }
        .viewer-body video, .viewer-body audio { max-width: 100%; }
        .viewer-body iframe { width: 100%; height: 100%; border: none; }
        .viewer-body pre { text-align: left; background: #282c34; color: #abb2bf; padding: 20px; border-radius: 0; overflow: auto; width: 100%; height: 100%; font-family: 'Consolas', 'Monaco', monospace; font-size: 0.9rem; margin: 0; box-sizing: border-box; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <div class="header-title">
                <span>📁 PyBrowser</span>
                <span class="hostname">{{ hostname }}</span>
            </div>
            <div class="header-actions">
                <button class="download-btn" id="downloadBtn" onclick="downloadSelected()" title="Baixar selecionados">
                    <span id="downloadCount">0</span> selecionado(s) 📥
                </button>
                {% if current_path %}
                <a href="{% if parent_path %}/browse/{{ parent_path }}{% else %}/{% endif %}" class="circle-btn" title="Voltar">
                    <svg viewBox="0 0 24 24"><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/></svg>
                </a>
                {% endif %}
                <a href="/" class="circle-btn" title="Início">
                    <svg viewBox="0 0 24 24"><path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z"/></svg>
                </a>
                <button class="circle-btn" onclick="openFolderModal()" title="Nova Pasta">
                    <svg viewBox="0 0 24 24"><path d="M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-1 8h-3v3h-2v-3h-3v-2h3V9h2v3h3v2z"/></svg>
                </button>
                <button class="circle-btn" onclick="openUploadModal()" title="Upload">
                    <svg viewBox="0 0 24 24"><path d="M9 16h6v-6h4l-7-7-7 7h4v6zm-4 2h14v2H5v-2z"/></svg>
                </button>
                <button class="circle-btn" onclick="openSearchModal()" title="Busca Avançada">
                    <svg viewBox="0 0 24 24"><path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/></svg>
                </button>
            </div>
        </div>
        
        <div class="breadcrumb">
            <a href="/">Home</a>
            {% if current_path %}
                {% set parts = current_path.split('/') %}
                {% for part in parts %}
                    <span>></span>
                    {% set path_so_far = '/'.join(parts[:loop.index]) %}
                    {% if loop.last %}
                        <strong>{{ part }}</strong>
                    {% else %}
                        <a href="/browse/{{ path_so_far }}">{{ part }}</a>
                    {% endif %}
                {% endfor %}
            {% endif %}
        </div>
        
        <div class="search-sort-bar">
            <div class="search-box">
                <form method="get" style="margin: 0;">
                    <input type="text" name="search" placeholder="Buscar arquivos e pastas..." value="{{ search_query or '' }}">
                    <input type="hidden" name="sort" value="{{ sort_by }}">
                    <span class="search-icon">🔍</span>
                </form>
            </div>
            <div class="sort-buttons">
                <a href="?sort=name{% if search_query %}&search={{ search_query }}{% endif %}" class="sort-btn {% if sort_by == 'name' or not sort_by %}active{% endif %}" title="Ordenar por Nome">📝 Nome</a>
                <a href="?sort=date{% if search_query %}&search={{ search_query }}{% endif %}" class="sort-btn {% if sort_by == 'date' %}active{% endif %}" title="Ordenar por Data">📅 Data</a>
                <a href="?sort=type{% if search_query %}&search={{ search_query }}{% endif %}" class="sort-btn {% if sort_by == 'type' %}active{% endif %}" title="Ordenar por Tipo">📂 Tipo</a>
            </div>
        </div>
        
        {% for item in items %}
        <div class="item">
            <input type="checkbox" class="item-checkbox" data-path="{{ item.path }}" onchange="updateDownloadButton()">
            <a href="{% if item.is_dir %}/browse/{{ item.path }}{% else %}/download/{{ item.path }}{% endif %}" class="item-info">
                <span class="icon-type">{{ item.icon }}</span>
                <span class="item-name">{{ item.name }}</span>
            </a>
            <span class="item-date">{{ item.created_date }}</span>
            
            {% if item.is_viewable %}
            <button class="circle-btn" onclick="viewFile('{{ item.path }}', '{{ item.name }}', '{{ item.ext }}')" title="Visualizar">
                <svg viewBox="0 0 24 24"><path d="M12 4.5C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5zM12 17c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5zm0-8c-1.66 0-3 1.34-3 3s1.34 3 3 3 3-1.34 3-3-1.34-3-3-3z"/></svg>
            </button>
            {% endif %}
            
            <button class="circle-btn" onclick="confirmDelete('{{ item.path }}', '{{ item.name }}')" title="Deletar">
                <svg viewBox="0 0 24 24"><path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/></svg>
            </button>
        </div>
        {% endfor %}
    </div>

    <div id="uploadModal" class="modal">
        <div class="modal-content">
            <h3 style="margin-top: 0; color: #2c3e50;">Upload em: /{{ current_path }}</h3>
            <form id="uploadForm" action="/upload" method="post" enctype="multipart/form-data">
                <input type="hidden" name="path" value="{{ current_path }}">
                <label class="upload-option">
                    <strong>Selecionar Arquivos</strong>
                    <input type="file" id="fileInput" name="files" multiple onchange="showSelectedFiles()">
                </label>
                <label class="upload-option">
                    <strong>Selecionar Pasta</strong>
                    <input type="file" id="folderInput" name="files" webkitdirectory directory onchange="showSelectedFiles()">
                </label>
                <div id="fileList" style="display: none;">
                    <div class="file-list-container">
                        <table class="file-list-table">
                            <thead>
                                <tr>
                                    <th>Nome do Arquivo</th>
                                    <th style="width: 100px;">Tamanho</th>
                                </tr>
                            </thead>
                            <tbody id="fileListItems"></tbody>
                        </table>
                    </div>
                </div>
                <div style="margin-top: 20px; display: flex; gap: 10px; justify-content: center;">
                    <button type="button" onclick="closeUploadModal()" style="padding: 10px 20px; background: #95a5a6; color: white; border: none; border-radius: 8px; cursor: pointer;">Cancelar</button>
                    <button type="submit" id="uploadButton" style="padding: 10px 20px; background: #27ae60; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: bold; display: none;">Upload</button>
                </div>
            </form>
        </div>
    </div>

    <div id="folderModal" class="modal">
        <div class="modal-content">
            <h3 style="margin-top: 0; color: #2c3e50;">Nova Pasta em: /{{ current_path }}</h3>
            <form action="/create_folder" method="post">
                <input type="hidden" name="path" value="{{ current_path }}">
                <input type="text" name="folder_name" placeholder="Nome da pasta" 
                       style="width: 100%; padding: 12px; border: 2px solid #cbd5e0; border-radius: 8px; font-size: 1rem; box-sizing: border-box;" 
                       required autofocus>
                <div style="margin-top: 20px; display: flex; gap: 10px; justify-content: center;">
                    <button type="button" onclick="closeFolderModal()" style="padding: 10px 20px; background: #95a5a6; color: white; border: none; border-radius: 8px; cursor: pointer;">Cancelar</button>
                    <button type="submit" style="padding: 10px 20px; background: #2c3e50; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: bold;">Criar</button>
                </div>
            </form>
        </div>
    </div>

    <div id="deleteModal" class="modal">
        <div class="modal-content">
            <h3 style="margin-top: 0; color: #e74c3c;">⚠️ Confirmar Exclusão</h3>
            <p style="margin: 20px 0;">Tem certeza que deseja deletar <strong id="deleteItemName"></strong>?</p>
            <p style="font-size: 0.9rem; color: #7f8c8d;">Esta ação não pode ser desfeita.</p>
            <form id="deleteForm" method="post" action="">
                <div style="margin-top: 20px; display: flex; gap: 10px; justify-content: center;">
                    <button type="button" onclick="closeDeleteModal()" style="padding: 10px 20px; background: #95a5a6; color: white; border: none; border-radius: 8px; cursor: pointer;">Cancelar</button>
                    <button type="submit" style="padding: 10px 20px; background: #e74c3c; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: bold;">Deletar</button>
                </div>
            </form>
        </div>
    </div>

    <div id="searchModal" class="modal">
        <div class="modal-content search-modal-content">
            <h3 style="margin-top: 0; color: #2c3e50;">🔍 Busca Avançada</h3>
            <div class="search-input-container">
                <input type="text" id="advancedSearchInput" placeholder="Digite o nome do arquivo ou pasta..." onkeypress="if(event.key==='Enter') performAdvancedSearch()">
                <button onclick="performAdvancedSearch()">Buscar</button>
            </div>
            <div class="search-results" id="searchResults">
                <div class="search-empty">Digite algo e clique em Buscar para pesquisar em todos os diretórios</div>
            </div>
            <div style="margin-top: 20px; text-align: center;">
                <button onclick="closeSearchModal()" style="padding: 10px 20px; background: #95a5a6; color: white; border: none; border-radius: 8px; cursor: pointer;">Fechar</button>
            </div>
        </div>
    </div>

    <div id="viewerModal" class="viewer-modal">
        <div class="viewer-content">
            <div class="viewer-header">
                <span class="viewer-title" id="viewerTitle"></span>
                <button class="viewer-close" onclick="closeViewer()">✕</button>
            </div>
            <div class="viewer-body" id="viewerBody">
                <!-- Conteúdo do arquivo será carregado aqui -->
            </div>
        </div>
    </div>

    <script>
        function openUploadModal() { 
            document.getElementById('uploadModal').style.display = 'flex';
            // Limpar seleção anterior
            document.getElementById('fileInput').value = '';
            document.getElementById('folderInput').value = '';
            document.getElementById('fileList').style.display = 'none';
            document.getElementById('uploadButton').style.display = 'none';
        }
        function closeUploadModal() { 
            document.getElementById('uploadModal').style.display = 'none'; 
        }
        
        function showSelectedFiles() {
            const fileInput = document.getElementById('fileInput');
            const folderInput = document.getElementById('folderInput');
            const fileList = document.getElementById('fileList');
            const fileListItems = document.getElementById('fileListItems');
            const uploadButton = document.getElementById('uploadButton');
            
            // Determinar qual input foi usado
            const files = fileInput.files.length > 0 ? fileInput.files : folderInput.files;
            
            if (files.length > 0) {
                fileListItems.innerHTML = '';
                
                // Função para formatar tamanho do arquivo
                function formatFileSize(bytes) {
                    if (bytes === 0) return '0 B';
                    const k = 1024;
                    const sizes = ['B', 'KB', 'MB', 'GB'];
                    const i = Math.floor(Math.log(bytes) / Math.log(k));
                    return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
                }
                
                // Mostrar primeiros 50 arquivos
                const maxDisplay = 50;
                let totalSize = 0;
                
                for (let i = 0; i < Math.min(files.length, maxDisplay); i++) {
                    const file = files[i];
                    const tr = document.createElement('tr');
                    
                    const tdName = document.createElement('td');
                    tdName.textContent = file.webkitRelativePath || file.name;
                    tr.appendChild(tdName);
                    
                    const tdSize = document.createElement('td');
                    tdSize.className = 'file-size';
                    tdSize.textContent = formatFileSize(file.size);
                    tr.appendChild(tdSize);
                    
                    fileListItems.appendChild(tr);
                    totalSize += file.size;
                }
                
                // Calcular tamanho total de todos os arquivos
                for (let i = 0; i < files.length; i++) {
                    if (i >= maxDisplay) totalSize += files[i].size;
                }
                
                if (files.length > maxDisplay) {
                    const tr = document.createElement('tr');
                    const td = document.createElement('td');
                    td.colSpan = 2;
                    td.className = 'file-more';
                    td.textContent = `... e mais ${files.length - maxDisplay} arquivo(s)`;
                    tr.appendChild(td);
                    fileListItems.appendChild(tr);
                }
                
                // Adicionar linha de resumo
                const trTotal = document.createElement('tr');
                trTotal.style.fontWeight = 'bold';
                trTotal.style.background = '#ecf0f1';
                
                const tdTotal = document.createElement('td');
                tdTotal.textContent = `Total: ${files.length} arquivo(s)`;
                trTotal.appendChild(tdTotal);
                
                const tdTotalSize = document.createElement('td');
                tdTotalSize.textContent = formatFileSize(totalSize);
                trTotal.appendChild(tdTotalSize);
                
                fileListItems.appendChild(trTotal);
                
                fileList.style.display = 'block';
                uploadButton.style.display = 'inline-block';
            } else {
                fileList.style.display = 'none';
                uploadButton.style.display = 'none';
            }
        }
        
        function openFolderModal() { document.getElementById('folderModal').style.display = 'flex'; }
        function closeFolderModal() { document.getElementById('folderModal').style.display = 'none'; }
        
        function confirmDelete(path, name) {
            document.getElementById('deleteItemName').textContent = name;
            document.getElementById('deleteForm').action = '/delete/' + path;
            document.getElementById('deleteModal').style.display = 'flex';
        }
        
        function closeDeleteModal() { document.getElementById('deleteModal').style.display = 'none'; }
        
        function updateDownloadButton() {
            const checkboxes = document.querySelectorAll('.item-checkbox:checked');
            const downloadBtn = document.getElementById('downloadBtn');
            const downloadCount = document.getElementById('downloadCount');
            
            if (checkboxes.length > 0) {
                downloadBtn.classList.add('show');
                downloadCount.textContent = checkboxes.length;
            } else {
                downloadBtn.classList.remove('show');
            }
        }
        
        function downloadSelected() {
            const checkboxes = document.querySelectorAll('.item-checkbox:checked');
            if (checkboxes.length === 0) return;
            
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '/download_selected';
            
            checkboxes.forEach(checkbox => {
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'items[]';
                input.value = checkbox.dataset.path;
                form.appendChild(input);
            });
            
            document.body.appendChild(form);
            form.submit();
            document.body.removeChild(form);
            
            // Desmarcar todos após download
            setTimeout(() => {
                checkboxes.forEach(cb => cb.checked = false);
                updateDownloadButton();
            }, 500);
        }
        
        function viewFile(path, name, ext) {
            document.getElementById('viewerTitle').textContent = name;
            const viewerBody = document.getElementById('viewerBody');
            const viewUrl = '/view/' + path;
            
            // Limpar conteúdo anterior
            viewerBody.innerHTML = '';
            
            // Imagens
            if (['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp', '.ico'].includes(ext)) {
                viewerBody.innerHTML = '<img src="' + viewUrl + '" alt="' + name + '">';
            }
            // Vídeos
            else if (['.mp4', '.webm', '.ogg'].includes(ext)) {
                viewerBody.innerHTML = '<video controls autoplay><source src="' + viewUrl + '" type="video/' + ext.substring(1) + '">Seu navegador não suporta vídeo.</video>';
            }
            // Áudio
            else if (['.mp3', '.wav', '.ogg', '.m4a'].includes(ext)) {
                viewerBody.innerHTML = '<audio controls autoplay><source src="' + viewUrl + '" type="audio/' + ext.substring(1) + '">Seu navegador não suporta áudio.</audio>';
            }
            // PDF
            else if (ext === '.pdf') {
                viewerBody.innerHTML = '<iframe src="' + viewUrl + '"></iframe>';
            }
            // Arquivos de texto/código
            else {
                fetch(viewUrl)
                    .then(response => response.text())
                    .then(text => {
                        const pre = document.createElement('pre');
                        pre.textContent = text;
                        viewerBody.appendChild(pre);
                    })
                    .catch(err => {
                        viewerBody.innerHTML = '<p style="color: #e74c3c;">Erro ao carregar arquivo.</p>';
                    });
            }
            
            document.getElementById('viewerModal').style.display = 'flex';
        }
        
        function closeViewer() { document.getElementById('viewerModal').style.display = 'none'; }
        
        function openSearchModal() {
            document.getElementById('searchModal').style.display = 'flex';
            document.getElementById('advancedSearchInput').focus();
        }
        
        function closeSearchModal() {
            document.getElementById('searchModal').style.display = 'none';
        }
        
        function performAdvancedSearch() {
            const query = document.getElementById('advancedSearchInput').value.trim();
            const resultsDiv = document.getElementById('searchResults');
            
            if (!query) {
                resultsDiv.innerHTML = '<div class="search-empty">Por favor, digite algo para buscar</div>';
                return;
            }
            
            resultsDiv.innerHTML = '<div class="search-loading">🔍 Buscando...</div>';
            
            fetch('/api/search?q=' + encodeURIComponent(query))
                .then(response => response.json())
                .then(data => {
                    if (data.results.length === 0) {
                        resultsDiv.innerHTML = '<div class="search-empty">Nenhum resultado encontrado para "' + query + '"</div>';
                        return;
                    }
                    
                    let html = '';
                    data.results.forEach(item => {
                        html += '<div class="search-result-item">';
                        html += '<span class="search-result-icon">' + item.icon + '</span>';
                        html += '<div class="search-result-info">';
                        html += '<div class="search-result-name">' + item.name + '</div>';
                        html += '<div class="search-result-path">📍 ' + (item.parent_path || '/') + '</div>';
                        html += '</div>';
                        html += '<button class="search-navigate-btn" onclick="navigateToItem(\'' + item.parent_path + '\', \'' + item.path + '\')">Ir para local</button>';
                        html += '</div>';
                    });
                    
                    resultsDiv.innerHTML = html;
                })
                .catch(err => {
                    resultsDiv.innerHTML = '<div class="search-empty" style="color: #e74c3c;">Erro ao buscar. Tente novamente.</div>';
                });
        }
        
        function navigateToItem(parentPath, itemPath) {
            closeSearchModal();
            const url = parentPath ? '/browse/' + parentPath + '?highlight=' + encodeURIComponent(itemPath) : '/?highlight=' + encodeURIComponent(itemPath);
            window.location.href = url;
        }
        
        // Destacar item se houver parâmetro highlight na URL
        window.addEventListener('DOMContentLoaded', function() {
            const urlParams = new URLSearchParams(window.location.search);
            const highlightPath = urlParams.get('highlight');
            
            if (highlightPath) {
                const checkboxes = document.querySelectorAll('.item-checkbox');
                checkboxes.forEach(checkbox => {
                    if (checkbox.dataset.path === highlightPath) {
                        const item = checkbox.closest('.item');
                        if (item) {
                            item.classList.add('highlight');
                            setTimeout(() => {
                                item.scrollIntoView({ behavior: 'smooth', block: 'center' });
                            }, 100);
                            setTimeout(() => {
                                item.classList.remove('highlight');
                            }, 3000);
                        }
                    }
                });
            }
        });
        
        window.onclick = function(event) {
            if (event.target.className === 'modal') {
                closeUploadModal();
                closeFolderModal();
                closeDeleteModal();
                closeSearchModal();
            }
            if (event.target.id === 'viewerModal') {
                closeViewer();
            }
        }
    </script>
</body>
</html>