<%
// buttons is provided to this template
const numCols = (buttons && buttons.COLS && buttons.COLS.length) || 1;
const colWidth = (12 / numCols) >= 1 ? Math.floor(12 / numCols) : null;

// chunk the flat ROWS array into logical rows of numCols items
const chunks = [];
for (let i = 0; i < (buttons.ROWS || []).length; i += numCols) {
  chunks.push((buttons.ROWS || []).slice(i, i + numCols));
}
%>

<style>
  .btn-grid { gap: 0.5rem; }
  .btn-grid .cell { display: flex; align-items: stretch; }
  .btn-grid .blank-cell { height: 3.75rem; } /* placeholder height */
  .btn-grid .double-height { height: 9.5rem; } /* adjust to taste */
  .btn-grid .cell > button { width: 100%; white-space: normal; }
</style>

<div class="container">
  <!-- column headers -->
  <div class="row mb-2">
    <% for (let c = 0; c < numCols; c++) { %>
      <div class="<%= colWidth ? 'col-' + colWidth : 'col' %>">
        <h5><%= buttons.COLS[c] || '' %></h5>
      </div>
    <% } %>
  </div>

  <!-- button grid -->
  <div class="btn-grid">
    <% chunks.forEach(function(row) { %>
      <div class="row mb-2">
        <% for (let c = 0; c < numCols; c++) {
             const cell = row[c];
             const isEmpty = !cell || Object.keys(cell).length === 0;
             const colClass = '<%= colWidth ? "col-' + colWidth + '" : "col" %>'; // placeholder for layout below
        %>
          <div class="<%= colWidth ? 'col-' + colWidth : 'col' %> cell">
            <% if (isEmpty) { %>
              <div class="blank-cell"></div>
            <% } else { 
                 // build data attributes from context if present
                 const ctx = cell.context || {};
                 const dataAttrs = [];
                 if (ctx.context) dataAttrs.push('data-context="' + ctx.context + '"');
                 if (ctx.timeout)  dataAttrs.push('data-timeout="' + ctx.timeout + '"');
                 if (ctx.cid)      dataAttrs.push('data-cid="' + ctx.cid + '"');
                 if (ctx.dial)     dataAttrs.push('data-dial="' + ctx.dial + '"');
            %>
              <button
                type="button"
                class="btn <%= cell.btnClass || 'btn-secondary' %> <%= cell.doubleHeight ? 'double-height' : '' %>"
                name="<%= cell.name || '' %>"
                <%= dataAttrs.join(' ') %>
              ><%= cell.text || '' %></button>
            <% } %>
          </div>
        <% } %>
      </div>
    <% }); %>
  </div>
</div>