import Image from "next/image";
import { Container } from "@/components/Container";
import { Button } from "@/components/Button";
import { MotionReveal } from "@/components/MotionReveal";
import { ProductAccessRail } from "@/components/products/ProductAccessRail";
import { VideoEmbed } from "@/components/academy/VideoEmbed";
import { audienceAvatarsForProduct } from "@/lib/photos";
import { lookupIcon } from "@/lib/product-pages/icons";
import { renderMarkdown } from "@/lib/markdown/render";
import { getViewer } from "@/lib/auth/viewer";
import type { ProductPageDefaults } from "@/lib/product-pages/defaults";
import type { ProductPageCustomSection } from "@/lib/db/schema";

/** "Join" CTAs are irrelevant once the viewer is already signed in. */
function shouldHide(href: string | null | undefined, signedIn: boolean): boolean {
  if (!signedIn) return false;
  if (!href) return false;
  return href === "/join" || href.startsWith("/join?") || href.startsWith("/join#");
}

type Props = {
  data: ProductPageDefaults;
  /** Optional slot rendered between the main section and the audience strip. */
  children?: React.ReactNode;
};

/**
 * Shared product landing page template. All copy, images, features, audiences,
 * FAQs, and CTAs come from the product_pages DB row (or source-code defaults
 * when unpopulated). Keeps each /products/<slug>/page.tsx a one-liner.
 */
