{% extends "base.html" %}

{% block title %}{{ app.name }} - Painel de Deploy & Gestão{% endblock %}
{% block header_title %}{{ app.name }}{% endblock %}

{% block header_actions %}
<button class="btn btn-primary" onclick="openModal('modal-upload-deploy')">
    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12"/></svg>
    <span>+ NOVO DEPLOY (ZIP)</span>
</button>
<a href="{{ url_for('server_detail', server_id=app.server.id) }}" class="btn btn-secondary">
    <svg width="18" height="18" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18"/></svg>
    <span>Voltar ao Servidor</span>
</a>
{% endblock %}

{% block content %}
<!-- App Header Banner with Live Dynamic Status -->
<div style="background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px; margin-bottom: 24px;">
    <div style="display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 16px;">
        <div>
            <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 6px;">
                <h1 style="font-size: 28px; font-weight: 800; color: #fff;">{{ app.name }}</h1>
                {% if app.access_type == 'ip_direct' %}
                    <span class="badge" style="background: rgba(251, 191, 36, 0.2); color: #fbbf24; border: 1px solid rgba(251, 191, 36, 0.4); font-size: 13px;">🌐 IP DIRETO</span>
                {% else %}
                    <span class="badge" style="background: rgba(16, 185, 129, 0.2); color: #4ade80; border: 1px solid rgba(16, 185, 129, 0.4); font-size: 13px;">🔀 NGINX PROXY</span>
                {% endif %}
                <span class="badge {{ app.badge_cls }}" style="font-size: 13px; padding: 4px 12px;">{{ app.status }}</span>
            </div>
            <div style="font-size: 14px; color: var(--text-muted); margin-bottom: 6px;">{{ health.reason }}</div>
            <div style="font-size: 15px;">
                <span style="color: var(--text-dim);">URL de acesso atual:</span>
                <a href="{{ app.current_access_url }}" target="_blank" style="color: var(--primary); font-weight: 700; font-family: monospace; text-decoration: none; margin-left: 6px;">
                    {{ app.current_access_url }}
                </a>
            </div>
        </div>
        <div style="display: flex; gap: 12px;">
            <button class="btn btn-secondary" onclick="restartApp({{ app.id }})">🔄 REINICIAR APLICAÇÃO</button>
            <button class="btn btn-secondary" onclick="loadLiveLogs({{ app.id }})">📜 LOGS AO VIVO</button>
        </div>
    </div>

    <!-- Navigation Tabs Bar (8 Organized Tabs) -->
    <div style="display: flex; gap: 8px; border-top: 1px solid var(--border-color); padding-top: 16px; flex-wrap: wrap;">
        <button class="tab-btn active" onclick="switchTab(event, 'tab-overview')">📊 Visão Geral & Saúde</button>
        <button class="tab-btn" onclick="switchTab(event, 'tab-deploys')">🚀 Deploys & Releases ({{ app.deployments|length }})</button>
        <button class="tab-btn" onclick="switchTab(event, 'tab-files')" onclick="loadRemoteFiles({{ app.id }}, '')">📁 Arquivos & Versões</button>
        <button class="tab-btn" onclick="switchTab(event, 'tab-backups')">💾 Backups & Snapshots</button>
        <button class="tab-btn" onclick="switchTab(event, 'tab-logs')">📜 Logs Ao Vivo</button>
        <button class="tab-btn" onclick="switchTab(event, 'tab-execution')">⚙ Configuração</button>
        <button class="tab-btn" onclick="switchTab(event, 'tab-database')">🗄 Banco de Dados ({% if app.database %}Conectado{% else %}Ausente{% endif %})</button>
        <button class="tab-btn" onclick="switchTab(event, 'tab-danger')" style="color: #f87171;">🚨 Zona de Perigo</button>
    </div>
</div>

