(function () {
  const maxBarHeight = 150;

  function numberAttr(element, name) {
    const value = Number(element.getAttribute(name));
    return Number.isFinite(value) ? value : 0;
  }

  function applyChartBars() {
    document.querySelectorAll(".bar-chart").forEach((chart) => {
      const bars = Array.from(chart.querySelectorAll(".bar-chart-col"));
      const maxValue = Math.max(0, ...bars.map((bar) => numberAttr(bar, "data-chart-value")));

      bars.forEach((bar) => {
        const fill = bar.querySelector(".bar-chart-bar");
        if (!fill) {
          return;
        }
        const value = numberAttr(bar, "data-chart-value");
        let height = numberAttr(fill, "data-height-px");
        if (maxValue > 0) {
          height = value <= 0 ? 0 : Math.max(8, Math.round((value / maxValue) * maxBarHeight));
        }
        fill.style.height = `${Math.min(maxBarHeight, height)}px`;
      });
    });
  }

  function applyStatusBars() {
    const rows = Array.from(document.querySelectorAll(".stat-bar"));
    const maxValue = Math.max(0, ...rows.map((row) => numberAttr(row, "data-stat-value")));

    rows.forEach((row) => {
      const fill = row.querySelector(".stat-bar-fill");
      if (!fill) {
        return;
      }
      const value = numberAttr(row, "data-stat-value");
      let width = numberAttr(fill, "data-width-percent");
      if (maxValue > 0) {
        width = value <= 0 ? 0 : Math.round((value / maxValue) * 100);
      }
      fill.style.width = `${Math.max(0, Math.min(100, width))}%`;
    });
  }

  function init() {
    applyChartBars();
    applyStatusBars();
  }

  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", init);
  } else {
    init();
  }
})();
