// Estado global do aplicativo
let roomsList = [];
let activeRoomId = null;
let currentSlideIndex = 0;
let mapEditor = null;
let viewer3D = null;

// Estados para Mapeamento Multibloco
let activeBlock = "Bloco C";
let activeBlockFilter = "all";
let activeStatusFilter = "all";

// Caminhos padrões para as plantas baixas geradas a partir dos PDFs
const blockMaps = {
  "Bloco C": "bloco_c_terreo.png",
  "Bloco E - Térreo": "bloco_e.png",
  "Bloco E - Superior": "bloco_e.png" // Usa bloco_e.png como base até que uma específica seja carregada
};

// Inicialização ao carregar a página
document.addEventListener('DOMContentLoaded', () => {
  // Instanciar o Editor de Mapa
  mapEditor = new MapEditor('map-container', 'map-svg', 'map-image');
  
  // Instanciar o Visualizador 3D
  viewer3D = new Viewer3D('container-3d', 'threed-empty-state');

  // Registrar Callbacks no Editor de Mapa
  mapEditor.onSelectRoomCallback = (roomId) => {
    openRoomDetails(roomId);
  };
  
  mapEditor.onUpdateRoomsCallback = (updatedRoom) => {
    // Salvar alterações de polígono no servidor
    saveRoomPolygon(updatedRoom.id, updatedRoom.polygon);
  };

  // Carregar dados das salas
  fetchRooms();

  // Registrar Ouvintes de Eventos da UI
  initUIEvents();
  
  // Inicializar controles de zoom e arrastar (pan) no mapa 2D
  initMapZoomAndPan();
});

// ==========================================================================
// COMUNICAÇÃO COM A API (BACKEND LOCAL)
// ==========================================================================

// Buscar lista de salas do servidor
async function fetchRooms() {
  try {
    const response = await fetch('/api/rooms');
    if (!response.ok) throw new Error("Erro ao buscar dados do servidor");
    
    roomsList = await response.json();
    
    // Inicializar visualização
    updateDashboardStats();
    applySearchAndFilter();
    
    // Iniciar no Bloco C
    switchActiveBlock("Bloco C");

  } catch (error) {
    console.error("Erro na requisição:", error);
    document.getElementById('rooms-grid').innerHTML = `
      <div class="loading-spinner" style="color: var(--status-maintenance-text)">
        <i class="fa-solid fa-triangle-exclamation"></i>
        <span>Erro ao conectar ao servidor local. Verifique se o Node.js está rodando.</span>
      </div>
    `;
  }
}

