import Link from "next/link";
import { getServerSession } from "next-auth";
import { authOptions } from "@/lib/auth-options";
import { listPublishedCourses } from "@/lib/course-queries";
import { CourseCard } from "@/components/course-card";
import { prisma } from "@/lib/prisma";
import { getLandingContent } from "@/lib/landing";

export default async function HomePage() {
  const session = await getServerSession(authOptions);
  const courses = await listPublishedCourses();
  const landing = await getLandingContent();

  let enrolledIds = new Set<string>();
  if (session?.user?.id) {
    const rows = await prisma.enrollment.findMany({
      where: { userId: session.user.id },
      select: { courseId: true },
    });
    enrolledIds = new Set(rows.map((r) => r.courseId));
  }

  return (
    <>
      <section className="hero">
        <div className="container">
          <h1>{landing.heroTitle}</h1>
          <p className="lead">{landing.heroLead}</p>
          <div className="hero-actions">
            <Link href={landing.primaryCta.href} className="btn btn-primary">
              {landing.primaryCta.label}
            </Link>
            {landing.secondaryCta ? (
              <Link href={landing.secondaryCta.href} className="btn btn-ghost">
                {landing.secondaryCta.label}
              </Link>
            ) : null}
          </div>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <h2>Unsere Kurse &amp; Module</h2>
          <div className="course-grid">
            {courses.map((c) => (
              <CourseCard key={c.id} course={c} enrolled={enrolledIds.has(c.id)} />
            ))}
          </div>
        </div>
      </section>

      <section className="section">
        <div className="container">
          <h2>{landing.benefitSectionTitle}</h2>
          <div className="course-grid">
            {landing.benefits.map((b, idx) => (
              <div key={idx} className="panel">
                <h3>{b.title}</h3>
                <p className="muted">{b.body}</p>
              </div>
            ))}
          </div>
        </div>
      </section>
    </>
  );
}
