/* ============================================================
   Blog data — fetched from Sanity CDN at runtime.
   Project ID is a read-only public identifier; no secret is exposed.
   ============================================================ */

const SANITY_PROJECT_ID = 'jwhvodcc';   // replace with your Sanity project ID
const SANITY_DATASET    = 'production';
const SANITY_API_VER    = '2021-10-21';

const GROQ = `*[_type == "post"] | order(publishedAt desc) {
  "id":          slug.current,
  title,
  summary,
  "iso":         publishedAt,
  kind,
  "tags":        tags[],
  featured,
  "readMinutes": readMinutes,
  body
}`;

function formatDate(iso) {
  return new Date(iso + 'T00:00:00').toLocaleDateString('en-US', {
    month: 'short', day: 'numeric', year: 'numeric',
  });
}

function computeTags(posts) {
  const counts = {};
  for (const p of posts) for (const t of (p.tags || [])) counts[t] = (counts[t] || 0) + 1;
  return Object.keys(counts).sort((a, b) => counts[b] - counts[a]);
}

async function loadPosts() {
  const url =
    `https://${SANITY_PROJECT_ID}.apicdn.sanity.io/v${SANITY_API_VER}/data/query/${SANITY_DATASET}` +
    `?query=${encodeURIComponent(GROQ)}`;

  const res = await fetch(url);
  if (!res.ok) throw new Error(`Sanity fetch failed: ${res.status}`);
  const { result } = await res.json();

  return result.map(p => ({
    id:       p.id,
    title:    p.title,
    summary:  p.summary,
    iso:      p.iso,
    date:     formatDate(p.iso),
    year:     new Date(p.iso + 'T00:00:00').getFullYear(),
    read:     (p.readMinutes || 5) + ' min',
    kind:     p.kind || 'essay',
    tags:     p.tags || [],
    featured: p.featured || false,
    content:  p.body || [],
  }));
}

window.loadPosts = loadPosts;
window.computeTags = computeTags;
