import type { Metadata } from "next";
import Image from "next/image";

import { PlanCardActions } from "@/components/cart/plan-card-actions";
import { PageShell } from "@/components/layout/page-shell";
import { GlassCard } from "@/components/shared/glass-card";
import { getSession } from "@/lib/auth/session";
import { getCatalogProducts } from "@/lib/cms/server";
import { getEntitlements } from "@/lib/db/store";
import { buildCmsPageMetadata } from "@/lib/seo/page-metadata";
import { cn } from "@/lib/utils";

export const dynamic = "force-dynamic";

export async function generateMetadata(): Promise<Metadata> {
  return buildCmsPageMetadata(
    "programs",
    "Programs & Plans",
    "Premium coaching packages, multi-month plans, diet-only and workout-only options, detox, and meal ebooks.",
    "/programs",
  );
}

export default async function ProgramsPage() {
  const [products, session] = await Promise.all([getCatalogProducts(), getSession()]);
  const ownedIds = session?.email ? await getEntitlements(session.email) : [];
  const hasActivePlan = products.some(
    (p) => p.type === "program" && ownedIds.includes(p.id),
  );

  return (
    <PageShell
      title="PROGRAMS"
      description={
        hasActivePlan
          ? "Your current plan is highlighted below. Upgrade anytime or manage access from your dashboard."
          : "Pick the tier that matches your timeline — full coaching, training only, nutrition only, or detox."
      }
      breadcrumbs={[{ label: "Home", href: "/" }, { label: "Programs" }]}
      width="wide"
    >
      <div className="space-y-16">
        {products
          .filter((p) => p.type !== "ebook")
          .map((p, i) => (
            <section
              key={p.id}
              id={p.slug}
              className="scroll-mt-28 border-b border-border/60 pb-16 last:border-0"
            >
              <GlassCard className="overflow-hidden p-0 sm:flex">
                <div className="relative aspect-video overflow-hidden bg-black sm:w-[380px] sm:shrink-0">
                  <Image
                    src={p.image}
	                    alt={p.title}
	                    fill
	                    priority={i === 0}
	                    className={cn(
                      "object-cover",
                      i < 2 && "object-[50%_20%] sm:object-[50%_24%]",
                      i === 2 && "object-top",
                      i > 2 && "object-[50%_18%] sm:object-[50%_22%]",
                    )}
	                    sizes="(max-width: 639px) calc(100vw - 2rem), 380px"
	                  />
                </div>
                <div className="flex flex-1 flex-col p-8 lg:p-10">
                  <span className="text-primary text-xs font-semibold uppercase tracking-widest">
                    {p.type}
                  </span>
                  <h2 className="font-display mt-2 text-3xl lg:text-4xl">{p.title}</h2>
                  <p className="text-muted-foreground mt-4 flex-1 leading-relaxed">{p.description}</p>
                  <ul className="text-muted-foreground mt-6 grid gap-2.5 text-sm sm:grid-cols-2">
                    {p.features.map((f) => (
                      <li key={f} className="flex gap-2">
                        <span className="text-primary">✓</span> {f}
                      </li>
                    ))}
                  </ul>
                  <div className="mt-8 flex flex-wrap items-end justify-between gap-4">
                    <div>
                      {p.compareAtInr ? (
                        <p className="text-muted-foreground text-sm line-through">₹{p.compareAtInr}</p>
                      ) : null}
                      <p className="font-display text-primary text-4xl">₹{p.priceInr}</p>
                    </div>
                    <PlanCardActions
                      productId={p.id}
                      isOwned={ownedIds.includes(p.id)}
                      hasActivePlan={hasActivePlan}
                    />
                  </div>
                </div>
              </GlassCard>
            </section>
          ))}
      </div>
    </PageShell>
  );
}
