function displayValue(value) {
  return String(value ?? "-");
}

function statusText(status = {}) {
  return [
    status.lastAction ?? "-",
    status.runStatus ?? "-",
    status.error ?? "-",
  ].join(" | ");
}

export function renderMachineSessionControlView(container, view = {}) {
  if (!container) {
    throw new Error("A control view container is required.");
  }

  const document = container.ownerDocument;
  container.textContent = "";

  const statusNode = document.createElement("div");
  statusNode.dataset.controlViewStatus = "";
  statusNode.textContent = statusText(view.status);
  container.appendChild(statusNode);

  const sectionsNode = document.createElement("div");
  sectionsNode.dataset.controlViewSections = "";
  container.appendChild(sectionsNode);

  const sectionNodes = [];
  for (const section of view.sections ?? []) {
    const sectionNode = document.createElement("section");
    sectionNode.dataset.sectionId = section.id;
    sectionNode.dataset.controlViewSectionId = section.id;

    const heading = document.createElement("h3");
    heading.textContent = section.title;
    sectionNode.appendChild(heading);

    const list = document.createElement("dl");
    for (const row of section.rows ?? []) {
      const term = document.createElement("dt");
      term.textContent = row.label;
      const def = document.createElement("dd");
      def.dataset.controlViewRow = row.label;
      def.textContent = displayValue(row.value);
      list.append(term, def);
    }

    sectionNode.appendChild(list);
    sectionsNode.appendChild(sectionNode);
    sectionNodes.push(sectionNode);
  }

  return {
    statusNode,
    sectionsNode,
    sectionNodes,
  };
}
