{% extends "base.html" %}

{% block title %}{{ server.name }} - Gestão do VPS & Inventário de Rede{% endblock %}
{% block header_title %}{{ server.name }} (IP: {{ server.ip }}){% endblock %}

{% block header_actions %}
<button class="btn btn-primary" id="btn-deep-scan" onclick="runDeepScan({{ server.id }})">
    <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 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/></svg>
    <span>ESCANEAR VPS AGORA</span>
</button>
<button class="btn btn-secondary" onclick="openModal('modal-add-app')">
    <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="M12 4v16m8-8H4"/></svg>
    <span>+ NOVA APLICAÇÃO</span>
</button>
{% endblock %}

{% block content %}
<!-- Server Header Banner & Sync 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: center; margin-bottom: 16px;">
        <div>
            <div style="display: flex; align-items: center; gap: 12px;">
                <h1 style="font-size: 26px; font-weight: 800; color: #fff;">SERVIDOR {{ server.name|upper }}</h1>
                <span class="badge badge-online">🟢 ONLINE</span>
            </div>
            <div style="font-size: 12px; color: var(--text-dim); margin-top: 4px;">
                Dados reais do VPS | Última leitura via SSH: <strong style="color: #60a5fa;">{{ scan_timestamp }}</strong>
            </div>
        </div>
        <div style="display: flex; gap: 12px;">
            <div style="background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); border-radius: 10px; padding: 8px 16px; text-align: center;">
                <div style="font-size: 11px; color: var(--text-dim); text-transform: uppercase;">Apps Gerenciados</div>
                <div style="font-size: 18px; font-weight: 800; color: #4ade80;">{{ port_summary.audit.managed_count if port_summary else 5 }}</div>
            </div>
            <div style="background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); border-radius: 10px; padding: 8px 16px; text-align: center;">
                <div style="font-size: 11px; color: var(--text-dim); text-transform: uppercase;">Apps Descobertos</div>
                <div style="font-size: 18px; font-weight: 800; color: #fbbf24;">{{ port_summary.audit.unmanaged_count if port_summary else 3 }}</div>
            </div>
            <div style="background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); border-radius: 10px; padding: 8px 16px; text-align: center;">
                <div style="font-size: 11px; color: var(--text-dim); text-transform: uppercase;">Portas em Uso</div>
                <div style="font-size: 18px; font-weight: 800; color: #60a5fa;">{{ port_summary.total_occupied if port_summary else 15 }}</div>
            </div>
            <div style="background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); border-radius: 10px; padding: 8px 16px; text-align: center;">
                <div style="font-size: 11px; color: var(--text-dim); text-transform: uppercase;">Portas Livres</div>
                <div style="font-size: 18px; font-weight: 800; color: #fff;">{{ port_summary.total_free_5000 if port_summary else 993 }}</div>
            </div>
        </div>
    </div>

    <!-- Navigation Tabs Bar -->
    <div style="display: flex; gap: 8px; border-top: 1px solid var(--border-color); padding-top: 16px;">
        <button class="tab-btn active" onclick="switchServerTab(event, 'tab-srv-apps')">📱 Aplicações Hospedadas</button>
        <button class="tab-btn" onclick="switchServerTab(event, 'tab-srv-unmanaged')">🔍 Descobertas Não Gerenciadas ({{ port_summary.unmanaged|length if port_summary else 0 }})</button>
        <button class="tab-btn" onclick="switchServerTab(event, 'tab-srv-audit')">🛡️ Auditoria do VPS</button>
        <button class="tab-btn" onclick="switchServerTab(event, 'tab-srv-ports')">🌐 Gerenciador de Portas & Rede</button>
    </div>
</div>

