import type { Metadata } from 'next'
import type { Course } from '@/payload-types'
import { CourseCard } from '@/components/Course'
import { Shell } from '@/components/Shell'
import { pageMeta } from '@/lib/meta'
import { type Locale, 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('catalogue', locale)
  return pageMeta(locale, '/courses', p.seo?.title, p.seo?.description)
}

/**
 * The catalogue, grouped the way the platform files its courses: one heading per category, in the platform's
 * order. When the platform cannot be asked there are no categories to group by, and the courses sit in one
 * grid as they always did.
 */
export default async function Courses({ params }: Props) {
  const { locale } = await params
  const [{ settings, courses, categories }, p] = await Promise.all([loadSite(locale), loadPage('catalogue', locale)])

  type WithCategory = Course & { categoryId?: number }
  const groups = categories.length
    ? categories
        .map((k) => ({ ...k, items: (courses as WithCategory[]).filter((c) => c.categoryId === k.id) }))
        .filter((g) => g.items.length)
    : [{ id: 0, slug: 'all', name: '', items: courses as WithCategory[] }]

  return (
    <Shell locale={locale} path="/courses" settings={settings} courses={courses}>
      <main id="main" className="section">
        <div className="wrap">
          <h1>{p.h1}</h1>
          <p className="lead">{p.lead}</p>
          {groups.map((g) => (
            <section key={g.slug} className="course-group" id={g.slug} aria-labelledby={g.name ? `cat-${g.slug}` : undefined}>
              {g.name ? (
                <h2 className="course-group-title" id={`cat-${g.slug}`}>
                  {g.name}
                  <span className="course-group-count">{g.items.length}</span>
                </h2>
              ) : null}
              <div className="grid grid--3">
                {g.items.map((c) => (
                  <CourseCard key={c.id} course={c} locale={locale} settings={settings} level={g.name ? 3 : 2} />
                ))}
              </div>
            </section>
          ))}
        </div>
      </main>
    </Shell>
  )
}