export async function ProductLanding({ data, children }: Props) {
  const viewer = await getViewer();
  const signedIn = viewer.signedIn;
  const avatars = audienceAvatarsForProduct(data.slug);
  const accessTiles = data.accessTiles.map((t) => ({
    href: t.href,
    label: t.label,
    description: t.description,
    Icon: lookupIcon(t.iconName),
  }));

  const showHeroPrimary =
    Boolean(data.heroPrimaryCtaLabel && data.heroPrimaryCtaHref) &&
    !shouldHide(data.heroPrimaryCtaHref, signedIn);
  const showHeroSecondary =
    Boolean(data.heroSecondaryCtaLabel && data.heroSecondaryCtaHref) &&
    !shouldHide(data.heroSecondaryCtaHref, signedIn);
  const showCtaPrimary =
    Boolean(data.ctaPrimaryLabel && data.ctaPrimaryHref) &&
    !shouldHide(data.ctaPrimaryHref, signedIn);
  const showCtaSecondary =
    Boolean(data.ctaSecondaryLabel && data.ctaSecondaryHref) &&
    !shouldHide(data.ctaSecondaryHref, signedIn);
  const showCtaBand = Boolean(data.ctaTitle) && (showCtaPrimary || showCtaSecondary || !signedIn);

  return (
    <>
      <ProductAccessRail
        productName={data.heroTitle || data.slug}
        productTagline={data.accessRailTagline}
        tiles={accessTiles}
        membersOnly={data.accessRailMembersOnly}
      />

      <section className="bg-white pt-10 pb-12 md:pt-14 md:pb-16">
        <Container>
          <div className="grid items-center gap-10 md:grid-cols-[1.15fr_1fr]">
            <div>
              {data.heroEyebrow ? (
                <div className="inline-flex items-center gap-2 rounded-full border border-[var(--color-line)] bg-[var(--color-mist)] px-3 py-1.5 text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                  <span className="h-1.5 w-1.5 rounded-full bg-[var(--color-blue)]" />
                  {data.heroEyebrow}
                </div>
              ) : null}
              <h1 className="mt-6 font-display text-[40px] md:text-[58px] font-extrabold leading-[1.05] tracking-[-0.025em] text-[var(--color-ink)]">
                {data.heroTitle}
              </h1>
              {data.heroTagline ? (
                <p className="mt-4 text-[20px] font-medium text-[var(--color-blue)]">
                  {data.heroTagline}
                </p>
              ) : null}
              {data.heroDescription ? (
                <p className="mt-6 max-w-2xl text-[17px] leading-relaxed text-[var(--color-slate)]">
                  {data.heroDescription}
                </p>
              ) : null}
              {(showHeroPrimary || showHeroSecondary) ? (
                <div className="mt-8 flex flex-wrap items-center gap-4">
                  {showHeroPrimary ? (
                    <Button href={data.heroPrimaryCtaHref!}>
                      {data.heroPrimaryCtaLabel}
                    </Button>
                  ) : null}
                  {showHeroSecondary ? (
                    <Button href={data.heroSecondaryCtaHref!} variant="ghost">
                      {data.heroSecondaryCtaLabel}
                    </Button>
                  ) : null}
                </div>
              ) : null}
            </div>
            {data.heroImagePath ? (
              <div className="relative aspect-[4/3] overflow-hidden rounded-2xl border border-[var(--color-line)] shadow-sm">
                <Image
                  src={data.heroImagePath}
                  alt={data.heroImageAlt ?? ""}
                  fill
                  sizes="(max-width: 768px) 100vw, 45vw"
                  className="object-cover"
                  priority
                />
              </div>
            ) : null}
          </div>
        </Container>
      </section>

      {data.sectionHeading || data.features.length > 0 ? (
        <section className="border-t border-[var(--color-line)] bg-white py-10 md:py-14">
          <Container>
            {data.sectionHeading || data.sectionBody ? (
              <div className="max-w-2xl">
                {data.sectionEyebrow ? (
                  <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                    {data.sectionEyebrow}
                  </div>
                ) : null}
                {data.sectionHeading ? (
                  <h2 className="mt-3 font-display text-[32px] md:text-[40px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)]">
                    {data.sectionHeading}
                  </h2>
                ) : null}
                {data.sectionBody ? (
                  <p className="mt-5 text-[17px] leading-relaxed text-[var(--color-slate)]">
                    {data.sectionBody}
                  </p>
                ) : null}
              </div>
            ) : null}

            {data.showcaseImagePath ? (
              <div className="relative mt-12 overflow-hidden rounded-2xl border border-[var(--color-line)] shadow-sm">
                <div className="relative aspect-[16/9] w-full">
                  <Image
                    src={data.showcaseImagePath}
                    alt={data.showcaseImageAlt ?? ""}
                    fill
                    sizes="(max-width: 768px) 100vw, 80vw"
                    className="object-cover"
                  />
                  <div className="pointer-events-none absolute inset-0 bg-gradient-to-t from-black/55 via-black/10 to-transparent" />
                  {data.showcaseEyebrow || data.showcaseCaption ? (
                    <div className="absolute inset-x-0 bottom-0 p-6 md:p-8">
                      {data.showcaseEyebrow ? (
                        <div className="text-[11px] font-bold uppercase tracking-wider text-white/80">
                          {data.showcaseEyebrow}
                        </div>
                      ) : null}
                      {data.showcaseCaption ? (
                        <div className="mt-1 max-w-xl font-display text-[18px] font-bold leading-snug text-white md:text-[22px]">
                          {data.showcaseCaption}
                        </div>
                      ) : null}
                    </div>
                  ) : null}
                </div>
              </div>
            ) : null}

            {data.features.length > 0 ? (
              <div className="mt-14 grid gap-6 md:grid-cols-2 lg:grid-cols-3">
                {data.features.map((f, i) => {
                  const Icon = lookupIcon(f.iconName);
                  return (
                    <MotionReveal
                      key={`${f.title}-${i}`}
                      index={i}
                      className="rounded-xl border border-[var(--color-line)] bg-white p-7 transition-[border-color,transform,box-shadow] hover:-translate-y-1 hover:border-[var(--color-blue)] hover:shadow-[0_16px_40px_rgba(30,64,255,0.08)]"
                    >
                      <div className="flex h-10 w-10 items-center justify-center rounded-lg bg-[var(--color-mist)] text-[var(--color-blue)]">
                        <Icon className="h-5 w-5" aria-hidden />
                      </div>
                      <h3 className="mt-5 font-display text-[19px] font-bold tracking-tight text-[var(--color-ink)]">
                        {f.title}
                      </h3>
                      <p className="mt-2 text-[15px] leading-relaxed text-[var(--color-slate)]">
                        {f.body}
                      </p>
                    </MotionReveal>
                  );
                })}
              </div>
            ) : null}
          </Container>
        </section>
      ) : null}

      {data.customSections && data.customSections.length > 0 ? (
        <CustomSections sections={data.customSections} />
      ) : null}

      {children}

      {data.audiences.length > 0 ? (
        <section className="border-t border-[var(--color-line)] bg-[var(--color-mist)]/40 py-10 md:py-14">
          <Container>
            {data.audienceHeading ? (
              <div className="max-w-2xl">
                <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                  Who it&rsquo;s for
                </div>
                <h2 className="mt-3 font-display text-[32px] md:text-[40px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)]">
                  {data.audienceHeading}
                </h2>
                {data.audienceBody ? (
                  <p className="mt-5 text-[17px] leading-relaxed text-[var(--color-slate)]">
                    {data.audienceBody}
                  </p>
                ) : null}
              </div>
            ) : null}
            <div className="mt-12 grid gap-6 md:grid-cols-3">
              {data.audiences.map((a, i) => {
                const avatar = avatars[i];
                return (
                  <MotionReveal
                    key={`${a.title}-${i}`}
                    index={i}
                    className="rounded-xl border border-[var(--color-line)] bg-white p-7 transition-[border-color,transform] hover:-translate-y-1 hover:border-[var(--color-blue)]"
                  >
                    {avatar ? (
                      <div className="relative h-16 w-16 overflow-hidden rounded-full ring-4 ring-[var(--color-mist)]">
                        {/* eslint-disable-next-line @next/next/no-img-element */}
                        <img
                          src={avatar.path}
                          alt=""
                          loading="lazy"
                          className="h-full w-full object-cover"
                        />
                      </div>
                    ) : null}
                    <h3 className="mt-5 font-display text-[20px] font-bold tracking-tight text-[var(--color-ink)]">
                      {a.title}
                    </h3>
                    <p className="mt-3 text-[15px] leading-relaxed text-[var(--color-slate)]">
                      {a.body}
                    </p>
                  </MotionReveal>
                );
              })}
            </div>
          </Container>
        </section>
      ) : null}

      {data.faqs.length > 0 ? (
        <section className="border-t border-[var(--color-line)] bg-white py-10 md:py-14">
          <Container>
            <div className="max-w-2xl">
              <div className="text-[11px] font-bold uppercase tracking-wider text-[var(--color-blue)]">
                Questions
              </div>
              <h2 className="mt-3 font-display text-[32px] md:text-[40px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)]">
                Frequently asked.
              </h2>
            </div>
            <div className="mt-12 max-w-3xl divide-y divide-[var(--color-line)] border-y border-[var(--color-line)]">
              {data.faqs.map((f, i) => (
                <details key={`${f.question}-${i}`} className="group py-5">
                  <summary className="flex cursor-pointer items-start justify-between gap-6 list-none [&::-webkit-details-marker]:hidden">
                    <span className="font-display text-[17px] font-semibold tracking-tight text-[var(--color-ink)]">
                      {f.question}
                    </span>
                    <span className="mt-1 text-[var(--color-blue)] transition-transform group-open:rotate-45">
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="2"
                        strokeLinecap="round"
                        className="h-4 w-4"
                      >
                        <path d="M12 5v14M5 12h14" />
                      </svg>
                    </span>
                  </summary>
                  <p className="mt-3 max-w-2xl text-[15px] leading-relaxed text-[var(--color-slate)]">
                    {f.answer}
                  </p>
                </details>
              ))}
            </div>
          </Container>
        </section>
      ) : null}

      {showCtaBand ? (
        <section className="bg-[var(--color-blue)] py-12 md:py-16 text-white">
          <Container>
            <div className="flex flex-col items-start gap-8 md:flex-row md:items-center md:justify-between">
              <div className="max-w-2xl">
                <h2 className="font-display text-[30px] md:text-[38px] font-extrabold leading-tight tracking-[-0.02em]">
                  {data.ctaTitle}
                </h2>
                {data.ctaBody ? (
                  <p className="mt-4 text-[17px] leading-relaxed text-white/80">
                    {data.ctaBody}
                  </p>
                ) : null}
              </div>
              {(showCtaPrimary || showCtaSecondary) ? (
                <div className="shrink-0 flex flex-wrap gap-3">
                  {showCtaPrimary ? (
                    <Button href={data.ctaPrimaryHref!} variant="on-blue">
                      {data.ctaPrimaryLabel}
                    </Button>
                  ) : null}
                  {showCtaSecondary ? (
                    <Button href={data.ctaSecondaryHref!} variant="on-blue">
                      {data.ctaSecondaryLabel}
                    </Button>
                  ) : null}
                </div>
              ) : null}
            </div>
          </Container>
        </section>
      ) : null}
    </>
  );
}