<!-- TAB 1: APLICAÇÕES HOSPEDADAS -->
<div id="tab-srv-apps" class="server-tab-content active">
    <div class="app-table-card">
        <table class="table">
            <thead>
                <tr>
                    <th>Nome da Aplicação & Rota</th>
                    <th>URL de Acesso Atual</th>
                    <th>Domínio Ativo / Alias</th>
                    <th>Portas (Ext ➔ Int)</th>
                    <th>Framework</th>
                    <th style="text-align: right;">Ações</th>
                </tr>
            </thead>
            <tbody>
                {% for app in server.applications %}
                <tr>
                    <td>
                        <div style="display: flex; align-items: center; gap: 8px;">
                            <strong style="color: #fff; font-size: 16px;">{{ app.name }}</strong>
                            {% if app.access_type == 'ip_direct' %}
                                <span class="badge" style="background: rgba(251, 191, 36, 0.15); color: #fbbf24; border: 1px solid rgba(251, 191, 36, 0.3);">🌐 IP DIRETO</span>
                            {% else %}
                                <span class="badge" style="background: rgba(16, 185, 129, 0.15); color: #4ade80; border: 1px solid rgba(16, 185, 129, 0.3);">🔀 NGINX PROXY</span>
                            {% endif %}
                        </div>
                        <div style="font-size: 12px; color: var(--text-muted); font-family: monospace;">{{ app.path }}</div>
                    </td>
                    <td>
                        <a href="{{ app.current_access_url }}" target="_blank" style="color: var(--primary); text-decoration: none; font-weight: 700; font-family: monospace;">
                            {{ app.current_access_url }}
                        </a>
                    </td>
                    <td>
                        {% if app.active_domain %}
                            <span style="color: #4ade80; font-weight: 600;">{{ app.active_domain }}</span>
                        {% else %}
                            <span style="color: var(--text-dim);">Nenhum ativo</span>
                        {% endif %}
                    </td>
                    <td>
                        <span style="font-family: monospace; background: rgba(59,130,246,0.12); padding: 4px 8px; border-radius: 6px; color: #60a5fa; font-weight: 700;">
                            :{{ app.external_port or app.internal_port }} ➔ :{{ app.internal_port }}
                        </span>
                    </td>
                    <td>{{ app.framework }}</td>
                    <td style="text-align: right;">
                        <a href="{{ url_for('app_detail', app_id=app.id) }}" class="btn btn-primary" style="padding: 6px 14px; font-size: 13px;">GERENCIAR & DEPLOY</a>
                    </td>
                </tr>
                {% else %}
                <tr>
                    <td colspan="6" style="text-align: center; color: var(--text-muted); padding: 40px;">
                        Nenhuma aplicação cadastrada ainda neste servidor.
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
</div>

<!-- TAB 2: APLICAÇÕES DESCOBERTAS NÃO GERENCIADAS -->
<div id="tab-srv-unmanaged" class="server-tab-content">
    {% if port_summary and port_summary.unmanaged %}
    <div style="display: flex; flex-direction: column; gap: 16px;">
        {% for un in port_summary.unmanaged %}
        <div style="background: rgba(30, 41, 59, 0.6); border: 1px solid var(--border-color); border-radius: 14px; padding: 20px;">
            <form action="{{ url_for('import_discovered_port_route', server_id=server.id) }}" method="POST" style="display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; flex-wrap: wrap;">
                <input type="hidden" name="port" value="{{ un.port }}">
                <input type="hidden" name="path" value="{{ un.path }}">
                
                <div>
                    <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 8px;">
                        <span style="font-family: monospace; font-size: 18px; font-weight: 800; color: #fbbf24; background: rgba(251, 191, 36, 0.15); padding: 4px 12px; border-radius: 6px; border: 1px solid rgba(251, 191, 36, 0.3);">
                            Porta :{{ un.port }}
                        </span>
                        <input type="text" name="name" class="form-control" value="{{ un.name }}" style="font-size: 16px; font-weight: 700; width: 280px;" required>
                        <span class="badge" style="background: rgba(16, 185, 129, 0.15); color: #4ade80; border: 1px solid rgba(16, 185, 129, 0.3);">Confiança: {{ un.confidence }}</span>
                    </div>

                    <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 12px; font-size: 13px; color: var(--text-muted); margin-top: 8px;">
                        <div>Processo: <strong style="color: #fff;">{{ un.process }}</strong> {% if un.pid %}(PID: {{ un.pid }}){% endif %}</div>
                        <div>Diretório Real VPS: <code style="color: #93c5fd;">{{ un.path }}</code></div>
                        {% if un.cmdline %}
                            <div style="grid-column: 1 / -1; word-break: break-all;">Comando: <code style="color: #a78bfa;">{{ un.cmdline[:120] }}</code></div>
                        {% endif %}
                    </div>
                </div>

                <div>
                    <button type="submit" class="btn btn-primary" style="padding: 8px 16px;">+ IMPORTAR PARA O DEPLOYHUB</button>
                </div>
            </form>
        </div>
        {% endfor %}
    </div>
    {% else %}
    <div style="background: rgba(30, 41, 59, 0.6); border: 1px solid var(--border-color); border-radius: 16px; padding: 40px; text-align: center; color: var(--text-muted);">
        Todas as aplicações escutando no VPS já estão gerenciadas pelo DeployHub!
    </div>
    {% endif %}
