/** Section markup of /donations, keyed by CMS section key (markup unchanged from the static page). */
import Link from "next/link";
import { Fragment } from "react";
import { CtaLink } from "@/app/(site)/_components/home/parts";
import type { Cta, CtaImageContent, FeatureCardsContent, ListingPreviewContent, PageHeroContent, RichTitle, TextImageContent } from "@/app/(site)/_lib/pageContent";
import { Columns, LinkRow, PageHero, Paras, contactBtn } from "../blocks";
import { SplitTitle } from "../parts";
import { joined, nextIs, prevIs, type SectionRenderers } from "../render";

const HL = "text-[#0056D2]";

/** The introduction's title: the highlight in the accent colour, the rest on a new line. */
function IntroTitle({ title }: { title: RichTitle }) {
  const { text, highlight } = title;
  const at = highlight ? text.indexOf(highlight) : -1;
  if (!highlight || at < 0) return <span className="text-[#1A1A1A]">{text}</span>;
  const before = text.slice(0, at).trim();
  const after = text.slice(at + highlight.length).trim();
  return (
    <>
      {before && <span className="text-[#1A1A1A]">{before}</span>}
      {before && " "}
      <span className="donations-intro-accent">{highlight}</span>
      {after && (
        <>
          <br /> <span className="text-[#1A1A1A]">{after}</span>
        </>
      )}
    </>
  );
}

/**
 * Placeholder campaign card. The cards will come from the campaigns API (the page's
 * campaigns section then carries them); until then the design's sample card is shown
 * `count` times (at most 3).
 */
function CampaignCard({ last }: { last: boolean }) {
  return (
    <Link
      href="/campaign-detail"
      className={`campaign-card campaign-card-link bg-white rounded-[6px] border border-[#e8ecf2] shadow-[0_4px_24px_rgba(15,27,46,0.07)] overflow-hidden flex flex-col${last ? " md:col-span-2 xl:col-span-1" : ""}`}
      data-reveal=""
    >
      <div className="relative">
        <img
          src="/assets/images/donations/campaign-education.jpg"
          alt="Children learning together around a globe"
          className="w-full aspect-[380/200] object-cover block"
          width="380"
          height="200"
          loading="lazy"
        />{" "}
        <span className="campaign-badge absolute top-3 right-3 px-[10px] py-[4px] text-[10px] font-bold tracking-[0.06em] text-white rounded-[4px]">
          Education
        </span>
      </div>
      <div className="p-5 flex flex-col flex-1">
        <div className="flex items-center justify-between gap-2 mb-3 text-[12px]">
          <span className="text-[#2E2E2E]">
            By <span className="text-[#0056D2] font-semibold">Unionists Group</span>
          </span>{" "}
          <span className="text-[#2E2E2E]">200 Days To Go</span>
        </div>
        <h3 className="text-[16px] font-bold text-[#1A1A1A] mb-2 leading-[1.35]">Education for Every Child</h3>
        <p className="text-[13px] text-[#4A4A4A] leading-[1.6] mb-5 flex-1">
          Figma ipsum component variant main layer. Asset strikethrough overflow distribute pixel Move share fill export frame mask list.
        </p>
        <div className="mb-2">
          <div className="progress-track h-[6px] rounded-full bg-[#eef0f3] overflow-hidden">
            <div className="progress-fill h-full rounded-full" data-progress="86.54" style={{ width: "0", background: "#FFB800" }}></div>
          </div>
        </div>
        <div className="mb-5">
          <div className="flex items-baseline justify-between gap-3">
            <div className="text-[14px] font-bold text-[#1A1A1A]">$45,000</div>{" "}
            <span className="text-[14px] text-[#1A1A1A] progress-label shrink-0" data-target="86.54">
              0%
            </span>
          </div>
          <div className="text-[12px] text-[#2E2E2E]">raised of $52,000</div>
        </div>{" "}
        <span className="campaign-donate-btn w-full inline-flex items-center justify-center py-[13px] text-[12px] font-bold tracking-[0.08em] uppercase rounded-[6px] text-white">
          Donate
        </span>
      </div>
    </Link>
  );
}

