/* global window */
/* Registro de artigos do blog da Moore AI (multilíngue: i18n {pt,en,es}).
   Cada post chama registerArticle(...) e é empurrado para window.MOORE_ARTICLES.
   Este arquivo carrega antes dos posts. */

window.MOORE_ARTICLES = window.MOORE_ARTICLES || [];

/* Extrai texto puro de um valor inline (string, objeto de link/ênfase ou array). */
function inlineText(value) {
  if (value == null) return '';
  if (typeof value === 'string') return value;
  if (Array.isArray(value)) return value.map(inlineText).join(' ');
  if (typeof value === 'object') return inlineText(value.text);
  return '';
}

/* Conta palavras de um corpo de blocos para estimar o tempo de leitura. */
function countWords(body) {
  let text = '';
  (body || []).forEach((block) => {
    if (block.text) text += ' ' + inlineText(block.text);
    if (block.title) text += ' ' + inlineText(block.title);
    if (block.items) text += ' ' + block.items.map(inlineText).join(' ');
    if (block.headers) text += ' ' + block.headers.map(inlineText).join(' ');
    if (block.rows) text += ' ' + block.rows.map((row) => row.map(inlineText).join(' ')).join(' ');
  });
  const words = text.trim().split(/\s+/).filter(Boolean);
  return words.length;
}

function registerArticle(article) {
  const i18n = article.i18n || {};
  const readingMinutes = {};
  ['pt', 'en', 'es'].forEach((l) => {
    const c = i18n[l];
    readingMinutes[l] = c && c.body ? Math.max(1, Math.round(countWords(c.body) / 200)) : 1;
  });
  const enriched = { ...article, readingMinutes };
  window.MOORE_ARTICLES.push(enriched);
  return enriched;
}

window.registerArticle = registerArticle;
window.mooreInlineText = inlineText;
window.mooreGetArticle = function (slug) {
  return (window.MOORE_ARTICLES || []).find((a) => a.slug === slug) || null;
};
