---
const { posts, tag } = Astro.props;

// Extract first cover image directly from the raw markdown body.
// Cheap regex — avoids rendering the full HTML for each card.
function firstImage(body) {
  const m = body && body.match(/!\[[^\]]*\]\((\/images\/[^)]+)\)/);
  return m ? m[1] : null;
}

const enriched = posts.map((p) => ({
  ...p,
  cover: firstImage(p.body),
}));
const hero = enriched[0];
const rest = enriched.slice(1);

const fmt = (d) => new Date(d).toLocaleDateString('en-US',
  { year: 'numeric', month: 'long', day: 'numeric' });
---
{tag && (
  <h2 class="tag-banner">
    Tagged: <em>{tag}</em>
  </h2>
)}

{enriched.length > 0 && !tag && hero && (
  <article class="post-hero" data-reveal>
    {hero.cover && (
      <div class="post-hero-img">
        <img src={hero.cover} alt="" loading="eager" />
      </div>
    )}
    <div class="post-hero-body">
      <div class="post-hero-flag">Top story</div>
      <h2 class="post-hero-title">
        <a class="card-link" href={`/${hero.slug}/`}>{hero.title}</a>
      </h2>
      <p class="post-hero-excerpt">{hero.rawExcerpt}</p>
      <div class="post-hero-meta">
        <span>{fmt(hero.date)}</span>
        {hero.tags.slice(0, 4).map((t) => (
          <span class="post-hero-tag"><a href={`/tag/${t}/`}>{t}</a></span>
        ))}
      </div>
    </div>
  </article>
)}

{(tag ? enriched : rest).map((post, i) => (
  <article class="post-row" data-reveal style={`animation-delay:${Math.min(i * 50, 500)}ms`}>
    {post.cover && (
      <div class="post-row-img">
        <img src={post.cover} alt="" loading="lazy" />
      </div>
    )}
    <div class="post-row-body">
      <h3 class="post-row-title">
        <a class="card-link" href={`/${post.slug}/`}>{post.title}</a>
      </h3>
      <p class="post-row-excerpt">{post.rawExcerpt}</p>
      <div class="post-row-meta">
        <time>{fmt(post.date)}</time>
        {post.tags.slice(0, 3).map((t) => (
          <span class="post-row-tag"><a href={`/tag/${t}/`}>{t}</a></span>
        ))}
      </div>
    </div>
  </article>
))}

{enriched.length === 0 && (
  <p class="post-empty">No posts yet.</p>
)}

<script is:inline>
(() => {
  const els = document.querySelectorAll('[data-reveal]');
  if (!('IntersectionObserver' in window)) {
    els.forEach((e) => e.classList.add('is-visible'));
    return;
  }
  const obs = new IntersectionObserver((entries) => {
    for (const e of entries) {
      if (e.isIntersecting) {
        e.target.classList.add('is-visible');
        obs.unobserve(e.target);
      }
    }
  }, { rootMargin: '0px 0px -10% 0px', threshold: 0.05 });
  els.forEach((e) => obs.observe(e));
})();
</script>
