import Link from "next/link";
import Image from "next/image";
import { headers } from "next/headers";
import { notFound } from "next/navigation";
import {
  cleanWebinarText,
  getRelatedWebinars,
  getWebinarBySlug,
  getWebinarImage,
  getWebinarPdfUrl,
} from "@/lib/webinars";
import { getContentMetadataForRequest, getRequestMetadataInput } from "@/lib/siteSeo";
import CVHeader from "@/components/layout/CVHeader";
import CVFooter from "@/components/layout/CVFooter";

export const dynamic = "force-dynamic";

export async function generateMetadata({ params }) {
  const { slug } = await params;
  const webinar = await getWebinarBySlug(slug);
  if (!webinar) return {};

  const title = cleanWebinarText(webinar.topic, 'Cambridge Veritas Webinar');
  const description = cleanWebinarText(
    webinar.description,
    'Watch this Cambridge Veritas webinar for expert insights and practical professional development.'
  );

  return getContentMetadataForRequest({
    ...getRequestMetadataInput(await headers(), {
      pathname: `/webinars/past-webinars/${slug}`,
    }),
    title: `${title} | Cambridge Veritas Webinar`,
    description,
    keywords: webinar.keywords,
    image: getWebinarImage(webinar),
    imageAlt: title,
    type: 'article',
  });
}