function CustomSections({ sections }: { sections: ProductPageCustomSection[] }) {
  return (
    <>
      {sections.map((s, i) => {
        const striped =
          i % 2 === 0
            ? "bg-white border-t border-[var(--color-line)]"
            : "bg-[var(--color-mist)]/30 border-t border-[var(--color-line)]";
        return (
          <section key={i} className={`${striped} py-10 md:py-14`}>
            <Container>
              {renderCustomSection(s)}
            </Container>
          </section>
        );
      })}
    </>
  );
}

function renderCustomSection(s: ProductPageCustomSection) {
  const heading = s.heading ? (
    <h2 className="font-display text-[28px] md:text-[36px] font-extrabold leading-tight tracking-[-0.02em] text-[var(--color-ink)]">
      {s.heading}
    </h2>
  ) : null;
  const bodyHtml = s.body ? renderMarkdown(s.body) : "";
  const cta =
    s.ctaLabel && s.ctaHref ? (
      <div className="mt-6">
        <Button href={s.ctaHref}>{s.ctaLabel}</Button>
      </div>
    ) : null;

  if (s.type === "image" && s.imagePath) {
    return (
      <div className="grid items-center gap-8 md:grid-cols-[1fr_1.1fr]">
        <div>
          {heading}
          {bodyHtml ? (
            <div
              className="prose prose-slate mt-5 max-w-2xl text-[16px] leading-relaxed text-[var(--color-slate)]"
              dangerouslySetInnerHTML={{ __html: bodyHtml }}
            />
          ) : null}
          {cta}
        </div>
        <div className="relative aspect-[4/3] overflow-hidden rounded-2xl border border-[var(--color-line)] shadow-sm">
          <Image
            src={s.imagePath}
            alt={s.imageAlt || s.heading || ""}
            fill
            sizes="(max-width: 768px) 100vw, 50vw"
            className="object-cover"
          />
        </div>
      </div>
    );
  }

  if (s.type === "video" && s.videoUrl) {
    return (
      <div className="mx-auto max-w-4xl">
        {heading}
        {bodyHtml ? (
          <div
            className="prose prose-slate mt-5 max-w-2xl text-[16px] leading-relaxed text-[var(--color-slate)]"
            dangerouslySetInnerHTML={{ __html: bodyHtml }}
          />
        ) : null}
        <div className="mt-6">
          <VideoEmbed
            provider={s.videoProvider || "youtube"}
            url={s.videoUrl}
            title={s.heading || "Video"}
          />
        </div>
        {cta}
      </div>
    );
  }

  if (s.type === "quote") {
    return (
      <figure className="mx-auto max-w-3xl border-l-4 border-[var(--color-blue)] pl-6">
        <blockquote className="font-display text-[24px] md:text-[32px] font-extrabold leading-tight tracking-[-0.015em] text-[var(--color-ink)]">
          &ldquo;{s.body}&rdquo;
        </blockquote>
        {s.heading ? (
          <figcaption className="mt-4 text-[14px] font-semibold text-[var(--color-slate)]">
            — {s.heading}
          </figcaption>
        ) : null}
        {cta}
      </figure>
    );
  }

  // Default: text
  return (
    <div className="mx-auto max-w-3xl">
      {heading}
      {bodyHtml ? (
        <div
          className="prose prose-slate mt-5 max-w-none text-[16px] leading-relaxed text-[var(--color-slate)]"
          dangerouslySetInnerHTML={{ __html: bodyHtml }}
        />
      ) : null}
      {cta}
    </div>
  );
}
