import type { Metadata } from 'next'
import { CategoryCard, CourseCard } from '@/components/Cards'
import { Icon, type IconName } from '@/components/icons'
import { Shell } from '@/components/Shell'
import { publicConfig } from '@/lib/config'
import { pageMeta } from '@/lib/meta'
import { type Locale, categoryOf, loadPage, loadSite, localHref, media } from '@/lib/site'

type Props = { params: Promise<{ locale: Locale }> }

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { locale } = await params
  const h = await loadPage('home', locale)
  return pageMeta(locale, '/', h.seo?.title, h.seo?.description)
}

/**
 * The home page: hero, learning areas, featured courses, why Thinkera, and a call to action.
 *
 * Every word is a CMS field and every course and category is the platform's. A band whose heading has
 * not been written is not rendered at all — an editor adding the heading is what turns it on, so the
 * page is never half-finished-looking with an empty section in the middle of it.
 */
export default async function Home({ params }: Props) {
  const { locale } = await params
  const [{ settings: s, courses, categories }, h, cat] = await Promise.all([
    loadSite(locale),
    loadPage('home', locale),
    loadPage('catalogue', locale),
  ])
  const cfg = publicConfig()
  const hero = media(h.heroImage)
  const f = cat.filters

  // The three cards under «featured»: what a visitor can start today comes first, because a catalogue
  // that leads with four «coming soon» cards reads as an academy with nothing to sell.
  const featured = [...courses].sort((a, b) => rank(a.status) - rank(b.status)).slice(0, 3)

  return (
    <Shell locale={locale} path="/" settings={s} courses={courses} config={cfg}>
      <section className="hero">
        <div className="container hero-layout">
          <div>
            {h.eyebrow ? <span className="eyebrow">{h.eyebrow}</span> : null}
            <h1>
              {h.h1}
              {h.h1Accent ? (
                <>
                  <br />
                  <span className="accent">{h.h1Accent}</span>
                </>
              ) : null}
            </h1>
            <p>{h.lead}</p>
            <div className="actions">
              <a className="btn" href={localHref(locale, '/courses')}>
                {h.browseCta || s.cta?.all}
                <Icon name="arrow" />
              </a>
              <a className="btn secondary" href={localHref(locale, '/categories')}>
                {h.categoriesCta}
              </a>
            </div>
            {(h.facts || []).length ? (
              <div className="hero-facts">
                {(h.facts || []).map((x) => (
                  <div key={x.id || x.n}>
                    <b>{x.n}</b>
                    <span>{x.label}</span>
                  </div>
                ))}
              </div>
            ) : null}
          </div>

          {/* The art panel. A picture set in the CMS fills it; with none, the drawn placeholder stands
              in. Either way it is decoration — aria-hidden, and it says nothing the words do not. */}
          <div className="hero-art" aria-hidden="true">
            {hero?.url ? (
              <img src={hero.url} alt="" width={720} height={560} />
            ) : (
              <div className="art-inner">
                <div className="art-screen">
                  <Icon name="layers" />
                </div>
                <div className="art-lines" />
                <div className="art-lines last" />
              </div>
            )}
            {h.noteOne ? <div className="float-note top">✓ {h.noteOne}</div> : null}
            {h.noteTwo ? <div className="float-note">✦ {h.noteTwo}</div> : null}
          </div>
        </div>
      </section>

      {h.catTitle && categories.length ? (
        <section className="section muted">
          <div className="container">
            <div className="section-head">
              <div>
                {h.catEyebrow ? <span className="eyebrow">{h.catEyebrow}</span> : null}
                <h2>{h.catTitle}</h2>
                <p>{h.catText}</p>
              </div>
              {h.catLink ? (
                <a className="link" href={localHref(locale, '/categories')}>
                  {h.catLink} ↗
                </a>
              ) : null}
            </div>
            <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>
          </div>
        </section>
      ) : null}

      {featured.length ? (
        <section className="section">
          <div className="container">
            <div className="section-head">
              <div>
                {h.featuredEyebrow ? <span className="eyebrow">{h.featuredEyebrow}</span> : null}
                <h2>{h.coursesTitle}</h2>
                <p>{h.coursesLead}</p>
              </div>
              {h.featuredLink ? (
                <a className="link" href={localHref(locale, '/courses')}>
                  {h.featuredLink} ↗
                </a>
              ) : null}
            </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>
        </section>
      ) : null}

      {(h.why || []).length ? (
        <section className="section muted features">
          <div className="container">
            <div className="section-head">
              <div>
                {h.whyEyebrow ? <span className="eyebrow">{h.whyEyebrow}</span> : null}
                <h2>{h.whyTitle}</h2>
              </div>
            </div>
            <div className="grid">
              {(h.why || []).map((v) => (
                <div className="feature" key={v.id || v.title}>
                  <div className="feature-icon">
                    <Icon name={(v.icon || 'book') as IconName} />
                  </div>
                  <h3>{v.title}</h3>
                  <p>{v.text}</p>
                </div>
              ))}
            </div>
          </div>
        </section>
      ) : null}

      {h.ctaTitle ? (
        <section className="section">
          <div className="container">
            <div className="cta">
              <div>
                <h2>{h.ctaTitle}</h2>
                <p>{h.ctaLead}</p>
              </div>
              <a className="btn" href={localHref(locale, '/courses')}>
                {h.browseCta || s.cta?.all}
                <Icon name="arrow" />
              </a>
            </div>
          </div>
        </section>
      ) : null}
    </Shell>
  )
}

/** Available first, then partly available, then what is still coming. */
function rank(status: string | null | undefined): number {
  return status === 'live' ? 0 : status === 'partial' ? 1 : 2
}
