All files / scripts/data-transformers/content-generators dashboard-section.ts

98.78% Statements 163/165
88.81% Branches 127/143
100% Functions 25/25
98.73% Lines 156/158

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626                                                                                                              102x               102x   102x   102x                           102x           102x 3x 3x 3x       3x   1x               1x     1x 1x             1x     1x     3x 2x     3x               5x     5x 11x   5x     38x       5x                                                                                                                     40x   40x 1x 1x     40x 40x 40x 40x         40x 40x 45x 45x 45x       40x 45x 45x 45x           40x   40x           40x                       25x     25x     25x               336x 336x 336x 3x   336x 336x                               21x 21x 21x 21x     21x 1x         20x 40x 1x                 19x 19x 19x 19x 38x 76x 76x 76x 76x     19x             19x 19x   21x 21x     21x 21x 38x   21x     21x 38x 38x 38x 76x 76x 76x 76x 76x 76x   38x       21x           21x 21x                                         19x 19x 19x 19x 19x 19x 19x 19x 19x   19x 19x                                             97x 97x                                 100x 100x 3x             97x 100x   100x 100x     100x 100x 57x   57x 57x 57x 57x 57x     40x 21x 19x 19x       95x               100x         100x 100x 3x 3x                   95x       100x       100x                                                                                                                           92x   92x 121x 121x     92x 92x 92x     92x           92x 92x 100x     92x     92x 92x 6x 9x 9x   6x               87x           87x            
/**
 * @module data-transformers/content-generators/dashboard-section
 * @description Generates embeddable Chart.js dashboard sections and CSS-only
 * multi-panel dashboards that can be injected into any article type via the
 * `TemplateSection` extensibility pattern.
 *
 * Agentic workflows call `generateDashboardSection()` (single-chart) or
 * `generateMultiPanelDashboardSection()` (multi-panel AI-driven) with chart
 * configurations sourced from MCP servers or CIA-data and append the returned
 * `TemplateSection` to the article's `sections` array.
 *
 * The generated HTML includes:
 * - One `<canvas>` element per Chart.js chart (config in `data-chart-config`)
 * - CSS-only heat maps (no JS required) for stakeholder impact matrices
 * - CSS-only gauge dials for coalition stress / confidence indicators
 * - Optional data tables for accessibility (screen-reader fallback)
 * - ARIA labels and roles throughout for WCAG 2.1 AA compliance
 *
 * Client-side Chart.js chart initialisation is NOT performed automatically by
 * this module. Embedding pages MUST load Chart.js and run an initializer (for
 * example, a shared `chart-factory.ts` or any loader that scans canvases for
 * `data-chart-config` and calls `createChart()` or equivalent).
 *
 * **Dependencies** (loaded by the Vite build from `package.json`):
 * - chart.js ^4.5.1
 * - chartjs-plugin-annotation ^3.1.0
 *
 * @author Hack23 AB
 * @license Apache-2.0
 */
 
import { escapeHtml } from '../../html-utils.js';
import type { Language } from '../../types/language.js';
import type {
  TemplateSection,
  DashboardData,
  DashboardChartConfig,
  DashboardTableConfig,
  DashboardAnnotation,
  MultiPanelDashboard,
  DashboardPanel,
  HeatMapConfig,
  GaugeConfig,
} from '../../types/article.js';
import { L } from '../helpers.js';
 
// ---------------------------------------------------------------------------
// Chart.js configuration serialiser (JSON for data-chart-config attribute)
// ---------------------------------------------------------------------------
 
/**
 * Produce a JSON-safe Chart.js `config` object string for a single chart.
 * We emit only the data & options that Chart.js actually needs.
 */