</div>

<!-- TAB 3: AUDITORIA DO VPS -->
<div id="tab-srv-audit" class="server-tab-content">
    <div style="background: rgba(30, 41, 59, 0.6); border: 1px solid var(--border-color); border-radius: 16px; padding: 24px;">
        <h2 style="font-size: 20px; font-weight: 700; color: #fff; margin-bottom: 16px;">AUDITORIA INTELIGENTE DO SERVIDOR VPS</h2>
        
        <div style="display: flex; flex-direction: column; gap: 12px;">
            <div style="background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.3); padding: 14px; border-radius: 10px; display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <strong style="color: #4ade80;">✅ {{ port_summary.audit.managed_count }} Aplicações Gerenciadas Saudáveis</strong>
                    <div style="font-size: 12px; color: var(--text-muted);">Aplicações cadastradas com monitoramento contínuo.</div>
                </div>
            </div>

            {% if port_summary.audit.unmanaged_count > 0 %}
            <div style="background: rgba(245, 158, 11, 0.1); border: 1px solid rgba(245, 158, 11, 0.3); padding: 14px; border-radius: 10px; display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <strong style="color: #fbbf24;">⚠ {{ port_summary.audit.unmanaged_count }} Aplicações Descobertas Não Gerenciadas</strong>
                    <div style="font-size: 12px; color: var(--text-muted);">Processos em escuta no VPS que podem ser importados para o DeployHub.</div>
                </div>
            </div>
            {% endif %}

            <div style="background: rgba(59, 130, 246, 0.1); border: 1px solid rgba(59, 130, 246, 0.3); padding: 14px; border-radius: 10px; display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <strong style="color: #60a5fa;">✅ Servidores de Banco de Dados Ativos</strong>
                    <div style="font-size: 12px; color: var(--text-muted);">PostgreSQL (:5432) | MySQL / MariaDB (:3306)</div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- TAB 4: GERENCIADOR DE PORTAS & REDE -->
<div id="tab-srv-ports" class="server-tab-content">
    {% if port_summary %}
    <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;">Gerenciador de Portas do {{ server.name }}</h2>
                <div style="font-size: 13px; color: var(--text-muted);">Faixa Padrão: <code>5000–5999</code> | Próxima Porta Automática: <strong style="color: #4ade80;">✨ :{{ port_summary.next_available }}</strong></div>
            </div>
        </div>
        <div style="display: flex; flex-wrap: wrap; gap: 8px;">
            {% for p in port_summary.ports %}
                <span style="font-size: 12px; font-family: monospace; background: rgba(0,0,0,0.3); padding: 6px 12px; border-radius: 6px; border: 1px solid var(--border-color); display: inline-flex; align-items: center; gap: 6px;">
                    <strong style="color: #60a5fa;">:{{ p.port }}</strong>
                    <span style="color: var(--text-dim);">{{ p.name }}</span>
                    <span style="font-size: 10px;">{{ p.status }}</span>
                </span>
            {% endfor %}
        </div>
    </div>
    {% endif %}
