/**
 * Archetype: table — title + a striped data table.
 *
 * Slots:
 *   - title     (optional)
 *   - headers   (required) array of column header strings
 *   - rows      (required) array of arrays — one inner array per row
 *
 * Stripes use the palette's `surface` colour for odd rows; numeric-
 * looking cells right-align automatically. Data-heavy renders numbers
 * in monospace.
 */
import { applyChrome, placeText } from './_helpers.js';
import { textStyle } from '../typography.js';

export const id = 'table';
export const slots = ['title', 'headers', 'rows'];

function isNumeric(value) {
  if (value === null || value === undefined) return false;
  const s = String(value).replace(/[\s,$%]/g, '');
  return s !== '' && !isNaN(Number(s));
}

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

  const cfg = resolved.archetypeConfig('table');
  const { header, body } = resolved.spacing;

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

  const headers = content.headers || [];
  const rows = content.rows || [];
  if (headers.length === 0) return;

  // Header row
  const headerRow = headers.map(h => ({
    text: String(h ?? ''),
    options: {
      bold: true,
      color: resolved.palette.text,
      fontFace: resolved.typography.subtitle.fontFace,
      fontSize: resolved.typography.body.fontSize,
      fill: { color: resolved.palette.surface },
      align: 'left',
    },
  }));

  // Data rows
  const monoFont = cfg.monospaceNumbers ? resolved.typography.mono.fontFace : null;
  const tableRows = rows.map((row, i) => row.map((cell) => {
    const numeric = isNumeric(cell);
    const fontFace = (numeric && monoFont) ? monoFont : resolved.typography.body.fontFace;
    return {
      text: cell === null || cell === undefined ? '' : String(cell),
      options: {
        color: resolved.palette.text,
        fontFace,
        fontSize: resolved.typography.body.fontSize,
        align: numeric ? 'right' : 'left',
        fill: (cfg.striped && i % 2 === 1) ? { color: resolved.palette.surface } : undefined,
      },
    };
  }));

  slide.addTable([headerRow, ...tableRows], {
    x: body.x, y: body.y, w: body.w, h: body.h,
    border: { type: 'solid', pt: 0.5, color: resolved.palette.subtle },
    autoPage: false,
  });
}