function serialiseChartConfig(chart: DashboardChartConfig): string {
  const datasets = chart.datasets.map(ds => ({
    label: ds.label,
    data: ds.data,
    ...(ds.backgroundColor ? { backgroundColor: ds.backgroundColor } : {}),
    ...(ds.borderColor ? { borderColor: ds.borderColor } : {}),
    ...(ds.borderWidth != null ? { borderWidth: ds.borderWidth } : {}),
  }));
 
  const annotationPluginBlock = buildAnnotations(chart.annotations);
 
  const hasTitle = chart.title != null && chart.title.trim() !== '';
 
  const config = {
    type: chart.type,
    data: {
      ...(chart.labels ? { labels: chart.labels } : {}),
      datasets,
    },
    options: {
      plugins: {
        title: { display: hasTitle, text: chart.title },
        ...(annotationPluginBlock ? { annotation: annotationPluginBlock } : {}),
      },
    },
  };
 
  return JSON.stringify(config);
}
 
function buildAnnotations(
  annotations?: DashboardAnnotation[],
): Record<string, unknown> | undefined {
  if (!annotations || annotations.length === 0) return undefined;
  const result: Record<string, unknown> = {};
  annotations.forEach((a, i) => {
    const key = `annotation${i}`;
 
    let config: Record<string, unknown> | undefined;
 
    switch (a.type) {
      case 'line': {
        config = {
          type: 'line',
          yMin: a.value,
          yMax: a.value,
          ...(a.borderColor ? { borderColor: a.borderColor } : {}),
          ...(a.backgroundColor ? { backgroundColor: a.backgroundColor } : {}),
          ...(a.label ? { label: { display: true, content: a.label } } : {}),
        };
        break;
      }
      case 'label': {
        const content = a.label != null ? a.label : String(a.value);
        config = {
          type: 'label',
          content,
          yValue: a.value,
          ...(a.borderColor ? { borderColor: a.borderColor } : {}),
          ...(a.backgroundColor ? { backgroundColor: a.backgroundColor } : {}),
        };
        break;
      }
      default:
        break;
    }
 
    if (config) {
      result[key] = config;
    }
  });
  return Object.keys(result).length > 0 ? { annotations: result } : undefined;
}
 
// ---------------------------------------------------------------------------
// Table renderer
// ---------------------------------------------------------------------------
 
function renderTable(table: DashboardTableConfig): string {
  const caption = table.caption
    ? `    <caption>${escapeHtml(table.caption)}</caption>\n`
    : '';
  const headerCells = table.headers
    .map(h => `<th scope="col">${escapeHtml(h)}</th>`)
    .join('');
  const bodyRows = table.rows
    .map(
      row =>
        `      <tr>${row.map(cell => `<td>${escapeHtml(cell)}</td>`).join('')}</tr>`,
    )
    .join('\n');
 
  return `  <table class="dashboard-table">
${caption}    <thead><tr>${headerCells}</tr></thead>
    <tbody>
${bodyRows}
    </tbody>
  </table>`;
}
 
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
 
/**
 * Options for the dashboard section generator.
 */
export interface DashboardSectionOptions {
  /** Chart and table configurations */
  data: DashboardData;
  /** Target language for labels */
  lang: Language | string;
}
 
/**
 * Generate an embeddable dashboard section with Chart.js charts.
 *
 * Returns a `TemplateSection` that can be appended to `ArticleData.sections`.
 * Each chart is rendered as a `<canvas>` element with its Chart.js config
 * stored in a `data-chart-config` attribute, consistent with the codebase's
 * "no inline scripts" pattern. Client-side initialisation is NOT automatic —
 * embedding pages must load Chart.js and run an initializer that reads
 * `data-chart-config` (e.g. the shared chart-factory module).
 *
 * @example
 * ```ts
 * import { generateDashboardSection } from './content-generators/dashboard-section.js';
 *
 * const section = generateDashboardSection({
 *   data: {
 *     title: 'Party Seat Distribution',
 *     summary: 'Current Riksdag seat allocation after 2022 election.',
 *     charts: [{
 *       id: 'seat-chart',
 *       type: 'bar',
 *       title: 'Seats by Party',
 *       labels: ['S', 'M', 'SD', 'C', 'V', 'KD', 'L', 'MP'],
 *       datasets: [{
 *         label: 'Seats',
 *         data: [107, 68, 73, 24, 24, 19, 16, 18],
 *         backgroundColor: ['#e8112d','#1b49dd','#dddd00','#009933','#da291c','#000077','#006ab3','#83cf39'],
 *       }],
 *     }],
 *   },
 *   lang: 'en',
 * });
 *
 * articleData.sections = [...(articleData.sections ?? []), section];
 * ```
 */
