<?php
// includes/footer.php — Rodapé padrão do sistema
// Compatível com PHP 8.3.31 + MySQL 8.0.45
?>
</main><!-- /main -->
</div><!-- /shell -->

<!-- Toast Container (melhorado) -->
<div class="toast-container" id="toastContainer"></div>

<!-- Modal container genérico -->
<div class="modal-overlay" id="modal-overlay" onclick="if(event.target===this)fecharModalGenerico()">
  <div class="modal" id="modal-content-wrap">
    <div class="modal-header">
      <div class="modal-title" id="modal-generico-titulo">Informação</div>
      <button class="modal-close" onclick="fecharModalGenerico()">✕</button>
    </div>
    <div class="modal-body" id="modal-inner"></div>
    <div class="modal-footer" id="modal-footer-generico" style="display:none;">
      <button class="btn btn-ghost btn-sm" onclick="fecharModalGenerico()">Cancelar</button>
      <button class="btn btn-primary btn-sm" id="modal-btn-confirmar">Confirmar</button>
    </div>
  </div>
</div>

<!-- Loading Overlay -->
<div class="loading-overlay" id="loadingOverlay" style="display: none;">
    <div class="loading-spinner"></div>
    <div class="loading-text">Processando...</div>
</div>

<!-- Script principal do sistema -->
<?php if (file_exists(__DIR__ . '/../assets/app.js')): ?>
<script src="assets/app.js?v=<?php echo APP_VERSION; ?>"></script>
<?php endif; ?>

<script>
// ══════════════════════════════════════════
//  SISTEMA DE TOAST GLOBAL
// ══════════════════════════════════════════
function showToast(message, type, duration) {
    type = type || 'info';
    duration = duration || 5000;
    
    var container = document.getElementById('toastContainer');
    if (!container) return;
    
    var toast = document.createElement('div');
    toast.className = 'toast toast-' + type;
    toast.innerHTML = 
        '<div class="toast-content">' +
            '<span class="toast-icon">' + getToastIcon(type) + '</span>' +
            '<span class="toast-message">' + escapeHtml(message) + '</span>' +
        '</div>' +
        '<button class="toast-close" onclick="this.parentElement.remove()">×</button>';
    
    container.appendChild(toast);
    
    // Animação de entrada
    setTimeout(function() { toast.classList.add('show'); }, 10);
    
    // Auto-remover
    setTimeout(function() {
        toast.classList.remove('show');
        toast.classList.add('hide');
        setTimeout(function() { 
            if (toast.parentElement) toast.remove(); 
        }, 300);
    }, duration);
}

function getToastIcon(type) {
    var icons = {
        success: '✓',
        error: '✗',
        warning: '⚠',
        info: 'ℹ'
    };
    return icons[type] || icons.info;
}

function escapeHtml(text) {
    var div = document.createElement('div');
    div.textContent = String(text || '');
    return div.innerHTML;
}

// ══════════════════════════════════════════
//  LOADING OVERLAY
// ══════════════════════════════════════════
function showLoading(message) {
    message = message || 'Processando...';
    var overlay = document.getElementById('loadingOverlay');
    if (overlay) {
        var textEl = overlay.querySelector('.loading-text');
        if (textEl) textEl.textContent = message;
        overlay.style.display = 'flex';
    }
}

function hideLoading() {
    var overlay = document.getElementById('loadingOverlay');
    if (overlay) overlay.style.display = 'none';
}

// ══════════════════════════════════════════
//  MODAL GENÉRICO
// ══════════════════════════════════════════
function fecharModalGenerico() {
    var overlay = document.getElementById('modal-overlay');
    if (overlay) {
        overlay.classList.remove('open');
        document.body.style.overflow = '';
    }
}

function abrirModalGenerico(titulo, conteudo, callbackConfirmar, textoConfirmar) {
    var overlay = document.getElementById('modal-overlay');
    var tituloEl = document.getElementById('modal-generico-titulo');
    var conteudoEl = document.getElementById('modal-inner');
    var footerEl = document.getElementById('modal-footer-generico');
    var btnConfirmar = document.getElementById('modal-btn-confirmar');
    
    if (!overlay) return;
    
    if (tituloEl) tituloEl.textContent = titulo || 'Informação';
    if (conteudoEl) conteudoEl.innerHTML = conteudo || '';
    
    if (callbackConfirmar && typeof callbackConfirmar === 'function') {
        if (footerEl) footerEl.style.display = 'flex';
        if (btnConfirmar) {
            btnConfirmar.textContent = textoConfirmar || 'Confirmar';
            btnConfirmar.onclick = function() {
                callbackConfirmar();
                fecharModalGenerico();
            };
        }
    } else {
        if (footerEl) footerEl.style.display = 'none';
    }
    
    overlay.classList.add('open');
    document.body.style.overflow = 'hidden';
}

