// {{APP_NAME}} - UI logic (Mixed variant)

rdesk.on("data_ready", function(data) {
  if (data.chart) {
    document.getElementById("main-chart").src = data.chart;
  }
  if (data.kpis) updateKPIs(data.kpis);
  renderTable(data.rows, data.cols);
  updateStatus("Initial data rendered");
});

rdesk.on("get_data_result", function(data) {
  if (data.chart) {
    document.getElementById("main-chart").src = data.chart;
  }
  if (data.kpis) updateKPIs(data.kpis);
  renderTable(data.rows, data.cols);
  updateStatus("Refreshed - " + data.rows.length + " rows");
});

rdesk.on("filter_result", function(result) {
  renderTable(result.data.rows, result.data.cols);
  if (result.chart) document.getElementById("main-chart").src = result.chart;
  if (result.kpis) updateKPIs(result.kpis);
  updateStatus("Showing " + result.count + " rows");
});

rdesk.on("__loading__", function(state) {
  updateStatus(state.active ? (state.message || "Working...") : "Ready");
});

function updateKPIs(kpis) {
  document.getElementById("kpi-mpg").textContent = kpis.avg_mpg || "-";
  document.getElementById("kpi-count").textContent = kpis.count || "-";
  document.getElementById("kpi-hp").textContent = kpis.avg_hp || "-";
}

function renderTable(rows, cols) {
  var head = document.getElementById("table-head");
  var body = document.getElementById("table-body");
  if (!head || !body || !rows || rows.length === 0) return;

  head.innerHTML = "<tr>" + cols.slice(0, 6).map(function(c) {
    return "<th>" + c + "</th>";
  }).join("") + "</tr>";

  body.innerHTML = rows.slice(0, 20).map(function(row) {
    return "<tr>" + cols.slice(0, 6).map(function(c) {
      return "<td>" + (row[c] !== undefined ? row[c] : "") + "</td>";
    }).join("") + "</tr>";
  }).join("");
}

function updateStatus(msg) {
  var el = document.getElementById("status-label");
  if (el) el.textContent = msg;
}

// Request data on load
rdesk.ready(function() {
  rdesk.send("get_data", {});
});
