import type { Metadata } from 'next'
import { CategoryCard, CourseCard } from '@/components/Cards'
import { Shell } from '@/components/Shell'
import { publicConfig } from '@/lib/config'
import { pageMeta } from '@/lib/meta'
import { type Locale, categoryOf, loadPage, loadSite } from '@/lib/site'

type Props = { params: Promise<{ locale: Locale }> }

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { locale } = await params
  const p = await loadPage('categories', locale)
  return pageMeta(locale, '/categories', p.seo?.title, p.seo?.description)
}

/**
 * The learning areas, each with how many courses sit under it.
 *
 * The areas are the platform's own categories and the counts are worked out from the catalogue, so a
 * category added or emptied on the platform is right here on the next request with nothing edited.
 * A card opens the catalogue already filtered to that area.
 */
export default async function CategoriesPage({ params }: Props) {
  const { locale } = await params
  const [{ settings: s, courses, categories }, p, cat] = await Promise.all([
    loadSite(locale),
    loadPage('categories', locale),
    loadPage('catalogue', locale),
  ])
  const cfg = publicConfig()
  const featured = [...courses]
    .sort((a, b) => (a.status === 'live' ? 0 : 1) - (b.status === 'live' ? 0 : 1))
    .slice(0, 3)

  return (
    <Shell locale={locale} path="/categories" settings={s} courses={courses} config={cfg}>
      <div className="container pagehead">
        <h1>{p.h1}</h1>
        <p>{p.lead}</p>
      </div>
      <section className="container">
        <div className="grid category-grid">
          {categories.map((k) => (
            <CategoryCard key={k.id} category={k} locale={locale} forms={cat.count || {}}
                          count={courses.filter((c) => categoryOf(c, categories)?.id === k.id).length} />
          ))}
        </div>

        {p.featuredTitle && featured.length ? (
          <div className="section">
            <div className="section-head">
              <div>
                <h2>{p.featuredTitle}</h2>
                <p>{p.featuredLead}</p>
              </div>
            </div>
            <div className="grid">
              {featured.map((c) => (
                <CourseCard key={c.id} course={c} settings={s} locale={locale}
                            category={categoryOf(c, categories)} priceWasLabel={cat.labels?.priceWas} />
              ))}
            </div>
          </div>
        ) : null}
      </section>
    </Shell>
  )
}
