// ================================================================
// gerenciar.js - VERSÃO CORRIGIDA E OTIMIZADA (INFALÍVEL)
// ================================================================

import { DataService } from './api.js';

// --- CONFIGURAÇÕES GLOBAIS ---
const MESSAGING_API_URL = 'http://192.168.1.10:3001/send-message';

// --- FUNÇÕES AUXILIARES GLOBAIS ---
function showGlobalLoading(message = 'Processando...') {
    const overlay = document.getElementById('global-loading-overlay');
    const msgElement = document.getElementById('loading-message');
    if (msgElement) msgElement.textContent = message;
    if (overlay) overlay.classList.remove('hidden');
}

function hideGlobalLoading() {
    const overlay = document.getElementById('global-loading-overlay');
    if (overlay) overlay.classList.add('hidden');
}

function formatPhoneNumber(phone) {
    if (!phone) return '';
    const digits = phone.replace(/\D/g, '');
    if (digits.length === 13) {
        return `+${digits.slice(0, 2)} (${digits.slice(2, 4)}) ${digits.slice(4, 5)} ${digits.slice(5, 9)}-${digits.slice(9)}`;
    }
    if (digits.length === 12) {
        return `+${digits.slice(0, 2)} (${digits.slice(2, 4)}) ${digits.slice(4, 8)}-${digits.slice(8)}`;
    }
    return phone;
}
// =========================================================
// EXIBIR LISTA DE CLIENTES RESPONSIVA (GERENCIAR TORRES)
// =========================================================
window.mostrarListaClientes = function(torreNome, setorNome, nomesCodificados) {
    // Descriptografa os nomes (evita erros com aspas e acentos no HTML)
        const clientNamesStr = decodeURIComponent(nomesCodificados);
        
        if (!clientNamesStr || clientNamesStr.trim() === '') {
            Swal.fire('Vazio', `Não há clientes registrados no ${setorNome}.`, 'info');
            return;
        }

        // Transforma a string de nomes separados por vírgula em uma lista limpa
        const namesArray = clientNamesStr.split(',').map(nome => nome.trim()).filter(nome => nome !== '');

        // Cria a interface responsiva: max-h-60 limita a altura e overflow-y-auto cria a barra de rolagem
        const listHtml = `
            <div class="max-h-60 overflow-y-auto p-3 bg-slate-50 rounded-lg border border-slate-200 text-left shadow-inner">
                <ul class="divide-y divide-slate-200">
                    ${namesArray.map(name => `
                        <li class="py-2 text-sm text-slate-700 font-medium flex items-center">
                            <i class="fas fa-user-check text-indigo-400 mr-3"></i> ${name}
                        </li>
                    `).join('')}
                </ul>
            </div>
            <div class="mt-3 text-xs text-slate-500 font-bold text-right uppercase tracking-wider">
                Total: ${namesArray.length} cliente(s)
            </div>
        `;

        Swal.fire({
            title: `<span class="text-lg">${torreNome} <br> <span class="text-indigo-600 text-sm">${setorNome}</span></span>`,
            html: listHtml,
            confirmButtonColor: '#4f46e5',
            confirmButtonText: 'Fechar Lista',
            width: '90%', // Deixa largo no celular
            maxWidth: '400px' // Mas não deixa ficar gigante no computador
        });
};
// --- LÓGICA PRINCIPAL DA PÁGINA ---
document.addEventListener('DOMContentLoaded', async () => {

    function showFeedbackModal(title, message, type = 'success', onCloseCallback = null) {
        const feedbackModal = document.getElementById('feedback-modal');
        if (!feedbackModal) {
            alert(`${title}\n\n${message}`);
            return;
        }

        const modalTitleEl = feedbackModal.querySelector('#modal-title');
        const modalMessageEl = feedbackModal.querySelector('#modal-message');
        const modalIconContainerEl = feedbackModal.querySelector('#modal-icon-container');
        const modalCloseButtonEl = feedbackModal.querySelector('#modal-close-button');
        
        const successIcon = `<i class="fas fa-check-circle fa-2x text-green-500"></i>`;
        const errorIcon = `<i class="fas fa-times-circle fa-2x text-red-500"></i>`;
        const infoIcon = `<i class="fas fa-info-circle fa-2x text-blue-500"></i>`;
        
        if(modalTitleEl) modalTitleEl.textContent = title;
        if(modalMessageEl) modalMessageEl.textContent = message;

        let icon = successIcon;
        if (type === 'error') icon = errorIcon;
        if (type === 'info') icon = infoIcon;
        if(modalIconContainerEl) modalIconContainerEl.innerHTML = icon;

        if (type === 'success') {
            modalCloseButtonEl?.classList.add('hidden');
            setTimeout(() => {
                feedbackModal.classList.add('hidden');
                if (onCloseCallback) onCloseCallback();
            }, 2500);
        } else {
            modalCloseButtonEl?.classList.remove('hidden');
        }

        feedbackModal.classList.remove('hidden');
    }

    const storedUser = sessionStorage.getItem('currentUser');
    if (!storedUser) {
        alert('Sua sessão expirou. Por favor, faça o login novamente.');
        window.location.href = 'login.html';
        throw new Error("Sessão do usuário não encontrada, execução interrompida.");
    }

    const currentUser = JSON.parse(storedUser);

    // --- VARIÁVEIS DE ESTADO ---
    let mainInventory = [];
    let towersData = [];
    let safetyStockProducts = [];
    let clientList = []; 
    let messageTemplates = []; 
    let itensConsumiveis = []; 
    let historicoConsumo = [];
    let users = [];
    let itensParaAlocar = [];
    let itensParaRetirar = [];
    let newTowerSectors = [];
    let clientLimit = 1;
    let vehicleInventory = {};
    let vehicleList = [];

    // --- FUNÇÃO RESTAURADA (ATUALIZA AS TORRES APÓS MUDANÇAS) ---
    async function fetchAllTorresData() {
        try {
            const torresResult = await DataService.getTowers(currentUser.role);
            towersData = torresResult.data || [];
            
            try {
                const invResult = await DataService.getInventory(currentUser.role);
                mainInventory = invResult.data || [];
            } catch (e) { mainInventory = []; }
            
            return true;
        } catch (error) {
            showToast(`Erro ao recarregar dados das torres: ${error.message}`, 'error');
            return false;
        }
    }

    // --- FUNÇÕES DE CARREGAMENTO INICIAL ---
    async function loadVehicleData() {
        try {
            const inventoryResult = await DataService.getAllVehicleInventories(currentUser.role);
            vehicleInventory = inventoryResult.data || {};
        } catch (error) {
            vehicleInventory = {}; 
        }

        try {
            const listResult = await DataService.getVehicles(currentUser.role);
            vehicleList = listResult.data || [];
        } catch (error) {
            vehicleList = [];
            showToast("Erro ao carregar lista de veículos.", "error");
        }
    }

    function populateAllVehicleSelects() {
        const vehicles = (Array.isArray(vehicleList) && vehicleList.length > 0) ? vehicleList : [];
        if (vehicles.length === 0) return;

        const targetIds = ['transfer-vehicle-select', 'combustivel-veiculo-select'];
        targetIds.forEach(id => {
            const selectElement = document.getElementById(id);
            if (selectElement) {
                const currentValue = selectElement.value;
                let optionsHTML = `<option value="">-- Selecione o veículo --</option>`;
                vehicles.forEach(vehicle => {
                    const valor = vehicle.nome_tabela || vehicle.id || "";
                    const texto = vehicle.nome_exibicao || vehicle.nome || vehicle.veiculo_nome || "Veículo sem nome";
                    if (valor) {
                        optionsHTML += `<option value="${valor}">${texto}</option>`;
                    }
                });
                selectElement.innerHTML = optionsHTML;
                selectElement.value = currentValue;
            }
        });
    }

    function showToast(message, type = 'success') {
        const container = document.getElementById('toast-container'); if (!container) return;
        const icon = type === 'success' ? 'fa-check-circle' : 'fa-times-circle';
        const color = type === 'success' ? 'bg-green-500' : 'bg-red-500';
        const toast = document.createElement('div');
        toast.className = `toast flex items-center gap-3 text-white font-bold ${color} px-6 py-3 rounded-lg shadow-xl`;
        toast.innerHTML = `<i class="fas ${icon}"></i> <p>${message}</p>`;
        container.appendChild(toast);
        setTimeout(() => { toast.remove(); }, 3500);
    }
    const emptyStateHTML = (message, iconClass) => `<div class="text-center p-8 text-slate-500"><i class="${iconClass} fa-2x text-slate-300 mb-4"></i><p class="text-sm">${message}</p></div>`;

    // ===================================================================
    // ===== CÓDIGO DA CENTRAL DE COMUNICAÇÃO ============================
    // ===================================================================

    const comunicacaoModal = document.getElementById('comunicacao-modal');
    const comunicacaoTabs = document.querySelectorAll('.comunicacao-tab');
    const comunicacaoContentClientes = document.getElementById('comunicacao-content-clientes');
    const comunicacaoContentFuncionarios = document.getElementById('comunicacao-content-funcionarios');
    const torresSelect = document.getElementById('comunicacao-torres-select');
    const setoresSelect = document.getElementById('comunicacao-setores-select');
    const filterBtn = document.getElementById('comunicacao-filter-btn');
    const recipientsList = document.getElementById('comunicacao-recipients-list');
    const recipientCount = document.getElementById('comunicacao-recipient-count');
    const selectAllBtn = document.getElementById('comunicacao-select-all-btn');
    const deselectAllBtn = document.getElementById('comunicacao-deselect-all-btn');
    const templateSelect = document.getElementById('comunicacao-template-select');
    const messageBody = document.getElementById('comunicacao-message-body');
    const saveTemplateBtn = document.getElementById('comunicacao-save-template-btn');
    const sendBtn = document.getElementById('comunicacao-send-btn');
    const attachMediaBtn = document.getElementById('attach-media-btn');
    const mediaFileInput = document.getElementById('media-file-input');
    const attachmentPreview = document.getElementById('attachment-preview');

    async function openComunicacaoModal() {
        showGlobalLoading('Carregando dados...');
        try {
            const [towersResult, templatesResult, clientsResult] = await Promise.all([
                DataService.getTowers(currentUser.role),
                DataService.getMessageTemplates(currentUser.role),
                DataService.getClients(currentUser.role)
            ]);
            
            towersData = towersResult.data || [];
            messageTemplates = templatesResult.data || [];
            clientList = clientsResult.data || [];

            populateComunicacaoTorres();
            populateComunicacaoTemplates();
            updateStepIndicator();
        } catch (error) {
            showFeedbackModal('Erro', `Não foi possível carregar os dados: ${error.message}`, 'error');
        } finally {
            hideGlobalLoading();
        }
    }

    function switchComunicacaoTab(activeTabId) {
        comunicacaoTabs.forEach(tab => {
            const isTabActive = tab.id === activeTabId;
            tab.className = `comunicacao-tab whitespace-nowrap py-4 px-2 border-b-2 font-medium text-sm ${isTabActive ? 'text-indigo-600 border-indigo-500' : 'text-gray-500 border-transparent hover:text-gray-700'}`;
        });
        if(comunicacaoContentClientes) comunicacaoContentClientes.classList.toggle('hidden', activeTabId !== 'comunicacao-tab-clientes');
        if(comunicacaoContentFuncionarios) comunicacaoContentFuncionarios.classList.toggle('hidden', activeTabId !== 'comunicacao-tab-funcionarios');
    }

    function populateComunicacaoTorres() {
        torresSelect.innerHTML = '';
        towersData.forEach(torre => {
            torresSelect.add(new Option(torre.nome, torre.id));
        });
        updateComunicacaoSetores();
    }

    function updateComunicacaoSetores() {
        const selectedTorreIds = Array.from(torresSelect.selectedOptions).map(opt => opt.value);
        setoresSelect.innerHTML = '';
        setoresSelect.disabled = true;

        if (selectedTorreIds.length > 0) {
            const setoresDisponiveis = new Map();
            towersData
                .filter(torre => selectedTorreIds.includes(String(torre.id)))
                .forEach(torre => {
                    (torre.setores || []).forEach(setor => {
                        setoresDisponiveis.set(setor.nome, setor);
                    });
                });
            
            if (setoresDisponiveis.size > 0) {
                setoresDisponiveis.forEach(setor => {
                    setoresSelect.add(new Option(setor.nome, setor.nome));
                });
                setoresSelect.disabled = false;
            }
        }
    }

    function renderRecipients(clients) {
        recipientsList.innerHTML = '';
        if (clients.length === 0) {
            recipientsList.innerHTML = '<p class="text-center text-gray-400 mt-8">Nenhum cliente encontrado.</p>';
            updateRecipientCount();
            return;
        }
        clients.forEach(client => {
            const hasPhone = client.telefone && client.telefone.trim() !== '';
            const itemHtml = `
                <div class="recipient-card flex items-center p-2 rounded-md hover:bg-slate-200">
                    <input type="checkbox" id="client-check-${client.id}" value="${client.id}" class="h-4 w-4 shrink-0 rounded border-gray-300 text-indigo-600 focus:ring-indigo-500" ${!hasPhone ? 'disabled' : ''}>
                    <label for="client-check-${client.id}" class="ml-3 flex-grow cursor-pointer ${!hasPhone ? 'text-gray-400' : ''}">
                        <span class="block text-sm font-medium">${client.name}</span>
                        <span class="block text-xs text-gray-500">${hasPhone ? client.telefone : 'Sem telefone'}</span>
                    </label>
                    <button class="edit-client-btn text-slate-400 hover:text-indigo-600 p-2" data-client-id="${client.id}" title="Editar Cliente">
                        <i class="fas fa-pencil-alt"></i>
                    </button>
                </div>
            `;
            recipientsList.insertAdjacentHTML('beforeend', itemHtml);
        });
        updateRecipientCount();
    }

    function updateRecipientCount() {
        const selectedCount = recipientsList.querySelectorAll('input:checked').length;
        recipientCount.textContent = `${selectedCount} selecionados`;
    }

    function populateComunicacaoTemplates() {
        templateSelect.innerHTML = '<option value="">-- Carregar Modelo --</option>';
        messageTemplates.forEach(template => {
            templateSelect.add(new Option(template.titulo, template.id));
        });
    }

    async function handleSaveTemplate() {
        const message = messageBody.value.trim();
        if (!message) { return showToast('A mensagem não pode estar vazia.', 'error'); }
        const title = prompt("Digite um título para este modelo:", "Aviso de Manutenção");
        if (!title) return;

        try {
            await DataService.saveMessageTemplate({ titulo: title, mensagem: message }, currentUser.role);
            showToast('Modelo salvo com sucesso!');
            const templatesResult = await DataService.getMessageTemplates(currentUser.role);
            messageTemplates = templatesResult.data || [];
            populateComunicacaoTemplates();
        } catch(error) {
            showFeedbackModal('Erro', `Não foi possível salvar o modelo: ${error.message}`, 'error');
        }
    }

    attachMediaBtn?.addEventListener('click', () => { mediaFileInput.click(); });

    mediaFileInput?.addEventListener('change', () => {
        const numFiles = mediaFileInput.files.length;
        if (numFiles > 0) {
            attachmentPreview.textContent = `${numFiles} arquivo(s) selecionado(s).`;
        } else {
            attachmentPreview.textContent = '';
        }
    });

    async function handlePrepararEnvio() {
        const selectedCheckboxes = recipientsList.querySelectorAll('input:checked');
        const message = messageBody.value;
        const mediaFiles = mediaFileInput.files; 

        if (selectedCheckboxes.length === 0) { return showToast('Nenhum destinatário selecionado.', 'error'); }
        if (!message && mediaFiles.length === 0) { return showToast('Você precisa de uma mensagem ou um anexo de mídia.', 'error'); }
        
        const numbersToSend = Array.from(selectedCheckboxes).map(checkbox => {
            const client = clientList.find(c => String(c.id) === checkbox.value);
            return client ? client.telefone.replace(/\D/g, '') : null;
        }).filter(Boolean);

        Swal.fire({
            title: 'Confirmar Envio?',
            text: `Você está prestes a iniciar o envio para ${numbersToSend.length} cliente(s). Deseja continuar?`,
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sim, iniciar envio!',
            cancelButtonText: 'Cancelar'
        }).then(async (result) => {
            if (result.isConfirmed) {
                showGlobalLoading('Preparando e enviando ordem...');
                try {
                    const formData = new FormData();
                    formData.append('numbers', JSON.stringify(numbersToSend));
                    formData.append('message', message);
                    
                    if (mediaFiles.length > 0) {
                        for (let i = 0; i < mediaFiles.length; i++) {
                            formData.append('media[]', mediaFiles[i]);
                        }
                    }

                    const response = await fetch(MESSAGING_API_URL, {
                        method: 'POST',
                        body: formData,
                    });

                    const result = await response.json();
                    if (result.status === 'aceito') {
                        Swal.fire('Processo Iniciado!', 'Seu servidor de mensagens começou o envio.', 'success');
                    } else {
                        throw new Error(result.message || 'Erro desconhecido no servidor.');
                    }
                } catch (error) {
                    Swal.fire('Erro de Conexão!', `Não foi possível se conectar ao seu servidor. Detalhes: ${error.message}`, 'error');
                } finally {
                    hideGlobalLoading();
                }
            }
        });
    }

    function updateStepIndicator() {
        const stepFiltros = document.getElementById('step-filtros');
        const stepMensagem = document.getElementById('step-mensagem');
        const stepEnvio = document.getElementById('step-envio');
        const divider12 = document.getElementById('divider-1-2');
        const divider23 = document.getElementById('divider-2-3');
        
        const clientesFiltrados = !recipientsList.querySelector('p'); 
        const mensagemPreenchida = messageBody.value.trim() !== '';
        const destinatariosSelecionados = recipientsList.querySelectorAll('input:checked').length > 0;

        [stepFiltros, stepMensagem, stepEnvio].forEach(step => step.classList.remove('active', 'completed'));
        [divider12, divider23].forEach(div => div.classList.remove('completed'));

        stepFiltros.classList.add('active');

        if (clientesFiltrados) {
            stepFiltros.classList.add('completed');
            divider12.classList.add('completed');
            stepMensagem.classList.add('active');
        }

        if (mensagemPreenchida && clientesFiltrados) { 
            stepMensagem.classList.add('completed');
        }

        if (destinatariosSelecionados) {
            stepMensagem.classList.add('completed'); 
            divider12.classList.add('completed'); 
            divider23.classList.add('completed');
            stepEnvio.classList.add('active');
        }
    }

    async function handleFiltroClientes() {
        showGlobalLoading('Filtrando clientes...');
        const selectedTorreIds = Array.from(torresSelect.selectedOptions).map(opt => String(opt.value));
        const selectedSetores = Array.from(setoresSelect.selectedOptions).map(opt => opt.value);

        try {
            let filteredClients = clientList;

            if (selectedTorreIds.length > 0) {
                 const torresSelecionadasNomes = towersData
                    .filter(t => selectedTorreIds.includes(String(t.id)))
                    .map(t => t.nome);
                
                filteredClients = filteredClients.filter(c => torresSelecionadasNomes.includes(c.tower));
            }

            if (selectedSetores.length > 0) {
                filteredClients = filteredClients.filter(c => selectedSetores.includes(c.sector));
            }
            
            renderRecipients(filteredClients); 
        } catch (error) {
             showFeedbackModal('Erro', `Não foi possível filtrar os clientes: ${error.message}`, 'error');
        } finally {
            hideGlobalLoading();
        }
    }

    torresSelect?.addEventListener('change', updateComunicacaoSetores);
    filterBtn?.addEventListener('click', handleFiltroClientes);
    recipientsList?.addEventListener('change', (e) => { if (e.target.type === 'checkbox') { updateRecipientCount(); }});
    selectAllBtn?.addEventListener('click', () => { recipientsList.querySelectorAll('input[type="checkbox"]:not(:disabled)').forEach(cb => cb.checked = true); updateRecipientCount(); updateStepIndicator(); });
    deselectAllBtn?.addEventListener('click', () => { recipientsList.querySelectorAll('input[type="checkbox"]:checked').forEach(cb => cb.checked = false); updateRecipientCount(); updateStepIndicator(); });
    templateSelect?.addEventListener('change', () => {
        const selectedTemplate = messageTemplates.find(t => String(t.id) === templateSelect.value);
        messageBody.value = selectedTemplate ? selectedTemplate.mensagem : '';
        updateStepIndicator();
    });
    messageBody?.addEventListener('input', updateStepIndicator);
    saveTemplateBtn?.addEventListener('click', handleSaveTemplate);
    sendBtn?.addEventListener('click', handlePrepararEnvio);

    recipientsList?.addEventListener('click', async (e) => {
        const editButton = e.target.closest('.edit-client-btn');
        if (editButton) {
            const clientId = editButton.dataset.clientId;
            const client = clientList.find(c => String(c.id) === clientId);
            if (!client) return;

            const nameConfirmed = confirm(`Você confirma o nome do cliente: "${client.name}"?`);
            if (!nameConfirmed) return;

            const newPhoneRaw = prompt("Edite ou adicione o número de WhatsApp do cliente:", client.telefone || '');
            if (newPhoneRaw === null) return;

            const formattedPhone = formatPhoneNumber(newPhoneRaw);

            try {
                showGlobalLoading('Atualizando cliente...');
                const payload = { id: clientId, name: client.name, telefone: formattedPhone };
                const result = await DataService.updateClient(payload, currentUser.role);

                client.telefone = formattedPhone;
                handleFiltroClientes(); 
                showToast(result.message);

            } catch (error) {
                showFeedbackModal('Erro', error.message, 'error');
            } finally {
                hideGlobalLoading();
            }
        } 
        else if (e.target.type === 'checkbox') {
            updateRecipientCount();
            updateStepIndicator();
        }
    });

    // =========================================================
    // PERMISSÕES E CONFIGURAÇÕES GERAIS
    // =========================================================

    function applyCardPermissions() {
        const userRole = currentUser.role;
        const cardsConfig = {
            'card-torres': ['Estoquista', 'Desenvolvedor', 'Administrador', 'Operador', 'Suporte'],
            'card-consumo': ['Estoquista', 'Desenvolvedor', 'Administrador'],
            'card-combustivel': ['Estoquista', 'Desenvolvedor', 'Administrador'],
            'card-notificacoes': ['Estoquista', 'Desenvolvedor','Administrador'],
            'card-seguranca': ['Estoquista', 'Desenvolvedor', 'Administrador'],
            'card-configuracoes': ['Estoquista', 'Desenvolvedor', 'Administrador'],
            'card-password-recovery': ['Desenvolvedor']
        };
        for (const cardId in cardsConfig) {
            const card = document.getElementById(cardId);
            if (card) {
                if (cardsConfig[cardId].includes(userRole)) {
                    card.classList.remove('hidden'); 
                } else {
                    card.classList.add('hidden'); 
                }
            }
        }
    }

    async function loadConfiguracoes() {
        try {
            const result = await DataService.getConfiguracao({ chave: 'CLIENT_LIMIT_PER_SECTOR' }, currentUser.role);
            if (result.data && result.data.valor) {
                clientLimit = parseInt(result.data.valor, 10);
            }
            const configInput = document.getElementById('config-client-limit');
            if(configInput) configInput.value = clientLimit;
        } catch (error) {
            console.error("Usando limite padrão de clientes.");
        }
    }

    // =========================================================
    // LÓGICA DE ESTOQUE DE SEGURANÇA
    // =========================================================

    async function renderSafetyStockEditor() {
        const container = document.getElementById('safety-stock-content');
        if (!container) return;

        container.innerHTML = `
            <div class="mb-4">
                <div class="flex items-center relative w-full h-12 rounded-full focus-within:shadow-lg bg-white border-2 border-slate-200 overflow-hidden transition">
                    <div class="grid place-items-center h-full w-12 text-slate-400"><i class="fas fa-search"></i></div>
                    <input class="peer h-full w-full outline-none text-sm text-slate-700 pr-2" type="text" id="safety-stock-search" placeholder="Buscar por nome do item...">
                </div>
            </div>
            <div id="safety-stock-list-container">${emptyStateHTML('Carregando itens...', 'fas fa-spinner fa-spin')}</div>
        `;

        document.getElementById('safety-stock-search').addEventListener('keyup', (e) => {
            updateSafetyStockList(e.target.value);
        });

        try {
            const result = await DataService.getAllStockDefinitions(currentUser.role);
            if (result && result.status === 'success' && Array.isArray(result.data)) {
                safetyStockProducts = result.data;
                updateSafetyStockList();
            } else {
                throw new Error(result.message || 'Formato inesperado.');
            }
        } catch (error) {
            document.getElementById('safety-stock-list-container').innerHTML = emptyStateHTML(`Erro ao carregar itens: ${error.message}`, 'fas fa-exclamation-triangle');
        }
    }

    function updateSafetyStockList(searchTerm = '') {
        const listContainer = document.getElementById('safety-stock-list-container');
        if (!listContainer) return;

        const term = searchTerm.toLowerCase().trim();
        let itemsToDisplay = safetyStockProducts;
        if (term) {
            itemsToDisplay = safetyStockProducts.filter(item => (item.nome && item.nome.toLowerCase().includes(term)));
        }

        const produtos = itemsToDisplay.filter(item => item.tipo === 'produto');
        const consumiveis = itemsToDisplay.filter(item => item.tipo === 'consumivel');

        if (itemsToDisplay.length === 0) {
            listContainer.innerHTML = emptyStateHTML('Nenhum item encontrado para sua busca.', 'fas fa-box-open');
            return;
        }
        
        const createHtmlList = (items, type) => {
            if (items.length === 0) return '';
            const title = type === 'produto' ? 'Produtos (Patrimônio)' : 'Itens Consumíveis';
            const icon = type === 'produto' ? 'fa-box' : 'fa-cogs';
            return `
                <h4 class="text-lg font-bold text-slate-600 border-b pb-2 mb-3 mt-4 flex items-center gap-2"><i class="fas ${icon}"></i>${title}</h4>
                <div class="space-y-4">${items.map(item => `
                    <div class="grid grid-cols-1 md:grid-cols-3 items-center gap-4 p-3 bg-slate-50 rounded-lg border">
                        <span class="font-semibold text-slate-700 col-span-1">${item.nome || 'Sem nome'}</span>
                        <div class="md:col-span-1"><input type="number" value="${item.estoque_minimo || 0}" min="0" class="form-input w-full text-center p-2" id="stock-input-${type}-${item.id}"></div>
                        <div class="md:col-span-1 text-right"><button data-item-id="${item.id}" data-item-type="${type}" class="save-safety-stock-btn btn-primary py-2 px-4 text-sm w-full md:w-auto">Salvar</button></div>
                    </div>`).join('')}
                </div>`;
        };
        listContainer.innerHTML = createHtmlList(produtos, 'produto') + createHtmlList(consumiveis, 'consumivel');
    }

    document.getElementById('safety-stock-content')?.addEventListener('click', async (e) => {
        const saveButton = e.target.closest('.save-safety-stock-btn');
        if (saveButton) {
            const itemId = saveButton.dataset.itemId;
            const itemType = saveButton.dataset.itemType;
            const input = document.getElementById(`stock-input-${itemType}-${itemId}`);
            const newStockLevel = parseInt(input.value, 10);

            if (isNaN(newStockLevel) || newStockLevel < 0) {
                showToast('Por favor, insira um valor numérico válido.', 'error');
                return;
            }

            saveButton.textContent = 'Salvando...';
            saveButton.disabled = true;
            try {
                let result;
                if (itemType === 'produto') {
                    result = await DataService.updateSafetyStock({ productId: itemId, newStockLevel }, currentUser.role);
                } else {
                    result = await DataService.updateConsumableSafetyStock({ itemId, newStockLevel }, currentUser.role);
                }
                showToast(result.message);
            } catch (error) {
                showToast(error.message, 'error');
            } finally {
                saveButton.textContent = 'Salvar';
                saveButton.disabled = false;
            }
        }
    });

    // =========================================================
    // LÓGICA DE TORRES
    // =========================================================

    function configureModalPermissions() {
        const userRole = currentUser.role;
        const allTabs = document.querySelectorAll('.torres-tab');
        const alocarSectionElements = document.querySelectorAll('#section-torres-alocar button, #section-torres-alocar select, #section-torres-alocar input');
        const retirarSectionElements = document.querySelectorAll('#section-torres-retirar button, #section-torres-retirar select');
        const geralSectionElements = document.querySelectorAll('#section-torres-geral button, #section-torres-geral input');

        allTabs.forEach(tab => tab.style.display = 'flex');
        document.querySelectorAll('#modal-torres button, #modal-torres input, #modal-torres select').forEach(el => el.disabled = false);

        if (userRole === 'Operador' || userRole === 'Suporte') {
            allTabs.forEach(tab => {
                if (tab.dataset.tab !== 'alocar') {
                    tab.style.display = 'none';
                }
            });
            alocarSectionElements.forEach(el => { el.disabled = false; });

        } else if (userRole === 'Administrador') {
            retirarSectionElements.forEach(el => el.disabled = true);
            geralSectionElements.forEach(el => el.disabled = true);
        }
    }

    document.getElementById('modal-torres')?.addEventListener('click', async (e) => {
        const summary = e.target.closest('summary') || e.target.closest('.tower-history-summary');
        
        if (summary) {
            const details = summary.parentElement; 
            const historyContent = details.querySelector('.tower-history-content');
            const historyList = historyContent ? historyContent.querySelector('.history-list') : null;
            const torreId = summary.dataset.torreId;

            if (historyContent && historyList) {
                historyContent.style.display = 'block'; 
                
                if (!historyList.hasAttribute('data-loaded')) {
                    historyList.innerHTML = '<li class="p-2 text-slate-500">Carregando histórico...</li>';
                    try {
                        const result = await DataService.getTowerHistory({ torreId }, currentUser.role);
                        if (result.data && result.data.length > 0) {
                            historyList.innerHTML = result.data.map(item => `
                                <li class="border-b border-slate-200 py-2">
                                    <p class="text-sm font-semibold text-slate-700">${item.descricao}</p>
                                    <p class="text-xs text-slate-500">
                                        ${new Date(item.data_evento).toLocaleString('pt-BR')} - <strong>${item.usuario_responsavel}</strong>
                                    </p>
                                </li>
                            `).join('');
                        } else {
                            historyList.innerHTML = '<li class="p-2 text-slate-400 italic">Nenhum histórico registrado.</li>';
                        }
                        historyList.setAttribute('data-loaded', 'true');
                    } catch (error) {
                        historyList.innerHTML = `<li class="text-red-500">Erro: ${error.message}</li>`;
                    }
                }
            }
        }

        const addButton = e.target.closest('.add-observation-btn');
        if (addButton) {
            const torreId = addButton.dataset.torreId;
            const textarea = document.getElementById(`observation-text-${torreId}`);
            const descricao = textarea.value.trim();

            if (descricao) {
                try {
                    const result = await DataService.addTowerObservation({ torreId, descricao, userName: currentUser.name }, currentUser.role);
                    showToast(result.message);
                    textarea.value = '';
                    
                    const details = addButton.closest('details');
                    const historyList = details.querySelector('.history-list');
                    if(historyList) historyList.removeAttribute('data-loaded');
                    
                    details.open = false;
                    setTimeout(() => details.open = true, 100);
                } catch (error) {
                    showToast(error.message, 'error');
                }
            } else {
                showToast('A observação não pode estar vazia.', 'error');
            }
        }
    });

    document.getElementById('config-torre-search-input')?.addEventListener('keyup', e => {
        renderTorresParaConfiguracao(e.target.value);
    });

    document.getElementById('config-torres-list-container')?.addEventListener('click', async (e) => {
        const saveBtn = e.target.closest('.save-config-limit-btn');
        if (saveBtn) {
            const setorId = saveBtn.dataset.setorId;
            const input = document.getElementById(`config-limit-input-${setorId}`);
            const novoLimite = parseInt(input.value, 10);

            if (isNaN(novoLimite) || novoLimite < 1) {
                showToast('O limite deve ser um número maior que zero.', 'error');
                return;
            }

            showGlobalLoading('Salvando...');
            try {
                const result = await DataService.updateSectorLimit({ setorId, limite: novoLimite }, currentUser.role);
                showToast(result.message);
            } catch (error) {
                showToast(error.message, 'error');
            } finally {
                hideGlobalLoading();
            }
        }
    });

    function populateSetoresSelectAlocar(torreId) {
        const selectSetor = document.getElementById('setor-alocar-selecionar');
        if (!selectSetor) return;
        selectSetor.innerHTML = '<option value="">-- Opcional --</option>';
        selectSetor.disabled = true;
        if (torreId) {
            const torre = towersData.find(t => String(t.id) === String(torreId));
            if (torre && torre.setores && torre.setores.length > 0) {
                torre.setores.forEach(setor => {
                    selectSetor.innerHTML += `<option value="${setor.id}">${setor.nome}</option>`;
                });
                selectSetor.disabled = false;
            }
        }
    }

    function populateSetoresSelectRetirar(torreId) {
        const selectSetor = document.getElementById('setor-retirar-selecionar');
        if (!selectSetor) return;
        selectSetor.innerHTML = '<option value="">-- Todos os Setores --</option>';
        selectSetor.disabled = true;
        if (torreId) {
            const torre = towersData.find(t => String(t.id) === String(torreId));
            if (torre && torre.setores && torre.setores.length > 0) {
                torre.setores.forEach(setor => {
                    const setorTemItens = torre.itens.some(item => String(item.setor_id) === String(setor.id));
                    if (setorTemItens) {
                         selectSetor.innerHTML += `<option value="${setor.id}">${setor.nome}</option>`;
                    }
                });
                if (selectSetor.options.length > 1) {
                    selectSetor.disabled = false;
                }
            }
        }
    }

    document.addEventListener('change', function(e) {
        if (!e.target) return; 
        if (e.target.id === 'torre-alocar-select') {
            populateSetoresSelectAlocar(e.target.value);
        }
        if (e.target.id === 'torre-retirar-selecionar') {
            const torreId = e.target.value;
            renderItensNaTorre(torreId); 
            populateSetoresSelectRetirar(torreId);
        }
        if(e.target.id === 'setor-retirar-selecionar') {
            const torreId = document.getElementById('torre-retirar-selecionar').value;
            const setorId = e.target.value;
            renderItensNaTorre(torreId, setorId);
        }
    });

    // ======================================================================
    // FUNÇÕES DE TROCA DE ABAS EXPOSTAS PARA O WINDOW (PARA O ONCLICK FUNCIONAR)
    // ======================================================================

    window.switchTorresTab = function(activeTabName) {
        document.querySelectorAll('#section-torres-alocar, #section-torres-retirar, #section-torres-total, #section-torres-geral').forEach(section => {
            section.classList.add('hidden');
        });
        document.querySelectorAll('.torres-tab').forEach(tab => {
            const isActive = tab.dataset.tab === activeTabName;
            tab.className = `torres-tab flex items-center gap-2 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-all duration-200 ${isActive ? 'text-indigo-600 border-indigo-500' : 'text-slate-500 border-transparent hover:text-slate-700 hover:border-slate-300'}`;
        });
        const activeSection = document.getElementById(`section-torres-${activeTabName}`);
        if (activeSection) {
            activeSection.classList.remove('hidden');
        }

        if (activeTabName === 'alocar') { 
            itensParaAlocar = []; 
            renderMateriaisDisponiveis(''); 
            renderCarrinhoAlocar();
            populateTorresSelectAlocar(); 
        }
        if (activeTabName === 'retirar') { 
            itensParaRetirar = []; 
            populateTorresSelectRetirar(); 
            renderItensNaTorre(document.getElementById('torre-retirar-selecionar')?.value); 
            renderCarrinhoRetirar(); 
        }
        if (activeTabName === 'total') {
            const totalSearchInput = document.getElementById('torres-pesquisa-total');
            if (totalSearchInput) totalSearchInput.value = '';
            renderTotalTorres(''); 
        }
        if (activeTabName === 'geral') { 
            newTowerSectors = []; 
            const torreNomeInput = document.getElementById('geral-torre-nome'); 
            if(torreNomeInput) torreNomeInput.value = ''; 
            const setorInput = document.getElementById('geral-setor-input'); 
            if(setorInput) setorInput.value = ''; 
            renderSectorsTags(); 
            renderGeralSearchResults(''); 
        }
        configureModalPermissions();
    };

    window.switchConsumoTab = async function(activeTabName) {
        document.querySelectorAll('.consumo-tab').forEach(tab => {
            tab.className = `consumo-tab flex items-center gap-2 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-all duration-200 ${tab.dataset.tab === activeTabName ? 'text-teal-500 border-teal-500' : 'text-slate-500 border-transparent hover:text-slate-700 hover:border-slate-300'}`;
        });
        ['registrar', 'relatorio', 'cadastrar', 'transferir'].forEach(tab => {
            const section = document.getElementById(`section-consumo-${tab}`);
            if (section) section.classList.toggle('hidden', tab !== activeTabName);
        });

        if (activeTabName === 'cadastrar') { await renderItensConsumiveis(''); }
        if (activeTabName === 'registrar') { await populateConsumoUsuarioSelect(); await populateConsumoMaterialSelect(); }
        if (activeTabName === 'relatorio') { await renderRelatorioConsumo(''); }
        if (activeTabName === 'transferir') { await populateTransferFormSelects_MANUAL(); }
    };

    window.switchCombustivelTab = async function(activeTabName) {
        document.querySelectorAll('.combustivel-tab').forEach(tab => {
            const isActive = tab.dataset.tab === activeTabName;
            tab.className = `combustivel-tab flex items-center gap-2 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-all duration-200 ${isActive ? 'text-zinc-600 border-zinc-600' : 'text-slate-500 border-transparent hover:text-slate-700 hover:border-slate-300'}`;
        });
        ['registrar', 'historico'].forEach(tab => {
            const section = document.getElementById(`section-combustivel-${tab}`);
            if (section) section.classList.toggle('hidden', tab !== activeTabName);
        });

        if (activeTabName === 'registrar') {
            const select = document.getElementById('combustivel-veiculo-select');
            const formContainer = document.getElementById('combustivel-form-container');
            const prompt = document.getElementById('combustivel-prompt-selecao');

            if (select) {
                select.removeEventListener('change', handleVeiculoSelectionChange); 
                select.addEventListener('change', handleVeiculoSelectionChange);

                if (select.value) {
                    if(formContainer) formContainer.classList.remove('hidden');
                    if(prompt) prompt.classList.add('hidden');
                    handleVeiculoSelectionChange({ target: select });
                } else {
                    if(formContainer) formContainer.classList.add('hidden');
                    if(prompt) prompt.classList.remove('hidden');
                }
            }
        }
        if (activeTabName === 'historico') {
            if (typeof renderHistoricoCombustivel === 'function') {
                await renderHistoricoCombustivel('');
            }
        }
    };


    const createItemCardHTML = (item, type, isSelected) => {
        const selectedClasses = isSelected ? 'border-indigo-400 bg-indigo-50/70 shadow-sm' : 'border-slate-200 bg-white';
        const itemName = item.nomeProduto || item.nome || 'Nome Indefinido';
        return `<div data-patrimonio="${item.patrimonio}" data-type="${type}" class="item-card flex items-center justify-between p-3 rounded-lg border-2 ${selectedClasses} hover:border-indigo-300 cursor-pointer transition-all duration-200">
                    <div class="flex items-center gap-4">
                        <i class="fas fa-box-open text-slate-400 fa-lg"></i>
                        <div>
                            <span class="font-semibold text-slate-800">${itemName}</span>
                            <span class="block text-xs text-slate-500">Patrimônio: ${item.patrimonio}</span>
                        </div>
                    </div>
                    <div class="w-6 h-6 rounded-full flex items-center justify-center border-2 ${isSelected ? 'border-indigo-600 bg-indigo-600' : 'border-slate-300'} transition-all duration-200">
                        ${isSelected ? '<i class="fas fa-check text-white text-xs"></i>' : ''}
                    </div>
                </div>`;
    };

    function renderMateriaisDisponiveis(searchTerm = '') {
        const container = document.getElementById('torres-materiais-disponiveis');
        if (!container) return;
        const term = searchTerm.toLowerCase();
        const filtered = mainInventory.filter(item => 
            (item.produto && item.produto.toLowerCase().includes(term)) || 
            (item.patrimonio && item.patrimonio.toLowerCase().includes(term))
        );
        if (filtered.length === 0) {
            container.innerHTML = emptyStateHTML('Nenhum material encontrado no estoque principal.', 'fas fa-box-open');
            return;
        }
        container.innerHTML = filtered.map(item => {
            const isSelected = itensParaAlocar.some(i => i.patrimonio === item.patrimonio);
            const selectedClasses = isSelected ? 'border-indigo-400 bg-indigo-50/70 shadow-sm' : 'border-slate-200 bg-white';
            return `<div data-patrimonio="${item.patrimonio}" data-produto-id="${item.id}" data-produto-nome="${item.produto}" data-type="alocar" class="item-card flex items-center justify-between p-3 rounded-lg border-2 ${selectedClasses} hover:border-indigo-300 cursor-pointer transition-all duration-200">
                        <div class="flex items-center gap-4">
                            <i class="fas fa-box-open text-slate-400 fa-lg"></i>
                            <div>
                                <span class="font-semibold text-slate-800">${item.produto}</span>
                                <span class="block text-xs text-slate-500">Patrimônio: ${item.patrimonio}</span>
                            </div>
                        </div>
                        <div class="w-6 h-6 rounded-full flex items-center justify-center border-2 ${isSelected ? 'border-indigo-600 bg-indigo-600' : 'border-slate-300'} transition-all duration-200">
                            ${isSelected ? '<i class="fas fa-check text-white text-xs"></i>' : ''}
                        </div>
                    </div>`;
        }).join('');
    }

    function renderItensNaTorre(torreId, setorId = null) {
        const container = document.getElementById('torres-itens-na-torre');
        if (!container) return;
        const torre = towersData.find(t => String(t.id) === String(torreId));
        let itensNaTorre = (torre && torre.itens) ? [...torre.itens] : [];
        if (setorId) {
            itensNaTorre = itensNaTorre.filter(item => String(item.setor_id) === String(setorId));
        }
        container.innerHTML = '';
        if (itensNaTorre.length === 0) {
            container.innerHTML = emptyStateHTML('Nenhum item encontrado nesta torre/setor.', 'fas fa-satellite-dish');
            return;
        }
        itensNaTorre.forEach(item => {
            const isSelected = itensParaRetirar.some(cartItem => cartItem.patrimonio === item.patrimonio);
            if (!isSelected) { 
                const itemCard = createItemCardHTML(item, 'retirar', false); 
                container.innerHTML += itemCard;
            }
        });
    }

    const renderCarrinho = (containerId, items) => { const container = document.getElementById(containerId); if (!container) return; if (items.length === 0) { container.innerHTML = `<p class="text-center text-sm text-slate-500 py-4">Nenhum item selecionado.</p>`; return; } container.innerHTML = items.map(item => `<div class="flex items-center justify-between text-sm bg-white p-2 rounded-md border"><span>${item.nome}</span><span class="font-mono text-xs text-slate-600">${item.patrimonio}</span></div>`).join(''); };
    const renderCarrinhoAlocar = () => renderCarrinho('carrinho-alocar', itensParaAlocar);
    const renderCarrinhoRetirar = () => renderCarrinho('carrinho-retirar', itensParaRetirar);

    function populateTorresSelectAlocar() {
        const select = document.getElementById('torre-alocar-select');
        if (!select) return;
        select.innerHTML = '<option value="">-- Escolha uma torre --</option>';
        if (towersData && towersData.length > 0) {
            towersData.forEach(torre => {
                select.innerHTML += `<option value="${torre.id}">${torre.nome}</option>`;
            });
        }
        select.value = "";
    }

    async function renderTotalTorres(searchTerm = '') {
        const container = document.getElementById('torres-resultado-total');
        if (!container) return;
        const term = searchTerm.trim().toLowerCase();
        const filteredTowers = towersData.filter(torre => torre.nome.toLowerCase().includes(term));

        if (filteredTowers.length === 0) {
            container.innerHTML = emptyStateHTML('Nenhuma torre encontrada para sua busca.', 'fas fa-broadcast-tower');
            return;
        }

        try {
            const CLIENT_LIMIT = clientLimit;
            container.innerHTML = filteredTowers.map(torre => {
                const totalSetores = torre.setores ? torre.setores.length : 0;
                const totalItens = torre.itens ? torre.itens.length : 0;
                const setoresHtml = (torre.setores && totalSetores > 0)
                ? `<ul class="space-y-2">${torre.setores.map(setor => {
                    const clientCount = parseInt(setor.clientes || 0, 10);
                    const clientLimitForSector = parseInt(setor.limite || CLIENT_LIMIT, 10);
                    const clientNames = setor.client_names || '';
                    
                    const nomesCodificados = encodeURIComponent(clientNames);
                    
                    // VERIFICA SE PASSOU DO LIMITE
                    const isOverLimit = clientCount >= clientLimitForSector;
                    
                    // Se passou do limite, aplica vermelho e a classe pulsate-red. Senão, fica azul.
                    const btnColorsClass = isOverLimit 
                        ? 'bg-red-100 text-red-700 hover:bg-red-200 pulsate-red shadow border border-red-300' 
                        : 'bg-indigo-100 text-indigo-700 hover:bg-indigo-200';
                    
                    const badgeClientes = clientCount > 0 
                        ? `<button onclick="window.mostrarListaClientes('${torre.nome}', '${setor.nome}', '${nomesCodificados}')" class="text-xs ${btnColorsClass} hover:shadow transition-all px-3 py-1 rounded-full font-bold cursor-pointer focus:outline-none whitespace-nowrap"><i class="fas fa-users mr-1"></i> ${clientCount} / ${clientLimitForSector}</button>`
                        : `<span class="text-xs bg-slate-100 text-slate-500 px-3 py-1 rounded-full whitespace-nowrap"><i class="fas fa-user-slash mr-1"></i> 0 / ${clientLimitForSector}</span>`;
                    
                    return `<li class="text-sm flex justify-between items-center py-1 border-b border-gray-50 last:border-0 hover:bg-gray-50 transition px-1 rounded">
                                <span class="font-medium text-slate-700 ${isOverLimit ? 'text-red-600 font-bold' : ''}">${setor.nome}</span>
                                ${badgeClientes}
                            </li>`;
                }).join('')}</ul>`
                : '<p class="text-sm text-slate-500 italic pl-4">Nenhum setor cadastrado.</p>';
                // ================================================================= 
                let itensHtml = `<p class="text-sm text-slate-500 italic pl-4">Nenhum item alocado.</p>`;
                if (totalItens > 0) {
                    const groupedBySector = (torre.itens || []).reduce((acc, item) => {
                        const sectorId = (item.setor_id == null || item.setor_id == 0) ? 'geral' : item.setor_id;
                        if (!acc[sectorId]) { acc[sectorId] = []; }
                        acc[sectorId].push(item);
                        return acc;
                    }, {});

                    let htmlContent = Object.entries(groupedBySector).map(([sectorId, itemsInGroup]) => {
                        let sectorName = 'Na Torre (Geral)';
                        if (sectorId !== 'geral') {
                            const setorInfo = (torre.setores || []).find(s => String(s.id) === String(sectorId));
                            sectorName = `Setor ${setorInfo ? setorInfo.nome : `Inválido`}`;
                        }
                        const itemsList = itemsInGroup.map(item => `<li>${item.nomeProduto} - Pat: ${item.patrimonio}</li>`).join('');
                        return `<ul class="list-disc list-inside text-sm mb-2"><strong>${sectorName}:</strong>${itemsList}</ul>`;
                    }).join('');
                    if (htmlContent) itensHtml = htmlContent;
                }

                const historicoHtml = `
                    <div class="mt-4 pt-4 border-t border-slate-200">
                        <details class="group">
                            <summary class="tower-history-summary cursor-pointer font-semibold text-indigo-600 list-none group-open:mb-2" data-torre-id="${torre.id}">
                                Ver Histórico e Observações ▸
                            </summary>
                            <div class="tower-history-content" style="display:none;">
                                <ul class="history-list space-y-2 max-h-48 overflow-y-auto pr-2"></ul>
                                <div class="mt-4">
                                    <textarea id="observation-text-${torre.id}" class="form-input w-full" rows="2" placeholder="Adicionar uma nova observação..."></textarea>
                                    <button class="add-observation-btn btn-primary mt-2 text-sm" data-torre-id="${torre.id}">Adicionar Observação</button>
                                </div>
                            </div>
                        </details>
                    </div>
                `;
                return `
                    <div class="bg-white border border-slate-200 rounded-lg shadow-md p-6 mb-4">
                        <h3 class="text-xl font-bold text-slate-800 border-b pb-3 mb-3">${torre.nome}</h3>
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div><h4 class="font-semibold text-slate-700 mb-2">Setores (${totalSetores}):</h4>${setoresHtml}</div>
                            <div><h4 class="font-semibold text-slate-700 mb-2">Itens Alocados (${totalItens}):</h4>${itensHtml}</div>
                        </div>
                        ${historicoHtml} 
                    </div>`;
            }).join('');
        } catch (error) {
            container.innerHTML = emptyStateHTML(`Erro ao carregar dados complementares: ${error.message}`, 'fas fa-exclamation-triangle');
        }
    }

    function populateTorresSelectRetirar() {
        const select = document.getElementById('torre-retirar-selecionar');
        if (!select) return;
        select.innerHTML = '<option value="">-- Escolha uma torre --</option>';
        if (towersData && towersData.length > 0) {
            towersData.forEach(torre => {
                if (torre.itens && torre.itens.length > 0) {
                    select.innerHTML += `<option value="${torre.id}">${torre.nome} (${torre.itens.length} items)</option>`;
                }
            });
        }
    }

    function renderTorresParaConfiguracao(searchTerm = '') {
        const container = document.getElementById('config-torres-list-container');
        if (!container) return;
        const term = searchTerm.trim().toLowerCase();
        const filteredTowers = towersData.filter(t => t.nome.toLowerCase().includes(term));

        if (filteredTowers.length === 0) {
            if (term) container.innerHTML = emptyStateHTML('Nenhuma torre encontrada para sua busca.', 'fas fa-question-circle');
            else container.innerHTML = emptyStateHTML('Digite o nome de uma torre para começar a gerenciar os limites dos setores.', 'fas fa-search');
            return;
        }

        let resultsHTML = '';
        filteredTowers.forEach(torre => {
            resultsHTML += `
                <div class="p-4 border rounded-lg bg-white shadow-sm mb-3">
                    <h5 class="font-bold text-indigo-700 flex items-center gap-2"><i class="fas fa-broadcast-tower"></i>${torre.nome}</h5>
                    <div class="pl-6 mt-3 text-sm text-slate-600 space-y-3">
                        ${(torre.setores && torre.setores.length > 0) ? torre.setores.map(s => `
                            <div class="flex items-center justify-between gap-2 py-1">
                                <span>- ${s.nome}</span>
                                <div class="flex items-center gap-2">
                                    <label class="text-xs">Limite:</label>
                                    <input type="number" value="${s.limite}" class="form-input p-1 w-20 text-center" id="config-limit-input-${s.id}">
                                    <button data-setor-id="${s.id}" class="save-config-limit-btn btn-primary-small text-xs px-2 py-1">Salvar</button>
                                </div>
                            </div>
                        `).join('') : '<p class="text-slate-400 italic">Nenhum setor cadastrado para esta torre.</p>'}
                    </div>
                </div>`;
        });
        container.innerHTML = resultsHTML;
    }

    function renderSectorsTags() { const container = document.getElementById('setores-tag-container'); if (!container) return; const input = document.getElementById('geral-setor-input'); container.querySelectorAll('span').forEach(tag => tag.remove()); newTowerSectors.forEach(sector => { const tagElement = document.createElement('span'); tagElement.className = 'flex items-center gap-2 bg-indigo-100 text-indigo-800 text-sm font-semibold pl-3 pr-2 py-1.5 rounded-full'; tagElement.innerHTML = `${sector} <button data-sector="${sector}" class="remove-sector-btn font-bold text-indigo-500 hover:text-indigo-800">&times;</button>`; container.insertBefore(tagElement, input); }); }
    
    // --- FUNÇÃO RESTAURADA DA ABA GERAL DAS TORRES ---
    function renderGeralSearchResults(searchTerm = '') {
        const container = document.getElementById('geral-pesquisa-resultados');
        if (!container) return;
        
        const term = searchTerm.trim().toLowerCase();
        if (!term) {
            container.innerHTML = emptyStateHTML('Digite para buscar por torres e gerenciar os setores.', 'fas fa-search');
            return;
        }

        let resultsHTML = '';
        towersData.filter(t => t.nome.toLowerCase().includes(term)).forEach(torre => {
            resultsHTML += `
                <div class="p-4 border rounded-lg bg-white shadow-sm mb-3">
                    <div class="flex items-center justify-between border-b pb-2 mb-3">
                        <h5 class="font-bold text-indigo-700 flex items-center gap-2"><i class="fas fa-broadcast-tower"></i>${torre.nome}</h5>
                        <button data-torre-id="${torre.id}" data-torre-nome="${torre.nome}" class="delete-tower-btn text-red-500 hover:text-red-700 p-2 rounded-full hover:bg-red-50 transition" title="Excluir Torre Inteira"><i class="fas fa-trash-alt"></i></button>
                    </div>
                    <div class="pl-6 text-sm text-slate-600 space-y-3">
                        ${(torre.setores && torre.setores.length > 0) ? torre.setores.map(s => `
                            <div class="flex items-center justify-between gap-2 py-1">
                                <span>- ${s.nome}</span>
                                <div class="flex items-center gap-2">
                                    <label class="text-xs">Limite:</label>
                                    <input type="number" value="${s.limite}" class="form-input p-1 w-20 text-center" id="limit-input-${s.id}">
                                    <button data-setor-id="${s.id}" class="save-limit-btn btn-primary-small text-xs px-2 py-1">Salvar</button>
                                    <button data-setor-id="${s.id}" data-setor-nome="${s.nome}" class="delete-sector-btn text-red-500 hover:text-red-700 ml-1 p-1" title="Excluir Setor"><i class="fas fa-trash"></i></button>
                                </div>
                            </div>
                        `).join('') : '<p class="text-slate-400 italic">Nenhum setor cadastrado para esta torre.</p>'}
                        <div class="flex items-center gap-2 pt-3 border-t border-dashed mt-3">
                            <input type="text" id="add-sector-input-${torre.id}" placeholder="Nome do novo setor" class="form-input p-1.5 flex-grow text-sm">
                            <button data-torre-id="${torre.id}" class="add-sector-btn btn-primary-small text-xs px-3 py-1.5">Adicionar</button>
                        </div>
                    </div>
                </div>`;
        });
        
        container.innerHTML = resultsHTML || emptyStateHTML('Nenhuma torre encontrada para o termo buscado.', 'fas fa-question-circle');
    }
    
    function handleAddSector(e) {
        if (e.key === 'Enter') {
            e.preventDefault();
            const input = e.target;
            const sectorName = input.value.replace(/^[\s-]+/, '').toUpperCase();
            if (sectorName && !newTowerSectors.includes(sectorName)) {
                newTowerSectors.push(sectorName);
                renderSectorsTags();
            }
            input.value = '';
        }
    }
    function handleRemoveSector(e) { const removeBtn = e.target.closest('.remove-sector-btn'); if (removeBtn) { const sectorToRemove = removeBtn.dataset.sector; newTowerSectors = newTowerSectors.filter(s => s !== sectorToRemove); renderSectorsTags(); } }
    
    function handleRegisterTower() {
        const btnCadastrar = document.getElementById('geral-cadastrar-btn');
        const torreNomeInput = document.getElementById('geral-torre-nome');
        const torreNome = torreNomeInput.value.trim().toUpperCase();
        
        if (!torreNome) {
            showToast('Por favor, insira um nome para a torre.', 'error');
            return;
        }

        const payload = {
            nome: torreNome,
            setores: JSON.stringify(newTowerSectors)
        };

        if (btnCadastrar) {
            btnCadastrar.disabled = true;
            btnCadastrar.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Cadastrando...';
        }

        DataService.addTorre(payload, currentUser.role)
            .then(result => {
                showToast(result.message);
                renderGeralSearchResults(torreNome);
                newTowerSectors = [];
                torreNomeInput.value = '';
                renderSectorsTags();
                renderTotalTorres(''); 
            })
            .catch(error => { 
                showToast(error.message, 'error'); 
            })
            .finally(() => {
                if (btnCadastrar) {
                    btnCadastrar.disabled = false;
                    btnCadastrar.innerHTML = '<i class="fas fa-plus"></i> Cadastrar Torre';
                }
            });
    }

    document.getElementById('geral-pesquisa-resultados')?.addEventListener('click', async (e) => {
        const addBtn = e.target.closest('.add-sector-btn');
        if (addBtn) {
            addBtn.disabled = true;
            const torreId = addBtn.dataset.torreId;
            const input = document.getElementById(`add-sector-input-${torreId}`);
            const novoSetor = input.value.replace(/^[\s-]+/, '').toUpperCase();

            if (!novoSetor) {
                showToast('O nome do novo setor não pode estar vazio.', 'error');
                addBtn.disabled = false;
                return;
            }
            try {
                const payload = { torreId, novoSetorNome: novoSetor };
                const result = await DataService.addSectorToTower(payload, currentUser.role);
                showToast(result.message);
                input.value = '';
                await fetchAllTorresData();
                renderGeralSearchResults(document.getElementById('geral-pesquisa-input').value);
            } catch (error) {
                showToast(error.message, 'error');
            } finally {
                addBtn.disabled = false;
            }
        }

        const saveBtn = e.target.closest('.save-limit-btn');
        if (saveBtn) {
            const setorId = saveBtn.dataset.setorId;
            const input = document.getElementById(`limit-input-${setorId}`);
            const novoLimite = parseInt(input.value, 10);
            if (isNaN(novoLimite) || novoLimite < 1) {
                showToast('Limite inválido.', 'error');
                return;
            }
            try {
                const result = await DataService.updateSectorLimit({ setorId, limite: novoLimite }, currentUser.role);
                showToast(result.message);
                await fetchAllTorresData(); 
            } catch (error) {
                showToast(error.message, 'error');
            }
        }

        // --- LÓGICA DE EXCLUIR SETOR ---
        const deleteSectorBtn = e.target.closest('.delete-sector-btn');
        if (deleteSectorBtn) {
            const setorId = deleteSectorBtn.dataset.setorId;
            const setorNome = deleteSectorBtn.dataset.setorNome;
            
            Swal.fire({
                title: 'Excluir Setor?',
                text: `Você tem certeza que deseja excluir o setor "${setorNome}"? Esta ação não pode ser desfeita.`,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Sim, excluir!',
                cancelButtonText: 'Cancelar'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    showGlobalLoading('Excluindo setor...');
                    try {
                        const res = await DataService.excluirSetor(setorId, currentUser.role);
                        showToast(res.message || 'Setor excluído.', 'success');
                        await fetchAllTorresData();
                        renderGeralSearchResults(document.getElementById('geral-pesquisa-input').value);
                    } catch (error) {
                        showToast(error.message, 'error');
                    } finally { hideGlobalLoading(); }
                }
            });
        }

        // --- LÓGICA DE EXCLUIR TORRE ---
        const deleteTowerBtn = e.target.closest('.delete-tower-btn');
        if (deleteTowerBtn) {
            const torreId = deleteTowerBtn.dataset.torreId;
            const torreNome = deleteTowerBtn.dataset.torreNome;
            
            Swal.fire({
                title: 'Excluir TORRE INTEIRA?',
                html: `Atenção: Você está prestes a excluir a torre <strong>${torreNome}</strong> e todos os seus setores. Tem certeza?`,
                icon: 'error',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'EXCLUIR TORRE',
                cancelButtonText: 'Cancelar'
            }).then(async (result) => {
                if (result.isConfirmed) {
                    showGlobalLoading('Excluindo torre...');
                    try {
                        const res = await DataService.excluirTorre(torreId, currentUser.role);
                        showToast(res.message || 'Torre excluída.', 'success');
                        await fetchAllTorresData();
                        renderGeralSearchResults(document.getElementById('geral-pesquisa-input').value);
                        renderTotalTorres('');
                    } catch (error) {
                        showToast(error.message, 'error');
                    } finally { hideGlobalLoading(); }
                }
            });
        }
    });

    function handleTorresItemClick(e) {
        const card = e.target.closest('.item-card');
        if (!card) return;
        const patrimonio = card.dataset.patrimonio;
        const type = card.dataset.type;
        let sourceArray = [];
        if (type === 'alocar') {
            sourceArray = mainInventory;
        } else {
            const selectedTowerId = document.getElementById('torre-retirar-selecionar')?.value;
            const selectedTower = towersData.find(t => t.id == selectedTowerId);
            sourceArray = selectedTower ? selectedTower.itens : [];
        }

        const itemData = sourceArray.find(i => i.patrimonio === patrimonio);
        if (!itemData) return;

        let targetCarrinho = type === 'alocar' ? itensParaAlocar : itensParaRetirar;
        const itemIndex = targetCarrinho.findIndex(i => i.patrimonio === patrimonio);
        if (itemIndex > -1) {
            targetCarrinho.splice(itemIndex, 1);
        } else {
            targetCarrinho.push({
                nome: itemData.nomeProduto || itemData.produto, 
                patrimonio: itemData.patrimonio,
                id: itemData.id
            });
        }
        if (type === 'alocar') {
            renderMateriaisDisponiveis(document.getElementById('torres-pesquisa-materiais')?.value);
            renderCarrinhoAlocar();
        } else {
            renderItensNaTorre(document.getElementById('torre-retirar-selecionar')?.value);
            renderCarrinhoRetirar();
        }
    }

    async function renderItensConsumiveis(searchTerm = '') {
        const container = document.getElementById('item-consumivel-lista');
        if (!container) return;
        container.innerHTML = emptyStateHTML('Carregando itens...', 'fas fa-spinner fa-spin');
        try {
            const result = await DataService.getItensConsumiveis(currentUser.role);
            const itensRecebidos = Array.isArray(result.data) ? result.data : [];
            itensConsumiveis = itensRecebidos;
            const term = searchTerm.toLowerCase();
            const filtered = itensRecebidos.filter(item => item.nome.toLowerCase().includes(term));
            if (filtered.length === 0) {
                container.innerHTML = emptyStateHTML('Nenhum item consumível cadastrado.', 'fas fa-box');
                return;
            }
            container.innerHTML = filtered.map(item =>
                `<div class="p-3 border rounded-md bg-white flex justify-between items-center">
                    <div>
                        <p class="font-semibold text-slate-700">${item.nome}</p>
                        <p class="text-xs text-slate-500">Unidade: ${item.unidade}</p>
                    </div>
                    <div class="flex items-center gap-4">
                        <div class="text-right">
                            <p class="text-lg font-bold text-teal-600">${item.quantidadeEstoque}</p>
                            <p class="text-xs text-slate-500">em estoque</p>
                        </div>
                        <button data-item-id="${item.id}" data-item-name="${item.nome}" class="recarregar-item-btn bg-blue-100 text-blue-700 hover:bg-blue-200 p-2 rounded-full h-8 w-8 flex items-center justify-center">
                            <i class="fas fa-plus"></i>
                        </button>
                    </div>
                </div>`
            ).join('');
        } catch (error) {
            container.innerHTML = emptyStateHTML(`Erro ao carregar: ${error.message}`, 'fas fa-exclamation-triangle');
        }
    }

    document.getElementById('item-consumivel-lista')?.addEventListener('click', async (e) => {
        const recarregarBtn = e.target.closest('.recarregar-item-btn');
        if (recarregarBtn) {
            const itemId = recarregarBtn.dataset.itemId;
            const itemName = recarregarBtn.dataset.itemName;
            const quantidadeStr = prompt(`Quantas unidades de "${itemName}" você deseja adicionar ao estoque?`);
            if (quantidadeStr === null) return; 

            const quantidadeAdicionada = parseInt(quantidadeStr, 10);
            if (isNaN(quantidadeAdicionada) || quantidadeAdicionada <= 0) {
                showToast('Por favor, insira uma quantidade válida e maior que zero.', 'error');
                return;
            }

            try {
                const result = await DataService.recarregarItemConsumivel({ itemId, quantidadeAdicionada }, currentUser.role);
                showToast(result.message); 
                await renderItensConsumiveis(document.getElementById('item-consumivel-pesquisa').value);
            } catch (error) {
                showToast(error.message, 'error');
            }
        }
    });
    
    async function handleCadastrarItemConsumivel() {
        const nomeInput = document.getElementById('item-consumivel-nome');
        const unidadeInput = document.getElementById('item-consumivel-unidade');
        const quantidadeInput = document.getElementById('item-consumivel-quantidade');
        const nome = nomeInput.value.trim();
        const unidade = unidadeInput.value.trim();
        const quantidadeEstoque = parseInt(quantidadeInput.value, 10);

        if (!nome || !unidade || isNaN(quantidadeEstoque) || quantidadeEstoque < 0) {
            showToast('Por favor, preencha todos os campos corretamente.', 'error');
            return;
        }

        const newItem = { nome, unidade, quantidadeEstoque };
        try {
            const result = await DataService.addItemConsumivel(newItem, currentUser.role);
            showToast(result.message || 'Item cadastrado com sucesso!');
            await renderItensConsumiveis('');
            nomeInput.value = '';
            unidadeInput.value = '';
            quantidadeInput.value = '';
        } catch(error) {
            showToast(error.message, 'error');
        }
    }

    async function populateTransferFormSelects_MANUAL() {
        const itemSelect = document.getElementById('transfer-item-select');
        if (!itemSelect) return;
        try {
            const result = await DataService.getItensConsumiveis(currentUser.role);
            itemSelect.innerHTML = '<option value="">-- Selecione um item --</option>';
            result.data.forEach(item => {
                if (item.quantidadeEstoque > 0) {
                    itemSelect.innerHTML += `<option value="${item.id}">${item.nome} (Estoque: ${item.quantidadeEstoque})</option>`;
                }
            });
        } catch (error) {
            itemSelect.innerHTML = '<option value="">Erro ao carregar itens</option>';
        }
    }

    async function handleTransferConsumable() {
        const itemId = document.getElementById('transfer-item-select').value;
        const vehicleName = document.getElementById('transfer-vehicle-select').value;
        const quantity = parseInt(document.getElementById('transfer-quantity-input').value, 10);

        if (!itemId || !vehicleName || !quantity || quantity <= 0) {
            showToast('Por favor, preencha todos os campos corretamente.', 'error');
            return;
        }

        const payload = { itemId, vehicleName, quantity };
        showGlobalLoading('Transferindo...');
        try {
            const result = await DataService.transferConsumableToVehicle(payload, currentUser.role);
            showToast(result.message, 'success');
            document.getElementById('transfer-form').reset();
            await populateTransferFormSelects_MANUAL();
        } catch (error) {
            showToast(error.message, 'error');
        } finally {
            hideGlobalLoading();
        }
    }

    async function populateConsumoUsuarioSelect() {
        const select = document.getElementById('consumo-usuario-select');
        if (!select) return;
        select.innerHTML = '<option value="">Carregando...</option>';
        try {
            const result = await DataService.getUsers(currentUser.role); 
            users = result.data;
            select.innerHTML = '<option value="">Selecione o Usuário</option>';
            users.forEach(user => {
                const option = document.createElement('option');
                option.value = user.id;
                option.textContent = user.name;
                select.appendChild(option);
            });
        } catch(error) {
            select.innerHTML = '<option value="">Erro ao carregar usuários</option>';
        }
    }

    async function populateConsumoMaterialSelect() {
        const select = document.getElementById('consumo-material-select');
        if (!select) return;
        select.innerHTML = '<option value="">Carregando...</option>';
        try {
            const result = await DataService.getItensConsumiveis(currentUser.role);
            itensConsumiveis = result.data;
            select.innerHTML = '<option value="">Selecione o Material</option>';
            itensConsumiveis.forEach(item => {
                if (item.quantidadeEstoque > 0) {
                    const option = document.createElement('option');
                    option.value = item.id;
                    option.textContent = `${item.nome} (Estoque: ${item.quantidadeEstoque})`;
                    select.appendChild(option);
                }
            });
        } catch(error) {
             select.innerHTML = '<option value="">Erro ao carregar materiais</option>';
        }
    }

    async function handleRegistrarConsumo() {
        const usuarioSelect = document.getElementById('consumo-usuario-select');
        const materialSelect = document.getElementById('consumo-material-select');
        const quantidadeInput = document.getElementById('consumo-quantidade-input');

        const usuarioId = parseInt(usuarioSelect.value, 10);
        const itemId = parseInt(materialSelect.value, 10);
        const quantidadeConsumida = parseInt(quantidadeInput.value, 10);
        
        const item = itensConsumiveis.find(i => i.id == itemId);

        if (!usuarioId || !itemId || isNaN(quantidadeConsumida) || quantidadeConsumida <= 0) {
            showToast('Por favor, preencha todos os campos.', 'error');
            return;
        }
        if (quantidadeConsumida > item.quantidadeEstoque) {
            showToast(`Quantidade insuficiente em estoque. Disponível: ${item.quantidadeEstoque}`, 'error');
            return;
        }

        const consumoData = { itemId, quantidadeConsumida, usuarioId };

        try {
            const result = await DataService.registrarConsumo(consumoData, currentUser.role);
            showToast(result.message || 'Consumo registrado com sucesso!');
            quantidadeInput.value = '';
            materialSelect.value = '';
            await populateConsumoMaterialSelect(); 
            await renderItensConsumiveis(''); 
        } catch(error) {
            showToast(error.message, 'error');
        }
    }
    
    async function handleAlocarItens() {
        const torreSelect = document.getElementById('torre-alocar-select');
        const setorSelect = document.getElementById('setor-alocar-selecionar'); 
        const torreId = torreSelect.value;
        const setorId = setorSelect.value; 

        if (!torreId || itensParaAlocar.length === 0) {
            showToast('Selecione uma torre e adicione itens para alocar.', 'error');
            return;
        }

        showGlobalLoading('Alocando itens...');
        const patrimonios = itensParaAlocar.map(item => item.patrimonio);
        const payload = { torreId, setorId: setorId || null, patrimonios: JSON.stringify(patrimonios) };

        try {
            const result = await DataService.alocarItemTorre(payload, currentUser.role);
            showToast(result.message);
            itensParaAlocar = [];
            renderCarrinhoAlocar();
            await fetchAllTorresData(); 
            renderMateriaisDisponiveis('');
            renderTotalTorres('');
        } catch (error) {
            showToast(error.message, 'error');
        } finally {
            hideGlobalLoading();
        }
    }

    async function handleRetirarItens() {
        if (itensParaRetirar.length === 0) {
            showToast('Nenhum item selecionado para retirada.', 'error');
            return;
        }
        showGlobalLoading('Retirando itens...');
        const patrimonios = itensParaRetirar.map(item => item.patrimonio);
        try {
            const result = await DataService.retirarItemTorre({ patrimonios: JSON.stringify(patrimonios) }, currentUser.role);
            showToast(result.message);
            itensParaRetirar = [];
            renderCarrinhoRetirar();
            await fetchAllTorresData();
            const torreId = document.getElementById('torre-retirar-selecionar').value;
            renderItensNaTorre(torreId);
            populateTorresSelectRetirar();
        } catch (error) {
            showToast(error.message, 'error');
        } finally {
            hideGlobalLoading();
        }
    }

    async function renderRelatorioConsumo(searchTerm = '') {
        const tbody = document.getElementById('consumo-relatorio-tbody');
        if (!tbody) return;
        tbody.innerHTML = `<tr><td colspan="4">${emptyStateHTML('Carregando histórico...', 'fas fa-spinner fa-spin')}</td></tr>`;
        try {
            const today = new Date();
            const result = await DataService.getHistoricoConsumo({ month: today.getMonth() + 1, year: today.getFullYear() }, currentUser.role);
            const historicoConsumo = Array.isArray(result.data) ? result.data : [];
            const term = searchTerm.toLowerCase();
            const filteredLogs = historicoConsumo.filter(log =>
                (log.usuario_nome && log.usuario_nome.toLowerCase().includes(term)) ||
                (log.item_nome && log.item_nome.toLowerCase().includes(term)) ||
                (log.data_consumo_formatada && log.data_consumo_formatada.includes(term))
            );
            if (filteredLogs.length === 0) {
                tbody.innerHTML = `<tr><td colspan="4">${emptyStateHTML('Nenhum registro encontrado para este mês.', 'fas fa-file-alt')}</td></tr>`;
                return;
            }
            const groupedByUser = filteredLogs.reduce((acc, log) => {
                const userName = log.usuario_nome;
                if (!acc[userName]) { acc[userName] = []; }
                acc[userName].push(log);
                return acc;
            }, {});
            tbody.innerHTML = Object.entries(groupedByUser).flatMap(([userName, logs]) => 
                logs.map((log, index) => 
                    `<tr class="hover:bg-slate-50">
                        ${index === 0 ? `<td class="px-6 py-4 whitespace-nowrap text-sm text-slate-800 font-medium align-top" rowspan="${logs.length}">${userName}</td>` : ''}
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-500">${log.data_consumo_formatada || 'N/A'}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-800">${log.item_nome || 'N/A'}</td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-800 font-bold">${log.quantidade_consumida || '0'}</td>
                    </tr>`
                ).join('')
            ).join('');
        } catch (error) {
             tbody.innerHTML = `<tr><td colspan="4">${emptyStateHTML(`Erro ao carregar: ${error.message}`, 'fas fa-exclamation-triangle')}</td></tr>`;
        }
    }

    async function handleVeiculoSelectionChange(e) {
        const selectElement = e.target || document.getElementById('combustivel-veiculo-select');
        const vehicleName = selectElement.value; 
        const formContainer = document.getElementById('combustivel-form-container');
        const prompt = document.getElementById('combustivel-prompt-selecao');
        const alerta = document.getElementById('combustivel-alerta-primeiro-registro');
        const calculadoInput = document.getElementById('combustivel-calculado'); 
        const hodometroInput = document.getElementById('combustivel-hodometro');
        
        if (calculadoInput) calculadoInput.value = '-- Km/L';

        if (vehicleName) {
            if(formContainer) formContainer.classList.remove('hidden');
            if(prompt) prompt.classList.add('hidden');
            
            try {
                showGlobalLoading('Buscando histórico...');
                const result = await DataService.getHistoricoCombustivel(currentUser.role);
                const allFuelLogs = result.data || [];
                const vehicleLogs = allFuelLogs
                    .filter(log => log.veiculo_nome === vehicleName)
                    .sort((a, b) => parseInt(b.hodometro) - parseInt(a.hodometro)); 

                if (vehicleLogs.length === 0) {
                    if(alerta) {
                        alerta.innerHTML = `Primeiro registro para <strong>${vehicleName}</strong>.`;
                        alerta.classList.remove('hidden');
                    }
                    if(hodometroInput) hodometroInput.value = ''; 
                } else {
                    if(alerta) alerta.classList.add('hidden');
                    const ultimoHodometro = vehicleLogs[0].hodometro;
                    if(hodometroInput) hodometroInput.value = ultimoHodometro;
                }
                const dataInput = document.getElementById('combustivel-data');
                if(dataInput && !dataInput.value) dataInput.valueAsDate = new Date();
            } catch (error) {
                console.error(error);
                showToast('Erro ao buscar histórico.', 'error');
            } finally {
                hideGlobalLoading();
            }
        } else {
            if(formContainer) formContainer.classList.add('hidden');
            if(prompt) prompt.classList.remove('hidden');
            if(alerta) alerta.classList.add('hidden');
        }
    }

    async function handleRegistrarAbastecimento() {
        const veiculoNome = document.getElementById('combustivel-veiculo-select').value;
        const data = document.getElementById('combustivel-data').value;
        const hodometro = parseInt(document.getElementById('combustivel-hodometro').value, 10);
        const litros = parseFloat(document.getElementById('combustivel-litros').value.replace(',', '.'));
        const valor = parseFloat(document.getElementById('combustivel-valor').value.replace(',', '.'));
        
        if (!veiculoNome || !data || isNaN(hodometro) || isNaN(litros) || isNaN(valor) || hodometro <= 0 || litros <= 0 || valor <= 0) {
            showToast('Por favor, preencha todos os campos com valores válidos.', 'error');
            return;
        }

        const payload = { veiculoNome, data, hodometro, litros, valor };

        showGlobalLoading('Registrando abastecimento...');
        try {
            const result = await DataService.addAbastecimento(payload, currentUser.role);
            showToast(result.message);
            document.getElementById('combustivel-hodometro').value = '';
            document.getElementById('combustivel-litros').value = '';
            document.getElementById('combustivel-valor').value = '';
            document.getElementById('combustivel-calculado').value = '-- Km/L';
            if (!document.getElementById('section-combustivel-historico').classList.contains('hidden')) {
                await renderHistoricoCombustivel('');
            }
            await handleVeiculoSelectionChange({ target: document.getElementById('combustivel-veiculo-select') });
        } catch (error) {
            showToast(error.message, 'error');
        } finally {
            hideGlobalLoading();
        }
    }    

    async function renderHistoricoCombustivel(searchTerm = '') {
        const tbody = document.getElementById('combustivel-historico-tbody');
        if (!tbody) return;
        tbody.innerHTML = `<tr><td colspan="6">${emptyStateHTML('Carregando histórico...', 'fas fa-spinner fa-spin')}</td></tr>`;
        
        try {
            const result = await DataService.getHistoricoCombustivel(currentUser.role);
            const historicoAbastecimentos = result.data;
            const consumoMap = new Map();

            const historicoPorVeiculo = historicoAbastecimentos.reduce((acc, log) => {
                const veiculoId = log.veiculo_id || log.veiculo_nome; 
                if (!acc[veiculoId]) acc[veiculoId] = [];
                acc[veiculoId].push(log);
                return acc;
            }, {});

            for (const veiculoId in historicoPorVeiculo) {
                const logsDoVeiculo = historicoPorVeiculo[veiculoId].sort((a, b) => parseInt(a.hodometro) - parseInt(b.hodometro));
                for (let i = 0; i < logsDoVeiculo.length - 1; i++) {
                    const atual = logsDoVeiculo[i];
                    const proximo = logsDoVeiculo[i + 1];
                    const distancia = proximo.hodometro - atual.hodometro;
                    const litrosGastos = parseFloat(atual.litros); 
                    if (distancia > 0 && litrosGastos > 0) {
                       const consumo = (distancia / litrosGastos).toFixed(2);
                       consumoMap.set(atual.id, consumo);
                    }
                }
            }

            const term = searchTerm.toLowerCase();
            const filtered = historicoAbastecimentos.filter(log =>
                log.veiculo_nome.toLowerCase().includes(term) ||
                log.data_formatada.includes(term)
            );
            
            const displayList = filtered.sort((a, b) => new Date(b.data_abastecimento) - new Date(a.data_abastecimento) || b.hodometro - a.hodometro);

            if (displayList.length === 0) {
                tbody.innerHTML = `<tr><td colspan="6">${emptyStateHTML('Nenhum histórico encontrado.', 'fas fa-file-invoice-dollar')}</td></tr>`;
                return;
            }

            tbody.innerHTML = displayList.map(log => {
                const consumoKm_L = consumoMap.get(log.id) || 'N/A';
                return `<tr class="hover:bg-slate-50">
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-500">${log.data_formatada}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm font-semibold text-slate-800">${log.veiculo_nome}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-800">${parseInt(log.hodometro).toLocaleString('pt-BR')} Km</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-800">${parseFloat(log.litros).toFixed(2)} L</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-800 font-medium">R$ ${parseFloat(log.valor_total).toFixed(2)}</td>
                            <td class="px-6 py-4 whitespace-nowrap text-sm text-slate-800 font-bold">${consumoKm_L}</td>
                        </tr>`;
            }).join('');
        } catch (error) {
            tbody.innerHTML = `<tr><td colspan="6">${emptyStateHTML(`Erro ao carregar: ${error.message}`, 'fas fa-times-circle')}</td></tr>`;
        }
    }

    function updateFloatingLabel(inputElement) {
        if (!inputElement) return;
        const group = inputElement.closest('.floating-label-group');
        if (!group) return;
        if (inputElement.value && inputElement.value !== "") {
            group.classList.add('has-value');
        } else {
            group.classList.remove('has-value');
        }
    }

    document.querySelectorAll('.floating-label-input').forEach(element => {
        element.addEventListener('change', (e) => updateFloatingLabel(e.target));
        element.addEventListener('input', (e) => updateFloatingLabel(e.target));
        updateFloatingLabel(element);
    });

    // ======================================================================
    // MÁGICA: FUNÇÕES DE TROCA DE ABAS EXPOSTAS PARA O WINDOW
    // ======================================================================

    window.switchTorresTab = function(activeTabName) {
        document.querySelectorAll('#section-torres-alocar, #section-torres-retirar, #section-torres-total, #section-torres-geral').forEach(section => {
            section.classList.add('hidden');
        });
        document.querySelectorAll('.torres-tab').forEach(tab => {
            const isActive = tab.dataset.tab === activeTabName;
            tab.className = `torres-tab flex items-center gap-2 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-all duration-200 ${isActive ? 'text-indigo-600 border-indigo-500' : 'text-slate-500 border-transparent hover:text-slate-700 hover:border-slate-300'}`;
        });
        const activeSection = document.getElementById(`section-torres-${activeTabName}`);
        if (activeSection) {
            activeSection.classList.remove('hidden');
        }

        if (activeTabName === 'alocar') { 
            itensParaAlocar = []; 
            renderMateriaisDisponiveis(''); 
            renderCarrinhoAlocar();
            populateTorresSelectAlocar(); 
        }
        if (activeTabName === 'retirar') { 
            itensParaRetirar = []; 
            populateTorresSelectRetirar(); 
            renderItensNaTorre(document.getElementById('torre-retirar-selecionar')?.value); 
            renderCarrinhoRetirar(); 
        }
        if (activeTabName === 'total') {
            const totalSearchInput = document.getElementById('torres-pesquisa-total');
            if (totalSearchInput) totalSearchInput.value = '';
            renderTotalTorres(''); 
        }
        if (activeTabName === 'geral') { 
            newTowerSectors = []; 
            const torreNomeInput = document.getElementById('geral-torre-nome'); 
            if(torreNomeInput) torreNomeInput.value = ''; 
            const setorInput = document.getElementById('geral-setor-input'); 
            if(setorInput) setorInput.value = ''; 
            renderSectorsTags(); 
            renderGeralSearchResults(''); 
        }
        configureModalPermissions();
    };

    window.switchConsumoTab = async function(activeTabName) {
        document.querySelectorAll('.consumo-tab').forEach(tab => {
            tab.className = `consumo-tab flex items-center gap-2 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-all duration-200 ${tab.dataset.tab === activeTabName ? 'text-teal-500 border-teal-500' : 'text-slate-500 border-transparent hover:text-slate-700 hover:border-slate-300'}`;
        });
        ['registrar', 'relatorio', 'cadastrar', 'transferir'].forEach(tab => {
            const section = document.getElementById(`section-consumo-${tab}`);
            if (section) section.classList.toggle('hidden', tab !== activeTabName);
        });

        if (activeTabName === 'cadastrar') { await renderItensConsumiveis(''); }
        if (activeTabName === 'registrar') { await populateConsumoUsuarioSelect(); await populateConsumoMaterialSelect(); }
        if (activeTabName === 'relatorio') { await renderRelatorioConsumo(''); }
        if (activeTabName === 'transferir') { await populateTransferFormSelects_MANUAL(); }
    };

    window.switchCombustivelTab = async function(activeTabName) {
        document.querySelectorAll('.combustivel-tab').forEach(tab => {
            const isActive = tab.dataset.tab === activeTabName;
            tab.className = `combustivel-tab flex items-center gap-2 whitespace-nowrap py-4 px-1 border-b-2 font-medium text-sm transition-all duration-200 ${isActive ? 'text-zinc-600 border-zinc-600' : 'text-slate-500 border-transparent hover:text-slate-700 hover:border-slate-300'}`;
        });
        ['registrar', 'historico'].forEach(tab => {
            const section = document.getElementById(`section-combustivel-${tab}`);
            if (section) section.classList.toggle('hidden', tab !== activeTabName);
        });

        if (activeTabName === 'registrar') {
            const select = document.getElementById('combustivel-veiculo-select');
            const formContainer = document.getElementById('combustivel-form-container');
            const prompt = document.getElementById('combustivel-prompt-selecao');

            if (select) {
                select.removeEventListener('change', handleVeiculoSelectionChange); 
                select.addEventListener('change', handleVeiculoSelectionChange);

                if (select.value) {
                    if(formContainer) formContainer.classList.remove('hidden');
                    if(prompt) prompt.classList.add('hidden');
                    handleVeiculoSelectionChange({ target: select });
                } else {
                    if(formContainer) formContainer.classList.add('hidden');
                    if(prompt) prompt.classList.remove('hidden');
                }
            }
        }
        if (activeTabName === 'historico') {
            if (typeof renderHistoricoCombustivel === 'function') {
                await renderHistoricoCombustivel('');
            }
        }
    };


    // =========================================================
    // === SISTEMA DE MODAIS (REFEITO E INFALÍVEL) ===
    // =========================================================

    // 1. Função Global e Imediata de Abertura
    window.abrirModalGenerico = async function(modalId) {
        console.log(`[AÇÃO] Forçando abertura do modal: ${modalId}`);
        const modal = document.getElementById(modalId);
        
        if (!modal) {
            console.error(`Erro: Modal ${modalId} não existe no HTML.`);
            return;
        }

        // Abre na hora (Visual primeiro)
        modal.classList.remove('hidden');
        modal.style.display = 'flex';
        document.body.classList.add('overflow-hidden');

        // Mostra loading
        if (modalId !== 'comunicacao-modal') {
            showGlobalLoading('Carregando dados...');
        }

        // Aguarda os dados
        try {
            if (modalId === 'modal-torres') {
                const towersResult = await DataService.getTowers(currentUser.role);
                towersData = towersResult.data || [];
                try {
                    const invResult = await DataService.getInventory(currentUser.role);
                    mainInventory = invResult.data || [];
                } catch (e) { mainInventory = []; }
                if (typeof window.switchTorresTab === 'function') window.switchTorresTab('alocar');
            } 
            else if (modalId === 'modal-consumo') {
                if (typeof populateAllVehicleSelects === 'function') populateAllVehicleSelects();
                if (typeof window.switchConsumoTab === 'function') await window.switchConsumoTab('registrar');
            }
            else if (modalId === 'modal-combustivel') {
                if (typeof populateAllVehicleSelects === 'function') populateAllVehicleSelects();
                if (typeof window.switchCombustivelTab === 'function') await window.switchCombustivelTab('registrar');
            }
            else if (modalId === 'modal-configuracoes') {
                const result = await DataService.getTowers(currentUser.role);
                towersData = result.data || [];
                if (typeof renderTorresParaConfiguracao === 'function') renderTorresParaConfiguracao('');
            } 
            else if (modalId === 'modal-seguranca') {
                if (typeof renderSafetyStockEditor === 'function') await renderSafetyStockEditor();
            } 
            else if (modalId === 'comunicacao-modal') {
                if (typeof openComunicacaoModal === 'function') await openComunicacaoModal();
            }
            else if (modalId === 'password-recovery-modal') {
                 if (typeof openPasswordRecoveryModal === 'function') openPasswordRecoveryModal();
            }
        } catch (err) {
            console.error("Erro interno ao carregar dados do modal:", err);
        } finally {
            hideGlobalLoading();
        }
    };

    function checkUrlForModal() {
        const urlParams = new URLSearchParams(window.location.search);
        const modalToOpen = urlParams.get('open_modal');
        const validModals = ['modal-torres', 'modal-consumo', 'modal-combustivel', 'modal-seguranca', 'modal-configuracoes', 'comunicacao-modal', 'password-recovery-modal'];
        if (modalToOpen && validModals.includes(modalToOpen)) {
            window.abrirModalGenerico(modalToOpen);
        }
    }

    // 2. Controlador Único de Fechamento (Para X e Fundo Escuro)
    document.addEventListener('click', (e) => {
        // A. Clicou em qualquer botão de fechar (X)?
        const btnFechar = e.target.closest('.modal-close-button') || 
                          e.target.closest('#comunicacao-modal-close-button') || 
                          e.target.closest('#close-recovery-modal-btn');
                          
        if (btnFechar) {
            e.preventDefault();
            const modal = btnFechar.closest('.modal-overlay') || btnFechar.closest('.fixed.inset-0') || btnFechar.closest('#comunicacao-modal');
            if (modal) {
                modal.classList.add('hidden');
                modal.style.display = 'none';
                document.body.classList.remove('overflow-hidden');
            }
        }
        
        // B. Clicou fora do modal (no fundo escuro)?
        if (e.target.classList.contains('modal-overlay') || 
            e.target.id === 'comunicacao-modal' || 
            e.target.id === 'password-recovery-modal') {
            
            e.target.classList.add('hidden');
            e.target.style.display = 'none';
            document.body.classList.remove('overflow-hidden');
        }
    });

    // Eventos remanescentes dos modais antigos (agora são opcionais, o html comanda)
    document.getElementById('torres-materiais-disponiveis')?.addEventListener('click', handleTorresItemClick);
    document.getElementById('torres-itens-na-torre')?.addEventListener('click', handleTorresItemClick);
    document.getElementById('torres-resultado-total')?.addEventListener('click', e => { const header = e.target.closest('.accordion-header'); if (header) { const content = header.nextElementSibling; header.querySelector('.fa-chevron-down').classList.toggle('rotate-180'); content.style.maxHeight = content.style.maxHeight ? null : content.scrollHeight + "px"; } });
    document.getElementById('geral-setor-input')?.addEventListener('keyup', handleAddSector);
    document.getElementById('setores-tag-container')?.addEventListener('click', e => { handleRemoveSector(e); document.getElementById('geral-setor-input')?.focus(); });
    document.getElementById('geral-cadastrar-btn')?.addEventListener('click', handleRegisterTower);
    document.getElementById('geral-pesquisa-input')?.addEventListener('keyup', e => renderGeralSearchResults(e.target.value));
    document.getElementById('torres-pesquisa-materiais')?.addEventListener('keyup', e => renderMateriaisDisponiveis(e.target.value));
    document.getElementById('torres-pesquisa-total')?.addEventListener('keyup', e => renderTotalTorres(e.target.value));
    document.getElementById('alocar-itens-btn')?.addEventListener('click', handleAlocarItens);
    document.addEventListener('click', function(e) {if (e.target && e.target.id === 'retirar-itens-btn') {handleRetirarItens();}});
    
    document.getElementById('item-consumivel-adicionar-btn')?.addEventListener('click', handleCadastrarItemConsumivel);
    document.getElementById('item-consumivel-pesquisa')?.addEventListener('keyup', (e) => renderItensConsumiveis(e.target.value));
    document.getElementById('consumo-registrar-btn')?.addEventListener('click', handleRegistrarConsumo);
    document.getElementById('consumo-relatorio-pesquisa')?.addEventListener('keyup', (e) => renderRelatorioConsumo(e.target.value));
    document.getElementById('transfer-consumable-btn')?.addEventListener('click', handleTransferConsumable);
    
    document.getElementById('combustivel-veiculo-select')?.addEventListener('change', handleVeiculoSelectionChange);
    document.getElementById('combustivel-registrar-btn')?.addEventListener('click', handleRegistrarAbastecimento);
    document.getElementById('combustivel-historico-pesquisa')?.addEventListener('keyup', e => renderHistoricoCombustivel(e.target.value));
    

    // 3. Inicialização em Background e Limpeza Final
    console.log("🚀 Iniciando sistema remodelado...");
    loadVehicleData().then(() => {
        if(typeof populateAllVehicleSelects === 'function') populateAllVehicleSelects();
    }).catch(e => console.warn(e));
    
    checkUrlForModal();

}); // <--- FIM DO ARQUIVO (Fechamento do DOMContentLoaded)