/** Section markup of /global-presence, keyed by CMS section key (markup unchanged from the static page). */
import { Fragment } from "react";
import type { CtaButtonsContent, FeatureCardsContent, Office, OfficeListContent, OfficeMapContent, PageHeroContent, TextImageContent } from "@/app/(site)/_lib/pageContent";
import { Columns, LinkRow, PageHero, Paras, contactBtn } from "../blocks";
import { SplitTitle } from "../parts";
import type { SectionContext, SectionRenderers } from "../render";
import { GLOBAL_PRESENCE_DEFAULTS } from "./defaults";
import { OfficeMap, type MapPin } from "./OfficeMap";

const HL = "text-[#0056D2]";
const BUILT_IN_OFFICES = GLOBAL_PRESENCE_DEFAULTS.find((s) => s.key === "offices")?.content;

/**
 * The map's pins: the offices of the page's office-list that have a position (none
 * when that section is hidden). While the page shows its built-in content, the map
 * keeps the static page's pins (undefined = OfficeMap's BUILT_IN_PINS).
 */
function pinsFor(ctx: SectionContext | undefined): MapPin[] | undefined {
  const offices = ctx?.sections.find((s) => s.key === "offices");
  if (!ctx || offices?.content === BUILT_IN_OFFICES) return undefined;
  const items = (offices?.content as OfficeListContent | undefined)?.items;
  if (!Array.isArray(items)) return [];
  return items
    .filter((o): o is Office & { position: { lat: number; lng: number } } => Number.isFinite(o?.position?.lat) && Number.isFinite(o?.position?.lng))
    .map((o) => ({ location: o.location, name: o.name, ...(o.description ? { description: o.description } : {}), lat: o.position.lat, lng: o.position.lng }));
}

/** Timeline grid columns (md and up) by number of cards, at most 4. */
const COLS = ["md:grid-cols-1", "md:grid-cols-1", "md:grid-cols-2", "md:grid-cols-3", "md:grid-cols-4"];
/** A timeline dot centred over each column, e.g. 16.66%, 50%, 83.33% for 3. */
const dotLeft = (i: number, n: number) => `${Math.floor(((i + 0.5) / n) * 10000) / 100}%`;