export function generateDashboardSection(opts: DashboardSectionOptions): TemplateSection {
  const { data, lang } = opts;
 
  const lbl = (key: string): string => {
    const val = L(lang, key);
    return typeof val === 'string' ? val : key;
  };
 
  const rawTitle = typeof data.title === 'string' ? data.title.trim() : '';
  const titleText = rawTitle || lbl('dashboardTitle');
  const trimmedSummary = data.summary?.trim();
  const summaryBlock = trimmedSummary
    ? `    <p class="dashboard-summary">${escapeHtml(trimmedSummary)}</p>\n`
    : '';
 
  // Sanitise chart IDs once — ensure non-empty and unique for valid DOM ids
  const usedIds = new Set<string>();
  const sanitisedCharts = data.charts.map((chart, index) => {
    const baseId = chart.id.replace(/[^a-zA-Z0-9_-]/g, '') || `chart-${index}`;
    const safeId = deduplicateId(baseId, usedIds);
    return { ...chart, safeId };
  });
 
  // Chart canvases with config in data attribute (no inline scripts)
  const chartBlocks = sanitisedCharts.map(chart => {
    const config = serialiseChartConfig(chart);
    const ariaLabel = chart.title && chart.title.trim() ? chart.title : chart.safeId;
    return `    <div class="dashboard-chart-wrapper">
      <canvas id="${escapeHtml(chart.safeId)}" role="img" aria-label="${escapeHtml(ariaLabel)}" data-chart-config="${escapeHtml(config)}"></canvas>
    </div>`;
  }).join('\n');
 
  // Tables (optional)
  const tableBlocks = (data.tables ?? []).map(t => renderTable(t)).join('\n');
 
  const html = `<section class="article-dashboard" aria-label="${escapeHtml(titleText)}">
    <h2>${escapeHtml(titleText)}</h2>
${summaryBlock}${chartBlocks}
${tableBlocks}
  </section>`;
 
  return {
    id: 'article-dashboard',
    html,
    className: 'article-dashboard-section',
  };
}
 
// ---------------------------------------------------------------------------
// CSS-only chart renderers (no Chart.js dependency)
// ---------------------------------------------------------------------------
 
/** Allowed layout values for the multi-panel grid */
const VALID_LAYOUTS = new Set(['grid-2x2', 'grid-3x2', 'full-width', 'sidebar']);
 
/** Allowed relevance values for AI insight styling */
const VALID_RELEVANCE = new Set(['high', 'medium', 'low']);
 
/** Intensity used when all heatmap cell values are equal (mid-scale) */
const EQUAL_VALUES_INTENSITY = 0.5;
 
/**
 * Ensure `baseId` is globally unique across the entire dashboard section by
 * suffixing `-1`, `-2`, etc. when the id is already in `usedIds`.
 * The unique id is added to the Set before returning.
 */
function deduplicateId(baseId: string, usedIds: Set<string>): string {
  let safeId = baseId;
  let counter = 1;
  while (usedIds.has(safeId)) {
    safeId = `${baseId}-${counter++}`;
  }
  usedIds.add(safeId);
  return safeId;
}
 
/**
 * Render a CSS-only heat map as an accessible grid table.
 *
 * Intensity is driven by a `--intensity` CSS custom property (0–1) on each
 * data cell, allowing the stylesheet to map it to a colour scale without any
 * inline scripts.
 *
 * @param config - Heat map configuration
 * @param panelId - Parent panel id used to prefix the DOM id for uniqueness
 * @param usedIds - Shared Set tracking all emitted DOM ids to prevent duplicates
 */
