import type { PageSection } from '../../../lib/page-editor-service.js'
import { str, type PostRenderContext } from './parts.js'

/**
 * A grid of related posts. Uses resolved posts from context when available;
 * otherwise renders placeholder cards so the layout reads correctly in the
 * editor before data is wired up.
 */
export function RelatedPostsSection({
  section,
  context,
}: {
  section: PageSection
  context?: PostRenderContext
}) {
  const c = section.content
  const heading = str(c, 'heading', 'Related posts')
  const count = Number.parseInt(str(c, 'count', '3'), 10) || 3

  const resolved = context?.relatedPosts ?? []
  const cards =
    resolved.length > 0
      ? resolved.slice(0, count)
      : Array.from({ length: count }, (_, i) => ({
          title: `Related post ${i + 1}`,
          excerpt: 'A short summary of the related post will appear here.',
          url: undefined as string | undefined,
        }))

  const cols = count >= 4 ? 'sm:grid-cols-2 lg:grid-cols-4' : 'sm:grid-cols-3'

  return (
    <div className="mx-auto max-w-5xl px-6">
      {heading && (
        <h2 className="text-foreground mb-6 text-2xl font-semibold tracking-tight">{heading}</h2>
      )}
      <div className={`grid grid-cols-1 gap-4 ${cols}`}>
        {cards.map((post, i) => (
          <div
            key={i}
            className="border-border bg-card overflow-hidden rounded-xl border shadow-sm"
          >
            <div className="bg-muted aspect-[16/9]" aria-hidden />
            <div className="p-4">
              <p className="text-foreground text-base font-medium">{post.title}</p>
              {post.excerpt && (
                <p className="text-muted-foreground mt-1 line-clamp-2 text-sm">{post.excerpt}</p>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  )
}
