<?php
require_once __DIR__ . '/../../../includes/config.php';
if (!isSuperAdmin()) { header('Location: /pages/login.php'); exit; }
$superAdmin = getSuperAdmin();
$pageTitle = 'Deploy para Produção';
$currentPage = 'deploy';
include __DIR__ . '/../includes/header.php';
?>
<div class="app-container">
<?php include __DIR__ . '/../includes/sidebar.php'; ?>
<main class="main-content">
<?php include __DIR__ . '/../includes/topbar.php'; ?>
<div class="content-area">

<!-- Page Header -->
<div class="page-header">
    <div>
        <h1><iconify-icon icon="solar:rocket-bold" style="color: var(--gold);"></iconify-icon> Deploy Manager</h1>
        <p>Gerencie deploys entre Staging e Produção</p>
    </div>
</div>

<!-- Tabs -->
<div class="page-tabs">
    <button class="page-tab active" data-tab="deploy"><iconify-icon icon="solar:rocket-bold"></iconify-icon><span>Deploy</span></button>
    <button class="page-tab" data-tab="changesets"><iconify-icon icon="solar:layers-bold"></iconify-icon><span>Changesets</span></button>
    <button class="page-tab" data-tab="recovery"><iconify-icon icon="solar:folder-open-bold"></iconify-icon><span>Arquivos</span></button>
    <button class="page-tab" data-tab="reverse"><iconify-icon icon="solar:refresh-circle-bold"></iconify-icon><span>Sync Reverso</span></button>
    <button class="page-tab" data-tab="import"><iconify-icon icon="solar:import-bold"></iconify-icon><span>Importar/Exportar</span></button>
</div>

<!-- ==================== TAB DEPLOY ==================== -->
<div id="tabDeploy" class="tab-content active">
    
    <!-- Environment Flow -->
    <div class="env-flow">
        <div class="env-card env-staging">
            <div class="env-badge">STAGING</div>
            <div class="env-icon"><iconify-icon icon="solar:test-tube-bold" width="32"></iconify-icon></div>
            <div class="env-name">dev.duolead.com.br</div>
            <a href="https://dev.duolead.com.br" target="_blank" class="btn btn-sm btn-outline"><iconify-icon icon="solar:arrow-right-up-bold"></iconify-icon> Abrir</a>
        </div>
        <div class="env-arrow-container">
            <div class="env-arrow-line"></div>
            <div class="env-arrow-icon"><iconify-icon icon="solar:arrow-right-bold" width="24"></iconify-icon></div>
        </div>
        <div class="env-card env-production">
            <div class="env-badge">PRODUCTION</div>
            <div class="env-icon"><iconify-icon icon="solar:server-bold" width="32"></iconify-icon></div>
            <div class="env-name">duolead.com.br</div>
            <a href="https://duolead.com.br" target="_blank" class="btn btn-sm btn-outline"><iconify-icon icon="solar:arrow-right-up-bold"></iconify-icon> Abrir</a>
        </div>
    </div>

    <div class="panels-grid">
        <!-- Arquivos Modificados -->
        <div class="panel">
            <div class="panel-header">
                <div class="panel-icon"><iconify-icon icon="solar:file-check-bold"></iconify-icon></div>
                <div>
                    <h3>Arquivos Modificados</h3>
                    <span class="panel-subtitle">Diferenças entre staging e produção</span>
                </div>
                <div class="header-actions" style="margin-left:auto;">
                    <button id="btnCreateChangeset" class="btn btn-secondary btn-sm" style="display:none;"><iconify-icon icon="solar:add-folder-bold"></iconify-icon> Criar Changeset</button>
                    <button id="btnRefresh" class="btn btn-secondary btn-sm"><iconify-icon icon="solar:refresh-bold"></iconify-icon></button>
                </div>
            </div>
            <div class="files-container">
                <div id="statusLoading" class="loading-state"><iconify-icon icon="solar:refresh-bold" class="spin"></iconify-icon> Verificando...</div>
                <div id="statusResult" style="display:none;"></div>
            </div>
        </div>

        <!-- Ações de Deploy -->
        <div class="panel">
            <div class="panel-header">
                <div class="panel-icon green"><iconify-icon icon="solar:rocket-2-bold"></iconify-icon></div>
                <div>
                    <h3>Ações de Deploy</h3>
                    <span class="panel-subtitle">Sincronize com produção</span>
                </div>
            </div>
            
            <div class="action-buttons-grid">
                <button id="btnDeploy" class="deploy-action-btn deploy-btn-primary">
                    <div class="deploy-btn-icon"><iconify-icon icon="solar:rocket-bold" width="32"></iconify-icon></div>
                    <div class="deploy-btn-content">
                        <span class="deploy-btn-title">Deploy Completo</span>
                        <span class="deploy-btn-desc">Enviar todas as modificações para produção</span>
                    </div>
                    <iconify-icon icon="solar:arrow-right-bold" class="deploy-btn-arrow"></iconify-icon>
                </button>

                <button id="btnRollback" class="deploy-action-btn deploy-btn-warning" style="display:none;">
                    <div class="deploy-btn-icon"><iconify-icon icon="solar:rewind-back-bold" width="32"></iconify-icon></div>
                    <div class="deploy-btn-content">
                        <span class="deploy-btn-title">Reverter Deploy</span>
                        <span class="deploy-btn-desc">Restaurar versão anterior</span>
                    </div>
                    <iconify-icon icon="solar:arrow-right-bold" class="deploy-btn-arrow"></iconify-icon>
                </button>

                <button id="btnClearBackup" class="deploy-action-btn deploy-btn-danger" style="display:none;">
                    <div class="deploy-btn-icon"><iconify-icon icon="solar:trash-bin-trash-bold" width="32"></iconify-icon></div>
                    <div class="deploy-btn-content">
                        <span class="deploy-btn-title">Limpar Backup</span>
                        <span class="deploy-btn-desc">Remover pontos de restauração</span>
                    </div>
                    <iconify-icon icon="solar:arrow-right-bold" class="deploy-btn-arrow"></iconify-icon>
                </button>
            </div>
            
            <div id="deployResult" class="terminal-output" style="display:none;"></div>
        </div>
    </div>

    <!-- Histórico -->
    <div class="panel">
        <div class="panel-header">
            <div class="panel-icon blue"><iconify-icon icon="solar:history-bold"></iconify-icon></div>
            <div>
                <h3>Histórico de Deploy</h3>
                <span class="panel-subtitle">Últimas operações realizadas</span>
            </div>
        </div>
        <div id="historyLoading" class="loading-state"><iconify-icon icon="solar:refresh-bold" class="spin"></iconify-icon></div>
        <div id="historyResult" class="table-responsive" style="display:none;"></div>
    </div>
</div>