function renderHeatMap(config: HeatMapConfig, panelId: string, usedIds: Set<string>): string {
  // Deduplicate heatmap IDs: prefix with panelId and track across the dashboard
  let baseId = config.id.replace(/[^a-zA-Z0-9_-]/g, '') || 'heatmap';
  baseId = `${panelId}-${baseId}`;
  const safeId = deduplicateId(baseId, usedIds);
  const { rowLabels, columnLabels, cells } = config;
 
  // Validate rectangular shape: row count first, then per-row cell count
  if (cells.length !== rowLabels.length) {
    throw new Error(
      `HeatMapConfig "${config.id}": ${cells.length} data rows but ${rowLabels.length} row labels. ` +
      'Heat map rows must match rowLabels length.',
    );
  }
  for (let rIdx = 0; rIdx < cells.length; rIdx++) {
    if (cells[rIdx].length !== columnLabels.length) {
      throw new Error(
        `HeatMapConfig "${config.id}": row ${rIdx} has ${cells[rIdx].length} cells but there are ` +
        `${columnLabels.length} column labels. Heat map cells must be rectangular.`,
      );
    }
  }
 
  // Compute global min/max in a single streaming pass — no intermediate array allocation.
  // Non-finite values (NaN, Infinity) are treated as 0 to match gauge/confidence guards.
  let minVal = Infinity;
  let maxVal = -Infinity;
  let hasAnyCells = false;
  for (const row of cells) {
    for (const cell of row) {
      const v = Number.isFinite(cell.value) ? cell.value : 0;
      if (v < minVal) minVal = v;
      if (v > maxVal) maxVal = v;
      hasAnyCells = true;
    }
  }
  Iif (!hasAnyCells) {
    minVal = 0;
    maxVal = 100;
  }
  // When all values are equal, render every cell at mid-intensity (0.5) so a
  // uniform dataset is distinguishable from an empty one.  Use 1 as divisor to
  // avoid division by zero.
  const allEqual = maxVal - minVal === 0;
  const range = allEqual ? 1 : maxVal - minVal;
 
  const minLabel = config.minLabel ?? String(minVal);
  const maxLabel = config.maxLabel ?? String(maxVal);
 
  // Header row — corner cell uses role="presentation" (empty spacer, no meaningful content)
  const cornerCell = `<div role="presentation" class="heatmap-cell heatmap-corner"></div>`;
  const headerCells = columnLabels
    .map(col => `<div role="columnheader" class="heatmap-cell heatmap-col-label">${escapeHtml(col)}</div>`)
    .join('');
  const headerRow = `  <div role="row" class="heatmap-row heatmap-header">${cornerCell}${headerCells}</div>`;
 
  // Data rows
  const dataRows = cells.map((row, rIdx) => {
    const rowLabel = rowLabels[rIdx] ?? String(rIdx + 1);
    const rowHeaderCell = `<div role="rowheader" class="heatmap-cell heatmap-row-label">${escapeHtml(rowLabel)}</div>`;
    const dataCells = row.map((cell, cIdx) => {
      const colLabel = columnLabels[cIdx] ?? String(cIdx + 1);
      const numVal = Number.isFinite(cell.value) ? cell.value : 0;
      const intensity = allEqual ? EQUAL_VALUES_INTENSITY.toFixed(3) : ((numVal - minVal) / range).toFixed(3);
      const displayText = cell.label ?? String(numVal);
      const ariaText = `${escapeHtml(rowLabel)} / ${escapeHtml(colLabel)}: ${escapeHtml(displayText)}`;
      return `<div role="cell" class="heatmap-cell heatmap-data-cell" style="--intensity:${intensity}" aria-label="${ariaText}">${escapeHtml(displayText)}</div>`;
    }).join('');
    return `  <div role="row" class="heatmap-row">${rowHeaderCell}${dataCells}</div>`;
  }).join('\n');
 
  // Legend — outside role="table" so screen readers can access the scale context
  const legend = `  <div class="heatmap-legend">
    <span class="heatmap-legend-label">${escapeHtml(minLabel)}</span>
    <div class="heatmap-legend-scale"></div>
    <span class="heatmap-legend-label">${escapeHtml(maxLabel)}</span>
  </div>`;
 
  const safeTitle = config.title?.trim() || 'Heat map';
  return `<div class="dashboard-heatmap-wrapper">
<div id="${escapeHtml(safeId)}" class="dashboard-heatmap" role="table" aria-label="${escapeHtml(safeTitle)}">
${headerRow}
${dataRows}
</div>
${legend}
</div>`;
}
 
