(() => {
  const dashboard = document.querySelector('.portal-dashboard');
  if (!dashboard) return;

  dashboard.querySelectorAll('[data-animate-value]').forEach((node) => {
    const target = Number(node.dataset.animateValue || 0);
    if (!Number.isFinite(target) || target <= 0) return;
    const suffix = node.dataset.suffix || '';
    const duration = 500;
    const started = performance.now();
    const format = new Intl.NumberFormat('pt-PT', { maximumFractionDigits: 0 });
    const tick = (now) => {
      const progress = Math.min((now - started) / duration, 1);
      node.textContent = `${format.format(Math.round(target * progress))}${suffix}`;
      if (progress < 1) requestAnimationFrame(tick);
    };
    requestAnimationFrame(tick);
  });

  dashboard.querySelectorAll('[data-progress]').forEach((node) => {
    const value = Math.max(0, Math.min(100, Number(node.dataset.progress || 0)));
    requestAnimationFrame(() => node.style.setProperty('--portal-progress', `${value}%`));
  });

  const densityButton = dashboard.querySelector('[data-density-toggle]');
  if (densityButton) {
    const key = 'portal-dashboard-compact';
    const setCompact = (active) => {
      dashboard.classList.toggle('is-compact', active);
      densityButton.setAttribute('aria-pressed', active ? 'true' : 'false');
      densityButton.querySelector('.density-label').textContent = active ? 'Vista confortável' : 'Vista compacta';
    };
    setCompact(localStorage.getItem(key) === '1');
    densityButton.addEventListener('click', () => {
      const next = !dashboard.classList.contains('is-compact');
      localStorage.setItem(key, next ? '1' : '0');
      setCompact(next);
    });
  }
})();