/** The campaigns' View All button. The design puts it at the top of the next band (commitment). */
const ViewAll = ({ cta }: { cta: Cta }) => (
  <div className="donations-view-all-wrap">
    <CtaLink cta={cta} className="donations-view-all-btn" />
  </div>
);

export const DONATIONS_SECTIONS: SectionRenderers = {
  "page-hero": (c: PageHeroContent) => <PageHero c={c} width="max-w-[820px]" h1="text-[clamp(26px,3.8vw,38px)]" />,
  introduction: (c: TextImageContent) => (
    <section className="bg-white py-[72px]">
      <div className="w-full max-w-[1180px] mx-auto px-6">
        <div className="grid grid-cols-1 lg:grid-cols-2 gap-7 lg:gap-12 items-center">
          <Columns
            imagePosition={c.imagePosition}
            image={(side) => (
              <div className="rounded-[6px] overflow-hidden border border-[#e2e8f0]" data-reveal={side}>
                <img src={c.image.url} alt={c.image.alt ?? ""} className="w-full aspect-[560/300] h-auto block object-cover" width="560" height="300" loading="lazy" />
              </div>
            )}
            text={(side) => (
              <div data-reveal={side}>
                <h2 className="text-[clamp(22px,2.6vw,28px)] font-black leading-tight tracking-[-0.01em]">
                  <IntroTitle title={c.title} />
                </h2>
                <Paras body={c.body} first="mt-[18px] text-[15px] leading-[1.75] text-[#4A4A4A]" next="mt-4 text-[15px] leading-[1.75] text-[#4A4A4A]" />
              </div>
            )}
          />
        </div>
      </div>
    </section>
  ),
  offers: (c: FeatureCardsContent) => (
    <section className="bg-geometric-navy py-20 text-center">
      <div className="w-full max-w-[1180px] mx-auto px-6">
        {c.title && (
          <h2 className="text-[clamp(24px,3vw,32px)] font-black text-white leading-tight mb-10" data-reveal="">
            <SplitTitle title={c.title} hl={HL} />
          </h2>
        )}
        <div className="impact-offers-grid grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5 gap-4 text-left">
          {c.items.map((it, i) => (
            <div
              key={i}
              // An odd last card spans the row of two (as the 5th card of the design).
              className={`offer-card bg-[#0D2959] rounded-[6px] p-[24px_20px_28px]${i === c.items.length - 1 && c.items.length % 2 === 1 && c.items.length > 1 ? " sm:col-span-2 lg:col-span-1 xl:col-span-1" : ""}`}
              data-reveal=""
            >
              {it.icon?.url && (
                <div className="w-[52px] h-[52px] mb-[18px]">
                  <img src={it.icon.url} alt="" width="52" height="52" loading="lazy" className="w-[52px] h-[52px] object-contain" />
                </div>
              )}
              <h3 className="text-[14.5px] font-bold text-white mb-[10px] leading-[1.35]">{it.title}</h3>
              {it.description && <p className="text-[13px] text-[rgba(216,226,242,0.78)] leading-[1.55]">{it.description}</p>}
            </div>
          ))}
        </div>
      </div>
    </section>
  ),
  /** Placeholder cards until the campaigns API is connected; View All goes into the next band when that is commitment. */
  campaigns: (c: ListingPreviewContent, ctx) => {
    const n = Math.min(Math.max(c.count, 1), 3);
    return (
      <section className="bg-white py-[72px]">
        <div className="w-full max-w-[1180px] mx-auto px-6">
          <div className="text-center mb-10" data-reveal="">
            <h2 className="text-[clamp(22px,2.8vw,30px)] font-black text-[#1A1A1A] leading-tight tracking-[-0.01em]">
              <SplitTitle title={c.title} hl={HL} />
            </h2>
            {c.body && <p className="mt-3 text-[14px] text-[#4A4A4A] max-w-[560px] mx-auto leading-[1.65]">{c.body}</p>}
          </div>
          <div className="campaigns-grid grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-6">
            {Array.from({ length: n }, (_, i) => (
              <Fragment key={i}>
                {i > 0 && " "}
                <CampaignCard last={i === n - 1 && n % 2 === 1 && n > 1} />
              </Fragment>
            ))}
          </div>
          {c.cta && !nextIs(ctx, "commitment") && (
            <div className="mt-10 [&>.donations-view-all-wrap]:mb-0">
              <ViewAll cta={c.cta} />
            </div>
          )}
        </div>
      </section>
    );
  },
  commitment: (c: FeatureCardsContent, ctx) => {
    const viewAll = prevIs(ctx, "campaigns") ? (ctx!.sections[ctx!.index - 1].content as ListingPreviewContent | null)?.cta : undefined;
    return (
      <section className="bg-white pb-[80px]">
        <div className="w-full max-w-[1180px] mx-auto px-6">
          <div className="text-center mb-10" data-reveal="">
            {viewAll && joined("campaigns", () => <ViewAll cta={viewAll} />, ctx)}
            {c.title && (
              <h2 className="text-[clamp(22px,2.8vw,30px)] font-black text-[#1A1A1A] leading-tight tracking-[-0.01em]">
                <SplitTitle title={c.title} hl={HL} />
              </h2>
            )}
            {c.body && <p className="mt-3 text-[14px] text-[#4A4A4A] max-w-[640px] mx-auto leading-[1.65]">{c.body}</p>}
          </div>
          <div className="commitment-grid grid grid-cols-1 md:grid-cols-3 gap-[18px]">
            {c.items.map((it, i) => (
              <div key={i} className="commitment-card rounded-[6px] p-[28px_24px_30px]" data-reveal="">
                {it.icon?.url && (
                  <div className="w-12 h-12 mb-[18px]">
                    <img src={it.icon.url} alt="" width="48" height="48" loading="lazy" className="w-12 h-12 object-contain" />
                  </div>
                )}
                <h3 className="text-[15px] font-bold text-[#1A1A1A] mb-[10px] leading-[1.4]">{it.title}</h3>
                {it.description && <p className="text-sm text-[#4A4A4A] leading-[1.6]">{it.description}</p>}
              </div>
            ))}
          </div>
        </div>
      </section>
    );
  },
  "partner-cta": (c: CtaImageContent) => {
    const left = c.imagePosition === "left";
    return (
      <section className="donations-cta overflow-hidden" aria-label={c.title.text}>
        <div className="grid grid-cols-1 lg:grid-cols-2 min-h-0">
          <div
            className={
              left
                ? "donations-cta-content flex flex-col justify-center px-6 py-14 md:px-12 md:py-16 lg:px-14 lg:py-[72px] order-2 lg:order-2"
                : "donations-cta-content flex flex-col justify-center px-6 py-14 md:px-12 md:py-16 lg:px-14 lg:py-[72px] order-2 lg:order-1"
            }
            data-reveal={left ? "right" : "left"}
          >
            <h2 className="text-[clamp(24px,3vw,34px)] font-black text-[#1A1A1A] leading-tight tracking-[-0.01em] max-w-[480px]">
              <SplitTitle title={c.title} hl={HL} />
            </h2>
            {c.body && <p className="mt-5 text-[15px] leading-[1.75] text-[#4A4A4A] max-w-[500px]">{c.body}</p>}
            <div className="contact-panel-ctas mt-8">
              <LinkRow ctas={c.ctas} cls={contactBtn()} />
            </div>
          </div>
          <div
            className={
              left
                ? "donations-cta-visual relative min-h-[260px] sm:min-h-[320px] lg:min-h-[380px] order-1 lg:order-1 overflow-hidden"
                : "donations-cta-visual relative min-h-[260px] sm:min-h-[320px] lg:min-h-[380px] order-1 lg:order-2 overflow-hidden"
            }
            data-reveal={left ? "left" : "right"}
          >
            <img
              src={c.image.url}
              alt={c.image.alt ?? ""}
              className="donations-cta-image absolute inset-0 w-full h-full object-cover object-[70%_center]"
              width="1024"
              height="572"
              loading="lazy"
            />
          </div>
        </div>
      </section>
    );
  },
};
