import type { Metadata } from 'next'
import type { Course } from '@/payload-types'
import { CourseCard, UnitList } from '@/components/Course'
import { Shell } from '@/components/Shell'
import { pageMeta } from '@/lib/meta'
import { type Locale, 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)
}

export default async function Home({ params }: Props) {
  const { locale } = await params
  const [{ settings: s, courses }, h, cat] = await Promise.all([loadSite(locale), loadPage('home', locale), loadPage('catalogue', locale)])
  const free = localHref(locale, s.freeLessonHref)
  const hero = media(h.heroImage)
  const life = media(h.lifeImage)
  const unitsCourse = (typeof h.unitsCourse === 'object' && h.unitsCourse) || courses.find((c) => (c.units || []).length > 0)
  const unitsFull = courses.find((c) => c.id === (unitsCourse as Course | undefined)?.id) || (unitsCourse as Course | undefined)

  return (
    <Shell locale={locale} path="/" settings={s} courses={courses}>
      <main id="main">
        <section className="hero">
          <div className="wrap">
            <div className="hero-copy">
              <p className="eyebrow">{h.eyebrow}</p>
              <h1>
                {h.h1}
                {h.h1Accent ? <span className="spark">{h.h1Accent}</span> : null}
              </h1>
              <p>{h.lead}</p>
              <div className="btn-row">
                <a className="btn btn--on-dark" href={free}>
                  {s.cta?.free}
                </a>
                <a className="btn btn--ghost-dark" href={localHref(locale, '/courses')}>
                  {s.cta?.all}
                </a>
              </div>
              <ul className="hero-facts">
                {(h.facts || []).map((f) => (
                  <li key={f.id}>
                    <b className="num">{f.n}</b>
                    <span>{f.label}</span>
                  </li>
                ))}
              </ul>
            </div>
            {hero?.url ? (
              <div className="hero-art">
                <img src={hero.url} alt={hero.alt} width={hero.width || 476} height={hero.height || 900} />
              </div>
            ) : null}
          </div>
        </section>

        <section className="section" id="beyond">
          <div className="wrap">
            <h2>{h.bookTitle}</h2>
            <p className="lead">{h.bookLead}</p>
            <figure className="comp">
              <figcaption>{h.bookBarTitle}</figcaption>
              <div className="comp-bar" role="img" aria-label={h.bookBarTitle || ''}>
                {(h.bookBar || []).map((b) => (
                  <span key={b.id} className={`seg seg--${b.kind}`} style={{ flex: Number(b.n) || 1 }}>
                    <b className="num">{b.n}</b>
                    <span>{b.label}</span>
                  </span>
                ))}
              </div>
            </figure>
            {h.bookCode ? (
              <p className="code-note">
                <span aria-hidden="true" className="code-ico">
                  &lt;/&gt;
                </span>
                {h.bookCode}
              </p>
            ) : null}
            <h3 style={{ marginTop: 'var(--tk-space-7)' }}>{h.layersTitle}</h3>
            <div className="grid grid--3 layers">
              {(h.layers || []).map((l) => (
                <article key={l.id} className="layer">
                  <span className={`layer-badge${l.plain ? ' layer-badge--none' : ''}`} lang={l.plain ? undefined : 'en'}>
                    {l.badge}
                  </span>
                  <h4>{l.name}</h4>
                  <p className="muted">{l.text}</p>
                </article>
              ))}
            </div>
            {h.paths ? <p className="paths">{h.paths}</p> : null}
          </div>
        </section>

        <section className="section-tight band">
          <div className="wrap">
            <h2>{h.stepsTitle}</h2>
            <ol className="steps">
              {(h.steps || []).map((st) => (
                <li key={st.id} className="step">
                  <span className="step-n num">{st.n}</span>
                  <h3>{st.title}</h3>
                  <p className="muted">{st.text}</p>
                </li>
              ))}
            </ol>
          </div>
        </section>

        <section className="section">
          <div className="wrap life">
            {life?.url ? (
              <figure className="life-img">
                <img src={life.sizes?.wide?.url || life.url} alt={life.alt} width={1200} height={675} loading="lazy" />
              </figure>
            ) : null}
            <div>
              <h2>{h.lifeTitle}</h2>
              <p className="lead">{h.lifeText}</p>
              <div className="lboxes">
                {(h.lifeBoxes || []).map((b) => (
                  <div key={b.id} className="lbox">
                    <h3 lang="en">{b.title}</h3>
                    <p>{b.text}</p>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </section>

        {unitsFull && cat.labels ? (
          <section className="section-tight band">
            <div className="wrap">
              <h2>{h.unitsTitle}</h2>
              <p className="lead">{h.unitsLead}</p>
              <UnitList course={unitsFull} labels={cat.labels} />
            </div>
          </section>
        ) : null}

        <section className="section">
          <div className="wrap">
            <h2>{h.peopleTitle}</h2>
            <div className="grid grid--2">
              {(h.people || []).map((p) => (
                <article key={p.id} className="card person">
                  <h3>{p.name}</h3>
                  <p className="muted">{p.text}</p>
                </article>
              ))}
            </div>
          </div>
        </section>

        <section className="section-tight">
          <div className="wrap">
            <h2>{h.coursesTitle}</h2>
            <p className="lead">{h.coursesLead}</p>
            <div className="grid grid--3" style={{ marginTop: 'var(--tk-space-6)' }}>
              {courses.map((c) => (
                <CourseCard key={c.id} course={c} locale={locale} settings={s} />
              ))}
            </div>
          </div>
        </section>

        <section className="cta-band">
          <div className="wrap narrow center">
            <h2>{h.ctaTitle}</h2>
            <p className="lead">{h.ctaLead}</p>
            <div className="btn-row" style={{ justifyContent: 'center' }}>
              <a className="btn btn--on-dark" href={free}>
                {s.cta?.free}
              </a>
              <a className="btn btn--ghost-dark" href={localHref(locale, '/pricing')}>
                {s.cta?.enrol}
              </a>
            </div>
          </div>
        </section>

        <section className="section-tight">
          <div className="wrap narrow">
            <h2>{h.faqTitle}</h2>
            <div className="faq">
              {(h.faq || []).map((f) => (
                <details key={f.id}>
                  <summary>{f.q}</summary>
                  <p>{f.text}</p>
                </details>
              ))}
            </div>
          </div>
          {/* the same questions for search engines (FAQPage structured data), from the CMS like the list above */}
          {(h.faq || []).length > 0 && (
            <script
              type="application/ld+json"
              dangerouslySetInnerHTML={{
                __html: JSON.stringify({
                  '@context': 'https://schema.org',
                  '@type': 'FAQPage',
                  inLanguage: locale,
                  mainEntity: (h.faq || []).map((f) => ({
                    '@type': 'Question',
                    name: f.q,
                    acceptedAnswer: { '@type': 'Answer', text: f.text },
                  })),
                }).replace(/</g, '\\u003c'),
              }}
            />
          )}
        </section>
      </main>
    </Shell>
  )
}
