document.addEventListener('DOMContentLoaded', async () => {
  const page = document.body.dataset.page;
  document.querySelectorAll('[data-page-link]').forEach(link => {
    if (link.dataset.pageLink === page) link.classList.add('active');
  });

  const formatNumber = value => new Intl.NumberFormat('pt-BR').format(Number(value || 0));
  const renderStackItems = (target, items = []) => {
    if (!target) return;
    target.innerHTML = items.map(item => `
      <div class="list-item">
        <div>
          <h4>${item.detalhe || item.chave}</h4>
          <p>${item.chave}</p>
        </div>
        <span class="badge gray">${formatNumber(item.valor)}</span>
      </div>
    `).join('');
  };

  if (page === 'dashboard') {
    try {
      const response = await fetch('data/cetesb/licencas_dashboard_resumo.json');
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const summary = await response.json();
      const metrics = summary.metrics || {};
      Object.entries(metrics).forEach(([key, value]) => {
        document.querySelectorAll(`[data-metric="${key}"]`).forEach(node => {
          node.textContent = formatNumber(value);
        });
      });
      const dateBadge = document.querySelector('[data-summary-date-badge]');
      if (dateBadge && summary.as_of_date) dateBadge.textContent = `base ${summary.as_of_date}`;
      const sourceFile = document.querySelector('[data-source-file]');
      if (sourceFile && summary.source_csv) sourceFile.textContent = summary.source_csv.split('/').pop();
      renderStackItems(document.querySelector('[data-list="faixas_vencimento"]'), summary.faixas_vencimento);
      renderStackItems(document.querySelector('[data-list="top_agencias"]'), summary.top_agencias?.map(item => ({ ...item, detalhe: 'Volume por agência' })));
      renderStackItems(document.querySelector('[data-list="top_municipios"]'), summary.top_municipios?.map(item => ({ ...item, detalhe: 'Volume por município' })));
    } catch (error) {
      console.error('Falha ao carregar resumo CETESB', error);
    }
  }

  const statusButtons = document.querySelectorAll('[data-filter-status]');
  const statusRows = document.querySelectorAll('[data-status-row]');
  if (statusButtons.length && statusRows.length) {
    statusButtons.forEach(btn => btn.addEventListener('click', () => {
      statusButtons.forEach(b => b.classList.remove('active'));
      btn.classList.add('active');
      const status = btn.dataset.filterStatus;
      statusRows.forEach(row => {
        row.style.display = (status === 'all' || row.dataset.statusRow === status) ? '' : 'none';
      });
    }));
  }

  const drawerTargets = document.querySelectorAll('[data-drawer]');
  const drawerTitle = document.querySelector('[data-drawer-title]');
  const drawerBody = document.querySelector('[data-drawer-body]');
  const drawerGrid = document.querySelector('[data-drawer-grid]');
  if (drawerTargets.length && drawerTitle && drawerBody) {
    drawerTargets.forEach(item => item.addEventListener('click', () => {
      drawerTitle.textContent = item.dataset.title || 'Detalhe';
      drawerBody.textContent = item.dataset.body || 'Sem descrição.';
      if (drawerGrid) {
        const fields = [
          ['Tipo', item.dataset.type],
          ['Status', item.dataset.status],
          ['Validade', item.dataset.validade],
          ['Responsável', item.dataset.owner],
        ].filter(([,value]) => value);
        drawerGrid.innerHTML = fields.map(([label, value]) => `
          <div class="info-box"><small>${label}</small><strong>${value}</strong></div>
        `).join('');
      }
    }));
  }

  const hotspotTargets = document.querySelectorAll('[data-hotspot]');
  const hotspotName = document.querySelector('[data-hotspot-name]');
  const hotspotText = document.querySelector('[data-hotspot-text]');
  const hotspotFields = document.querySelector('[data-hotspot-fields]');
  if (hotspotTargets.length && hotspotName) {
    hotspotTargets.forEach(point => point.addEventListener('click', () => {
      hotspotTargets.forEach(p => p.style.transform = 'scale(1)');
      point.style.transform = 'scale(1.15)';
      hotspotName.textContent = point.dataset.name;
      hotspotText.textContent = point.dataset.text;
      hotspotFields.innerHTML = [
        ['Área', point.dataset.area],
        ['Categoria', point.dataset.type],
        ['Status', point.dataset.status],
        ['Licença', point.dataset.licenca],
      ].map(([k,v]) => `<div class="info-box"><small>${k}</small><strong>${v || '—'}</strong></div>`).join('');
    }));
    hotspotTargets[0].click();
  }

  const checklistInputs = document.querySelectorAll('[data-check-answer]');
  const progressText = document.querySelector('[data-check-progress-text]');
  const progressBar = document.querySelector('[data-check-progress-bar]');
  const answerGroups = document.querySelectorAll('[data-answer-group]');
  if (answerGroups.length) {
    answerGroups.forEach(group => {
      const targetId = group.dataset.answerTarget;
      const hiddenInput = document.getElementById(targetId);
      const buttons = group.querySelectorAll('[data-answer-value]');
      buttons.forEach(button => button.addEventListener('click', () => {
        buttons.forEach(b => b.classList.remove('active'));
        button.classList.add('active');
        if (hiddenInput) {
          hiddenInput.value = button.dataset.answerValue || '';
          hiddenInput.dispatchEvent(new Event('change', { bubbles: true }));
        }
      }));
    });
  }

  if (checklistInputs.length && progressText && progressBar) {
    const refresh = () => {
      const answered = [...checklistInputs].filter(el => {
        if (el.type === 'radio') {
          const group = document.querySelectorAll(`input[name="${el.name}"]`);
          return [...group].some(r => r.checked);
        }
        if (el.type === 'checkbox') return el.checked;
        return !!el.value;
      });
      const unique = new Set(answered.map(el => el.name || el.id));
      const total = new Set([...checklistInputs].map(el => el.name || el.id)).size;
      const pct = Math.round((unique.size / total) * 100);
      progressText.textContent = `${unique.size}/${total} respostas concluídas`;
      progressBar.style.width = `${pct}%`;
    };
    checklistInputs.forEach(input => input.addEventListener('change', refresh));
    refresh();
  }
});