function formatDate(dateString) {
  try {
    return new Date(dateString).toLocaleString("en-US", {
      day: "numeric",
      month: "short",
      year: "numeric",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return "Recorded session";
  }
}

function cleanText(text, fallback = "") {
  return cleanWebinarText(text, fallback);
}

export default async function WebinarDetailsPage({ params }) {
  const { slug } = await params;
  const webinar = await getWebinarBySlug(slug);

  if (!webinar) notFound();

  const related = await getRelatedWebinars(webinar.id);
  const webinarTitle =
    cleanText(webinar?.topic, "Cambridge Veritas Webinar");

  const webinarImage = getWebinarImage(webinar);
  const webinarPdf = getWebinarPdfUrl(webinar);

  const webinarPoints = [
    webinar?.pt1,
    webinar?.pt2,
    webinar?.pt3,
    webinar?.pt4,
    webinar?.pt5,
  ].filter(Boolean);

  return (
    <div className="min-h-screen bg-[#FDFAF7]">
      <CVHeader />

      <main className="overflow-x-hidden bg-[#FDFAF7] text-[#4A141E]">
      {/* HERO */}
      <header className="border-b-4 border-[#D4AF37] bg-gradient-to-r from-[#4A141E] via-[#3B0F18] to-[#4A141E]">
        <div className="mx-auto grid max-w-7xl gap-8 px-4 py-10 sm:px-6 lg:grid-cols-2 lg:items-center lg:px-8 lg:py-14">
          <div>
              <div className="inline-flex items-center gap-2 rounded-full border border-[#D4AF37]/35 bg-[#D4AF37]/8 px-4 py-2 text-xs font-black uppercase tracking-[0.18em] text-[#E6D3B1]">
              <span className="h-2 w-2 rounded-full bg-[#D4AF37]" />
              On Demand Webinar
            </div>

            <h1 className="mt-5 text-3xl font-black leading-tight text-white sm:text-4xl lg:text-5xl">
              {webinarTitle}
            </h1>

            <div className="mt-5 flex flex-wrap gap-3 text-sm font-bold text-[#E6D3B1]/80">
              <span className="rounded-full border border-[#D4AF37]/35 bg-white/10 px-4 py-2">
                {formatDate(webinar?.date)}
              </span>

              <span className="rounded-full border border-[#D4AF37]/35 bg-white/10 px-4 py-2">
                English
              </span>

              <span className="rounded-full border border-[#D4AF37]/35 bg-white/10 px-4 py-2">
                ESL Webinar
              </span>
            </div>

            <p className="mt-5 max-w-2xl text-base leading-relaxed text-[#E6D3B1]/80 sm:text-lg">
              {cleanText(
                webinar?.description,
                "Watch this Cambridge Veritas webinar recording for expert insights and practical guidance."
              )}
            </p>

            <div className="mt-7 flex flex-col gap-3 sm:flex-row">
              {webinar?.video && (
                <a
                  href={webinar.video}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="inline-flex items-center justify-center gap-2 rounded-2xl bg-[#D4AF37] px-6 py-4 text-sm font-black text-[#3B0F18] shadow-lg transition hover:bg-[#E6D3B1]"
                >
                  Watch Recording
                </a>
              )}

              <Link
                href="/webinars/past-webinars"
                className="inline-flex items-center justify-center rounded-2xl border border-[#D4AF37]/50 bg-white/10 px-6 py-4 text-sm font-black text-[#E6D3B1] transition hover:bg-white/15"
              >
                Back to Past Webinars
              </Link>
            </div>
          </div>

          {/* VIDEO THUMBNAIL */}
          <div className="overflow-hidden rounded-2xl border border-[#D4AF37]/40 bg-white/10 shadow-2xl">
            {webinar?.video ? (
              <a
                href={webinar.video}
                target="_blank"
                rel="noopener noreferrer"
                className="group block"
              >
                <div className="relative aspect-video">
                  <Image
                    src={webinarImage}
                    alt={webinarTitle}
                    fill
                    className="object-cover"
                  />

                  <div className="absolute inset-0 flex items-center justify-center bg-black/25 transition group-hover:bg-black/35">
                    <span className="flex h-16 w-16 items-center justify-center rounded-full bg-[#D4AF37] text-[#3B0F18] shadow-lg">
                      &#9658;
                    </span>
                  </div>
                </div>
              </a>
            ) : (
              <div className="relative aspect-video">
                <Image
                  src={webinarImage}
                  alt={webinarTitle}
                  fill
                  className="object-cover"
                />
              </div>
            )}
          </div>
        </div>
      </header>

      {/* CONTENT */}
      <section className="mx-auto max-w-7xl px-4 py-10 sm:px-6 lg:px-8 lg:py-14">
        <div className="grid gap-8 lg:grid-cols-[1fr_360px]">
          {/* MAIN */}
          <article className="rounded-2xl border border-[#E6D3B1] bg-white p-6 shadow-sm sm:p-8">
            <p className="text-xs font-black uppercase tracking-[0.22em] text-[#8B1C1C]">
              Webinar Details
            </p>

            <h2 className="mt-3 text-2xl font-black text-[#4A141E] sm:text-3xl">
              What This Session Covers
            </h2>

            <div
              className="prose prose-sm mt-5 max-w-none text-[#4A141E]/70"
              dangerouslySetInnerHTML={{
                __html: webinar?.description || "",
              }}
            />

            {webinarPoints.length > 0 && (
              <div className="mt-8 grid gap-4 sm:grid-cols-2">
                {webinarPoints.map((point, index) => (
                  <div
                    key={index}
                    className="flex gap-3 rounded-2xl border border-[#E6D3B1]/70 bg-[#FDFAF7] p-4"
                  >
                    <span className="mt-1 flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-[#D4AF37] text-xs font-black text-[#3B0F18]">
                      &#10003;
                    </span>

                    <p className="text-sm leading-relaxed text-[#4A141E]/75">
                      {point}
                    </p>
                  </div>
                ))}
              </div>
            )}

            {webinar?.extra_details && (
              <div
                className="mt-8 rounded-2xl border border-[#E6D3B1]/70 bg-[#FDFAF7] p-5 text-sm leading-relaxed text-[#4A141E]/70"
                dangerouslySetInnerHTML={{
                  __html: webinar.extra_details,
                }}
              />
            )}
          </article>

          {/* SIDEBAR */}
          <aside className="h-fit rounded-2xl border border-[#E6D3B1] bg-white p-6 shadow-sm">
            <p className="text-xs font-black uppercase tracking-[0.22em] text-[#8B1C1C]">
              Recording Access
            </p>

            <h2 className="mt-3 text-xl font-black text-[#4A141E]">
              Watch At Your Convenience
            </h2>

            <p className="mt-3 text-sm leading-relaxed text-[#4A141E]/65">
              Use this recorded session for revision, team training, or
              self-paced study.
            </p>

            {webinar?.video && (
              <a
                href={webinar.video}
                target="_blank"
                rel="noopener noreferrer"
                className="mt-5 inline-flex w-full items-center justify-center rounded-2xl bg-[#4A141E] px-6 py-4 text-sm font-black text-white transition hover:bg-[#8B1C1C]"
              >
                Watch Recording
              </a>
            )}

            {webinarPdf && (
              <a
                href={webinarPdf}
                target="_blank"
                rel="noopener noreferrer"
                className="mt-3 inline-flex w-full items-center justify-center rounded-2xl border border-[#E6D3B1] bg-[#FDFAF7] px-6 py-4 text-sm font-black text-[#8B1C1C] transition hover:border-[#D4AF37]"
              >
                Download Material
              </a>
            )}
          </aside>
        </div>
      </section>

      {/* RELATED WEBINARS */}
      {related.length > 0 && (
        <section className="border-t border-[#E6D3B1]/60 bg-white">
          <div className="mx-auto max-w-7xl px-4 py-10 sm:px-6 lg:px-8 lg:py-14">
            <div className="mb-8">
              <p className="text-xs font-black uppercase tracking-[0.22em] text-[#8B1C1C]">
                More Similar Webinars
              </p>

              <h2 className="mt-3 text-2xl font-black text-[#4A141E] sm:text-3xl">
                Related Webinars
              </h2>
            </div>

            <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
              {related.map((item) => (
                <article
                  key={item.id}
                  className="group overflow-hidden rounded-2xl border border-[#E6D3B1] bg-white shadow-sm transition hover:border-[#D4AF37] hover:shadow-lg"
                >
                  <Link
                    href={`/webinars/past-webinars/${item.slug}`}
                    className="flex h-full flex-col"
                  >
                    <div className="relative aspect-video overflow-hidden">
                      <Image
                        src={getWebinarImage(item)}
                        alt={item.topic}
                        fill
                        className="object-cover transition duration-300 group-hover:scale-105"
                      />
                    </div>

                    <div className="flex flex-1 flex-col p-5">
                      <div className="mb-4 inline-flex w-fit rounded-full bg-[#F6EFE9] px-3 py-1 text-xs font-black uppercase tracking-wide text-[#8B1C1C]">
                        On Demand
                      </div>

                      <h3 className="text-lg font-black leading-tight text-[#4A141E]">
                        {item.topic}
                      </h3>

                      <p className="mt-3 line-clamp-3 flex-1 text-sm leading-relaxed text-[#4A141E]/65">
                        {cleanText(item.description).substring(0, 130)}...
                      </p>

                      <div className="mt-5 flex items-center justify-between border-t border-[#E6D3B1]/60 pt-4">
                        <span className="text-sm font-black text-[#8B1C1C]">
                          Watch Recording
                        </span>
                        <span>&rarr;</span>
                      </div>
                    </div>
                  </Link>
                </article>
              ))}
            </div>
          </div>
        </section>
      )}
      </main>

      <CVFooter />
    </div>
  );
}