/**
 * Render a CSS-only semicircular gauge dial.
 *
 * The gauge angle is driven by a `--gauge-pct` CSS custom property (0–1),
 * which the stylesheet maps to a `conic-gradient` arc — no JS required.
 *
 * @param config - Gauge configuration
 * @param panelId - Parent panel id used to prefix the DOM id for uniqueness
 * @param usedIds - Shared Set tracking all emitted DOM ids to prevent duplicates
 */
function renderGauge(config: GaugeConfig, panelId: string, usedIds: Set<string>): string {
  // Deduplicate gauge IDs: prefix with panelId and track across the dashboard
  let baseId = config.id.replace(/[^a-zA-Z0-9_-]/g, '') || 'gauge';
  baseId = `${panelId}-${baseId}`;
  const safeId = deduplicateId(baseId, usedIds);
  const safeValue = Number.isFinite(config.value) ? config.value : 0;
  const clamped = Math.min(100, Math.max(0, safeValue));
  const pct = clamped / 100;
  const minLabel = config.minLabel ?? '0';
  const maxLabel = config.maxLabel ?? '100';
  const displayValue = `${clamped}%`;
 
  const safeTitle = config.title?.trim() || 'Gauge';
  return `<div id="${escapeHtml(safeId)}" class="dashboard-gauge" role="figure" aria-label="${escapeHtml(safeTitle)}: ${escapeHtml(displayValue)}">
  <div class="gauge-track" aria-hidden="true">
    <div class="gauge-fill" style="--gauge-pct:${pct.toFixed(3)}"></div>
    <div class="gauge-center"></div>
  </div>
  <div class="gauge-value" aria-hidden="true">${escapeHtml(displayValue)}</div>
  <div class="gauge-label">${escapeHtml(config.label ?? safeTitle)}</div>
  <div class="gauge-range" aria-hidden="true">
    <span class="gauge-min">${escapeHtml(minLabel)}</span>
    <span class="gauge-max">${escapeHtml(maxLabel)}</span>
  </div>
</div>`;
}
 
// ---------------------------------------------------------------------------
// Multi-panel dashboard helpers
// ---------------------------------------------------------------------------
 
/**
 * Sanitise a panel id for safe use as a DOM element id, and ensure uniqueness
 * across panels by tracking used ids in a shared Set.
 */
function sanitisePanelId(rawId: string, index: number, usedIds: Set<string>): string {
  const base = rawId.replace(/[^a-zA-Z0-9_-]/g, '') || `panel-${index}`;
  return deduplicateId(base, usedIds);
}
 
/**
 * Render a single dashboard panel including optional chart, heat map, gauge,
 * AI interpretation, confidence indicator, and accessible table fallback.
 *
 * Only one visual type may be set per panel (chart, heatMap, or gauge).
 * If more than one is provided, an error is thrown to prevent ambiguous output.
 */