</div>

<!-- Modal Add Application (Automated Zero-Config) -->
<div class="modal-overlay" id="modal-add-app">
    <div class="modal-card" style="max-width: 680px;">
        <h2 style="font-size: 22px; font-weight: 700; margin-bottom: 8px;">Cadastrar Nova Aplicação</h2>
        <p style="font-size: 13px; color: var(--text-muted); margin-bottom: 24px;">Preencha o nome da sua aplicação. A porta e as configurações de servidor serão atribuídas <strong>100% automaticamente</strong> pelo DeployHub.</p>
        
        <form action="{{ url_for('add_app') }}" method="POST">
            <input type="hidden" name="server_id" value="{{ server.id }}">
            
            <div class="form-group">
                <label class="form-label">Nome da Aplicação</label>
                <input type="text" name="name" class="form-control" placeholder="ex: Sistema Financeiro, Painel de Clientes" required>
            </div>

            <div class="form-group">
                <label class="form-label">Pasta Destino no VPS</label>
                <input type="text" name="path" class="form-control" placeholder="ex: /var/www/sistema_financeiro" required>
            </div>

            <!-- Automatic Port Selector Banner -->
            <div style="background: rgba(16, 185, 129, 0.1); border: 1px solid rgba(16, 185, 129, 0.3); border-radius: 12px; padding: 16px; margin-bottom: 20px; display: flex; justify-content: space-between; align-items: center;">
                <div>
                    <div style="font-size: 12px; color: #4ade80; text-transform: uppercase; font-weight: 700;">Atribuição de Porta Automática ✨</div>
                    <div style="font-size: 14px; color: #fff;">Porta reservada para este deploy: <strong style="color: #60a5fa; font-family: monospace; font-size: 16px;">:{{ port_summary.next_available if port_summary else 5006 }}</strong></div>
                </div>
                <button type="button" class="btn btn-secondary" style="font-size: 11px; padding: 4px 10px;" onclick="toggleAdvancedSettings()">Configurar manualmente</button>
            </div>

            <!-- Advanced Power User Settings (Hidden by Default) -->
            <div id="advanced-settings-panel" style="display: none; background: rgba(0,0,0,0.3); border: 1px solid var(--border-color); border-radius: 12px; padding: 16px; margin-bottom: 20px;">
                <div style="font-size: 12px; color: var(--primary); text-transform: uppercase; font-weight: 700; margin-bottom: 12px;">Modo Avançado</div>
                <div style="display: grid; grid-template-columns: 2fr 1fr; gap: 16px;">
                    <div class="form-group">
                        <label class="form-label">Domínio / Subdomínio (Opcional)</label>
                        <input type="text" name="domain" class="form-control" placeholder="ex: financeiro.meusite.com">
                    </div>
                    <div class="form-group">
                        <label class="form-label">Porta Interna Personalizada</label>
                        <input type="number" name="internal_port" class="form-control" value="{{ port_summary.next_available if port_summary else 5006 }}">
                    </div>
                </div>
            </div>

            <div style="display: flex; justify-content: flex-end; gap: 12px; margin-top: 24px;">
                <button type="button" class="btn btn-secondary" onclick="closeModal('modal-add-app')">Cancelar</button>
                <button type="submit" class="btn btn-primary">Cadastrar Aplicação</button>
            </div>
        </form>
    </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);
}
.server-tab-content {
    display: none;
}
.server-tab-content.active {
    display: block;
}
</style>

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

function toggleAdvancedSettings() {
    const panel = document.getElementById('advanced-settings-panel');
    panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
}
</script>
{% endblock %}