<!-- TAB 1: VISÃO GERAL & SAÚDE -->
<div id="tab-overview" class="tab-content active">
    <!-- Real-Time App Health Monitor Block (Separate Local vs Public Latency) -->
    <div style="background: rgba(30, 41, 59, 0.6); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px; margin-bottom: 24px;">
        <h2 style="font-size: 18px; font-weight: 700; color: #fff; margin-bottom: 16px;">MATRIZ DE SAÚDE EM TEMPO REAL DA APLICAÇÃO</h2>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 16px;">
            <div style="background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); border-radius: 10px; padding: 14px;">
                <div style="font-size: 11px; color: var(--text-dim); text-transform: uppercase;">Serviço Systemd</div>
                <div style="font-weight: 800; font-size: 16px; color: {% if health.systemd_active %}#4ade80{% else %}#f87171{% endif %};">
                    {% if health.systemd_active %}🟢 Ativo{% else %}🔴 Inativo{% endif %}
                </div>
                <div style="font-size: 11px; color: var(--text-muted); margin-top: 4px;">{{ health.service_name }}</div>
            </div>

            <div style="background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); border-radius: 10px; padding: 14px;">
                <div style="font-size: 11px; color: var(--text-dim); text-transform: uppercase;">Porta de Escuta</div>
                <div style="font-weight: 800; font-size: 16px; color: {% if health.port_listening %}#4ade80{% else %}#f87171{% endif %};">
                    {% if health.port_listening %}🟢 Escutando{% else %}🔴 Fechada{% endif %}
                </div>
                <div style="font-size: 11px; color: var(--text-muted); margin-top: 4px;">0.0.0.0:{{ health.port }}</div>
            </div>

            <div style="background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); border-radius: 10px; padding: 14px;">
                <div style="font-size: 11px; color: var(--text-dim); text-transform: uppercase;">HTTP Local (127.0.0.1)</div>
                <div style="font-weight: 800; font-size: 16px; color: {% if health.local_code in (200, 301, 302, 304) %}#4ade80{% else %}#f59e0b{% endif %};">
                    HTTP {{ health.local_code }}
                </div>
                <div style="font-size: 11px; color: #60a5fa; margin-top: 4px;">Latência: {{ health.local_ms }} ms</div>
            </div>

            <div style="background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); border-radius: 10px; padding: 14px;">
                <div style="font-size: 11px; color: var(--text-dim); text-transform: uppercase;">HTTP Público (IP)</div>
                <div style="font-weight: 800; font-size: 16px; color: {% if health.public_code in (200, 301, 302, 304) %}#4ade80{% else %}#f87171{% endif %};">
                    {% if health.public_code > 0 %}HTTP {{ health.public_code }}{% else %}🔴 Timeout / Bloqueado{% endif %}
                </div>
                <div style="font-size: 11px; color: #60a5fa; margin-top: 4px;">Latência: {{ health.public_ms }} ms</div>
            </div>
        </div>
    </div>

    <!-- Detailed System & Network Attributes -->
    <div style="background: rgba(17, 24, 39, 0.6); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px;">
        <h2 style="font-size: 18px; font-weight: 700; color: #fff; margin-bottom: 16px;">ATRIBUTOS DE REDE & VPS</h2>
        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px;">
            <div>
                <span style="font-size: 12px; color: var(--text-dim); text-transform: uppercase;">Servidor VPS</span>
                <div style="font-weight: 600; color: #fff;">{{ app.server.name }} ({{ app.server.ip }})</div>
            </div>
            <div>
                <span style="font-size: 12px; color: var(--text-dim); text-transform: uppercase;">Domínio Ativo</span>
                <div style="font-weight: 600; color: {% if app.active_domain %}#4ade80{% else %}var(--text-dim){% endif %};">
                    {{ app.active_domain or 'Nenhum' }}
                </div>
            </div>
            <div>
                <span style="font-size: 12px; color: var(--text-dim); text-transform: uppercase;">Portas (Ext ➔ Int)</span>
                <div style="font-weight: 600; color: #60a5fa; font-family: monospace;">:{{ app.external_port or app.internal_port }} ➔ :{{ app.internal_port }}</div>
            </div>
            <div>
                <span style="font-size: 12px; color: var(--text-dim); text-transform: uppercase;">Diretório do App</span>
                <div style="font-weight: 600; color: #fff; font-family: monospace;">{{ app.path }}</div>
            </div>
        </div>
    </div>
</div>

<!-- TAB 2: DEPLOYS & RELEASES -->
<div id="tab-deploys" class="tab-content">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
        <h2 style="font-size: 20px; font-weight: 700;">Histórico de Releases & Artefatos Imutáveis</h2>
        <button class="btn btn-primary" onclick="openModal('modal-upload-deploy')">+ NOVO DEPLOY</button>
    </div>
    
    <div class="app-table-card">
        <table class="table">
            <thead>
                <tr>
                    <th>Release</th>
                    <th>Versão & Hash SHA-256</th>
                    <th>Data do Deploy</th>
                    <th>Status</th>
                    <th style="text-align: right;">Ações Coerentes</th>
                </tr>
            </thead>
            <tbody>
                {% for dep in app.deployments %}
                <tr>
                    <td>
                        <strong style="color: #60a5fa; font-size: 15px;">Release #{{ dep.release_number or loop.revindex }}</strong>
                        {% if dep.is_active == 1 or (loop.first and dep.status == 'success' and not app.deployments|selectattr('is_active', 'equalto', 1)|list) %}
                            <span style="background: rgba(16, 185, 129, 0.2); color: var(--success); font-size: 10px; font-weight: 700; padding: 2px 6px; border-radius: 4px; margin-left: 6px;">ATUAL</span>
                        {% endif %}
                    </td>
                    <td>
                        <div style="font-weight: 700; color: #fff;">{{ dep.version }}</div>
                        {% if dep.sha256_hash %}
                            <div style="font-size: 11px; color: #93c5fd; font-family: monospace;" title="Hash SHA-256 do ZIP enviado">SHA-256: <code>{{ dep.sha256_hash[:12] }}...</code></div>
                        {% endif %}
                        <div style="font-size: 12px; color: var(--text-muted);">{{ dep.description or 'Sem descrição' }}</div>
                    </td>
                    <td style="font-size: 13px; color: var(--text-muted);">{{ dep.deployed_at }}</td>
                    <td>
                        {% if dep.status == 'success' %}
                            <span class="badge badge-online">Sucesso ({{ dep.duration_seconds }}s)</span>
                        {% else %}
                            <span class="badge badge-offline">Falhou</span>
                        {% endif %}
                    </td>
                    <td style="text-align: right;">
                        <div style="display: flex; gap: 6px; justify-content: flex-end;">
                            {% if dep.diagnostic %}
                                <button class="btn btn-secondary" style="padding: 4px 8px; font-size: 11px;" onclick="showDiagnosticModal({{ dep.id }})">DIAGNÓSTICO</button>
                            {% endif %}
                            {% if dep.stored_zip_path %}
                                <a href="{{ url_for('download_release_zip', app_id=app.id, deployment_id=dep.id) }}" class="btn btn-secondary" style="padding: 4px 8px; font-size: 11px;" title="Baixar artefato ZIP original enviado">BAIXAR ZIP</a>
                            {% endif %}
                            {% if dep.status == 'success' and not (dep.is_active == 1) %}
                                <button class="btn btn-secondary" style="padding: 4px 8px; font-size: 11px;" onclick="executeRollback({{ app.id }}, {{ dep.id }}, 'Release #{{ dep.release_number }} ({{ dep.version }})')">RESTAURAR</button>
                            {% elif dep.status == 'failed' %}
                                <button class="btn btn-primary" style="padding: 4px 8px; font-size: 11px;" onclick="openModal('modal-upload-deploy')">TENTAR NOVAMENTE</button>
                            {% endif %}
                        </div>
                    </td>
                </tr>
                {% else %}
                <tr>
                    <td colspan="5" style="text-align: center; color: var(--text-muted); padding: 30px;">
                        Nenhuma release registrada ainda. Envie um arquivo ZIP para realizar o primeiro deploy automatizado!
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>