function renderPanel(
  panel: DashboardPanel,
  index: number,
  lbl: (key: string) => string,
  usedIds: Set<string>,
): string {
  // Runtime validation: enforce mutual exclusivity of visual types
  const visualCount = [panel.chart, panel.heatMap, panel.gauge].filter(Boolean).length;
  if (visualCount > 1) {
    throw new Error(
      `DashboardPanel "${panel.id}" defines ${visualCount} visual types (chart/heatMap/gauge). ` +
      'Only one visual type is allowed per panel.',
    );
  }
 
  // Validate panel title — fall back to generated label when empty/whitespace
  const realTitle = panel.title?.trim();
  const safeTitle = realTitle || `${lbl('dashboardPanel')} ${index + 1}`;
 
  const panelId = sanitisePanelId(panel.id, index, usedIds);
  const headingId = deduplicateId(`${panelId}-heading`, usedIds);
 
  // Chart content (Chart.js canvas or CSS-only visual)
  let visualBlock = '';
  if (panel.chart) {
    const config = serialiseChartConfig(panel.chart);
    // Deduplicate chart IDs: prefix with panelId and track across the dashboard
    let baseChartId = panel.chart.id.replace(/[^a-zA-Z0-9_-]/g, '') || 'chart';
    baseChartId = `${panelId}-${baseChartId}`;
    const chartId = deduplicateId(baseChartId, usedIds);
    const ariaLabel = panel.chart.title?.trim() || chartId;
    visualBlock = `    <div class="panel-chart-wrapper">
      <canvas id="${escapeHtml(chartId)}" role="img" aria-label="${escapeHtml(ariaLabel)}" data-chart-config="${escapeHtml(config)}"></canvas>
    </div>`;
  } else if (panel.heatMap) {
    visualBlock = `    <div class="panel-heatmap-wrapper">\n${renderHeatMap(panel.heatMap, panelId, usedIds)}\n    </div>`;
  } else if (Epanel.gauge) {
    visualBlock = `    <div class="panel-gauge-wrapper">\n${renderGauge(panel.gauge, panelId, usedIds)}\n    </div>`;
  }
 
  // AI interpretation — use localised label as a visually-hidden semantic heading
  const interpretationBlock = panel.interpretation?.trim()
    ? `    <div class="panel-interpretation-wrapper">
      <h4 class="panel-interpretation-label sr-only">${escapeHtml(lbl('dashboardInterpretation'))}</h4>
      <p class="panel-interpretation">${escapeHtml(panel.interpretation.trim())}</p>
    </div>`
    : '';
 
  // Stakeholder view badge
  const stakeholderBlock = panel.stakeholderView?.trim()
    ? `    <p class="panel-stakeholder"><span class="panel-stakeholder-label">${escapeHtml(lbl('dashboardStakeholder'))}: </span>${escapeHtml(panel.stakeholderView.trim())}</p>`
    : '';
 
  // Confidence indicator — guard NaN/Infinity values
  let confidenceBlock = '';
  if (panel.confidenceLevel != null && Number.isFinite(panel.confidenceLevel)) {
    const pct = Math.min(100, Math.max(0, panel.confidenceLevel));
    confidenceBlock = `    <div class="panel-confidence" aria-label="${escapeHtml(lbl('dashboardConfidence'))}: ${pct}%">
      <span class="panel-confidence-label">${escapeHtml(lbl('dashboardConfidence'))}</span>
      <div class="panel-confidence-bar" role="meter" aria-label="${escapeHtml(lbl('dashboardConfidence'))}" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100" aria-valuetext="${pct}%" style="--confidence:${(pct / 100).toFixed(3)}">
        <div class="panel-confidence-fill"></div>
      </div>
      <span class="panel-confidence-value">${pct}%</span>
    </div>`;
  }
 
  // Accessible table fallback
  const tableBlock = panel.table ? renderTable(panel.table) : '';
 
  // Only add sr-only "Panel:" prefix when a real title is provided,
  // to avoid redundant "Panel: Panel 1" when the title falls back to a generated label.
  const headingPrefix = realTitle
    ? `<span class="panel-type-label sr-only">${escapeHtml(lbl('dashboardPanel'))}: </span>`
    : '';
 
  return `  <article class="dashboard-panel" id="${escapeHtml(panelId)}" aria-labelledby="${escapeHtml(headingId)}">
    <h3 id="${escapeHtml(headingId)}">${headingPrefix}${escapeHtml(safeTitle)}</h3>
${visualBlock}
${interpretationBlock}
${stakeholderBlock}
${confidenceBlock}
${tableBlock}
  </article>`;
}
 
// ---------------------------------------------------------------------------
// Multi-panel public API
// ---------------------------------------------------------------------------
 
/**
 * Options for the multi-panel dashboard section generator.
 */