// Fechar modal ao clicar fora (delegado no overlay)
document.getElementById('modal-overlay').addEventListener('click', function(e) {
    if (e.target === this) {
        fecharModalGenerico();
    }
});

// ══════════════════════════════════════════
//  CSRF TOKEN GLOBAL
// ══════════════════════════════════════════
var csrfToken = '<?php echo csrfToken(); ?>';

// ══════════════════════════════════════════
//  FETCH WRAPPER COM CSRF
// ══════════════════════════════════════════
function apiFetch(url, options) {
    options = options || {};
    
    var defaultHeaders = {
        'Content-Type': 'application/json',
        'X-CSRF-Token': csrfToken
    };
    
    var mergedHeaders = {};
    for (var key in defaultHeaders) {
        mergedHeaders[key] = defaultHeaders[key];
    }
    if (options.headers) {
        for (var key in options.headers) {
            mergedHeaders[key] = options.headers[key];
        }
    }
    
    var mergedOptions = {};
    for (var key in options) {
        mergedOptions[key] = options[key];
    }
    mergedOptions.headers = mergedHeaders;
    
    if (options.body && typeof options.body === 'object' && !(options.body instanceof FormData)) {
        mergedOptions.body = JSON.stringify(options.body);
    }
    
    showLoading();
    
    return fetch(url, mergedOptions)
        .then(function(response) {
            return response.json().then(function(data) {
                if (!response.ok) {
                    throw new Error(data.message || 'Erro na requisição');
                }
                return data;
            });
        })
        .catch(function(error) {
            showToast(error.message, 'error');
            throw error;
        })
        .finally(function() {
            hideLoading();
        });
}

// ══════════════════════════════════════════
//  FORMATAÇÃO DE VALORES
// ══════════════════════════════════════════
function formatarMoeda(valor) {
    valor = parseFloat(valor) || 0;
    return 'R$ ' + valor.toFixed(2).replace('.', ',');
}

function formatarTelefone(telefone) {
    if (!telefone) return '';
    var cleaned = String(telefone).replace(/\D/g, '');
    if (cleaned.length === 11) {
        return '(' + cleaned.slice(0, 2) + ') ' + cleaned.slice(2, 7) + '-' + cleaned.slice(7);
    }
    if (cleaned.length === 10) {
        return '(' + cleaned.slice(0, 2) + ') ' + cleaned.slice(2, 6) + '-' + cleaned.slice(6);
    }
    return telefone;
}

function formatarDocumento(doc) {
    if (!doc) return '';
    var cleaned = String(doc).replace(/\D/g, '');
    if (cleaned.length === 11) {
        return cleaned.replace(/(\d{3})(\d{3})(\d{3})(\d{2})/, '$1.$2.$3-$4');
    }
    if (cleaned.length === 14) {
        return cleaned.replace(/(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/, '$1.$2.$3/$4-$5');
    }
    return doc;
}

// ══════════════════════════════════════════
//  CONFIRM DIALOG CUSTOMIZADO
// ══════════════════════════════════════════
function confirmAction(message, onConfirm) {
    if (confirm(message)) {
        if (typeof onConfirm === 'function') {
            onConfirm();
        }
    }
}

// ══════════════════════════════════════════
//  RELÓGIO EM TEMPO REAL
// ══════════════════════════════════════════
var relogioEl = document.getElementById('relogio');
if (relogioEl) {
    function atualizarRelogio() {
        var now = new Date();
        relogioEl.textContent = now.toLocaleString('pt-BR');
    }
    atualizarRelogio();
    setInterval(atualizarRelogio, 1000);
}

// ══════════════════════════════════════════
//  FECHAR MODAIS COM ESC
// ══════════════════════════════════════════
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        var modal = document.getElementById('modal-overlay');
        if (modal && modal.classList.contains('open')) {
            fecharModalGenerico();
        }
    }
});

// ══════════════════════════════════════════
//  UTILITÁRIOS GERAIS
// ══════════════════════════════════════════
function debounce(func, wait) {
    var timeout;
    return function() {
        var context = this;
        var args = arguments;
        clearTimeout(timeout);
        timeout = setTimeout(function() {
            func.apply(context, args);
        }, wait);
    };
}