<!-- TAB 3: ARQUIVOS & VERSÕES (Navegador de Arquivos Remoto) -->
<div id="tab-files" class="tab-content">
    <div style="background: rgba(30, 41, 59, 0.6); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
            <div>
                <h2 style="font-size: 20px; font-weight: 700; color: #fff;">GERENCIADOR DE ARQUIVOS DO SERVIDOR</h2>
                <div style="font-size: 12px; color: var(--text-muted);">Diretório no VPS: <code id="file-current-path">{{ app.path }}</code></div>
            </div>
            <div style="display: flex; gap: 10px;">
                <button class="btn btn-secondary" style="font-size: 12px;" onclick="createLiveSnapshot({{ app.id }})">📸 CRIAR SNAPSHOT ATUAL</button>
                <button class="btn btn-primary" style="font-size: 12px;" onclick="loadRemoteFiles({{ app.id }}, '')">🔄 RECARREGAR ARQUIVOS</button>
            </div>
        </div>

        <div class="app-table-card">
            <table class="table">
                <thead>
                    <tr>
                        <th>Nome do Item</th>
                        <th>Tamanho</th>
                        <th>Modificado em</th>
                        <th>Permissão</th>
                        <th style="text-align: right;">Ações</th>
                    </tr>
                </thead>
                <tbody id="files-table-body">
                    <tr>
                        <td colspan="5" style="text-align: center; color: var(--text-muted); padding: 20px;">
                            Carregando arquivos do VPS via SSH...
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- TAB 4: BACKUPS & SNAPSHOTS -->
<div id="tab-backups" class="tab-content">
    <div style="background: rgba(30, 41, 59, 0.6); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px; margin-bottom: 24px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
            <div>
                <h2 style="font-size: 20px; font-weight: 700; color: #fff;">SNAPSHOTS E PORTABILIDADE COMPLETA</h2>
                <div style="font-size: 12px; color: var(--text-muted);">Gere snapshots do estado atual de produção ou exporte o projeto inteiro com 1 clique.</div>
            </div>
            <div style="display: flex; gap: 12px;">
                <button class="btn btn-success" onclick="createLiveSnapshot({{ app.id }})">📸 CRIAR SNAPSHOT AGORA</button>
                <a href="{{ url_for('export_full_route', app_id=app.id) }}" class="btn btn-primary">📦 EXPORTAR APLICAÇÃO COMPLETA</a>
            </div>
        </div>

        <div class="app-table-card">
            <table class="table">
                <thead>
                    <tr>
                        <th>Nome do Snapshot / Dump</th>
                        <th>Tipo</th>
                        <th>Tamanho</th>
                        <th>Data de Criação</th>
                        <th style="text-align: right;">Status</th>
                    </tr>
                </thead>
                <tbody>
                    {% for b in app.backups %}
                    <tr>
                        <td><strong style="color: #fff; font-family: monospace;">{{ b.file_name }}</strong></td>
                        <td><span class="badge" style="background: rgba(59,130,246,0.15); color: #60a5fa;">{{ b.backup_type|upper }}</span></td>
                        <td>{{ b.file_size_mb }} MB</td>
                        <td style="color: var(--text-muted);">{{ b.created_at }}</td>
                        <td style="text-align: right;"><span class="badge badge-online">Salvo</span></td>
                    </tr>
                    {% else %}
                    <tr>
                        <td colspan="5" style="text-align: center; color: var(--text-muted); padding: 30px;">
                            Nenhum snapshot ou dump gerado recentemente.
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- TAB 5: LOGS AO VIVO -->
<div id="tab-logs" class="tab-content">
    <div style="background: rgba(30, 41, 59, 0.6); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px;">
            <h2 style="font-size: 20px; font-weight: 700; color: #fff;">LOGS DO SERVIÇO SYSTEMD (journalctl -u {{ health.service_name }})</h2>
            <button class="btn btn-secondary" onclick="loadLiveLogs({{ app.id }})">ATUALIZAR LOGS</button>
        </div>
        
        <div id="live-logs-terminal" class="terminal-window" style="height: 400px; overflow-y: auto;">
            <div class="terminal-line">Clique em "LOGS AO VIVO" para carregar as últimas 100 linhas via SSH...</div>
        </div>
    </div>
