import { site } from '../config/site';

export interface PostSummary {
  slug: string; title: string; excerpt: string | null; category: string | null; tags: string[];
  cover_url: string | null; cover_alt: string; published_at: string | null; updated_at: string | null;
  reading_minutes: number; is_featured: boolean; author: string;
}
export interface PostDetail extends PostSummary {
  body: string; meta_title: string; meta_description: string | null; keywords: string | null; focus_keyword: string | null;
  noindex: boolean; related: PostSummary[];
}

let cache: Promise<PostSummary[]> | null = null;

async function getJson(path: string) {
  const ctrl = new AbortController();
  const timer = setTimeout(() => ctrl.abort(), 6000);
  try {
    const res = await fetch(`${site.buildApiUrl}${path}`, { headers: { Accept: 'application/json' }, signal: ctrl.signal });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return await res.json();
  } finally { clearTimeout(timer); }
}

/**
 * Published blog posts, read from the API at BUILD time (static site).
 * Never throws — the blog simply shows "no posts yet" if the API is down during the build.
 * New / edited posts appear after the next build (the API can trigger it via TMS_WEBSITE_DEPLOY_HOOK).
 */
export function getPosts(): Promise<PostSummary[]> {
  if (!cache) {
    cache = getJson('/public/posts?per_page=200').then((j) => (Array.isArray(j?.data) ? j.data : [])).catch((e) => {
      console.warn(`[blog] posts not loaded (${e.message}) — building the blog without posts`);
      return [];
    });
  }
  return cache;
}

export async function getPost(slug: string): Promise<PostDetail | null> {
  try { return (await getJson(`/public/posts/${encodeURIComponent(slug)}`))?.data ?? null; } catch { return null; }
}

export const fmtDate = (iso: string | null, lang: 'en' | 'es' = 'en') =>
  (iso ? new Date(iso).toLocaleDateString(lang === 'es' ? 'es-US' : 'en-US', { year: 'numeric', month: 'long', day: 'numeric' }) : '');
export const catSlug = (c: string) => c.toLowerCase().replace(/&/g, 'and').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');

/** "<h2>Title</h2>" → id="title" anchors + a table of contents */
export function withHeadingIds(html: string): { html: string; toc: { id: string; text: string }[] } {
  const toc: { id: string; text: string }[] = [];
  const used = new Set<string>();
  const out = html.replace(/<h2>([\s\S]*?)<\/h2>/g, (_m, inner: string) => {
    const text = inner.replace(/<[^>]+>/g, '').trim();
    let id = catSlug(text) || 'section';
    while (used.has(id)) id += '-2';
    used.add(id);
    toc.push({ id, text });
    return `<h2 id="${id}">${inner}</h2>`;
  });
  return { html: out, toc };
}