export const GLOBAL_PRESENCE_SECTIONS: SectionRenderers = {
  "page-hero": (c: PageHeroContent) => <PageHero c={c} />,
  introduction: (c: TextImageContent) => (
    <section className="bg-white py-10 md:py-12">
      <div className="w-full max-w-[1180px] mx-auto px-6">
        <div className="global-presence-powerhouse grid grid-cols-1 lg:grid-cols-2 gap-7 lg:gap-10 items-center">
          <Columns
            imagePosition={c.imagePosition}
            image={(side) => (
              <div className="global-presence-powerhouse__img-wrap rounded-[6px] overflow-hidden" data-reveal={side}>
                <img src={c.image.url} alt={c.image.alt ?? ""} className="global-presence-powerhouse-img" width="560" height="300" loading="lazy" />
              </div>
            )}
            text={(side) => (
              <div className="global-presence-powerhouse__content" data-reveal={side}>
                <h2 className="text-[clamp(20px,2.4vw,26px)] font-black leading-[1.2] tracking-[-0.01em]">
                  <SplitTitle title={c.title} hl={HL} rest="text-[#1A1A1A]" />
                </h2>
                <Paras body={c.body} first="mt-3 text-[14px] leading-[1.65] text-[#4A4A4A]" next="mt-3 text-[14px] leading-[1.65] text-[#4A4A4A]" />
              </div>
            )}
          />
        </div>
      </div>
    </section>
  ),
  offices: (c: OfficeListContent) => (
    <section className="bg-geometric-navy py-14 md:py-20 text-center" id="offices">
      <div className="w-full max-w-[1400px] mx-auto px-6">
        <div data-reveal="">
          <h2 className="text-[clamp(24px,3vw,32px)] font-black text-white leading-tight tracking-[-0.01em]">
            <SplitTitle title={c.title} hl={HL} />
          </h2>
          {c.body && <p className="mt-4 text-[14px] text-white/80 max-w-[640px] mx-auto leading-[1.7]">{c.body}</p>}
        </div>
        <div className="office-grid mt-10 grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4 text-left">
          {c.items.map((o, i) => (
            <article key={i} className="office-card rounded-[10px] p-5" data-reveal="">
              <img src="/assets/images/global-presence/icon-office-pin.png" alt="" className="office-pin-icon" width="24" height="24" decoding="async" />{" "}
              <h3 className="text-[14px] font-bold text-white leading-[1.35]">{o.location}</h3>
              <div className="office-card-divider my-3"></div>
              <p className="text-[13px] font-bold text-white leading-[1.4]">{o.name}</p>
              {o.description && <p className="mt-1 text-[12px] text-white/70 leading-[1.5]">{o.description}</p>}
            </article>
          ))}
        </div>
      </div>
    </section>
  ),
  map: (c: OfficeMapContent, ctx) => (
    <section className="bg-white pt-14 md:pt-20 pb-0 text-center">
      <div className="w-full max-w-[1180px] mx-auto px-6">
        <div data-reveal="">
          <h2 className="text-[clamp(22px,2.6vw,28px)] font-black text-[#1A1A1A] leading-tight tracking-[-0.01em]">
            <SplitTitle title={c.title} hl={HL} />
          </h2>
          {c.body && <p className="mt-4 text-[14px] text-[#4A4A4A] max-w-[640px] mx-auto leading-[1.7]">{c.body}</p>}
        </div>
        <div className="global-map-wrap mt-10 rounded-[6px] overflow-hidden shadow-[0_8px_36px_rgba(15,27,46,0.10)] border border-[#e2e8f0]" data-reveal="">
          <OfficeMap pins={pinsFor(ctx)} />
        </div>
      </div>
    </section>
  ),
  /** Timeline: one dot per column above the cards. */
  "growth-strategy": (c: FeatureCardsContent) => {
    const cols = Math.min(Math.max(c.items.length, 1), 4);
    return (
      <section className="bg-white pt-12 pb-16 md:pb-24 text-center">
        <div className="w-full max-w-[1180px] mx-auto px-6">
          <div data-reveal="">
            {c.title && (
              <h2 className="text-[clamp(22px,2.6vw,28px)] font-black text-[#1A1A1A] leading-tight tracking-[-0.01em]">
                <SplitTitle title={c.title} hl={HL} />
              </h2>
            )}
            {c.body && <p className="mt-4 text-[14px] text-[#4A4A4A] max-w-[720px] mx-auto leading-[1.7]">{c.body}</p>}
          </div>
          <div className="growth-timeline mt-12" data-reveal="">
            <div className="growth-timeline-track" aria-hidden="true">
              <div className="growth-timeline-line"></div>
              {Array.from({ length: cols }, (_, i) => (
                <Fragment key={i}>
                  {" "}
                  <span className="growth-timeline-dot" style={{ left: dotLeft(i, cols) }}></span>
                </Fragment>
              ))}
            </div>
            <div className={`growth-strategy-grid mt-8 grid grid-cols-1 ${COLS[cols]} gap-6 text-left`}>
              {c.items.map((it, i) => (
                <article key={i} className="growth-strategy-card rounded-[6px] p-6 md:p-7">
                  <h3 className="text-[15px] font-bold text-[#1A1A1A] leading-[1.35] mb-3">{it.title}</h3>
                  {it.description && <p className="text-[13.5px] text-[#4A4A4A] leading-[1.65]">{it.description}</p>}
                </article>
              ))}
            </div>
          </div>
        </div>
      </section>
    );
  },
  "connect-cta": (c: CtaButtonsContent) => (
    <section className="contact-cta global-presence-cta py-14 md:py-20 text-center">
      <div className="w-full max-w-[1100px] mx-auto px-6" data-reveal="">
        <h2 className="text-[clamp(20px,2.5vw,26px)] font-black text-[#1A1A1A] leading-tight mb-[14px]">
          <SplitTitle title={c.title} hl={HL} />
        </h2>
        {c.body && <p className="text-[15px] text-[#4A4A4A] mb-8 leading-[1.65]">{c.body}</p>}
        <div className="flex flex-col gap-3 lg:flex-row lg:flex-wrap lg:justify-center">
          <LinkRow ctas={c.ctas} cls={contactBtn()} />
        </div>
      </div>
    </section>
  ),
};