</div>

<!-- TAB 6: CONFIGURAÇÃO DE EXECUÇÃO -->
<div id="tab-execution" class="tab-content">
    <div style="background: rgba(30, 41, 59, 0.6); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
            <h2 style="font-size: 20px; font-weight: 700; color: #fff;">CONFIGURAÇÃO DE EXECUÇÃO & ENTRYPOINT</h2>
            <button class="btn btn-primary" onclick="openModal('modal-edit-entrypoint')">⚙ CONFIGURAÇÃO DE EXECUÇÃO</button>
        </div>

        <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 20px;">
            <div style="background: rgba(0,0,0,0.3); padding: 16px; border-radius: 10px; border: 1px solid var(--border-color);">
                <div style="font-size: 12px; color: var(--text-dim); text-transform: uppercase;">Arquivo Entrypoint</div>
                <div style="font-weight: 700; font-size: 16px; color: #60a5fa; font-family: monospace;">{{ app.entrypoint_file or 'app.py' }}</div>
            </div>
            <div style="background: rgba(0,0,0,0.3); padding: 16px; border-radius: 10px; border: 1px solid var(--border-color);">
                <div style="font-size: 12px; color: var(--text-dim); text-transform: uppercase;">Objeto WSGI</div>
                <div style="font-weight: 700; font-size: 16px; color: #4ade80; font-family: monospace;">{{ app.entrypoint_object or 'app' }}</div>
            </div>
            <div style="background: rgba(0,0,0,0.3); padding: 16px; border-radius: 10px; border: 1px solid var(--border-color);">
                <div style="font-size: 12px; color: var(--text-dim); text-transform: uppercase;">Workers / Timeout</div>
                <div style="font-weight: 700; font-size: 16px; color: #fff;">3 Workers | 600s Timeout</div>
            </div>
            <div style="background: rgba(0,0,0,0.3); padding: 16px; border-radius: 10px; border: 1px solid var(--border-color);">
                <div style="font-size: 12px; color: var(--text-dim); text-transform: uppercase;">Usuário do Serviço</div>
                <div style="font-weight: 700; font-size: 16px; color: #fff;">root (Linux VPS)</div>
            </div>
        </div>

        <div style="margin-top: 20px;">
            <div style="font-size: 12px; color: var(--text-dim); text-transform: uppercase; margin-bottom: 6px;">Comando Completo de Inicialização Systemd</div>
            <code style="display: block; background: rgba(0,0,0,0.5); padding: 14px; border-radius: 8px; color: #93c5fd; font-family: monospace; font-size: 14px; border: 1px solid var(--border-color);">
                {{ app.path }}/venv/bin/gunicorn --bind 0.0.0.0:{{ app.internal_port }} --workers 3 --timeout 600 {{ (app.entrypoint_file or 'app.py').split('.')[0] }}:{{ app.entrypoint_object or 'app' }}
            </code>
        </div>
    </div>
</div>