<!-- ==================== TAB CHANGESETS ==================== -->
<div id="tabChangesets" class="tab-content">
    <div class="panel">
        <div class="panel-header">
            <div class="panel-icon purple"><iconify-icon icon="solar:layers-bold"></iconify-icon></div>
            <div>
                <h3>Changesets</h3>
                <span class="panel-subtitle">Agrupe modificações para deploy seletivo</span>
            </div>
            <button id="btnNewChangeset" class="btn btn-primary btn-sm" style="margin-left:auto;"><iconify-icon icon="solar:add-circle-bold"></iconify-icon> Novo Changeset</button>
        </div>
        <div class="info-banner"><iconify-icon icon="solar:info-circle-bold"></iconify-icon><span>Changesets permitem agrupar arquivos relacionados e fazer deploy de funcionalidades específicas separadamente.</span></div>
        <div id="changesetsLoading" class="loading-state"><iconify-icon icon="solar:refresh-bold" class="spin"></iconify-icon></div>
        <div id="changesetsList" style="display:none;"></div>
    </div>
</div>

<!-- ==================== TAB RECOVERY ==================== -->
<div id="tabRecovery" class="tab-content">
    <div class="panel">
        <div class="panel-header">
            <div class="panel-icon orange"><iconify-icon icon="solar:folder-bold"></iconify-icon></div>
            <div>
                <h3>Explorador de Arquivos</h3>
                <span class="panel-subtitle">Navegue pelos arquivos de produção</span>
            </div>
            <div class="search-box" style="margin-left:auto;">
                <input type="text" id="fileSearch" placeholder="Buscar arquivo..." class="form-input">
                <button id="btnSearchFile" class="btn btn-secondary btn-sm"><iconify-icon icon="solar:magnifer-bold"></iconify-icon></button>
            </div>
        </div>
        <div id="fileBreadcrumb" class="file-breadcrumb"><a href="#" class="breadcrumb-item" data-path=""><iconify-icon icon="solar:home-bold"></iconify-icon> Raiz</a></div>
        <div id="fileListLoading" class="loading-state"><iconify-icon icon="solar:refresh-bold" class="spin"></iconify-icon></div>
        <div id="fileListResult" class="file-grid" style="display:none;"></div>
    </div>
    <div id="fileViewerSection" class="panel" style="display:none;">
        <div class="panel-header">
            <div class="panel-icon"><iconify-icon icon="solar:document-text-bold"></iconify-icon></div>
            <div>
                <h3 id="viewerFileName">Arquivo</h3>
                <div id="fileInfo" class="file-meta"></div>
            </div>
            <div class="viewer-actions" style="margin-left:auto;">
                <button id="btnDownloadFile" class="btn btn-secondary btn-sm"><iconify-icon icon="solar:download-bold"></iconify-icon></button>
                <button id="btnCloseViewer" class="btn btn-outline btn-sm" onclick="document.getElementById('fileViewerSection').style.display='none'"><iconify-icon icon="solar:close-circle-bold"></iconify-icon></button>
            </div>
        </div>
        <div class="code-viewer"><pre id="fileContent"></pre></div>
    </div>
</div>

<!-- ==================== TAB SYNC REVERSO ==================== -->
<div id="tabReverse" class="tab-content">
    <div class="env-flow reverse">
        <div class="env-card env-production">
            <div class="env-badge">PRODUCTION</div>
            <div class="env-icon"><iconify-icon icon="solar:server-bold" width="32"></iconify-icon></div>
            <div class="env-name">duolead.com.br</div>
        </div>
        <div class="env-arrow-container">
            <div class="env-arrow-line"></div>
            <div class="env-arrow-icon"><iconify-icon icon="solar:arrow-right-bold" width="24"></iconify-icon></div>
        </div>
        <div class="env-card env-staging">
            <div class="env-badge">STAGING</div>
            <div class="env-icon"><iconify-icon icon="solar:test-tube-bold" width="32"></iconify-icon></div>
            <div class="env-name">dev.duolead.com.br</div>
        </div>
    </div>
    <div class="panels-grid">
        <div class="panel">
            <div class="panel-header">
                <div class="panel-icon blue"><iconify-icon icon="solar:refresh-circle-bold"></iconify-icon></div>
                <div><h3>Arquivos Diferentes</h3><span class="panel-subtitle">Produção → Staging</span></div>
                <button id="btnRefreshReverse" class="btn btn-secondary btn-sm" style="margin-left:auto;"><iconify-icon icon="solar:refresh-bold"></iconify-icon></button>
            </div>
            <div class="info-banner warning"><iconify-icon icon="solar:shield-warning-bold"></iconify-icon><span>Use quando fizer edições diretas em Produção e quiser atualizar o Staging.</span></div>
            <div id="reverseStatusLoading" class="loading-state"><iconify-icon icon="solar:refresh-bold" class="spin"></iconify-icon> Verificando...</div>
            <div id="reverseStatusResult" style="display:none;"></div>
            <div id="reverseSelectionControls" style="display:none; margin-top: 0.75rem; padding-top: 0.75rem; border-top: 1px solid var(--border-light);">
                <div style="display: flex; gap: 0.5rem; align-items: center; flex-wrap: wrap;">
                    <button type="button" class="btn btn-secondary btn-sm" onclick="selectAllReverseFiles()"><iconify-icon icon="solar:check-square-bold"></iconify-icon> Todos</button>
                    <button type="button" class="btn btn-secondary btn-sm" onclick="deselectAllReverseFiles()"><iconify-icon icon="solar:square-bold"></iconify-icon> Nenhum</button>
                    <span id="reverseSelectedCount" style="margin-left: auto; font-size: 0.8rem; color: var(--text-muted);">0 selecionados</span>
                </div>
            </div>
        </div>
        <div class="panel">
            <div class="panel-header">
                <div class="panel-icon green"><iconify-icon icon="solar:play-bold"></iconify-icon></div>
                <div><h3>Executar Sincronização</h3><span class="panel-subtitle">Copiar arquivos para staging</span></div>
            </div>
            <div class="action-buttons-grid">
                <button id="btnReverseSync" class="deploy-action-btn deploy-btn-primary">
                    <div class="deploy-btn-icon"><iconify-icon icon="solar:refresh-circle-bold" width="32"></iconify-icon></div>
                    <div class="deploy-btn-content">
                        <span class="deploy-btn-title">Sincronizar Staging</span>
                        <span class="deploy-btn-desc">Copiar de Produção para Staging</span>
                    </div>
                    <iconify-icon icon="solar:arrow-right-bold" class="deploy-btn-arrow"></iconify-icon>
                </button>
            </div>
            <div id="reverseResult" class="terminal-output" style="display:none;"></div>
        </div>
    </div>
</div>

