/** Section markup of /services, keyed by CMS section key (markup unchanged from the static page). */
import { CtaLink } from "@/app/(site)/_components/home/parts";
import type { CtaButtonsContent, PageHeroContent, ServiceCard, ServiceListingContent, StatsContent, TextImageContent } from "@/app/(site)/_lib/pageContent";
import { Columns, CtaBand, PageHero, Paras } from "../blocks";
import { SplitTitle } from "../parts";
import type { SectionRenderers } from "../render";

const P_FIRST = "mt-[18px] text-[15px] leading-[1.75] text-[#2E2E2E]";
const P_NEXT = "mt-4 text-[15px] leading-[1.75] text-[#2E2E2E]";
const H2 = "text-[clamp(22px,2.6vw,28px)] font-black leading-tight tracking-[-0.01em]";

/** Division sections: banner modifier and heading id per section key. */
const DIVISION_STYLE: Record<string, string> = {
  "science-nutrition": "science",
  "trade-commerce": "trade",
  "sustainability-strategy": "sustainability",
  "innovation-knowledge": "innovation",
};

/** Columns of the card grid: the design has 2-, 3- and 4-column grids. */
function gridCols(n: number) {
  if (n <= 2) return 2;
  if (n % 4 === 0) return 4;
  return 3;
}

/** One service card. Links to other sites (a card's own link) open in a new tab. */
export function ServiceCardItem({ card, reverse = false }: { card: Pick<ServiceCard, "image" | "title" | "description" | "ctaLabel" | "href">; reverse?: boolean }) {
  return (
    <article className={reverse ? "service-card service-card--reverse" : "service-card"} data-reveal="">
      <div className="service-card-image">
        <img src={card.image.url} alt={card.image.alt ?? ""} width="400" height="280" loading="lazy" />
      </div>
      <div className="service-card-body">
        <h3 className="service-card-title">{card.title}</h3>
        {card.description && <p className="service-card-desc">{card.description}</p>}{" "}
        <CtaLink cta={{ label: card.ctaLabel, href: card.href, openInNewTab: /^https?:\/\//i.test(card.href) }} className="btn btn-service" />
      </div>
    </article>
  );
}

/** A division: banner (title, intro), then its services' cards. A division without published services shows the banner only. */
function Division({ sectionKey, c }: { sectionKey: string; c: ServiceListingContent }) {
  const v = DIVISION_STYLE[sectionKey];
  const headingId = `${v}-division-heading`;
  const cards = c.services ?? [];
  return (
    <section aria-labelledby={headingId}>
      <div className={`service-division-banner service-division-banner--${v}`} data-reveal="">
        <div className="w-full max-w-[1180px] mx-auto px-6">
          <h2 id={headingId}>
            <SplitTitle title={c.title} hl="text-[#0056D2]" />
          </h2>
          {c.body && <p>{c.body}</p>}
        </div>
      </div>
      {cards.length > 0 && (
        <div className={`service-cards-section service-cards-section--${v}`}>
          <div className="w-full max-w-[1180px] mx-auto px-6">
            <div className={`service-cards-grid service-cards-grid--${gridCols(cards.length)}`}>
              {cards.map((card, i) => (
                // The lone last card of an odd row (centred) has its image on the right.
                <ServiceCardItem key={card.slug || i} card={card} reverse={cards.length % 2 === 1 && cards.length > 1 && i === cards.length - 1} />
              ))}
            </div>
          </div>
        </div>
      )}
    </section>
  );
}

export const SERVICES_SECTIONS: SectionRenderers = {
  "page-hero": (c: PageHeroContent) => <PageHero c={c} wrap />,
  introduction: (c: TextImageContent) => (
    <section className="bg-white py-12 md:py-16 lg:py-20">
      <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="product-category-image product-category-image--service-intro" data-reveal={side}>
                <img src={c.image.url} alt={c.image.alt ?? ""} width="560" height="300" loading="lazy" />
              </div>
            )}
            text={(side) => (
              <div data-reveal={side}>
                <h2 className={H2}>
                  <SplitTitle title={c.title} hl="text-[#0056D2]" rest="text-ink" />
                </h2>
                <Paras body={c.body} first={P_FIRST} next={P_NEXT} />
              </div>
            )}
          />
        </div>
      </div>
    </section>
  ),
  "science-nutrition": (c: ServiceListingContent) => <Division sectionKey="science-nutrition" c={c} />,
  "trade-commerce": (c: ServiceListingContent) => <Division sectionKey="trade-commerce" c={c} />,
  "sustainability-strategy": (c: ServiceListingContent) => <Division sectionKey="sustainability-strategy" c={c} />,
  "innovation-knowledge": (c: ServiceListingContent) => <Division sectionKey="innovation-knowledge" c={c} />,
  "global-network": (c: TextImageContent) => (
    <section className="services-network-section">
      <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}
            text={(side) => (
              <div data-reveal={side}>
                <h2 className={H2}>
                  <SplitTitle title={c.title} hl="text-[#0056D2]" rest="text-ink" />
                </h2>
                <Paras body={c.body} first={P_FIRST} next={P_NEXT} />
              </div>
            )}
            image={(side) => (
              <div className="product-category-image services-network-image" data-reveal={side}>
                <img src={c.image.url} alt={c.image.alt ?? ""} width="560" height="340" loading="lazy" />
              </div>
            )}
          />
        </div>
      </div>
    </section>
  ),
  stats: (c: StatsContent) => (
    <section className="services-stats-section" aria-label="Key statistics">
      <div className="w-full max-w-[1180px] mx-auto px-6">
        <div className="grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-6 text-center">
          {c.items.map((it, i) => (
            // An odd last figure spans both columns on phones (the static page's fifth figure).
            <div key={i} className={c.items.length % 2 === 1 && i === c.items.length - 1 ? "col-span-2 md:col-span-1" : undefined} data-reveal="">
              {it.icon?.url && (
                <div className="services-stat-icon">
                  <img src={it.icon.url} alt="" width="72" height="72" loading="lazy" />
                </div>
              )}
              <div className="services-stat-number">{it.value}</div>
              {it.label && <p className="services-stat-label">{it.label}</p>}
            </div>
          ))}
        </div>
      </div>
    </section>
  ),
  "partner-cta": (c: CtaButtonsContent) => <CtaBand c={c} row="flex flex-col items-stretch gap-[14px] sm:flex-row sm:items-center sm:justify-center" />,
};