<!-- TAB 7: BANCO DE DADOS -->
<div id="tab-database" class="tab-content">
    {% if app.database %}
        <div style="background: rgba(30, 41, 59, 0.6); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                <div>
                    <h2 style="font-size: 22px; font-weight: 700; color: #fff;">{{ app.database.name }}</h2>
                    <div style="font-size: 13px; color: var(--text-muted); text-transform: uppercase;">Tipo: {{ app.database.db_type }}</div>
                </div>
                <button class="btn btn-success" onclick="triggerDbBackup({{ app.id }})">FAZER BACKUP AGORA</button>
            </div>

            <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 16px; margin-bottom: 24px;">
                <div>Host: <strong>{{ app.database.host }}:{{ app.database.port }}</strong></div>
                <div>Tamanho: <strong>{{ app.database.size_mb }} MB</strong></div>
                <div>Último Backup: <strong>{{ app.database.last_backup_at or 'Pendente' }}</strong></div>
            </div>

            <h3 style="font-size: 16px; font-weight: 700; color: #fff; margin-bottom: 12px;">Histórico de Dumps do Banco</h3>
            <div style="display: flex; flex-direction: column; gap: 8px;">
                {% for b in app.backups %}
                <div style="background: rgba(0,0,0,0.3); padding: 12px; border-radius: 8px; font-size: 13px; display: flex; justify-content: space-between; align-items: center;">
                    <div style="font-family: monospace; color: #fff;">{{ b.file_name }}</div>
                    <div style="color: var(--primary); font-weight: 700;">{{ b.file_size_mb }} MB</div>
                </div>
                {% else %}
                <div style="color: var(--text-muted);">Nenhum dump de banco salvo recentemente.</div>
                {% endfor %}
            </div>
        </div>
    {% else %}
        <div style="background: rgba(30, 41, 59, 0.6); border: 1px solid var(--border-color); border-radius: 16px; padding: 32px; text-align: center;">
            <div style="font-size: 32px; margin-bottom: 12px;">🗄</div>
            <h2 style="font-size: 20px; font-weight: 700; color: #fff; margin-bottom: 8px;">Nenhum Banco de Dados Associado a Esta Aplicação</h2>
            <p style="font-size: 13px; color: var(--text-muted); max-width: 500px; margin: 0 auto 24px;">O DeployHub pode verificar os arquivos do seu projeto (.env, requirements.txt, config.py) para identificar a presença de PostgreSQL ou MySQL automaticamente.</p>
            
            <div style="display: flex; justify-content: center; gap: 16px;">
                <button class="btn btn-primary" onclick="triggerAutoDetectDb({{ app.id }})">🔍 DETECTAR AUTOMATICAMENTE</button>
            </div>
        </div>
    {% endif %}
</div>

<!-- TAB 8: ZONA DE PERIGO -->
<div id="tab-danger" class="tab-content">
    <div style="background: rgba(239, 68, 68, 0.08); border: 1px solid rgba(239, 68, 68, 0.3); border-radius: 16px; padding: 24px;">
        <h2 style="font-size: 22px; font-weight: 700; color: #f87171; margin-bottom: 12px;">ZONA DE PERIGO: Excluir / Desinstalar Aplicação</h2>
        <p style="font-size: 13px; color: var(--text-muted); margin-bottom: 20px;">Esta ação remove a aplicação do painel e pode desinstalar completamente o serviço do VPS.</p>

        <!-- Impact Summary Card -->
        <div style="background: rgba(0,0,0,0.3); border: 1px solid rgba(239, 68, 68, 0.3); border-radius: 12px; padding: 16px; margin-bottom: 24px;">
            <div style="font-size: 12px; color: #f87171; text-transform: uppercase; font-weight: 700; margin-bottom: 8px;">Impacto Estimado da Exclusão</div>
            <div style="font-size: 14px; color: #fff;">Esta aplicação possui:</div>
            <ul style="margin: 8px 0 0 20px; font-size: 13px; color: var(--text-muted);">
                <li><strong style="color: #fff;">{{ impact.release_count }} releases</strong> registradas ({{ impact.valid_release_count }} releases válidas de sucesso)</li>
                <li><strong style="color: #60a5fa;">{{ impact.artifact_storage_mb }} MB</strong> de artefatos ZIP armazenados</li>
                <li><strong style="color: #4ade80;">{{ impact.db_backup_count }} backups</strong> de banco de dados</li>
            </ul>
        </div>

        <form action="{{ url_for('delete_app_route', app_id=app.id) }}" method="POST">
            <div style="display: flex; flex-direction: column; gap: 14px; margin-bottom: 24px;">
                <label style="background: rgba(255,255,255,0.03); border: 1px solid var(--border-color); padding: 14px; border-radius: 10px; cursor: pointer; display: flex; gap: 12px; align-items: flex-start;">
                    <input type="radio" name="delete_mode" value="remove_db_only" checked style="margin-top: 4px;">
                    <div>
                        <strong style="color: #fff; font-size: 15px;">1. Somente remover do DeployHub</strong>
                        <div style="font-size: 12px; color: var(--text-dim); margin-top: 2px;">O sistema continua funcionando normalmente no VPS. Apenas remove o cadastro deste painel.</div>
                    </div>
                </label>

                <label style="background: rgba(239, 68, 68, 0.08); border: 1px solid rgba(239, 68, 68, 0.3); padding: 14px; border-radius: 10px; cursor: pointer; display: flex; gap: 12px; align-items: flex-start;">
                    <input type="radio" name="delete_mode" value="uninstall_vps" style="margin-top: 4px;">
                    <div>
                        <strong style="color: #f87171; font-size: 15px;">2. Desinstalar aplicação do VPS</strong>
                        <div style="font-size: 12px; color: var(--text-dim); margin-top: 2px;">Para o serviço Systemd, remove a unidade, apaga a pasta <code>{{ app.path }}</code> e libera a porta <code>:{{ app.internal_port }}</code> no VPS.</div>
                    </div>
                </label>

                <label style="background: rgba(239, 68, 68, 0.15); border: 1px solid #ef4444; padding: 14px; border-radius: 10px; cursor: pointer; display: flex; gap: 12px; align-items: flex-start;">
                    <input type="radio" name="delete_mode" value="uninstall_vps_and_backups" style="margin-top: 4px;">
                    <div>
                        <strong style="color: #f87171; font-size: 15px;">3. Desinstalar tudo + Remover backups e ZIPs</strong>
                        <div style="font-size: 12px; color: var(--text-dim); margin-top: 2px;">Desinstala do VPS e apaga permanentemente todos os backups e arquivos ZIP armazenados.</div>
                    </div>
                </label>
            </div>

            <div style="display: flex; justify-content: flex-end;">
                <button type="submit" class="btn btn-primary" style="background: #dc2626; border-color: #dc2626;">CONFIRMAR EXCLUSÃO DA APLICAÇÃO</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal View Remote File Content -->