export interface MultiPanelDashboardOptions {
  /** Multi-panel dashboard configuration */
  data: MultiPanelDashboard;
  /** Target language for labels */
  lang: Language | string;
}
 
/**
 * Generate an embeddable multi-panel AI-driven dashboard section.
 *
 * Returns a `TemplateSection` containing a responsive grid of panels, each
 * of which may contain a Chart.js chart, a CSS-only heat map, or a CSS-only
 * gauge dial, plus AI-generated interpretation text and confidence indicators.
 * Cross-panel AI insights are rendered at the bottom.
 *
 * Accessibility: every chart canvas carries `role="img"` + `aria-label`;
 * heat maps use `role="table"` with row/column headers; gauges use
 * `role="figure"` + `aria-label`; confidence bars use `role="meter"`.
 *
 * @example
 * ```ts
 * const section = generateMultiPanelDashboardSection({
 *   data: {
 *     title: 'Coalition Stability Monitor',
 *     summary: 'AI-driven analysis of current coalition dynamics.',
 *     layout: 'grid-2x2',
 *     panels: [
 *       {
 *         id: 'alignment',
 *         title: 'Political Alignment',
 *         chart: { id: 'alignment-chart', type: 'radar', title: 'Party Positions', labels: ['Economy', 'Security'], datasets: [{ label: 'SD', data: [80, 70] }] },
 *         interpretation: 'SD leads on security issues.',
 *         confidenceLevel: 78,
 *       },
 *     ],
 *     aiInsights: [{ id: 'ins-1', text: 'Coalition majority at risk.', relevance: 'high' }],
 *   },
 *   lang: 'en',
 * });
 * articleData.sections = [...(articleData.sections ?? []), section];
 * ```
 */
export function generateMultiPanelDashboardSection(
  opts: MultiPanelDashboardOptions,
): TemplateSection {
  const { data, lang } = opts;
 
  const lbl = (key: string): string => {
    const val = L(lang, key);
    return typeof val === 'string' ? val : key;
  };
 
  const rawTitle = data.title?.trim();
  const titleText = rawTitle || lbl('dashboardTitle');
  const layoutClass = (data.layout && VALID_LAYOUTS.has(data.layout)) ? data.layout : 'grid-2x2';
 
  // Summary
  const summaryBlock = data.summary?.trim()
    ? `  <p class="multi-panel-summary">${escapeHtml(data.summary.trim())}</p>\n`
    : '';
 
  // Panels — single shared ID tracker ensures DOM id uniqueness across ALL emitted ids
  // (panel articles, chart canvases, heatmap/gauge containers, and heading ids)
  const usedIds = new Set<string>();
  const panelBlocks = data.panels
    .map((panel, idx) => renderPanel(panel, idx, lbl, usedIds))
    .join('\n');
 
  const panelsGrid = `  <div class="multi-panel-grid ${escapeHtml(layoutClass)}">\n${panelBlocks}\n  </div>`;
 
  // AI Insights section
  let insightsBlock = '';
  if (data.aiInsights && data.aiInsights.length > 0) {
    const insightItems = data.aiInsights.map(ins => {
      const relevanceClass = (ins.relevance && VALID_RELEVANCE.has(ins.relevance)) ? ` insight-${ins.relevance}` : '';
      return `      <li class="ai-insight-item${relevanceClass}">${escapeHtml(ins.text)}</li>`;
    }).join('\n');
    insightsBlock = `  <aside class="multi-panel-insights" aria-label="${escapeHtml(lbl('dashboardAiInsights'))}">
    <h3>${escapeHtml(lbl('dashboardAiInsights'))}</h3>
    <ul class="ai-insights-list">
${insightItems}
    </ul>
  </aside>`;
  }
 
  const html = `<section class="multi-panel-dashboard" aria-label="${escapeHtml(titleText)}">
  <h2>${escapeHtml(titleText)}</h2>
${summaryBlock}${panelsGrid}
${insightsBlock}
</section>`;
 
  return {
    id: 'multi-panel-dashboard',
    html,
    className: 'multi-panel-dashboard-section',
  };
}