<!-- ==================== TAB IMPORT/EXPORT ==================== -->
<div id="tabImport" class="tab-content">
    <div class="panels-grid">
        <div class="panel">
            <div class="panel-header">
                <div class="panel-icon green"><iconify-icon icon="solar:upload-bold"></iconify-icon></div>
                <div><h3>Importar Arquivo</h3><span class="panel-subtitle">Envie arquivos diretamente</span></div>
            </div>
            <div class="upload-zone" id="uploadArea">
                <iconify-icon icon="solar:cloud-upload-bold" width="48"></iconify-icon>
                <p class="upload-title">Arraste um arquivo aqui</p>
                <p class="upload-subtitle">ou clique para selecionar</p>
                <input type="file" id="fileInput" style="display:none;">
            </div>
            <div id="uploadPreview" class="upload-preview" style="display:none;"></div>
            <div class="form-group mt-2">
                <label class="form-label"><iconify-icon icon="solar:folder-path-connect-bold"></iconify-icon> Caminho de destino</label>
                <input type="text" id="targetPath" class="form-input" placeholder="Ex: pages/minha-pagina.php">
            </div>
            <div class="form-group">
                <label class="form-label"><iconify-icon icon="solar:server-bold"></iconify-icon> Ambiente</label>
                <select id="uploadEnvironment" class="form-select">
                    <option value="staging">Staging (dev.duolead.com.br)</option>
                    <option value="production">Production (duolead.com.br)</option>
                </select>
            </div>
            <button id="btnUpload" class="btn btn-primary btn-block" disabled><iconify-icon icon="solar:upload-bold"></iconify-icon> Enviar Arquivo</button>
        </div>
        <div class="panel">
            <div class="panel-header">
                <div class="panel-icon blue"><iconify-icon icon="solar:download-bold"></iconify-icon></div>
                <div><h3>Exportar Arquivo</h3><span class="panel-subtitle">Copie arquivos entre ambientes</span></div>
            </div>
            <div class="form-group">
                <label class="form-label"><iconify-icon icon="solar:transfer-horizontal-bold"></iconify-icon> Direção</label>
                <select id="exportDirection" class="form-select">
                    <option value="staging_to_production">Staging → Production</option>
                    <option value="production_to_staging">Production → Staging</option>
                </select>
            </div>
            <div id="exportBreadcrumb" class="file-breadcrumb"><a href="#" class="breadcrumb-item" data-path=""><iconify-icon icon="solar:home-bold"></iconify-icon> Raiz</a></div>
            <div id="exportFileListLoading" class="loading-state"><iconify-icon icon="solar:refresh-bold" class="spin"></iconify-icon></div>
            <div id="exportFileList" class="file-grid compact" style="display:none;"></div>
        </div>
    </div>
</div>

<!-- ==================== MODAL CHANGESET ==================== -->
<div id="changesetModal" class="modal-overlay" style="display:none;">
    <div class="modal-dialog">
        <div class="modal-header">
            <h3><iconify-icon icon="solar:layers-bold"></iconify-icon> Criar Changeset</h3>
            <button class="modal-close" onclick="closeChangesetModal()"><iconify-icon icon="solar:close-circle-bold"></iconify-icon></button>
        </div>
        <div class="modal-body">
            <div class="form-group">
                <label class="form-label">Nome do Changeset *</label>
                <input type="text" id="changesetName" class="form-input" placeholder="Ex: Fix carrinho de compras">
            </div>
            <div class="form-group">
                <label class="form-label">Descrição</label>
                <textarea id="changesetDescription" class="form-input" rows="2" placeholder="Descreva as mudanças..."></textarea>
            </div>
            <div class="form-group">
                <label class="form-label">Arquivos Selecionados (<span id="selectedFilesCount">0</span>)</label>
                <div id="selectedFilesList" class="selected-files-box"></div>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeChangesetModal()">Cancelar</button>
            <button id="btnSaveChangeset" class="btn btn-primary"><iconify-icon icon="solar:diskette-bold"></iconify-icon> Salvar Changeset</button>
        </div>
    </div>
</div>

</div>
</main>
</div>

<style>
/* Tabs */
.page-tabs { margin-bottom: 2rem; }
.page-tab span { display: none; }
@media (min-width: 768px) { .page-tab span { display: inline; } }
.tab-content { display: none; animation: fadeIn 0.3s ease; }
.tab-content.active { display: block; }