<div class="modal-overlay" id="modal-view-file">
    <div class="modal-card" style="max-width: 750px;">
        <h2 style="font-size: 20px; font-weight: 700; margin-bottom: 8px;" id="view-file-title">Visualizar Arquivo</h2>
        <div style="font-size: 12px; color: var(--text-dim); margin-bottom: 16px;" id="view-file-path">/path</div>
        
        <div class="terminal-window" style="height: 400px; overflow-y: auto;">
            <pre style="font-family: monospace; font-size: 12px; color: #93c5fd; white-space: pre-wrap;" id="view-file-content">Carregando conteúdo...</pre>
        </div>

        <div style="display: flex; justify-content: flex-end; margin-top: 20px;">
            <button class="btn btn-secondary" onclick="closeModal('modal-view-file')">Fechar</button>
        </div>
    </div>
</div>

<!-- Modal Edit Entrypoint -->
<div class="modal-overlay" id="modal-edit-entrypoint">
    <div class="modal-card">
        <h2 style="font-size: 22px; font-weight: 700; margin-bottom: 16px;">Configuração de Execução</h2>
        <form action="{{ url_for('update_entrypoint_route', app_id=app.id) }}" method="POST">
            <div class="form-group">
                <label class="form-label">Arquivo de Entrada (Entrypoint Script)</label>
                <input type="text" name="entrypoint_file" class="form-control" value="{{ app.entrypoint_file or 'app.py' }}" placeholder="ex: app.py, main.py, run.py" required>
            </div>
            <div class="form-group">
                <label class="form-label">Objeto da Aplicação (WSGI Variable)</label>
                <input type="text" name="entrypoint_object" class="form-control" value="{{ app.entrypoint_object or 'app' }}" placeholder="ex: app, application" required>
            </div>
            <div style="display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px;">
                <button type="button" class="btn btn-secondary" onclick="closeModal('modal-edit-entrypoint')">Cancelar</button>
                <button type="submit" class="btn btn-primary">Salvar Configurações</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal Deploy ZIP -->
<div class="modal-overlay" id="modal-upload-deploy">
    <div class="modal-card">
        <h2 style="font-size: 22px; font-weight: 700; margin-bottom: 20px;">Publicar Nova Release (Deploy ZIP Real)</h2>
        <form onsubmit="handleDeploySubmit(event, {{ app.id }})">
            <div class="form-group">
                <label class="form-label">Arquivo ZIP da Aplicação</label>
                <input type="file" name="zip_file" accept=".zip" class="form-control" required>
            </div>
            <div class="form-group">
                <label class="form-label">Identificador da Versão</label>
                <input type="text" name="version" class="form-control" value="v1.0" required>
            </div>
            <div class="form-group">
                <label class="form-label">Descrição das Alterações</label>
                <input type="text" name="description" class="form-control" placeholder="ex: Atualização de funcionalidades" required>
            </div>
            <div style="display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px;">
                <button type="button" class="btn btn-secondary" onclick="closeModal('modal-upload-deploy')">Cancelar</button>
                <button type="submit" class="btn btn-primary">FAZER DEPLOY AGORA</button>
            </div>
        </form>
    </div>
</div>

<!-- Modal Deploy Progress Terminal with Live Chronometer & Progress Bar -->
<div class="modal-overlay" id="modal-deploy-progress">
    <div class="modal-card" style="max-width: 720px;">
        <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 14px;">
            <h2 style="font-size: 22px; font-weight: 700; color: #fff;">Progresso do Deploy Automático</h2>
            <div style="background: rgba(59, 130, 246, 0.15); border: 1px solid rgba(59, 130, 246, 0.4); padding: 6px 14px; border-radius: 8px; font-family: monospace; font-size: 14px; color: #60a5fa; font-weight: 700; display: flex; align-items: center; gap: 8px;">
                <span>⏱️ TEMPO DECORRIDO:</span>
                <span id="deploy-chronometer" style="color: #fff; font-size: 16px;">00:00s</span>
            </div>
        </div>

        <!-- Animated Progress Bar & Percentage Banner -->
        <div style="margin-bottom: 18px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 6px; font-size: 13px;">
                <span id="deploy-status-text" style="font-weight: 700; color: #93c5fd;">Passo 1/11: Enviando e Inspecionando Projeto...</span>
                <span id="deploy-pct-text" style="font-weight: 800; color: #4ade80; font-family: monospace;">0%</span>
            </div>
            <div style="background: rgba(0,0,0,0.4); border: 1px solid var(--border-color); height: 12px; border-radius: 6px; overflow: hidden; position: relative;">
                <div id="deploy-progress-bar" style="background: linear-gradient(90deg, #3b82f6, #10b981); height: 100%; width: 0%; transition: width 0.4s ease; border-radius: 6px;"></div>
            </div>
        </div>
        
        <div id="deploy-terminal" class="terminal-window" style="height: 320px; overflow-y: auto;">
            <div class="terminal-line">Aguardando logs...</div>
        </div>

        <div style="display: flex; justify-content: flex-end; margin-top: 20px;">
            <button class="btn btn-secondary" onclick="closeModal('modal-deploy-progress')">Fechar</button>
        </div>
    </div>
