import React from 'react'
import ArtworkCard from './ArtworkCard'

function cx(...parts) {
  return parts.filter(Boolean).join(' ')
}

function getArtworkKey(item, index) {
  if (item?.id) return item.id
  if (item?.title || item?.name || item?.author) {
    return `${item.title || item.name || 'artwork'}-${item.author || item.author_name || item.uname || 'artist'}-${index}`
  }

  return `artwork-${index}`
}

export default function ArtworkGallery({
  items,
  layout = 'grid',
  compact = false,
  showStats = true,
  showAuthor = true,
  className = '',
  cardClassName = '',
  limit,
  containerProps = {},
  resolveCardProps,
  children,
}) {
  if (!Array.isArray(items) || items.length === 0) return null

  const visibleItems = typeof limit === 'number' ? items.slice(0, limit) : items
  const baseClassName = layout === 'masonry'
    ? 'grid gap-6'
    : 'grid grid-cols-1 gap-6 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4'

  return (
    <div className={cx(baseClassName, className)} {...containerProps}>
      {visibleItems.map((item, index) => {
        const cardProps = resolveCardProps?.(item, index) || {}
        const { className: resolvedClassName = '', ...restCardProps } = cardProps

        return (
          <ArtworkCard
            key={getArtworkKey(item, index)}
            artwork={item}
            compact={compact}
            showStats={showStats}
            showAuthor={showAuthor}
            className={cx(cardClassName, resolvedClassName)}
            {...restCardProps}
          />
        )
      })}
      {children}
    </div>
  )
}
