/**
 * Archetype: statTrio — three KPI cards in a row.
 *
 * The KPI dashboard standard: three numbers side by side, each with
 * a label, optional unit, and optional delta arrow. Reads as "the
 * dashboard glance" — what every executive deck has on slide 4.
 *
 * Slots:
 *   title  (optional) header text
 *   subtitle (optional)
 *   stats  (required) array of EXACTLY three:
 *          { label, value, unit?, delta?, deltaDirection?: 'up'|'down' }
 *   footnote (optional) source line at the bottom
 *
 * Cards use the theme's shape (sharp/soft/round/pill) for their
 * corners + shadow elevation.
 */
import { applyChrome, placeText, rule } from './_helpers.js';
import { kpiCard } from '../components.js';

export const id = 'statTrio';
export const slots = ['title', 'subtitle', 'stats', 'footnote'];

export default function render(slide, resolved, content, _pptx, ctx) {
  applyChrome(slide, resolved, { bgOverride: content.background, seed: 107, ctx });

  const { safe, header, body, contentGutter } = resolved.spacing;
  const palette = resolved.palette;

  // Header.
  placeText(slide, resolved, 'title', content.title, {
    x: header.x, y: header.y, w: header.w, h: 0.8,
  }, { color: palette.text, align: 'left' });

  if (content.subtitle) {
    placeText(slide, resolved, 'subtitle', content.subtitle, {
      x: header.x, y: header.y + 0.85, w: header.w, h: 0.5,
    }, { color: palette.subtle, align: 'left' });
  }

  // Three KPI cards — sized to fill the body region nicely.
  const stats = Array.isArray(content.stats) ? content.stats.slice(0, 3) : [];
  while (stats.length < 3) stats.push({});

  const gap = contentGutter;
  const cardW = (body.w - gap * 2) / 3;
  const cardH = Math.min(body.h - 0.5, 3.0);
  const cardY = body.y + (body.h - cardH) / 2;

  stats.forEach((s, i) => {
    if (!s || (s.value === undefined && !s.label)) return;
    kpiCard(slide, resolved, {
      x: body.x + i * (cardW + gap),
      y: cardY,
      w: cardW,
      h: cardH,
      label: s.label,
      value: s.value,
      unit: s.unit,
      delta: s.delta,
      deltaDirection: s.deltaDirection,
    });
  });

  if (content.footnote) {
    rule(slide, safe.x, safe.y + safe.h - 0.5, 0.5, palette.subtle, 0.5);
    placeText(slide, resolved, 'caption', content.footnote, {
      x: safe.x, y: safe.y + safe.h - 0.42, w: safe.w, h: 0.3,
    }, { color: palette.subtle, align: 'left' });
  }
}