</div>

<!-- Modal Diagnostic Checklist -->
<div class="modal-overlay" id="modal-diagnostic">
    <div class="modal-card" style="max-width: 650px;">
        <h2 style="font-size: 20px; font-weight: 700; margin-bottom: 16px;">Diagnóstico de Verificação da Release</h2>
        <div id="diagnostic-modal-content">
            <div style="color: var(--text-dim);">Carregando relatório de verificação...</div>
        </div>
        <div style="display: flex; justify-content: flex-end; margin-top: 20px;">
            <button class="btn btn-secondary" onclick="closeModal('modal-diagnostic')">Fechar</button>
        </div>
    </div>
</div>

<style>
.tab-btn {
    background: transparent;
    border: none;
    color: var(--text-muted);
    font-size: 13px;
    font-weight: 600;
    padding: 8px 16px;
    border-radius: 8px;
    cursor: pointer;
    transition: all 0.2s ease;
}
.tab-btn:hover {
    color: #fff;
    background: rgba(255,255,255,0.05);
}
.tab-btn.active {
    color: #fff;
    background: var(--primary);
}
.tab-content {
    display: none;
}
.tab-content.active {
    display: block;
}
</style>

<script>
function switchTab(evt, tabId) {
    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
    document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));
    evt.currentTarget.classList.add('active');
    document.getElementById(tabId).classList.add('active');
}

async function loadRemoteFiles(appId, subpath) {
    const tbody = document.getElementById('files-table-body');
    if (tbody) tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 20px;">Carregando arquivos do VPS...</td></tr>';

    try {
        const res = await fetch(`/app/${appId}/api/files?subpath=${encodeURIComponent(subpath)}`);
        const data = await res.json();
        
        document.getElementById('file-current-path').innerText = data.current_dir;

        if (data.items && data.items.length > 0) {
            tbody.innerHTML = data.items.map(item => `
                <tr>
                    <td>
                        <strong style="color: ${item.is_dir ? '#60a5fa' : '#fff'};">
                            ${item.is_dir ? '📁 ' : '📄 '} ${item.name}
                        </strong>
                    </td>
                    <td>${item.is_dir ? '-' : item.size_mb + ' MB'}</td>
                    <td style="color: var(--text-muted);">${item.mtime}</td>
                    <td><code style="color: #93c5fd;">${item.mode}</code></td>
                    <td style="text-align: right;">
                        ${item.is_dir ? `
                            <button class="btn btn-secondary" style="padding: 4px 8px; font-size: 11px;" onclick="loadRemoteFiles(${appId}, '${item.rel_path}')">ABRIR PASTA</button>
                        ` : `
                            <button class="btn btn-secondary" style="padding: 4px 8px; font-size: 11px;" onclick="viewFileContent(${appId}, '${item.rel_path}')">VER CONTEÚDO</button>
                        `}
                    </td>
                </tr>
            `).join('');
        } else {
            tbody.innerHTML = '<tr><td colspan="5" style="text-align: center; color: var(--text-muted); padding: 20px;">Diretório vazio.</td></tr>';
        }
    } catch (e) {
        if (tbody) tbody.innerHTML = `<tr><td colspan="5" style="text-align: center; color: #f87171; padding: 20px;">Erro ao carregar arquivos: ${e.message}</td></tr>`;
    }
}

async function viewFileContent(appId, relPath) {
    document.getElementById('view-file-title').innerText = relPath.split('/').pop();
    document.getElementById('view-file-path').innerText = relPath;
    document.getElementById('view-file-content').innerText = 'Carregando conteúdo do arquivo...';
    openModal('modal-view-file');

    try {
        const res = await fetch(`/app/${appId}/api/file/view?rel_path=${encodeURIComponent(relPath)}`);
        const data = await res.json();
        document.getElementById('view-file-content').innerText = data.content || 'Arquivo vazio.';
    } catch (e) {
        document.getElementById('view-file-content').innerText = `Erro ao carregar conteúdo: ${e.message}`;
    }
}

async function createLiveSnapshot(appId) {
    alert('Gerando snapshot do estado atual do VPS em segundo plano...');
    try {
        const res = await fetch(`/app/${appId}/snapshot/create`, { method: 'POST' });
        const data = await res.json();
        if (data.status === 'success') {
            alert(`Snapshot gerado com sucesso! Arquivo: ${data.snapshot.file_name} (${data.snapshot.size_mb} MB)`);
            window.location.reload();
        } else {
            alert(`Falha ao gerar snapshot: ${data.error}`);
        }
    } catch (e) {
        alert(`Erro de comunicação: ${e.message}`);
    }
}

