// articles.jsx — โหลดบทความจาก articles/<slug>/article.md (Markdown + YAML frontmatter)
// ค้นพบ slug ผ่าน articles/index.json, เรนเดอร์ body ด้วย marked.parse,
// เรียง newest-first ตาม `date` (ISO) ในส่วน frontmatter

const TH_MONTHS = [
  "ม.ค.", "ก.พ.", "มี.ค.", "เม.ย.", "พ.ค.", "มิ.ย.",
  "ก.ค.", "ส.ค.", "ก.ย.", "ต.ค.", "พ.ย.", "ธ.ค."
];

function formatThaiDate(iso) {
  const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso || "");
  if (!m) return iso || "";
  return `${parseInt(m[3], 10)} ${TH_MONTHS[parseInt(m[2], 10) - 1]} ${m[1]}`;
}

// YAML subset: "key: value", "key: \"quoted: value\"", numbers, true/false, [a, b, c]
function parseScalar(raw) {
  const s = raw.trim();
  if (s === "") return "";
  if (s === "true") return true;
  if (s === "false") return false;
  if (/^-?\d+(\.\d+)?$/.test(s)) return Number(s);
  if (s.startsWith("[") && s.endsWith("]")) {
    return s.slice(1, -1).split(",").map((x) => parseScalar(x)).filter((x) => x !== "");
  }
  if ((s.startsWith('"') && s.endsWith('"')) || (s.startsWith("'") && s.endsWith("'"))) {
    return s.slice(1, -1);
  }
  return s;
}

function parseFrontmatter(text) {
  // คาดหวัง: "---\n...meta...\n---\n...body..."
  const m = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/.exec(text);
  if (!m) return { meta: {}, body: text };
  const meta = {};
  for (const line of m[1].split(/\r?\n/)) {
    if (!line.trim() || line.trim().startsWith("#")) continue;
    const idx = line.indexOf(":");
    if (idx < 0) continue;
    const key = line.slice(0, idx).trim();
    const val = line.slice(idx + 1);
    meta[key] = parseScalar(val);
  }
  return { meta, body: m[2] };
}

async function fetchArticle(slug) {
  const res = await fetch(`articles/${slug}/article.md`, { cache: "no-cache" });
  if (!res.ok) throw new Error(`fetch failed: articles/${slug}/article.md ${res.status}`);
  const text = await res.text();
  const { meta, body } = parseFrontmatter(text);
  const bodyHtml = window.marked ? window.marked.parse(body) : `<p>${body}</p>`;
  return {
    id: slug,
    title: meta.title || slug,
    category: meta.category || "",
    date: formatThaiDate(meta.date),
    isoDate: meta.date || "",
    readTime: meta.readTime || "",
    featured: !!meta.featured,
    tags: Array.isArray(meta.tags) ? meta.tags : [],
    excerpt: meta.excerpt || "",
    image: meta.image ? `articles/${slug}/${meta.image}` : null,
    bodyHtml,
  };
}

async function loadArticles() {
  const res = await fetch("articles/index.json", { cache: "no-cache" });
  if (!res.ok) throw new Error(`fetch failed: articles/index.json ${res.status}`);
  const slugs = await res.json();
  const articles = await Promise.all(slugs.map((s) => fetchArticle(s).catch((e) => {
    console.warn(`[articles] skip ${s}:`, e);
    return null;
  })));
  return articles
    .filter(Boolean)
    .sort((a, b) => (a.isoDate < b.isoDate ? 1 : a.isoDate > b.isoDate ? -1 : 0));
}

Object.assign(window, { loadArticles, formatThaiDate });
