/**
 * Latest Instagram posts, fetched at build time with the Instagram API (Instagram Login).
 * Needs INSTAGRAM_TOKEN (a long-lived token of the professional account @shaninaway).
 * Without a token the section shows a follow card instead. See README → Instagram.
 */
export type InstagramPost = { id: string; caption: string; image: string; permalink: string; timestamp: string };

let cached: Promise<InstagramPost[]> | null = null;

export function getInstagramPosts(limit = 6): Promise<InstagramPost[]> {
  const token = import.meta.env.INSTAGRAM_TOKEN as string | undefined;
  if (!token) return Promise.resolve([]);
  cached ??= (async () => {
    try {
      const fields = 'id,caption,media_type,media_url,thumbnail_url,permalink,timestamp';
      const res = await fetch(`https://graph.instagram.com/me/media?fields=${fields}&limit=12&access_token=${token}`);
      if (!res.ok) throw new Error(`Instagram API ${res.status}`);
      const json = (await res.json()) as { data: any[] };
      return json.data.map((m) => ({
        id: m.id,
        caption: m.caption ?? '',
        image: m.media_type === 'VIDEO' ? m.thumbnail_url : m.media_url,
        permalink: m.permalink,
        timestamp: m.timestamp,
      }));
    } catch (err) {
      console.warn('[instagram] skipped:', (err as Error).message);
      return [];
    }
  })();
  return cached.then((posts) => posts.slice(0, limit));
}