async function restartApp(appId) {
    try {
        const res = await fetch(`/app/${appId}/restart`, { method: 'POST' });
        const data = await res.json();
        if (data.status === 'success') {
            alert('Serviço da aplicação reiniciado com sucesso no VPS!');
            window.location.reload();
        } else {
            alert(`Falha ao reiniciar: ${data.error}`);
        }
    } catch (e) {
        alert(`Erro de comunicação: ${e.message}`);
    }
}

async function loadLiveLogs(appId) {
    const term = document.getElementById('live-logs-terminal');
    if (term) term.innerHTML = '<div class="terminal-line">[INFO] Lendo últimas 100 linhas de logs do journalctl via SSH...</div>';
    switchTab({ currentTarget: document.querySelectorAll('.tab-btn')[4] }, 'tab-logs');

    try {
        const res = await fetch(`/app/${appId}/live-logs`);
        const data = await res.json();
        if (term && data.logs) {
            term.innerHTML = `<pre style="font-family: monospace; font-size: 12px; color: #93c5fd; white-space: pre-wrap;">${data.logs}</pre>`;
        }
    } catch (e) {
        if (term) term.innerHTML = `<div class="terminal-line text-danger">[ERROR] Falha ao ler logs: ${e.message}</div>`;
    }
}

async function triggerAutoDetectDb(appId) {
    try {
        const res = await fetch(`/app/${appId}/detect-db`, { method: 'POST' });
        const data = await res.json();
        if (data.status === 'success') {
            window.location.reload();
        } else {
            alert('Nenhum banco de dados configurado encontrado nos arquivos do VPS.');
        }
    } catch (e) {
        alert(`Erro na busca: ${e.message}`);
    }
}

const deploymentsData = {{ app.deployments|tojson|safe }};

function showDiagnosticModal(depId) {
    const dep = deploymentsData.find(d => d.id === depId);
    if (!dep || !dep.diagnostic) {
        alert('Diagnóstico detalhado indisponível para esta release.');
        return;
    }
    const diag = dep.diagnostic;
    const html = `
        <div style="background: rgba(0,0,0,0.4); border: 1px solid var(--border-color); border-radius: 12px; padding: 16px; font-family: monospace; font-size: 13px; display: flex; flex-direction: column; gap: 8px;">
            <div style="color: var(--primary); font-weight: 700;">VERIFICAÇÃO DA RELEASE #${dep.release_number || ''} (${dep.version})</div>
            <div style="font-size: 11px; color: var(--text-dim); word-break: break-all;">SHA-256 Completo: ${diag.sha256_hash || 'N/A'}</div>
            <hr style="border-color: var(--border-color); margin: 4px 0;">
            <div style="display: flex; justify-content: space-between;"><span>ZIP recebido:</span><strong style="color: #4ade80;">✅ ${diag.zip_size_mb || '0'} MB</strong></div>
            <div style="display: flex; justify-content: space-between;"><span>Arquivos extraídos:</span><strong style="color: #4ade80;">✅ ${diag.file_count || 0} arquivos</strong></div>
            <div style="display: flex; justify-content: space-between;"><span>Raiz detectada:</span><strong style="color: #60a5fa;">${diag.root_dir}</strong></div>
            <div style="display: flex; justify-content: space-between;"><span>Framework:</span><strong style="color: #fff;">${diag.framework}</strong></div>
            <div style="display: flex; justify-content: space-between;"><span>Entrypoint AST:</span><strong style="color: #fbbf24;">✅ ${diag.entrypoint}</strong></div>
            <div style="display: flex; justify-content: space-between;"><span>Venv Linux Nativo:</span><strong style="color: #4ade80;">✅ ${diag.venv_status}</strong></div>
            <div style="display: flex; justify-content: space-between;"><span>Dependências:</span><strong style="color: #4ade80;">✅ ${diag.dependencies_status}</strong></div>
            <div style="display: flex; justify-content: space-between;"><span>Serviço Systemd:</span><strong style="color: #93c5fd;">${diag.service_name}</strong></div>
            <div style="display: flex; justify-content: space-between;"><span>Processo WSGI:</span><strong style="color: #4ade80;">✅ ${diag.process_status}</strong></div>
            <div style="display: flex; justify-content: space-between;"><span>Porta em Escuta:</span><strong style="color: #60a5fa;">✅ ${diag.port_status}</strong></div>
            <div style="display: flex; justify-content: space-between;"><span>Teste Local (127.0.0.1):</span><strong style="color: #4ade80;">✅ ${diag.local_http_status}</strong></div>
            <div style="display: flex; justify-content: space-between;"><span>Teste Público (IP):</span><strong style="color: #4ade80;">✅ ${diag.public_http_status}</strong></div>
        </div>
    `;
    document.getElementById('diagnostic-modal-content').innerHTML = html;
    openModal('modal-diagnostic');
}

// Auto-load remote files on page render
document.addEventListener('DOMContentLoaded', () => {
    loadRemoteFiles({{ app.id }}, '');
});
</script>
{% endblock %}
