import React from 'react'
import CollectionCard from '../../components/profile/collections/CollectionCard'

function normalizeItems(items) {
  if (!Array.isArray(items)) return []

  return items.filter((item) => item && typeof item === 'object')
}

export default function HomeCollections({
  featured,
  recent,
  trending,
  editorial,
  community,
}) {
  const featuredItems = normalizeItems(featured)
  const recentItems = normalizeItems(recent)
  const trendingItems = normalizeItems(trending)
  const editorialItems = normalizeItems(editorial)
  const communityItems = normalizeItems(community)
  const displayItems = (
    trendingItems.length ? trendingItems :
    featuredItems.length ? featuredItems :
    recentItems.length ? recentItems :
    editorialItems.length ? editorialItems :
    communityItems
  ).slice(0, 3)

  if (!displayItems.length) {
    return null
  }

  return (
    <section className="mt-14 px-4 sm:px-6 lg:px-8">
      <div className="mb-5 flex items-center justify-between gap-4">
        <div>
          <h2 className="text-xl font-bold text-white">Trending Collections</h2>
          <p className="mt-1 max-w-2xl text-sm text-nova-300">
            Collections getting the strongest mix of follows, saves, and engagement right now.
          </p>
        </div>
        <a href="/collections/trending" className="shrink-0 text-sm text-nova-300 transition hover:text-white">
          All collections →
        </a>
      </div>

      <div className="grid gap-4 lg:grid-cols-2 xl:grid-cols-3">
        {displayItems.map((collection) => (
          <CollectionCard key={collection.id} collection={collection} isOwner={false} />
        ))}
      </div>
    </section>
  )
}