/* Environment Flow */
.env-flow { display: flex; align-items: center; justify-content: center; gap: 1rem; margin-bottom: 2rem; padding: 1.5rem; background: var(--bg-panel); border-radius: var(--radius-lg); box-shadow: var(--shadow-sm); }
.env-flow.reverse { flex-direction: row-reverse; }
.env-card { display: flex; flex-direction: column; align-items: center; gap: 0.75rem; padding: 1.5rem 2rem; background: var(--bg-input); border-radius: var(--radius-lg); border: 2px solid var(--border-light); min-width: 180px; transition: all 0.3s ease; }
.env-card:hover { transform: translateY(-2px); box-shadow: var(--shadow-md); }
.env-staging { border-color: var(--gold); }
.env-staging .env-badge { background: var(--gold); color: #1a1a1a; }
.env-staging .env-icon { color: var(--gold); }
.env-production { border-color: var(--success); }
.env-production .env-badge { background: var(--success); color: white; }
.env-production .env-icon { color: var(--success); }
.env-badge { padding: 0.25rem 0.75rem; border-radius: 2rem; font-size: 0.65rem; font-weight: 700; letter-spacing: 0.05em; }
.env-icon { font-size: 1.5rem; }
.env-name { font-size: 0.9rem; font-weight: 500; color: var(--text-primary); }
.env-arrow-container { display: flex; align-items: center; position: relative; width: 80px; }
.env-arrow-line { position: absolute; width: 100%; height: 2px; background: linear-gradient(90deg, var(--gold), var(--success)); }
.env-arrow-icon { position: relative; z-index: 1; width: 40px; height: 40px; display: flex; align-items: center; justify-content: center; background: var(--bg-panel); border: 2px solid var(--gold); border-radius: 50%; color: var(--gold); margin: 0 auto; animation: pulse 2s infinite; }
@keyframes pulse { 0%, 100% { transform: scale(1); } 50% { transform: scale(1.1); } }

/* ===== DEPLOY ACTION BUTTONS ===== */
.action-buttons-grid {
    display: flex;
    flex-direction: column;
    gap: 0.75rem;
}

.deploy-action-btn {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem 1.25rem;
    border: none;
    border-radius: var(--radius-lg);
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    text-align: left;
    width: 100%;
}

.deploy-action-btn:hover {
    transform: translateX(4px);
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

.deploy-action-btn:active {
    transform: translateX(2px);
}

.deploy-btn-icon {
    width: 52px;
    height: 52px;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 12px;
    flex-shrink: 0;
    transition: transform 0.3s ease;
}

.deploy-action-btn:hover .deploy-btn-icon {
    transform: scale(1.1);
}

.deploy-btn-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 0.25rem;
}

.deploy-btn-title {
    font-weight: 700;
    font-size: 1rem;
    letter-spacing: -0.01em;
}

.deploy-btn-desc {
    font-size: 0.8rem;
    opacity: 0.85;
}

.deploy-btn-arrow {
    font-size: 1.25rem;
    opacity: 0.6;
    transition: all 0.3s ease;
}

.deploy-action-btn:hover .deploy-btn-arrow {
    opacity: 1;
    transform: translateX(4px);
}

/* Primary Button - Deploy */
.deploy-btn-primary {
    background: linear-gradient(135deg, #CCA43B 0%, #B8963A 100%);
    color: #1a1a1a;
    box-shadow: 0 4px 12px rgba(204, 164, 59, 0.3);
}

.deploy-btn-primary .deploy-btn-icon {
    background: rgba(0, 0, 0, 0.12);
}

.deploy-btn-primary:hover {
    box-shadow: 0 8px 24px rgba(204, 164, 59, 0.4);
}

/* Warning Button - Rollback */
.deploy-btn-warning {
    background: linear-gradient(135deg, #F59E0B 0%, #D97706 100%);
    color: white;
    box-shadow: 0 4px 12px rgba(245, 158, 11, 0.25);
}

.deploy-btn-warning .deploy-btn-icon {
    background: rgba(255, 255, 255, 0.2);
}

.deploy-btn-warning:hover {
    box-shadow: 0 8px 24px rgba(245, 158, 11, 0.4);
}

/* Danger Button - Clear */
.deploy-btn-danger {
    background: linear-gradient(135deg, #EF4444 0%, #DC2626 100%);
    color: white;
    box-shadow: 0 4px 12px rgba(239, 68, 68, 0.25);
}

.deploy-btn-danger .deploy-btn-icon {
    background: rgba(255, 255, 255, 0.2);
}

.deploy-btn-danger:hover {
    box-shadow: 0 8px 24px rgba(239, 68, 68, 0.4);
}

/* Terminal Output */
.terminal-output { margin-top: 1rem; padding: 1rem; background: #0d1117; border-radius: var(--radius-md); font-family: 'Fira Code', monospace; font-size: 0.8rem; color: #c9d1d9; white-space: pre-wrap; max-height: 300px; overflow-y: auto; border: 1px solid #30363d; }

/* Files */
.files-container { max-height: 400px; overflow-y: auto; }
.files-list { display: flex; flex-direction: column; }
.file-item { display: flex; align-items: center; gap: 0.75rem; padding: 0.875rem 1rem; border-bottom: 1px solid var(--border-light); transition: background 0.2s; }
.file-item:hover { background: var(--bg-input); }
.file-item:last-child { border-bottom: none; }
.file-item input[type="checkbox"] { width: 18px; height: 18px; accent-color: var(--gold); cursor: pointer; }
.file-path { flex: 1; font-family: 'Fira Code', monospace; font-size: 0.85rem; word-break: break-all; color: var(--text-primary); }
.file-status { padding: 0.25rem 0.75rem; border-radius: 2rem; font-size: 0.7rem; font-weight: 600; text-transform: uppercase; }
.file-status.modified { background: rgba(245, 158, 11, 0.15); color: var(--warning); }
.file-status.new { background: rgba(34, 197, 94, 0.15); color: var(--success); }
.file-status.deleted { background: rgba(239, 68, 68, 0.15); color: var(--danger); }

/* Info Banner */
.info-banner { display: flex; align-items: center; gap: 0.75rem; padding: 1rem; background: rgba(59, 130, 246, 0.1); border: 1px solid rgba(59, 130, 246, 0.2); border-radius: var(--radius-md); margin-bottom: 1.5rem; font-size: 0.875rem; color: var(--info); }
.info-banner.warning { background: rgba(245, 158, 11, 0.1); border-color: rgba(245, 158, 11, 0.2); color: var(--warning); }

/* File Grid */
.file-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 0.75rem; max-height: 400px; overflow-y: auto; }
.file-grid.compact { grid-template-columns: 1fr; }
.file-list-item { display: flex; align-items: center; gap: 0.75rem; padding: 0.875rem; background: var(--bg-input); border-radius: var(--radius-md); cursor: pointer; transition: all 0.2s; border: 1px solid transparent; }
.file-list-item:hover { background: var(--gold-light); border-color: var(--gold); }

/* Breadcrumb */
.file-breadcrumb { display: flex; align-items: center; gap: 0.5rem; padding: 0.75rem 1rem; background: var(--bg-input); border-radius: var(--radius-md); margin-bottom: 1rem; overflow-x: auto; }
.breadcrumb-item { display: flex; align-items: center; gap: 0.25rem; color: var(--text-muted); text-decoration: none; white-space: nowrap; font-size: 0.875rem; }
.breadcrumb-item:hover { color: var(--gold); }

/* Code Viewer */
.code-viewer { background: #0d1117; border-radius: var(--radius-md); border: 1px solid #30363d; max-height: 500px; overflow: auto; }
.code-viewer pre { margin: 0; padding: 1rem; font-family: 'Fira Code', monospace; font-size: 0.8rem; color: #c9d1d9; white-space: pre-wrap; word-break: break-all; }
.file-meta { display: flex; gap: 1rem; font-size: 0.8rem; color: var(--text-muted); margin-top: 0.25rem; }

/* Upload */
.upload-zone { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 0.5rem; padding: 2.5rem; border: 2px dashed var(--border-light); border-radius: var(--radius-lg); cursor: pointer; transition: all 0.3s ease; margin-bottom: 1rem; text-align: center; }
.upload-zone:hover, .upload-zone.dragover { border-color: var(--gold); background: var(--gold-light); }
.upload-zone iconify-icon { color: var(--text-muted); }
.upload-title { font-weight: 500; margin: 0; color: var(--text-primary); }
.upload-subtitle { font-size: 0.8rem; margin: 0; color: var(--text-muted); }
.upload-preview { display: flex; align-items: center; gap: 0.75rem; padding: 0.875rem; background: var(--gold-light); border: 1px solid var(--gold); border-radius: var(--radius-md); margin-bottom: 1rem; font-size: 0.875rem; }

/* Changesets */
.changeset-card { background: var(--bg-input); border: 1px solid var(--border-light); border-radius: var(--radius-lg); padding: 1.25rem; margin-bottom: 1rem; transition: all 0.2s; }
.changeset-card:hover { border-color: var(--gold); box-shadow: var(--shadow-sm); }
.changeset-header { display: flex; align-items: center; justify-content: space-between; margin-bottom: 0.75rem; }
.changeset-name { font-weight: 600; display: flex; align-items: center; gap: 0.5rem; font-size: 1rem; }
.changeset-id { font-size: 0.7rem; color: var(--text-muted); font-family: monospace; background: var(--bg-dark); padding: 0.25rem 0.5rem; border-radius: var(--radius-sm); }
.changeset-meta { display: flex; gap: 1rem; font-size: 0.8rem; color: var(--text-muted); margin-bottom: 0.75rem; flex-wrap: wrap; }
.changeset-files { margin-bottom: 1rem; }
.changeset-files-list { max-height: 120px; overflow-y: auto; background: var(--bg-dark); border-radius: var(--radius-md); padding: 0.5rem; margin-top: 0.5rem; }
.changeset-file { font-family: monospace; font-size: 0.75rem; padding: 0.375rem 0.5rem; border-bottom: 1px solid var(--border-light); }
.changeset-file:last-child { border-bottom: none; }
.changeset-actions { display: flex; gap: 0.5rem; flex-wrap: wrap; }
.changeset-status { padding: 0.25rem 0.75rem; border-radius: 2rem; font-size: 0.7rem; font-weight: 600; }
.changeset-status.pending { background: rgba(245, 158, 11, 0.15); color: var(--warning); }
.changeset-status.deployed { background: rgba(34, 197, 94, 0.15); color: var(--success); }
.changeset-status.partial { background: rgba(249, 115, 22, 0.15); color: #fb923c; }
.changeset-status.rolled_back { background: rgba(239, 68, 68, 0.15); color: var(--danger); }
.no-changesets { text-align: center; padding: 3rem; color: var(--text-muted); }
.no-changesets iconify-icon { display: block; margin: 0 auto 1rem; opacity: 0.3; }

/* Modal */
.modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.7); backdrop-filter: blur(4px); display: flex; align-items: center; justify-content: center; z-index: 1000; padding: 1rem; }
.modal-dialog { background: var(--bg-panel); border-radius: var(--radius-lg); width: 100%; max-width: 550px; max-height: 90vh; overflow: hidden; box-shadow: var(--shadow-lg); animation: modalSlide 0.3s ease; }
@keyframes modalSlide { from { opacity: 0; transform: translateY(-20px); } to { opacity: 1; transform: translateY(0); } }
.modal-header { display: flex; align-items: center; justify-content: space-between; padding: 1.25rem 1.5rem; border-bottom: 1px solid var(--border-light); }
.modal-header h3 { margin: 0; display: flex; align-items: center; gap: 0.5rem; font-size: 1.1rem; }
.modal-close { background: none; border: none; color: var(--text-muted); font-size: 1.5rem; cursor: pointer; padding: 0.25rem; display: flex; transition: color 0.2s; }
.modal-close:hover { color: var(--danger); }
.modal-body { padding: 1.5rem; overflow-y: auto; }
.modal-footer { display: flex; justify-content: flex-end; gap: 0.75rem; padding: 1rem 1.5rem; border-top: 1px solid var(--border-light); background: var(--bg-input); }
.selected-files-box { max-height: 180px; overflow-y: auto; background: var(--bg-input); border-radius: var(--radius-md); border: 1px solid var(--border-light); }
.selected-file-item { display: flex; align-items: center; gap: 0.5rem; padding: 0.625rem 0.75rem; font-family: monospace; font-size: 0.8rem; border-bottom: 1px solid var(--border-light); }
.selected-file-item:last-child { border-bottom: none; }
.selected-file-item .remove-file { margin-left: auto; cursor: pointer; color: var(--text-muted); transition: color 0.2s; }
.selected-file-item .remove-file:hover { color: var(--danger); }

/* Utilities */
.search-box { display: flex; gap: 0.5rem; }
.search-box input { width: 200px; }
.table-responsive table { width: 100%; border-collapse: collapse; }
.table-responsive th, .table-responsive td { padding: 0.875rem 1rem; text-align: left; border-bottom: 1px solid var(--border-light); }
.table-responsive th { font-size: 0.75rem; font-weight: 600; color: var(--text-muted); text-transform: uppercase; letter-spacing: 0.05em; }
.table-responsive tbody tr:hover { background: var(--bg-input); }
.header-actions { display: flex; gap: 0.5rem; }
.mt-2 { margin-top: 1rem; }
.btn-block { width: 100%; }

/* Responsive */
@media (max-width: 768px) {
    .env-flow { flex-direction: column; padding: 1rem; }
    .env-flow.reverse { flex-direction: column; }
    .env-arrow-container { transform: rotate(90deg); width: 40px; height: 80px; }
    .env-card { width: 100%; min-width: auto; }
    .panels-grid { grid-template-columns: 1fr; }
    .search-box { width: 100%; }
    .search-box input { flex: 1; width: auto; }
}
</style>

<script>
// State
let selectedFiles = [];
let currentPath = '';
let changesetsData = [];
let hasBackup = false;

const API_URL = '/api/deploy.php';

// Tab navigation
document.querySelectorAll('.page-tab').forEach(tab => {
    tab.addEventListener('click', function() {
        const tabId = this.dataset.tab;
        document.querySelectorAll('.page-tab').forEach(t => t.classList.remove('active'));
        document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
        this.classList.add('active');
        const contentMap = {deploy:'tabDeploy',changesets:'tabChangesets',recovery:'tabRecovery',reverse:'tabReverse',import:'tabImport'};
        document.getElementById(contentMap[tabId]).classList.add('active');
        
        if (tabId === 'changesets') loadChangesets();
        if (tabId === 'recovery') loadFileList('');
        if (tabId === 'reverse') checkReverseStatus();
        if (tabId === 'import') loadExportFileList('');
    });
});

// API calls
async function apiCall(action, data = {}) {
    try {
        const response = await fetch(API_URL, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ action, ...data })
        });
        return await response.json();
    } catch (e) {
        return { success: false, error: e.message };
    }
}

// Check status
async function checkStatus() {
    document.getElementById('statusLoading').style.display = 'flex';
    document.getElementById('statusResult').style.display = 'none';
    
    const result = await apiCall('status');
    document.getElementById('statusLoading').style.display = 'none';
    document.getElementById('statusResult').style.display = 'block';
    
    if (result.success && result.data.changes && result.data.changes.length > 0) {
        let html = '<div class="files-list">';
        result.data.changes.forEach(f => {
            const status = f.status === 'new' ? 'new' : (f.status === 'deleted' ? 'deleted' : 'modified');
            html += `<div class="file-item">
                <input type="checkbox" data-file="${f.file}" onchange="toggleFileSelection('${f.file}')">
                <span class="file-path">${f.file}</span>
                <span class="file-status ${status}">${status}</span>
            </div>`;
        });
        html += '</div>';
        document.getElementById('statusResult').innerHTML = html;
        document.getElementById('btnCreateChangeset').style.display = 'inline-flex';
    } else {
        document.getElementById('statusResult').innerHTML = '<div class="loading-state" style="color: var(--success);"><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Todos os arquivos sincronizados</div>';
        document.getElementById('btnCreateChangeset').style.display = 'none';
    }
    
    hasBackup = result.data && result.data.backup_exists;
    document.getElementById('btnRollback').style.display = hasBackup ? 'flex' : 'none';
    document.getElementById('btnClearBackup').style.display = hasBackup ? 'flex' : 'none';
    
    loadHistory();
}

// Deploy
document.getElementById('btnDeploy').addEventListener('click', async function() {
    if (!confirm('Confirma deploy completo para produção?')) return;
    
    const btn = this;
    btn.disabled = true;
    btn.querySelector('.deploy-btn-title').textContent = 'Executando...';
    
    const resultDiv = document.getElementById('deployResult');
    resultDiv.style.display = 'block';
    resultDiv.innerHTML = '> Iniciando deploy...\n';
    
    const result = await apiCall('deploy');
    
    if (result.success) {
        resultDiv.innerHTML += `> ✓ Deploy concluído!\n> Arquivos: ${result.data.files_copied || 0}\n> Backup: ${result.data.backup_created ? 'Criado' : 'Existente'}`;
    } else {
        resultDiv.innerHTML += `> ✗ Erro: ${result.error}`;
    }
    
    btn.disabled = false;
    btn.querySelector('.deploy-btn-title').textContent = 'Deploy Completo';
    checkStatus();
});

// Rollback
document.getElementById('btnRollback').addEventListener('click', async function() {
    if (!confirm('Confirma reverter para a versão anterior?')) return;
    
    const btn = this;
    btn.disabled = true;
    btn.querySelector('.deploy-btn-title').textContent = 'Revertendo...';
    
    const resultDiv = document.getElementById('deployResult');
    resultDiv.style.display = 'block';
    resultDiv.innerHTML = '> Iniciando rollback...\n';
    
    const result = await apiCall('rollback');
    
    if (result.success) {
        resultDiv.innerHTML += `> ✓ Rollback concluído!\n> Arquivos restaurados: ${result.data.files_restored || 0}`;
    } else {
        resultDiv.innerHTML += `> ✗ Erro: ${result.error}`;
    }
    
    btn.disabled = false;
    btn.querySelector('.deploy-btn-title').textContent = 'Reverter Deploy';
    checkStatus();
});

// Clear backup
document.getElementById('btnClearBackup').addEventListener('click', async function() {
    if (!confirm('Confirma limpar todos os backups? Esta ação não pode ser desfeita.')) return;
    
    const btn = this;
    btn.disabled = true;
    btn.querySelector('.deploy-btn-title').textContent = 'Limpando...';
    
    const result = await apiCall('clear_backup');
    
    const resultDiv = document.getElementById('deployResult');
    resultDiv.style.display = 'block';
    resultDiv.innerHTML = result.success ? '> ✓ Backups removidos com sucesso!' : `> ✗ Erro: ${result.error}`;
    
    btn.disabled = false;
    btn.querySelector('.deploy-btn-title').textContent = 'Limpar Backup';
    checkStatus();
});

// History
async function loadHistory() {
    const result = await apiCall('history');
    document.getElementById('historyLoading').style.display = 'none';
    document.getElementById('historyResult').style.display = 'block';
    
    if (result.success && result.data && result.data.length > 0) {
        let html = '<table><thead><tr><th>Data</th><th>Ação</th><th>Status</th><th>Detalhes</th></tr></thead><tbody>';
        result.data.slice(0, 10).forEach(h => {
            const statusClass = h.status === 'success' ? 'success' : 'danger';
            html += `<tr>
                <td>${h.date}</td>
                <td>${h.action}</td>
                <td><span class="file-status ${statusClass}">${h.status}</span></td>
                <td>${h.details || '-'}</td>
            </tr>`;
        });
        html += '</tbody></table>';
        document.getElementById('historyResult').innerHTML = html;
    } else {
        document.getElementById('historyResult').innerHTML = '<div class="loading-state"><iconify-icon icon="solar:history-bold"></iconify-icon> Nenhum histórico</div>';
    }
}

// File selection for changesets
function toggleFileSelection(file) {
    const idx = selectedFiles.indexOf(file);
    if (idx > -1) {
        selectedFiles.splice(idx, 1);
    } else {
        selectedFiles.push(file);
    }
    updateSelectedFilesUI();
}

function updateSelectedFilesUI() {
    document.getElementById('selectedFilesCount').textContent = selectedFiles.length;
    const list = document.getElementById('selectedFilesList');
    if (selectedFiles.length === 0) {
        list.innerHTML = '<div class="selected-file-item" style="color: var(--text-muted);">Nenhum arquivo selecionado</div>';
    } else {
        list.innerHTML = selectedFiles.map(f => `<div class="selected-file-item"><iconify-icon icon="solar:file-text-bold"></iconify-icon><span>${f}</span><iconify-icon icon="solar:close-circle-bold" class="remove-file" onclick="toggleFileSelection('${f}');document.querySelector('[data-file=\\'${f}\\']').checked=false;"></iconify-icon></div>`).join('');
    }
}

// Modal
function openChangesetModal() {
    document.getElementById('changesetModal').style.display = 'flex';
    document.getElementById('changesetName').value = '';
    document.getElementById('changesetDescription').value = '';
    updateSelectedFilesUI();
}

function closeChangesetModal() {
    document.getElementById('changesetModal').style.display = 'none';
}

document.getElementById('btnCreateChangeset').addEventListener('click', openChangesetModal);
document.getElementById('btnNewChangeset').addEventListener('click', function() {
    selectedFiles = [];
    openChangesetModal();
});

// Save changeset
document.getElementById('btnSaveChangeset').addEventListener('click', async function() {
    const name = document.getElementById('changesetName').value.trim();
    if (!name) { alert('Nome é obrigatório'); return; }
    if (selectedFiles.length === 0) { alert('Selecione pelo menos um arquivo'); return; }
    
    this.disabled = true;
    this.textContent = 'Salvando...';
    
    const result = await apiCall('create_changeset', {
        name: name,
        description: document.getElementById('changesetDescription').value.trim(),
        files: selectedFiles
    });
    
    if (result.success) {
        closeChangesetModal();
        selectedFiles = [];
        document.querySelectorAll('.file-item input[type="checkbox"]').forEach(cb => cb.checked = false);
        alert('Changeset criado com sucesso!');
        loadChangesets();
    } else {
        alert('Erro: ' + result.error);
    }
    
    this.disabled = false;
    this.innerHTML = '<iconify-icon icon="solar:diskette-bold"></iconify-icon> Salvar Changeset';
});

// Changesets
async function loadChangesets() {
    document.getElementById('changesetsLoading').style.display = 'flex';
    document.getElementById('changesetsList').style.display = 'none';
    
    const result = await apiCall('list_changesets');
    document.getElementById('changesetsLoading').style.display = 'none';
    document.getElementById('changesetsList').style.display = 'block';
    
    if (result.success && result.data.changesets && result.data.changesets.length > 0) {
        changesetsData = result.data.changesets;
        let html = '';
        result.data.changesets.forEach(cs => {
            const statusClass = cs.status || 'pending';
            html += `<div class="changeset-card">
                <div class="changeset-header">
                    <div class="changeset-name"><iconify-icon icon="solar:layers-bold" style="color: var(--gold);"></iconify-icon> ${cs.name} <span class="changeset-id">#${cs.id.substring(0,8)}</span></div>
                    <span class="changeset-status ${statusClass}">${statusClass}</span>
                </div>
                <div class="changeset-meta">
                    <span><iconify-icon icon="solar:calendar-bold"></iconify-icon> ${cs.created_at}</span>
                    <span><iconify-icon icon="solar:file-text-bold"></iconify-icon> ${cs.files.length} arquivos</span>
                    ${cs.description ? `<span><iconify-icon icon="solar:document-text-bold"></iconify-icon> ${cs.description}</span>` : ''}
                </div>
                <div class="changeset-files">
                    <div class="changeset-files-list">${cs.files.map(f => `<div class="changeset-file">${f}</div>`).join('')}</div>
                </div>
                <div class="changeset-actions">
                    <button class="btn btn-primary btn-sm" onclick="deployChangeset('${cs.id}')"><iconify-icon icon="solar:rocket-bold"></iconify-icon> Deploy</button>
                    ${cs.status === 'deployed' ? `<button class="btn btn-warning btn-sm" onclick="rollbackChangeset('${cs.id}')"><iconify-icon icon="solar:rewind-back-bold"></iconify-icon> Reverter</button>` : ''}
                    <button class="btn btn-danger btn-sm" onclick="deleteChangeset('${cs.id}')"><iconify-icon icon="solar:trash-bin-trash-bold"></iconify-icon></button>
                </div>
            </div>`;
        });
        document.getElementById('changesetsList').innerHTML = html;
    } else {
        document.getElementById('changesetsList').innerHTML = '<div class="no-changesets"><iconify-icon icon="solar:layers-bold" width="64"></iconify-icon><p>Nenhum changeset criado</p><small>Crie changesets para agrupar arquivos e fazer deploy seletivo</small></div>';
    }
}

async function deployChangeset(id) {
    if (!confirm('Confirma deploy deste changeset?')) return;
    const result = await apiCall('deploy_changeset', { changeset_id: id });
    alert(result.success ? 'Changeset implantado!' : 'Erro: ' + result.error);
    loadChangesets();
    checkStatus();
}

async function rollbackChangeset(id) {
    if (!confirm('Confirma reverter este changeset?')) return;
    const result = await apiCall('rollback_changeset', { changeset_id: id });
    alert(result.success ? 'Changeset revertido!' : 'Erro: ' + result.error);
    loadChangesets();
    checkStatus();
}

async function deleteChangeset(id) {
    if (!confirm('Confirma excluir este changeset?')) return;
    const result = await apiCall('delete_changeset', { changeset_id: id });
    alert(result.success ? 'Changeset excluído!' : 'Erro: ' + result.error);
    loadChangesets();
}

// File browser
async function loadFileList(path) {
    currentPath = path;
    document.getElementById('fileListLoading').style.display = 'flex';
    document.getElementById('fileListResult').style.display = 'none';
    
    const result = await apiCall('list_files', { path: path });
    document.getElementById('fileListLoading').style.display = 'none';
    document.getElementById('fileListResult').style.display = 'grid';
    
    updateBreadcrumb(path, 'fileBreadcrumb');
    
    if (result.success && result.data && result.data.length > 0) {
        let html = '';
        result.data.forEach(f => {
            const icon = f.is_dir ? 'solar:folder-bold' : 'solar:file-text-bold';
            const color = f.is_dir ? 'var(--gold)' : 'var(--text-muted)';
            html += `<div class="file-list-item" onclick="${f.is_dir ? `loadFileList('${path ? path + '/' : ''}${f.name}')` : `viewFile('${path ? path + '/' : ''}${f.name}')`}">
                <iconify-icon icon="${icon}" style="color: ${color};"></iconify-icon>
                <span>${f.name}</span>
            </div>`;
        });
        document.getElementById('fileListResult').innerHTML = html;
    } else {
        document.getElementById('fileListResult').innerHTML = '<div class="loading-state">Pasta vazia</div>';
    }
}

async function viewFile(path) {
    const result = await apiCall('view_file', { path: path });
    if (result.success) {
        document.getElementById('fileViewerSection').style.display = 'block';
        document.getElementById('viewerFileName').textContent = path.split('/').pop();
        document.getElementById('fileInfo').innerHTML = `<span>Tamanho: ${result.data.size}</span><span>Modificado: ${result.data.modified}</span>`;
        document.getElementById('fileContent').textContent = result.data.content;
    } else {
        alert('Erro: ' + result.error);
    }
}

function updateBreadcrumb(path, elementId) {
    const parts = path.split('/').filter(p => p);
    let html = '<a href="#" class="breadcrumb-item" data-path="" onclick="loadFileList(\'\');return false;"><iconify-icon icon="solar:home-bold"></iconify-icon> Raiz</a>';
    let currentP = '';
    parts.forEach(p => {
        currentP += (currentP ? '/' : '') + p;
        html += ` <iconify-icon icon="solar:arrow-right-bold" style="opacity: 0.3;"></iconify-icon> <a href="#" class="breadcrumb-item" data-path="${currentP}" onclick="loadFileList('${currentP}');return false;">${p}</a>`;
    });
    document.getElementById(elementId).innerHTML = html;
}

// Reverse sync
async function checkReverseStatus() {
    document.getElementById('reverseStatusLoading').style.display = 'flex';
    document.getElementById('reverseStatusResult').style.display = 'none';
    
    const result = await apiCall('reverse_status');
    document.getElementById('reverseStatusLoading').style.display = 'none';
    document.getElementById('reverseStatusResult').style.display = 'block';
    
    if (result.success && result.data.changes && result.data.changes.length > 0) {
        let html = '<div class="files-list">';
        result.data.changes.forEach(f => {
            const statusClass = f.status === 'new' ? 'new' : (f.status === 'deleted' ? 'deleted' : 'modified');
            html += `<div class="file-item">
                <input type="checkbox" class="reverse-file-checkbox" data-file="${f.file}" onchange="updateReverseSelectedCount()" checked>
                <span class="file-path">${f.file}</span>
                <span class="file-status ${statusClass}">${f.status}</span>
            </div>`;
        });
        html += '</div>';
        document.getElementById('reverseStatusResult').innerHTML = html;
        document.getElementById('reverseSelectionControls').style.display = 'block';
        updateReverseSelectedCount();
    } else {
        document.getElementById('reverseStatusResult').innerHTML = '<div class="loading-state" style="color: var(--success);"><iconify-icon icon="solar:check-circle-bold"></iconify-icon> Staging está atualizado com Produção</div>';
        document.getElementById('reverseSelectionControls').style.display = 'none';
    }
}

// Funções de seleção para Reverse Sync
function selectAllReverseFiles() {
    document.querySelectorAll('.reverse-file-checkbox').forEach(cb => cb.checked = true);
    updateReverseSelectedCount();
}

function deselectAllReverseFiles() {
    document.querySelectorAll('.reverse-file-checkbox').forEach(cb => cb.checked = false);
    updateReverseSelectedCount();
}

function updateReverseSelectedCount() {
    const total = document.querySelectorAll('.reverse-file-checkbox').length;
    const selected = document.querySelectorAll('.reverse-file-checkbox:checked').length;
    document.getElementById('reverseSelectedCount').textContent = `${selected} de ${total} selecionados`;
}

function getSelectedReverseFiles() {
    return Array.from(document.querySelectorAll('.reverse-file-checkbox:checked')).map(cb => cb.dataset.file);
}

document.getElementById('btnReverseSync').addEventListener('click', async function() {
    const selectedFiles = getSelectedReverseFiles();
    
    if (selectedFiles.length === 0) {
        alert('Selecione pelo menos um arquivo para sincronizar.');
        return;
    }
    
    if (!confirm(`Confirma sincronização de ${selectedFiles.length} arquivo(s)?\n\nProdução → Staging`)) return;
    
    const btn = this;
    btn.disabled = true;
    btn.querySelector('.deploy-btn-title').textContent = 'Sincronizando...';
    
    const resultDiv = document.getElementById('reverseResult');
    resultDiv.style.display = 'block';
    resultDiv.innerHTML = `> Iniciando sync de ${selectedFiles.length} arquivo(s)...\n`;
    
    const result = await apiCall('reverse_sync', { files: selectedFiles });
    
    if (result.success) {
        resultDiv.innerHTML += `> ✓ Sincronização concluída!\n> Arquivos: ${result.data.files_copied || 0}`;
    } else {
        resultDiv.innerHTML += `> ✗ Erro: ${result.error}`;
    }
    
    btn.disabled = false;
    btn.querySelector('.deploy-btn-title').textContent = 'Sincronizar Staging';
    checkReverseStatus();
});

document.getElementById('btnRefreshReverse').addEventListener('click', checkReverseStatus);

// Export file browser
async function loadExportFileList(path) {
    document.getElementById('exportFileListLoading').style.display = 'flex';
    document.getElementById('exportFileList').style.display = 'none';
    
    const direction = document.getElementById('exportDirection').value;
    const source = direction === 'staging_to_production' ? 'staging' : 'production';
    
    const result = await apiCall('list_files', { path: path, environment: source });
    document.getElementById('exportFileListLoading').style.display = 'none';
    document.getElementById('exportFileList').style.display = 'grid';
    
    updateExportBreadcrumb(path);
    
    if (result.success && result.data && result.data.length > 0) {
        let html = '';
        result.data.forEach(f => {
            const icon = f.is_dir ? 'solar:folder-bold' : 'solar:file-text-bold';
            const color = f.is_dir ? 'var(--gold)' : 'var(--text-muted)';
            html += `<div class="file-list-item" onclick="${f.is_dir ? `loadExportFileList('${path ? path + '/' : ''}${f.name}')` : `exportFile('${path ? path + '/' : ''}${f.name}')`}">
                <iconify-icon icon="${icon}" style="color: ${color};"></iconify-icon>
                <span>${f.name}</span>
            </div>`;
        });
        document.getElementById('exportFileList').innerHTML = html;
    } else {
        document.getElementById('exportFileList').innerHTML = '<div class="loading-state">Pasta vazia</div>';
    }
}

function updateExportBreadcrumb(path) {
    const parts = path.split('/').filter(p => p);
    let html = '<a href="#" class="breadcrumb-item" onclick="loadExportFileList(\'\');return false;"><iconify-icon icon="solar:home-bold"></iconify-icon> Raiz</a>';
    let currentP = '';
    parts.forEach(p => {
        currentP += (currentP ? '/' : '') + p;
        html += ` <iconify-icon icon="solar:arrow-right-bold" style="opacity: 0.3;"></iconify-icon> <a href="#" class="breadcrumb-item" onclick="loadExportFileList('${currentP}');return false;">${p}</a>`;
    });
    document.getElementById('exportBreadcrumb').innerHTML = html;
}

async function exportFile(path) {
    if (!confirm(`Exportar "${path}" para o outro ambiente?`)) return;
    const direction = document.getElementById('exportDirection').value;
    const result = await apiCall('copy_file', { path: path, direction: direction });
    alert(result.success ? 'Arquivo copiado com sucesso!' : 'Erro: ' + result.error);
}

document.getElementById('exportDirection').addEventListener('change', () => loadExportFileList(''));

// Upload
const uploadArea = document.getElementById('uploadArea');
const fileInput = document.getElementById('fileInput');
let uploadFile = null;

uploadArea.addEventListener('click', () => fileInput.click());
uploadArea.addEventListener('dragover', e => { e.preventDefault(); uploadArea.classList.add('dragover'); });
uploadArea.addEventListener('dragleave', () => uploadArea.classList.remove('dragover'));
uploadArea.addEventListener('drop', e => {
    e.preventDefault();
    uploadArea.classList.remove('dragover');
    if (e.dataTransfer.files.length) handleFileSelect(e.dataTransfer.files[0]);
});
fileInput.addEventListener('change', e => { if (e.target.files.length) handleFileSelect(e.target.files[0]); });

function handleFileSelect(file) {
    uploadFile = file;
    document.getElementById('uploadPreview').style.display = 'flex';
    document.getElementById('uploadPreview').innerHTML = `<iconify-icon icon="solar:file-text-bold" style="color: var(--gold);"></iconify-icon><span>${file.name}</span><span style="color: var(--text-muted);">(${(file.size / 1024).toFixed(1)} KB)</span>`;
    document.getElementById('btnUpload').disabled = false;
}

document.getElementById('btnUpload').addEventListener('click', async function() {
    const targetPath = document.getElementById('targetPath').value.trim();
    const environment = document.getElementById('uploadEnvironment').value;
    
    if (!targetPath) { alert('Informe o caminho de destino'); return; }
    if (!uploadFile) { alert('Selecione um arquivo'); return; }
    
    this.disabled = true;
    this.textContent = 'Enviando...';
    
    const reader = new FileReader();
    reader.onload = async function(e) {
        const result = await apiCall('upload_file', {
            path: targetPath,
            content: e.target.result.split(',')[1],
            environment: environment
        });
        
        if (result.success) {
            alert('Arquivo enviado com sucesso!');
            document.getElementById('uploadPreview').style.display = 'none';
            document.getElementById('targetPath').value = '';
            uploadFile = null;
        } else {
            alert('Erro: ' + result.error);
        }
        
        document.getElementById('btnUpload').disabled = false;
        document.getElementById('btnUpload').innerHTML = '<iconify-icon icon="solar:upload-bold"></iconify-icon> Enviar Arquivo';
    };
    reader.readAsDataURL(uploadFile);
});

// Refresh
document.getElementById('btnRefresh').addEventListener('click', checkStatus);

// Init
checkStatus();
</script>

<?php include __DIR__ . '/../includes/footer.php'; ?>
