import Link from "next/link";
import Image from "next/image";
import { Aurora } from "@/components/aurora";
import { Button } from "@/components/button";
import { ExpandingCards } from "@/components/expanding-cards";
import { getHomepageContent, type Section } from "@/lib/homepage";

export const revalidate = 60; // ISR

/**
 * Section heading: dark text on line 1, gradient highlight on line 2. The break
 * is enforced here rather than left to the CMS copy, per the Canva ref — every
 * homepage heading gets it, and it survives editors rewording the text.
 */
function SectionHeading({ section, className }: { section: Section; className: string }) {
  return (
    <h2 className={`whitespace-normal lg:whitespace-pre-line ${className}`}>
      {section.heading}
      {section.highlight ? (
        <>
          {section.heading ? "\n" : null}
          <span className="text-gradient">{section.highlight}</span>
        </>
      ) : null}
      {section.headingSuffix}
      {section.heading2 ? (
        <>
          {"\n"}
          <span className="text-gradient">{section.heading2}</span>
        </>
      ) : null}
    </h2>
  );
}

function paragraphs(body?: string): string[] {
  return (body || "").split(/\n\n+/).map((p) => p.trim()).filter(Boolean);
}

export default async function Home() {
  const content = await getHomepageContent();
  const { hero, beyondSystems, growthPartnership, creatingImpact, insightsToAction } = content;

  return (
    <>
      {/* ============================ HERO ============================ */}
      <section className="relative overflow-hidden">
        {hero.banner ? (
          <Image
            src={hero.banner}
            alt=""
            fill
            priority
            sizes="100vw"
            className="-z-10 object-cover"
          />
        ) : (
          <Aurora className="-z-10" />
        )}
        <div className="mx-auto max-w-7xl px-6 pb-24 pt-36 sm:pt-44 lg:px-10">
          <div className="relative max-w-3xl">
            <h1 className="animate-rise font-display text-4xl font-bold leading-[1.2] tracking-tight text-ink sm:text-6xl">
              {hero.headline}
              {/* lg: not sm: — at 60px type the first line needs ~870px, so
                  forcing the break any earlier wraps it and strands a word. */}
              <br className="hidden lg:block" />
              {/* Space outside the span so the gradient starts on the letter. */}
              {" "}
              <span className="text-gradient font-bold">{hero.headlineHighlight}</span>
            </h1>

            {/* Growth arrow — foot on the baseline of the headline's 2nd line,
                per Canva. Anchored with `bottom-*`, NOT `-translate-y-1/2`:
                float-slow animates `transform`, which beats the utility and
                silently dropped the centring.
                Knobs: lg:bottom-5 (up) / -right-32 (right) */}
            <Image
              src={hero.growthImage || "/home/growthsign.png"}
              alt=""
              width={260}
              height={260}
              className="animate-float-slow pointer-events-none absolute -right-32 bottom-4 hidden h-36 w-auto object-contain drop-shadow-[0_12px_24px_rgba(54,184,95,0.35)] lg:bottom-5 lg:block xl:h-40"
            />
          </div>

          {/* Pull quote left, founder note right — one band, as in Canva.
              Knobs: lg:mt-28 (both down) / lg:w-[600px] (note right) */}
          <div className="mt-14 flex flex-col lg:mt-28 lg:flex-row lg:items-start">
            {/* Always rendered: reserves the 600px the note used to get from
                lg:ml-[600px], so it stays put with or without a quote. */}
            <div className="lg:w-[600px] lg:shrink-0 lg:pr-12">
              {hero.quote ? (
                <figure
                  className="animate-rise mb-12 lg:mb-0 lg:mt-6"
                  style={{ animationDelay: "100ms" }}
                >
                  {/* aria-hidden: <blockquote> already carries the semantics.
                      8rem because a `"` fills only a sliver of its em box; the
                      tight leading crops the empty box back down. */}
                  <span
                    aria-hidden
                    className="block font-display text-[5rem] leading-[0.62] text-teal/70 sm:text-[8rem]"
                  >
                    &ldquo;
                  </span>
                  {/* Width sets the two-line break, as in Canva. */}
                  {/* Negative pull: a `"` glyph sits high in its em box, so an
                      8rem span leaves ~65px of empty line-box under it. */}
                  {/* Pull scales with the mark: the dead line-box under a `"` is
                      proportional to font-size, so 5rem needs ~2rem, 8rem ~3.25rem. */}
                  <blockquote className="-mt-8 max-w-[31rem] text-base italic leading-relaxed text-ink sm:-mt-[3.25rem] sm:text-lg">
                    {hero.quote}
                  </blockquote>
                </figure>
              ) : null}
            </div>

            {/* Founder note — centered on mobile, right of the quote on lg+.
                Stays w-fit so the text never wraps. */}
            <div
              className="animate-rise mx-auto flex w-fit items-center gap-4 lg:mx-0"
              style={{ animationDelay: "120ms" }}
            >
              <Image
                src={hero.founderImage}
                alt={`${hero.founderName} - Founder`}
                width={68}
                height={96}
                className="h-24 w-[68px] shrink-0 overflow-hidden rounded-xl object-cover"
              />
              <div className="text-ink">
                <p className="text-sm leading-snug whitespace-nowrap">
                  {hero.founderNoteLabel}
                  <br />
                  <span className="font-bold">{hero.founderName}</span>
                </p>
                <Link
                  href="/letter"
                  className="mt-2 inline-block text-sm font-semibold text-ink underline underline-offset-2 hover:text-leaf-deep"
                >
                  {hero.founderCtaLabel}
                </Link>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ====================== BEYOND SYSTEMS ======================= */}
      <section className="mx-auto max-w-7xl px-6 py-20 lg:px-10">
        <SectionHeading
          section={beyondSystems}
          className="font-display text-3xl font-bold leading-[1.3] tracking-tight text-ink sm:text-4xl"
        />
        {beyondSystems.body ? (
          <p className="mt-5 max-w-5xl text-base leading-loose">{beyondSystems.body}</p>
        ) : null}

        <div className="mt-12">
          <ExpandingCards cards={content.stories} />
          <div className="-mt-7 flex items-baseline justify-between px-1">
            <Button href="/resources/impact-stories">{content.storiesCtaLabel}</Button>
          </div>
        </div>
      </section>

      {/* ================ GROWTH INTELLIGENCE PARTNERSHIP ============ */}
      <section className="relative overflow-hidden">
        <div className="bg-gradient-to-br from-wash-green via-wash-mint to-wash-sky">
          <div className="mx-auto grid max-w-7xl items-center gap-12 px-6 py-24 lg:grid-cols-2 lg:px-10">
            {/* Section image — CMS image if set, else the decorative gradient.
                Appears first on mobile, second on desktop. */}
            <div className="relative aspect-[500/583] w-full max-w-[500px] overflow-hidden rounded-[2rem] border border-line shadow-lift lg:order-2">
              {content.growthPartnershipImage ? (
                <Image
                  src={content.growthPartnershipImage}
                  alt=""
                  fill
                  sizes="(min-width: 1024px) 500px, 100vw"
                  className="object-cover object-[8%_center]"
                />
              ) : (
                <>
                  <div className="absolute inset-0 bg-gradient-to-br from-sky/40 via-wash-mint to-leaf/30" />
                  <div className="absolute inset-0 bg-[radial-gradient(70%_60%_at_30%_30%,rgba(255,255,255,0.55),transparent_60%)]" />
                  <div
                    className="absolute inset-0 opacity-[0.18]"
                    style={{
                      backgroundImage:
                        "linear-gradient(rgba(19,26,22,0.5) 1px,transparent 1px),linear-gradient(90deg,rgba(19,26,22,0.5) 1px,transparent 1px)",
                      backgroundSize: "26px 26px",
                    }}
                  />
                  <div className="absolute bottom-8 left-8 h-28 w-28 rounded-full bg-gradient-to-br from-leaf/70 to-teal/60 blur-[1px]" />
                  <div className="absolute right-10 top-10 h-20 w-20 rounded-full bg-gradient-to-br from-sky/70 to-teal/50" />
                </>
              )}
            </div>

            {/* Text content — appears second on desktop, first on mobile */}
            <div className="lg:order-1">
              <SectionHeading
                section={growthPartnership}
                className="font-display text-3xl font-bold leading-[1.3] tracking-tight text-ink sm:text-4xl"
              />
              <div className="mt-6 max-w-xl space-y-5 text-base leading-relaxed text-ink-soft">
                {paragraphs(growthPartnership.body).map((p, i) => (
                  <p key={i}>{p}</p>
                ))}
              </div>
              <div className="mt-9">
                <Button href="/partner-with-us">{content.growthPartnershipCtaLabel}</Button>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* ===================== IMPACT / STATS ======================== */}
      <section className="mx-auto max-w-7xl px-6 py-24 lg:px-10">
        <SectionHeading
          section={creatingImpact}
          className="font-display text-3xl font-bold leading-[1.3] tracking-tight text-ink sm:text-4xl"
        />
        {creatingImpact.body ? (
          <p className="mt-5 max-w-5xl text-base leading-loose">{creatingImpact.body}</p>
        ) : null}

        <div className="mt-12 grid gap-6 sm:grid-cols-3">
          {content.stats.map((stat) => (
            <div
              key={stat.label}
              className="flex items-start justify-between rounded-[1.5rem] border border-line bg-paper p-7 shadow-soft transition-shadow hover:shadow-lift"
            >
              <div>
                <p className="font-display text-2xl font-bold text-ink">
                  {stat.value}
                </p>
                <p className="mt-1 max-w-[8rem] text-lg leading-snug">{stat.label}</p>
              </div>
              {stat.icon && (stat.icon.startsWith("http") || stat.icon.startsWith("/")) ? (
                <Image
                  src={stat.icon}
                  alt=""
                  width={68}
                  height={68}
                  className="h-[68px] w-[68px] shrink-0 object-contain"
                />
              ) : stat.icon ? (
                <span className="text-4xl" aria-hidden>
                  {stat.icon}
                </span>
              ) : null}
            </div>
          ))}
        </div>

        {/* Logo cloud */}
        <div className="mt-14 border-t border-line pt-10">
          {/* Desktop (1024px+): static wrapped grid */}
          <div className="hidden flex-wrap items-center justify-between gap-x-4 gap-y-8 lg:flex">
            {content.logos.map((logo) =>
              logo.image ? (
                <Image
                  key={logo.name}
                  src={logo.image}
                  alt={logo.name}
                  width={200}
                  height={72}
                  className="h-14 w-auto max-w-[170px] object-contain transition hover:scale-105"
                />
              ) : (
                <span
                  key={logo.name}
                  className="font-display text-sm font-semibold uppercase tracking-wide text-ink/70 transition-colors hover:text-ink"
                >
                  {logo.name}
                </span>
              )
            )}
          </div>

          {/* Mobile: CSS-driven continuous ticker. Server-rendered + pure CSS
              animation means it scrolls WITHOUT JavaScript — so it works even on
              devices where the JS bundle never hydrates (old iOS Safari). Two
              identical copies of the logo set sit side by side and the track
              animates exactly one copy-width (-50%) for a seamless loop. */}
          {/* Mobile: CSS-animation ticker. Inline styles (Tailwind v4 layer CSS
              can be dropped on iOS 15 → 2-row stacking) + server-rendered so it
              scrolls without JS. Two identical copies slide one copy-width (-50%)
              for a seamless loop. NOTE: deliberately NO `will-change` — it is a
              known trigger for iOS Safari blanking the animated layer mid-scroll. */}
          {content.logos.length > 0 ? (
            <div className="lg:hidden" style={{ overflow: "hidden" }}>
              <div
                style={{
                  display: "flex",
                  flexWrap: "nowrap",
                  alignItems: "center",
                  width: "max-content",
                  animation: "logo-marquee 30s linear infinite",
                }}
              >
                {[0, 1].map((copy) => (
                  <div
                    key={copy}
                    style={{ display: "flex", flexShrink: 0, alignItems: "center" }}
                    aria-hidden={copy === 1 || undefined}
                  >
                    {content.logos.map((logo) =>
                      logo.image ? (
                        <div
                          key={logo.name}
                          style={{
                            display: "flex",
                            flexShrink: 0,
                            alignItems: "center",
                            marginRight: "3rem",
                          }}
                        >
                          <Image
                            src={logo.image}
                            alt={copy === 0 ? logo.name : ""}
                            width={240}
                            height={96}
                            loading="eager"
                            style={{
                              height: "4.5rem",
                              width: "auto",
                              maxWidth: "200px",
                              objectFit: "contain",
                            }}
                          />
                        </div>
                      ) : (
                        <span
                          key={logo.name}
                          className="font-display"
                          style={{
                            flexShrink: 0,
                            marginRight: "3rem",
                            whiteSpace: "nowrap",
                            fontSize: "1.125rem",
                            fontWeight: 600,
                            textTransform: "uppercase",
                            letterSpacing: "0.025em",
                            color: "rgba(19, 26, 22, 0.7)",
                          }}
                        >
                          {logo.name}
                        </span>
                      )
                    )}
                  </div>
                ))}
              </div>
            </div>
          ) : null}
        </div>
      </section>

      {/* ==================== INSIGHTS TO ACTION ===================== */}
      <section id="insights" className="mx-auto max-w-7xl px-6 pb-28 lg:px-10">
        <SectionHeading
          section={insightsToAction}
          className="font-display text-3xl font-bold leading-[1.3] tracking-tight text-ink sm:text-4xl"
        />
        {insightsToAction.body ? (
          <p className="mt-5 max-w-5xl text-base leading-relaxed">{insightsToAction.body}</p>
        ) : null}

        <div className="mt-12">
          <ExpandingCards cards={content.insights} plainDescription />
          <div className="-mt-7 flex items-end justify-between px-1">
            <Button href="/resources/insights">{content.insightsCtaLabel}</Button>
          </div>
        </div>
      </section>
    </>
  );
}
