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

interface GalleryImage {
  url?: string
  alt?: string
  caption?: string
}

/** A responsive image grid with captions. */
export function GallerySection({ section }: { section: PageSection }) {
  const c = section.content
  const heading = str(c, 'heading')
  const columns = Number.parseInt(str(c, 'columns', '3'), 10) || 3
  const images: GalleryImage[] = Array.isArray(c.images) ? (c.images as GalleryImage[]) : []
  const withUrl = images.filter((img) => img && typeof img.url === 'string' && img.url)

  const cols =
    columns === 2
      ? 'sm:grid-cols-2'
      : columns === 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>
      )}
      {withUrl.length > 0 ? (
        <div className={`grid grid-cols-1 gap-3 ${cols}`}>
          {withUrl.map((img, i) => (
            <figure key={i} className="border-border overflow-hidden rounded-lg border">
              <img
                src={img.url}
                alt={img.alt ?? ''}
                className="aspect-square w-full object-cover"
              />
              {img.caption && (
                <figcaption className="text-muted-foreground px-2 py-1.5 text-xs">
                  {img.caption}
                </figcaption>
              )}
            </figure>
          ))}
        </div>
      ) : (
        <div className={`grid grid-cols-1 gap-3 ${cols}`}>
          {Array.from({ length: columns }, (_, i) => (
            <div key={i} className="bg-muted aspect-square rounded-lg" aria-hidden />
          ))}
        </div>
      )}
    </div>
  )
}