// Salvar dados editados da sala no servidor
async function saveRoomDetails(roomId, updatedData) {
  try {
    const response = await fetch(`/api/rooms/${roomId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updatedData)
    });
    
    if (!response.ok) throw new Error("Erro ao salvar dados");
    
    const result = await response.json();
    
    // Atualizar lista local
    const index = roomsList.findIndex(r => r.id === roomId);
    if (index !== -1) {
      roomsList[index] = result.room;
    }
    
    // Sincronizar componentes e filtros
    updateDashboardStats();
    applySearchAndFilter();
    
    // Atualizar visualização do bloco atual
    switchActiveBlock(activeBlock);
    
    closeRoomDetails();
    
  } catch (error) {
    console.error("Erro ao salvar sala:", error);
    alert("Não foi possível salvar as alterações no disco.");
  }
}

// Salvar apenas as coordenadas do hotspot
async function saveRoomPolygon(roomId, polygon) {
  try {
    const response = await fetch(`/api/rooms/${roomId}`, {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ polygon })
    });
    
    if (response.ok) {
      const result = await response.json();
      // Atualizar lista local
      const index = roomsList.findIndex(r => r.id === roomId);
      if (index !== -1) {
        roomsList[index].polygon = polygon;
      }
      
      // Atualizar barra lateral e maquete 3D do bloco ativo
      const blockRooms = roomsList.filter(r => r.block === activeBlock);
      renderSidebarRoomsList(blockRooms);
      viewer3D.updateScene(blockRooms);
    }
  } catch (error) {
    console.error("Erro ao salvar polígono:", error);
  }
}

// ==========================================================================
// CONTROLE DE FLUXO DE BLOCOS (MULTIBLOCO)
// ==========================================================================

// Alternar entre blocos/pavimentos
function switchActiveBlock(blockName) {
  activeBlock = blockName;

  // Atualizar visual dos botões de abas do mapa (Tanto no 2D quanto no 3D)
  const mapTabButtons = document.querySelectorAll('#map-tabs .filter-btn, #map-tabs-3d .filter-btn');
  mapTabButtons.forEach(btn => {
    if (btn.dataset.map === blockName) {
      btn.classList.add('active');
    } else {
      btn.classList.remove('active');
    }
  });

  // Atualizar planta baixa exibida
  const storageKey = `mochilao_map_data_${activeBlock.replace(/\s+/g, '_').toLowerCase()}`;
  const savedMap = localStorage.getItem(storageKey);
  const mapImg = document.getElementById('map-image');

  if (savedMap) {
    mapImg.src = savedMap;
    document.getElementById('map-empty-state').style.display = 'none';
    document.getElementById('map-wrapper').style.display = 'inline-block';
    document.getElementById('editor-controls').style.display = 'flex';
  } else {
    // Tentar carregar mapa padrão pré-configurado
    const defaultMap = blockMaps[activeBlock];
    if (defaultMap) {
      mapImg.src = defaultMap;
      document.getElementById('map-empty-state').style.display = 'none';
      document.getElementById('map-wrapper').style.display = 'inline-block';
      document.getElementById('editor-controls').style.display = 'flex';
    } else {
      // Estado vazio se não houver mapa
      mapImg.src = "";
      document.getElementById('map-empty-state').style.display = 'flex';
      document.getElementById('map-wrapper').style.display = 'none';
      document.getElementById('editor-controls').style.display = 'none';
    }
  }

  // Garantir redimensionamento após o carregamento da imagem
  mapImg.onload = () => {
    setTimeout(() => {
      mapEditor.handleResize();
      resetMapZoomAndPan(); // Centralizar e resetar o zoom ao carregar novo mapa
    }, 100);
  };

  // Filtrar dados das salas deste bloco
  const blockRooms = roomsList.filter(r => r.block === activeBlock);

  // Atualizar o Quadro de Resumo de Informações
  updateBlockSummary(blockName, blockRooms);

  // Renderizar lista lateral de salas
  renderSidebarRoomsList(blockRooms);

  // Atualizar seletores de salas específicos desse bloco no editor
  populateRoomSelectors();

  // Filtrar e exibir hotspots apenas deste bloco no SVG
  mapEditor.setRooms(blockRooms);

  // Recarregar a cena 3D apenas para as salas do bloco ativo
  if (viewer3D) {
    viewer3D.updateScene(blockRooms);
  }
}

// Calcular e atualizar os dados do painel de informações do bloco
function updateBlockSummary(blockName, blockRooms) {
  // Títulos
  document.getElementById('summary-block-title').textContent = blockName;
  document.getElementById('summary-block-title-3d').textContent = blockName;

  // 1. Área Total Útil
  const totalArea = blockRooms.reduce((sum, r) => {
    const area = r.dimensions && r.dimensions.area ? parseFloat(r.dimensions.area) : 0;
    return sum + area;
  }, 0);

  document.getElementById('summary-total-area').textContent = `${totalArea.toFixed(1)} m²`;
  document.getElementById('summary-total-area-3d').textContent = `${totalArea.toFixed(1)} m²`;

  // 2. Salas e Labs (Contar salas excluindo corredores/acessos)
  const circulationKeywords = ["corredor", "escada", "acesso", "entrada", "hall", "outros", "refeitório"];
  const roomsOnly = blockRooms.filter(r => {
    const nameLower = r.name.toLowerCase();
    return !circulationKeywords.some(kw => nameLower.includes(kw));
  });

  document.getElementById('summary-rooms-count').textContent = roomsOnly.length;
  document.getElementById('summary-rooms-count-3d').textContent = roomsOnly.length;

  // 3. Acessos/Circulação (Contar corredores/acessos)
  const accessesOnly = blockRooms.filter(r => {
    const nameLower = r.name.toLowerCase();
    return circulationKeywords.some(kw => nameLower.includes(kw));
  });

  const accessText = `${accessesOnly.length} locais`;
  document.getElementById('summary-accesses-count').textContent = accessText;
  document.getElementById('summary-accesses-count-3d').textContent = accessText;
}

// Renderizar a lista lateral de salas nas abas 2D e 3D
function renderSidebarRoomsList(blockRooms) {
  const list2d = document.getElementById('sidebar-rooms-list-2d');
  const list3d = document.getElementById('sidebar-rooms-list-3d');

  list2d.innerHTML = '';
  list3d.innerHTML = '';

  if (blockRooms.length === 0) {
    const emptyMsg = '<div style="color: var(--text-muted); font-size: 12px; padding: 12px; text-align: center;">Nenhuma sala cadastrada</div>';
    list2d.innerHTML = emptyMsg;
    list3d.innerHTML = emptyMsg;
    return;
  }

  // Ordenar alfabeticamente
  const sortedRooms = [...blockRooms].sort((a, b) => a.name.localeCompare(b.name));

  sortedRooms.forEach(room => {
    const areaText = room.dimensions && room.dimensions.area ? `${room.dimensions.area.toFixed(1)} m²` : '-- m²';
    const isSelected = room.id === activeRoomId;

    const coursesText = room.courses 
      ? `<span class="room-item-courses" style="font-size: 10px; color: var(--accent-color); display: block; margin-top: 2px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 180px;" title="${room.courses}"><i class="fa-solid fa-graduation-cap" style="margin-right: 4px;"></i>${room.courses}</span>` 
      : '';

    // Item para Lista 2D
    const item2d = document.createElement('div');
    item2d.className = `sidebar-room-item ${isSelected ? 'active' : ''}`;
    item2d.dataset.id = room.id;
    item2d.innerHTML = `
      <div class="room-item-info">
        <span class="room-item-name" title="${room.name}">${room.name}</span>
        <span class="room-item-meta">${areaText} • Cap: ${room.capacity || '--'}</span>
        ${coursesText}
      </div>
      <div class="room-item-actions">
        <div class="room-item-indicator ${room.polygon ? 'mapped' : 'unmapped'}" title="${room.polygon ? 'Sala já mapeada no mapa' : 'Ainda não mapeada'}">
          <i class="fa-solid ${room.polygon ? 'fa-circle-check' : 'fa-circle-question'}"></i>
        </div>
        <button class="btn-action-sm btn-edit-room" title="Ver detalhes/Editar"><i class="fa-solid fa-pen-to-square"></i></button>
        <button class="btn-action-sm btn-map-room" title="Desenhar limites no mapa"><i class="fa-solid fa-pen-ruler"></i></button>
      </div>
    `;

    // Item para Lista 3D
    const item3d = document.createElement('div');
    item3d.className = `sidebar-room-item ${isSelected ? 'active' : ''}`;
    item3d.dataset.id = room.id;
    item3d.innerHTML = `
      <div class="room-item-info" style="width: calc(100% - 45px);">
        <span class="room-item-name" title="${room.name}">${room.name}</span>
        <span class="room-item-meta">${areaText} • Cap: ${room.capacity || '--'}</span>
        ${coursesText}
      </div>
      <div class="room-item-actions">
        <div class="room-item-indicator ${room.polygon ? 'mapped' : 'unmapped'}" title="${room.polygon ? 'Maquete 3D disponível' : 'Sem limites 3D'}">
          <i class="fa-solid ${room.polygon ? 'fa-circle-check' : 'fa-circle-question'}"></i>
        </div>
        <button class="btn-action-sm btn-edit-room" title="Ver detalhes/Editar"><i class="fa-solid fa-pen-to-square"></i></button>
      </div>
    `;

    // Evento de clique para abrir os detalhes
    const handleSelect = (e) => {
      e.stopPropagation();
      openRoomDetails(room.id);
    };

    item2d.addEventListener('click', handleSelect);
    item3d.addEventListener('click', handleSelect);

    item2d.querySelector('.btn-edit-room').addEventListener('click', handleSelect);
    item3d.querySelector('.btn-edit-room').addEventListener('click', handleSelect);

    // Evento específico do botão de desenho 2D
    item2d.querySelector('.btn-map-room').addEventListener('click', (e) => {
      e.stopPropagation();
      
      // Selecionar sala no dropdown do editor
      document.getElementById('map-room-select').value = room.id;
      mapEditor.setActiveRoom(room.id);

      // Ativar modo desenho
      const btnDraw = document.getElementById('btn-draw-mode');
      if (!mapEditor.isDrawing) {
        mapEditor.startDrawing(room.id);
        btnDraw.innerHTML = '<i class="fa-solid fa-ban"></i> Cancelar Desenho';
        btnDraw.classList.remove('btn-primary');
        btnDraw.classList.add('btn-danger');
      }
    });

    list2d.appendChild(item2d);
    list3d.appendChild(item3d);
  });
}

// ==========================================================================
// RENDERIZAÇÃO DA INTERFACE (UI)
// ==========================================================================

// Atualizar contadores do cabeçalho
function updateDashboardStats() {
  const total = roomsList.length;
  const ready = roomsList.filter(r => r.status === 'Pronto').length;
  const pending = roomsList.filter(r => r.status === 'Em Preparação').length;
  
  document.getElementById('total-rooms-val').textContent = total;
  document.getElementById('ready-rooms-val').textContent = ready;
  document.getElementById('pending-rooms-val').textContent = pending;
}

// Renderizar grade de cartões de sala no Dashboard
function renderRoomsGrid(rooms) {
  const grid = document.getElementById('rooms-grid');
  grid.innerHTML = '';
  
  if (rooms.length === 0) {
    grid.innerHTML = `
      <div class="loading-spinner">
        <i class="fa-solid fa-magnifying-glass"></i>
        <span>Nenhum ambiente encontrado com os filtros atuais.</span>
      </div>
    `;
    return;
  }

  rooms.forEach(room => {
    const card = document.createElement('div');
    card.className = 'room-card';
    card.dataset.id = room.id;
    
    // Obter primeira foto ou imagem padrão
    const coverUrl = room.images && room.images.length > 0 
      ? `/images/${encodeURIComponent(room.images[0])}` 
      : 'https://images.unsplash.com/photo-1541829019-259276a7f4fd?q=80&w=400&auto=format&fit=crop';
      
    // Status Badge
    let statusClass = 'pending';
    if (room.status === 'Pronto') statusClass = 'ready';
    else if (room.status === 'Manutenção') statusClass = 'maintenance';

    const areaText = room.dimensions && room.dimensions.area 
      ? `${room.dimensions.area.toFixed(1)} m²` 
      : '-- m²';

    const coursesBadge = room.courses 
      ? `<div class="room-card-courses" style="margin-top: 10px; font-size: 11px; color: var(--accent-color); display: flex; align-items: center; gap: 6px; border-top: 1px solid rgba(255,255,255,0.06); padding-top: 8px; width: 100%; overflow: hidden;">
          <i class="fa-solid fa-graduation-cap" style="flex-shrink: 0;"></i>
          <span style="overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-weight: 500;" title="${room.courses}">${room.courses}</span>
         </div>` 
      : '';

    card.innerHTML = `
      <div class="room-card-img" style="background-image: url('${coverUrl}')">
        <span class="room-badge ${statusClass}">${room.status}</span>
      </div>
      <div class="room-card-content" style="display: flex; flex-direction: column; justify-content: space-between; height: calc(100% - 140px);">
        <div>
          <div style="display: flex; justify-content: space-between; align-items: flex-start; gap: 8px; margin-bottom: 8px;">
            <h3>${room.name}</h3>
            <span style="font-size: 10px; padding: 2px 6px; background-color: var(--bg-tertiary); border-radius: 4px; color: var(--text-secondary); white-space: nowrap;">${room.block}</span>
          </div>
          <div class="room-meta">
            <div class="room-meta-item">
              <i class="fa-solid fa-ruler-combined"></i>
              <span>${areaText}</span>
            </div>
            <div class="room-meta-item">
              <i class="fa-solid fa-users"></i>
              <span>Cap: ${room.capacity || '--'}</span>
            </div>
            <div class="room-meta-item" style="margin-left: auto;">
              <i class="fa-solid fa-image"></i>
              <span>${room.images ? room.images.length : 0}</span>
            </div>
          </div>
        </div>
        ${coursesBadge}
      </div>
    `;
    
    card.addEventListener('click', () => openRoomDetails(room.id));
    grid.appendChild(card);
  });
}

// Popular o elemento <select> com a lista de salas filtradas pelo bloco atual
function populateRoomSelectors() {
  const select = document.getElementById('map-room-select');
  
  // Limpar mantendo a primeira opção
  select.innerHTML = '<option value="">Selecione uma sala...</option>';
  
  // Filtrar pelo bloco ativo
  const blockRooms = roomsList.filter(r => r.block === activeBlock);
  
  // Ordenar salas alfabeticamente
  const sortedRooms = [...blockRooms].sort((a, b) => a.name.localeCompare(b.name));
  
  sortedRooms.forEach(room => {
    const opt = document.createElement('option');
    opt.value = room.id;
    opt.textContent = room.name;
    select.appendChild(opt);
  });
}

// ==========================================================================
// GAVETA LATERAL DE DETALHES (DRAWER)
// ==========================================================================

// Abrir painel de detalhes da sala
function openRoomDetails(roomId) {
  const room = roomsList.find(r => r.id === roomId);
  if (!room) return;
  
  activeRoomId = roomId;
  
  // Preencher textos básicos
  document.getElementById('drawer-room-id').textContent = room.id.toUpperCase();
  document.getElementById('drawer-room-name').value = room.name;
  document.getElementById('room-status-select').value = room.status;
  document.getElementById('room-block-select').value = room.block || "Bloco C";
  document.getElementById('room-courses').value = room.courses || '';
  document.getElementById('room-notes').value = room.notes || '';
  
  // Preencher dimensões
  document.getElementById('dim-length').value = room.dimensions ? room.dimensions.length : '';
  document.getElementById('dim-width').value = room.dimensions ? room.dimensions.width : '';
  document.getElementById('dim-height').value = room.dimensions ? room.dimensions.height : '';
  document.getElementById('dim-area').value = room.dimensions && room.dimensions.area ? room.dimensions.area.toFixed(2) : '';
  document.getElementById('dim-capacity').value = room.capacity || '';

  // Configurar carrossel de fotos
  renderCarousel(room.images || []);
  
  // Renderizar inventário
  renderInventoryList(room.inventory || []);

  // Sincronizar destaque visual no mapa e no 3D
  mapEditor.setActiveRoom(roomId);
  
  // Destaque visual na lista lateral
  const sidebarItems = document.querySelectorAll('.sidebar-room-item');
  sidebarItems.forEach(item => {
    if (item.dataset.id === roomId) {
      item.classList.add('active');
      // Rolagem suave para o elemento na lista
      item.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
    } else {
      item.classList.remove('active');
    }
  });

  // Destacar no 3D (se o bloco ativo for o mesmo da sala)
  if (room.block === activeBlock) {
    viewer3D.highlightRoom(roomId);
  }

  // Abrir gaveta
  document.getElementById('details-drawer').classList.add('open');
}

// Fechar painel de detalhes
function closeRoomDetails() {
  document.getElementById('details-drawer').classList.remove('open');
  activeRoomId = null;
  mapEditor.setActiveRoom(null);
  viewer3D.highlightRoom(null);
  
  // Limpar destaque na lista lateral
  const sidebarItems = document.querySelectorAll('.sidebar-room-item');
  sidebarItems.forEach(item => item.classList.remove('active'));
}

// Renderizar as fotos do carrossel
function renderCarousel(images) {
  const slidesContainer = document.getElementById('drawer-carousel-slides');
  const dotsContainer = document.getElementById('carousel-dots');
  
  slidesContainer.innerHTML = '';
  dotsContainer.innerHTML = '';
  currentSlideIndex = 0;
  
  if (images.length === 0) {
    slidesContainer.innerHTML = `
      <div class="carousel-slide" style="background-image: url('https://images.unsplash.com/photo-1541829019-259276a7f4fd?q=80&w=400&auto=format&fit=crop'); display: flex; align-items: center; justify-content: center; background-color: var(--bg-tertiary);">
        <span style="color: var(--text-muted); font-size: 13px;">Nenhuma foto cadastrada</span>
      </div>
    `;
    document.getElementById('carousel-prev-btn').style.display = 'none';
    document.getElementById('carousel-next-btn').style.display = 'none';
    return;
  }

  images.forEach((img, idx) => {
    const slide = document.createElement('div');
    slide.className = 'carousel-slide';
    slide.style.backgroundImage = `url('/images/${encodeURIComponent(img)}')`;
    slidesContainer.appendChild(slide);
    
    const dot = document.createElement('div');
    dot.className = `carousel-dot ${idx === 0 ? 'active' : ''}`;
    dot.addEventListener('click', () => showSlide(idx));
    dotsContainer.appendChild(dot);
  });

  document.getElementById('carousel-prev-btn').style.display = images.length > 1 ? 'flex' : 'none';
  document.getElementById('carousel-next-btn').style.display = images.length > 1 ? 'flex' : 'none';
  
  updateCarouselPosition();
}

function showSlide(index) {
  const slides = document.querySelectorAll('.carousel-slide');
  if (index >= slides.length) currentSlideIndex = 0;
  else if (index < 0) currentSlideIndex = slides.length - 1;
  else currentSlideIndex = index;
  
  updateCarouselPosition();
}

function updateCarouselPosition() {
  const slidesContainer = document.getElementById('drawer-carousel-slides');
  slidesContainer.style.transform = `translateX(-${currentSlideIndex * 100}%)`;
  
  const dots = document.querySelectorAll('.carousel-dot');
  dots.forEach((dot, idx) => {
    if (idx === currentSlideIndex) dot.classList.add('active');
    else dot.classList.remove('active');
  });
}

// Renderizar lista de inventário de equipamentos
function renderInventoryList(inventory) {
  const list = document.getElementById('drawer-inventory-list');
  list.innerHTML = '';
  
  inventory.forEach(item => {
    addInventoryItemRow(item.name, item.quantity);
  });
}

// Adicionar uma linha de equipamento na interface do inventário
function addInventoryItemRow(name = '', quantity = 1) {
  const list = document.getElementById('drawer-inventory-list');
  
  const row = document.createElement('div');
  row.className = 'inventory-item';
  row.innerHTML = `
    <input type="text" placeholder="Nome do item (ex: Mesa, Projetor)" value="${name}" class="inv-item-name">
    <input type="number" min="1" value="${quantity}" class="inv-item-qty">
    <button class="btn-delete-item" title="Excluir item"><i class="fa-solid fa-trash-can"></i></button>
  `;
  
  row.querySelector('.btn-delete-item').addEventListener('click', () => {
    row.remove();
  });
  
  list.appendChild(row);
  list.scrollTop = list.scrollHeight; // Rolar para o fundo
}

// Coletar dados da interface e salvar no servidor
function saveCurrentRoomFromDrawer() {
  if (!activeRoomId) return;
  
  const name = document.getElementById('drawer-room-name').value.trim();
  if (!name) {
    alert("O nome da sala não pode ficar vazio!");
    return;
  }

  const length = parseFloat(document.getElementById('dim-length').value) || 0;
  const width = parseFloat(document.getElementById('dim-width').value) || 0;
  const height = parseFloat(document.getElementById('dim-height').value) || 0;
  const area = length * width;
  
  // Coletar inventário da tela
  const inventory = [];
  const items = document.querySelectorAll('.inventory-item');
  items.forEach(item => {
    const itemName = item.querySelector('.inv-item-name').value.trim();
    const qty = parseInt(item.querySelector('.inv-item-qty').value) || 1;
    if (itemName) {
      inventory.push({ name: itemName, quantity: qty });
    }
  });

  const updatedData = {
    name: name,
    status: document.getElementById('room-status-select').value,
    block: document.getElementById('room-block-select').value,
    dimensions: { length, width, height, area },
    capacity: parseInt(document.getElementById('dim-capacity').value) || null,
    courses: document.getElementById('room-courses').value,
    notes: document.getElementById('room-notes').value,
    inventory: inventory
  };

  saveRoomDetails(activeRoomId, updatedData);
}

// ==========================================================================
// REGISTRO DE EVENTOS DA UI
// ==========================================================================

function initUIEvents() {
  // Troca de Abas de Conteúdo
  const navItems = document.querySelectorAll('.nav-item');
  navItems.forEach(item => {
    item.addEventListener('click', (e) => {
      e.preventDefault();
      
      // Remover classe ativa dos links
      navItems.forEach(i => i.classList.remove('active'));
      item.classList.add('active');
      
      // Trocar seção visível
      const targetId = item.dataset.target;
      const sections = document.querySelectorAll('.content-section');
      sections.forEach(s => s.classList.remove('active'));
      document.getElementById(targetId).classList.add('active');
      
      // Ações extras ao entrar na aba
      if (targetId === 'map-2d') {
        setTimeout(() => mapEditor.handleResize(), 100);
      } else if (targetId === 'view-3d') {
        setTimeout(() => viewer3D.handleResize(), 100);
      }
    });
  });

  // Filtros de Status no Dashboard
  const statusFilterBtns = document.querySelectorAll('#status-filter-controls .filter-btn');
  statusFilterBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      statusFilterBtns.forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      activeStatusFilter = btn.dataset.filter;
      applySearchAndFilter();
    });
  });

  // Filtros de Bloco no Dashboard
  const blockFilterBtns = document.querySelectorAll('#block-filter-controls .filter-btn');
  blockFilterBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      blockFilterBtns.forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      activeBlockFilter = btn.dataset.block;
      applySearchAndFilter();
    });
  });

  // Abas do Seletor de Mapa (Tanto na aba 2D quanto na maquete 3D)
  const mapTabBtns = document.querySelectorAll('#map-tabs .filter-btn, #map-tabs-3d .filter-btn');
  mapTabBtns.forEach(btn => {
    btn.addEventListener('click', () => {
      const targetMap = btn.dataset.map;
      switchActiveBlock(targetMap);
    });
  });

  // Busca textual
  document.getElementById('search-input').addEventListener('input', () => {
    applySearchAndFilter();
  });

  // Eventos do Drawer
  document.getElementById('btn-close-drawer').addEventListener('click', closeRoomDetails);
  document.getElementById('btn-cancel-drawer').addEventListener('click', closeRoomDetails);
  document.getElementById('btn-save-drawer').addEventListener('click', saveCurrentRoomFromDrawer);
  
  // Evento de adição de equipamento no inventário
  document.getElementById('btn-add-inventory-item').addEventListener('click', () => {
    addInventoryItemRow();
  });

  // Mudança nas dimensões calcula área automaticamente
  const recalculateArea = () => {
    const l = parseFloat(document.getElementById('dim-length').value) || 0;
    const w = parseFloat(document.getElementById('dim-width').value) || 0;
    const area = l * w;
    document.getElementById('dim-area').value = area > 0 ? area.toFixed(2) : '';
    
    // heurística de capacidade se estiver vazia
    const capInput = document.getElementById('dim-capacity');
    if (!capInput.value && area > 0) {
      capInput.value = Math.floor(area / 1.5);
    }
  };
  document.getElementById('dim-length').addEventListener('input', recalculateArea);
  document.getElementById('dim-width').addEventListener('input', recalculateArea);

  // Navegação do Carrossel de Fotos
  document.getElementById('carousel-prev-btn').addEventListener('click', () => showSlide(currentSlideIndex - 1));
  document.getElementById('carousel-next-btn').addEventListener('click', () => showSlide(currentSlideIndex + 1));

  // Upload de Foto da Sala
  const roomPhotoUploadInput = document.getElementById('room-photo-upload');
  if (roomPhotoUploadInput) {
    roomPhotoUploadInput.addEventListener('change', async (e) => {
      const file = e.target.files[0];
      if (!file || !activeRoomId) return;

      const reader = new FileReader();
      reader.onload = async (event) => {
        const base64Data = event.target.result.split(',')[1];
        const filename = file.name;

        try {
          // Mostrar feedback de carregamento
          const labelUpload = document.querySelector('label[for="room-photo-upload"]');
          const originalText = labelUpload.innerHTML;
          labelUpload.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Enviando...';
          labelUpload.style.pointerEvents = 'none';

          const response = await fetch(`/api/rooms/${activeRoomId}/upload`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ filename, base64Data })
          });

          labelUpload.innerHTML = originalText;
          labelUpload.style.pointerEvents = 'auto';

          if (!response.ok) throw new Error("Erro no upload da foto");

          const result = await response.json();

          // Atualizar dados na lista local
          const index = roomsList.findIndex(r => r.id === activeRoomId);
          if (index !== -1) {
            roomsList[index] = result.room;
          }

          // Recarregar carrossel e dashboard/barra lateral
          renderCarousel(result.room.images || []);
          updateDashboardStats();
          applySearchAndFilter();
          
          // Se a sala estiver mapeada, refresca a barra lateral e mapa
          const blockRooms = roomsList.filter(r => r.block === activeBlock);
          renderSidebarRoomsList(blockRooms);
          
          // Limpar o valor do input para permitir enviar a mesma imagem novamente se desejado
          roomPhotoUploadInput.value = '';
          
        } catch (err) {
          console.error("Erro ao enviar foto:", err);
          alert("Não foi possível enviar a foto.");
          
          const labelUpload = document.querySelector('label[for="room-photo-upload"]');
          if (labelUpload) {
            labelUpload.innerHTML = '<i class="fa-solid fa-cloud-arrow-up"></i> Upload';
            labelUpload.style.pointerEvents = 'auto';
          }
        }
      };
      reader.readAsDataURL(file);
    });
  }

  // Upload do Mapa
  const fileInputs = [document.getElementById('map-upload'), document.getElementById('map-upload-empty')];
  fileInputs.forEach(input => {
    input.addEventListener('change', (e) => {
      const file = e.target.files[0];
      if (file) {
        handleMapImageFile(file);
      }
    });
  });

  // Botões do Editor de Mapa
  const btnDraw = document.getElementById('btn-draw-mode');
  btnDraw.addEventListener('click', () => {
    if (mapEditor.isDrawing) {
      mapEditor.cancelDrawing();
      btnDraw.innerHTML = '<i class="fa-solid fa-pen-ruler"></i> Desenhar Hotspot';
      btnDraw.classList.remove('btn-danger');
      btnDraw.classList.add('btn-primary');
    } else {
      const roomId = document.getElementById('map-room-select').value;
      if (!roomId) {
        alert("Selecione um ambiente no menu suspenso para vinculá-lo ao desenho do hotspot!");
        return;
      }
      mapEditor.startDrawing(roomId);
      btnDraw.innerHTML = '<i class="fa-solid fa-ban"></i> Cancelar Desenho';
      btnDraw.classList.remove('btn-primary');
      btnDraw.classList.add('btn-danger');
    }
  });

  // Redesenhar hotspots e polígonos caso mude a sala selecionada no editor
  document.getElementById('map-room-select').addEventListener('change', (e) => {
    const roomId = e.target.value;
    mapEditor.setActiveRoom(roomId);
    if (mapEditor.isDrawing) {
      mapEditor.cancelDrawing();
      btnDraw.innerHTML = '<i class="fa-solid fa-pen-ruler"></i> Desenhar Hotspot';
      btnDraw.classList.remove('btn-danger');
      btnDraw.classList.add('btn-primary');
    }
  });

  // Limpar hotspots da sala selecionada
  document.getElementById('btn-clear-hotspots').addEventListener('click', () => {
    const roomId = document.getElementById('map-room-select').value;
    if (!roomId) {
      alert("Selecione uma sala no menu para limpar o hotspot dela!");
      return;
    }
    if (confirm("Tem certeza que deseja apagar o hotspot desenhado para esta sala?")) {
      mapEditor.clearRoomPolygon(roomId);
    }
  });

  // Redimensionamento de Janela
  window.addEventListener('resize', () => {
    mapEditor.handleResize();
    viewer3D.handleResize();
  });
  
  // Botão resetar câmera 3D
  document.getElementById('btn-reset-camera').addEventListener('click', () => {
    viewer3D.resetCamera();
  });
}

// Aplicar busca e filtros combinados
function applySearchAndFilter() {
  const query = document.getElementById('search-input').value.toLowerCase().trim();

  const filtered = roomsList.filter(room => {
    const matchesSearch = room.name.toLowerCase().includes(query) || 
                          (room.notes && room.notes.toLowerCase().includes(query));
    const matchesStatus = activeStatusFilter === 'all' || room.status === activeStatusFilter;
    
    // Filtrar por Bloco C ou Bloco E de forma genérica no Dashboard
    let matchesBlock = true;
    if (activeBlockFilter !== 'all') {
      if (activeBlockFilter === 'Bloco E') {
        matchesBlock = room.block && room.block.startsWith('Bloco E');
      } else {
        matchesBlock = room.block === activeBlockFilter;
      }
    }
    
    return matchesSearch && matchesStatus && matchesBlock;
  });

  renderRoomsGrid(filtered);
}

// Processar arquivo de imagem do mapa e salvar por Bloco ativo
function handleMapImageFile(file) {
  const reader = new FileReader();
  reader.onload = (event) => {
    const mapUrl = event.target.result;
    
    // Configurar imagem no DOM
    const mapImg = document.getElementById('map-image');
    mapImg.src = mapUrl;
    
    // Salvar no localStorage de acordo com o bloco ativo
    const storageKey = `mochilao_map_data_${activeBlock.replace(/\s+/g, '_').toLowerCase()}`;
    try {
      localStorage.setItem(storageKey, mapUrl);
    } catch (e) {
      console.warn("Imagem muito grande para salvar no localStorage.");
    }

    mapImg.onload = () => {
      // Exibir elementos do mapa
      document.getElementById('map-empty-state').style.display = 'none';
      document.getElementById('map-wrapper').style.display = 'inline-block';
      document.getElementById('editor-controls').style.display = 'flex';
      
      // Ajustar SVG e renderizar polígonos
      setTimeout(() => {
        mapEditor.handleResize();
        resetMapZoomAndPan(); // Centralizar e resetar zoom
      }, 200);
    };
  };
  reader.readAsDataURL(file);
}

// ==========================================================================
// CONTROLE DE ZOOM E PAN (ARRRASTAR E AMPLIAR) DA PLANTA BAIXA 2D
// ==========================================================================

let activeQuickMapPopup = null;

function showQuickMapPopup(e, x, y) {
  // Remover popup ativo se houver
  if (activeQuickMapPopup) {
    activeQuickMapPopup.remove();
  }

  // Filtrar apenas as salas do bloco ativo que não estão mapeadas
  const blockRooms = roomsList.filter(r => r.block === activeBlock);
  const unmappedRooms = blockRooms.filter(r => !r.polygon);

  if (unmappedRooms.length === 0) {
    return; // Todas as salas do bloco já estão mapeadas!
  }

  const mapContainer = document.getElementById('map-container');
  const rect = mapContainer.getBoundingClientRect();
  const clickX = e.clientX - rect.left;
  const clickY = e.clientY - rect.top;

  const popup = document.createElement('div');
  popup.className = 'quick-map-popup';
  popup.style.position = 'absolute';
  popup.style.left = `${clickX}px`;
  popup.style.top = `${clickY}px`;
  popup.style.zIndex = '1000';
  popup.style.padding = '12px';
  popup.style.borderRadius = '8px';
  popup.style.width = '240px';
  popup.style.display = 'flex';
  popup.style.flexDirection = 'column';
  popup.style.gap = '8px';

  // Gerar as opções do menu
  let selectOptions = '<option value="">Escolher sala...</option>';
  unmappedRooms.sort((a, b) => a.name.localeCompare(b.name)).forEach(r => {
    selectOptions += `<option value="${r.id}">${r.name}</option>`;
  });

  popup.innerHTML = `
    <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
      <span style="font-size: 11px; font-weight: 700; text-transform: uppercase; color: var(--accent-color); display: flex; align-items: center; gap: 4px;">
        <i class="fa-solid fa-map-pin"></i> Mapear Sala Aqui
      </span>
      <button class="btn-close-popup" style="background: none; border: none; color: var(--text-muted); cursor: pointer; font-size: 12px;">
        <i class="fa-solid fa-xmark"></i>
      </button>
    </div>
    <select id="quick-room-select" style="width: 100%;">
      ${selectOptions}
    </select>
  `;

  mapContainer.appendChild(popup);
  activeQuickMapPopup = popup;

  // Ouvinte do botão fechar
  popup.querySelector('.btn-close-popup').addEventListener('click', (ev) => {
    ev.stopPropagation();
    popup.remove();
    activeQuickMapPopup = null;
  });

  // Ouvinte da seleção de sala
  popup.querySelector('#quick-room-select').addEventListener('change', async (ev) => {
    const roomId = ev.target.value;
    if (!roomId) return;

    // Criar um polígono retangular padrão ao redor do clique
    const halfSizeX = 0.02; // 2% da largura
    const halfSizeY = 0.02; // 2% da altura

    const px = Math.min(Math.max(x, halfSizeX), 1.0 - halfSizeX);
    const py = Math.min(Math.max(y, halfSizeY), 1.0 - halfSizeY);

    const polygon = [
      { x: px - halfSizeX, y: py - halfSizeY },
      { x: px + halfSizeX, y: py - halfSizeY },
      { x: px + halfSizeX, y: py + halfSizeY },
      { x: px - halfSizeX, y: py + halfSizeY }
    ];

    // Desativar select durante gravação
    ev.target.disabled = true;

    // Salvar polígono no servidor
    await saveRoomPolygon(roomId, polygon);

    // Fechar popup
    popup.remove();
    activeQuickMapPopup = null;

    // Atualizar mapa e barra lateral
    const blockRooms = roomsList.filter(r => r.block === activeBlock);
    mapEditor.setRooms(blockRooms);

    // Abrir imediatamente os detalhes da sala mapeada!
    openRoomDetails(roomId);
  });
}

function initMapZoomAndPan() {
  const mapContainer = document.getElementById('map-container');
  const mapWrapper = document.getElementById('map-wrapper');
  
  if (!mapContainer || !mapWrapper) return;
  
  let isPanning = false;
  let startX = 0;
  let startY = 0;
  let spacePressed = false;
  
  let clickStartX = 0;
  let clickStartY = 0;

  // Registrar escuta de teclado global para detecção do espaço (para pan no modo desenho)
  window.addEventListener('keydown', (e) => {
    if (e.code === 'Space' && document.activeElement.tagName !== 'INPUT' && document.activeElement.tagName !== 'TEXTAREA') {
      // Evitar scroll nativo da barra de espaço
      e.preventDefault();
      if (!spacePressed) {
        spacePressed = true;
        mapContainer.style.cursor = 'grab';
        mapContainer.classList.add('panning');
      }
    }
  });

  window.addEventListener('keyup', (e) => {
    if (e.code === 'Space') {
      spacePressed = false;
      mapContainer.style.cursor = mapEditor.isDrawing ? 'crosshair' : 'grab';
      mapContainer.classList.remove('panning');
    }
  });

  // Função para aplicar os valores de transform no mapa
  function applyTransform() {
    mapWrapper.style.transform = `translate(${panX}px, ${panY}px) scale(${scale})`;
    
    // Atualizar hotspots
    if (mapEditor) {
      mapEditor.handleResize();
    }
  }

  // Zoom pelo scroll do mouse (mousewheel)
  mapContainer.addEventListener('wheel', (e) => {
    e.preventDefault(); // Evitar scroll de página

    // Obter posição do mouse relativa ao container
    const rect = mapContainer.getBoundingClientRect();
    const mx = e.clientX - rect.left;
    const my = e.clientY - rect.top;

    // Posição no sistema de coordenadas do wrapper antes de aplicar o zoom
    const wx = (mx - panX) / scale;
    const wy = (my - panY) / scale;

    // Fator de zoom
    const zoomFactor = e.deltaY < 0 ? 1.15 : 0.85;
    const newScale = Math.min(Math.max(scale * zoomFactor, 0.4), 6.0);

    // Ajustar deslocamento (pan) para manter o ponto sob o mouse estático
    panX = mx - wx * newScale;
    panY = my - wy * newScale;
    scale = newScale;

    applyTransform();
  }, { passive: false });

  // Iniciar arraste (pan)
  mapContainer.addEventListener('mousedown', (e) => {
    // Só arrasta com clique esquerdo
    if (e.button !== 0) return;

    // Registrar ponto de início para diferenciar clique de arrasto
    clickStartX = e.clientX;
    clickStartY = e.clientY;

    // Se estiver desenhando hotspots, só permite arrastar se o Espaço estiver pressionado
    if (mapEditor.isDrawing && !spacePressed) return;

    // Evitar que arraste inicie se o clique for sobre um polígono no modo normal
    // a menos que estejamos arrastando com espaço ou clicando no fundo
    if (!mapEditor.isDrawing && e.target !== mapContainer && e.target.id !== 'map-svg' && e.target.id !== 'map-image' && !spacePressed) {
      return;
    }

    isPanning = true;
    startX = e.clientX - panX;
    startY = e.clientY - panY;
    mapContainer.style.cursor = 'grabbing';
    mapContainer.classList.add('panning');
    e.preventDefault();
  });

  // Mover o mouse para arrastar
  window.addEventListener('mousemove', (e) => {
    if (!isPanning) return;
    panX = e.clientX - startX;
    panY = e.clientY - startY;
    applyTransform();
  });

  // Soltar o clique
  window.addEventListener('mouseup', () => {
    if (isPanning) {
      isPanning = false;
      mapContainer.style.cursor = mapEditor.isDrawing ? 'crosshair' : 'grab';
      mapContainer.classList.remove('panning');
    }
  });

  // Evento de clique para o mapeamento rápido (Quick Map)
  mapContainer.addEventListener('click', (e) => {
    // Se o mouse se moveu mais de 5px, considera pan (arraste), não clique
    const dist = Math.hypot(e.clientX - clickStartX, e.clientY - clickStartY);
    if (dist > 5) return;

    if (mapEditor.isDrawing) return;

    // Só exibe se clicar diretamente no container, no SVG ou na imagem do mapa
    if (e.target.id === 'map-svg' || e.target.id === 'map-image' || e.target === mapContainer) {
      const rect = document.getElementById('map-image').getBoundingClientRect();
      const x = (e.clientX - rect.left) / rect.width;
      const y = (e.clientY - rect.top) / rect.height;

      // Se o clique foi dentro da imagem do mapa
      if (x >= 0 && x <= 1 && y >= 0 && y <= 1) {
        showQuickMapPopup(e, x, y);
      } else {
        if (activeQuickMapPopup) {
          activeQuickMapPopup.remove();
          activeQuickMapPopup = null;
        }
      }
    } else {
      // Se clicou fora do popup ativo, fecha ele
      if (activeQuickMapPopup && !activeQuickMapPopup.contains(e.target)) {
        activeQuickMapPopup.remove();
        activeQuickMapPopup = null;
      }
    }
  });

  // Controles flutuantes de botão
  document.getElementById('btn-zoom-in').addEventListener('click', () => {
    const mx = mapContainer.clientWidth / 2;
    const my = mapContainer.clientHeight / 2;
    const wx = (mx - panX) / scale;
    const wy = (my - panY) / scale;
    
    scale = Math.min(scale * 1.25, 6.0);
    panX = mx - wx * scale;
    panY = my - wy * scale;
    applyTransform();
  });

  document.getElementById('btn-zoom-out').addEventListener('click', () => {
    const mx = mapContainer.clientWidth / 2;
    const my = mapContainer.clientHeight / 2;
    const wx = (mx - panX) / scale;
    const wy = (my - panY) / scale;

    scale = Math.max(scale / 1.25, 0.4);
    panX = mx - wx * scale;
    panY = my - wy * scale;
    applyTransform();
  });

  document.getElementById('btn-zoom-reset').addEventListener('click', () => {
    resetMapZoomAndPan();
  });
}

// Resetar zoom e centralizar a imagem no container
function resetMapZoomAndPan() {
  const mapContainer = document.getElementById('map-container');
  const mapWrapper = document.getElementById('map-wrapper');
  const mapImg = document.getElementById('map-image');
  
  if (!mapContainer || !mapWrapper || !mapImg) return;

  // Obter dimensões originais da imagem
  const naturalWidth = mapImg.naturalWidth || 800;
  const naturalHeight = mapImg.naturalHeight || 600;

  // Obter dimensões do container
  const cw = mapContainer.clientWidth;
  const ch = mapContainer.clientHeight;

  // Se a imagem ainda não foi carregada com dimensões reais, aguarda um momento
  if (naturalWidth <= 0 || naturalHeight <= 0) return;

  // Definir dimensões reais no wrapper
  mapWrapper.style.width = `${naturalWidth}px`;
  mapWrapper.style.height = `${naturalHeight}px`;

  // Calcular escala de ajuste (fit scale) para cobrir 95% do container
  const fitScaleX = cw / naturalWidth;
  const fitScaleY = ch / naturalHeight;
  
  scale = Math.min(fitScaleX, fitScaleY) * 0.95;
  
  // Garantir limites mínimos/máximos de escala inicial
  scale = Math.min(Math.max(scale, 0.1), 4.0);

  // Centralizar o mapa
  panX = (cw - naturalWidth * scale) / 2;
  panY = (ch - naturalHeight * scale) / 2;

  mapWrapper.style.transform = `translate(${panX}px, ${panY}px) scale(${scale})`;
  
  if (mapEditor) {
    mapEditor.handleResize();
  }
}