function throttle(func, limit) {
    var inThrottle;
    return function() {
        var args = arguments;
        var context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(function() {
                inThrottle = false;
            }, limit);
        }
    };
}

// Copiar texto para área de transferência
function copiarTexto(texto) {
    if (navigator.clipboard && navigator.clipboard.writeText) {
        navigator.clipboard.writeText(texto).then(function() {
            showToast('Copiado para a área de transferência!', 'success', 2000);
        }).catch(function() {
            fallbackCopiar(texto);
        });
    } else {
        fallbackCopiar(texto);
    }
}

function fallbackCopiar(texto) {
    var textarea = document.createElement('textarea');
    textarea.value = texto;
    textarea.style.position = 'fixed';
    textarea.style.opacity = '0';
    document.body.appendChild(textarea);
    textarea.select();
    try {
        document.execCommand('copy');
        showToast('Copiado!', 'success', 2000);
    } catch (err) {
        showToast('Erro ao copiar', 'error');
    }
    document.body.removeChild(textarea);
}
</script>

<style>
/* ══════════════════════════════════════════
   TOAST STYLES
   ══════════════════════════════════════════ */
.toast-container {
    position: fixed;
    bottom: 80px;
    right: 20px;
    z-index: 10000;
    display: flex;
    flex-direction: column;
    gap: 10px;
    pointer-events: none;
}

.toast {
    background: var(--surface);
    border-left: 4px solid;
    border-radius: 8px;
    padding: 12px 16px;
    min-width: 280px;
    max-width: 380px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    box-shadow: 0 4px 16px rgba(0,0,0,0.4);
    transform: translateX(120%);
    transition: transform 0.3s ease, opacity 0.3s ease;
    pointer-events: all;
    opacity: 0;
}

.toast.show {
    transform: translateX(0);
    opacity: 1;
}

.toast.hide {
    transform: translateX(120%);
    opacity: 0;
}

.toast-success { border-left-color: var(--green); }
.toast-error { border-left-color: var(--red); }
.toast-warning { border-left-color: var(--amber); }
.toast-info { border-left-color: var(--cyan); }

.toast-content {
    display: flex;
    align-items: center;
    gap: 10px;
    flex: 1;
    min-width: 0;
}

.toast-icon {
    font-size: 18px;
    font-weight: bold;
    flex-shrink: 0;
}

.toast-success .toast-icon { color: var(--green); }
.toast-error .toast-icon { color: var(--red); }
.toast-warning .toast-icon { color: var(--amber); }
.toast-info .toast-icon { color: var(--cyan); }

.toast-message {
    font-size: 13px;
    line-height: 1.4;
    color: var(--text);
    word-break: break-word;
}

.toast-close {
    background: none;
    border: none;
    color: var(--muted);
    cursor: pointer;
    font-size: 18px;
    padding: 0 4px;
    margin-left: 10px;
    flex-shrink: 0;
    line-height: 1;
    transition: color 0.15s;
}

.toast-close:hover {
    color: var(--text);
}

/* ══════════════════════════════════════════
   LOADING OVERLAY
   ══════════════════════════════════════════ */
.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(5, 10, 25, 0.85);
    backdrop-filter: blur(4px);
    -webkit-backdrop-filter: blur(4px);
    z-index: 10001;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    gap: 16px;
}

.loading-spinner {
    width: 48px;
    height: 48px;
    border: 3px solid var(--border);
    border-top-color: var(--cyan);
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
}

.loading-text {
    color: var(--text);
    font-size: 14px;
    font-family: var(--mono);
    letter-spacing: 0.5px;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

/* ══════════════════════════════════════════
   MELHORIAS MOBILE PARA TOASTS
   ══════════════════════════════════════════ */
@media (max-width: 767px) {
    .toast-container {
        bottom: calc(62px + 12px);
        left: 12px;
        right: 12px;
    }
    
    .toast {
        min-width: unset;
        max-width: unset;
        width: 100%;
    }
}

@media (max-width: 400px) {
    .toast {
        padding: 10px 12px;
    }
    
    .toast-message {
        font-size: 12px;
    }
}
</style>

<?php if (!empty($pageScript)): ?>
<script src="assets/<?php echo e($pageScript); ?>?v=<?php echo APP_VERSION; ?>"></script>
<?php endif; ?>

<?php if (!empty($inlineScript)): ?>
<script><?php echo $inlineScript; ?></script>
<?php endif; ?>

</body>
</html>
