"use client";
import {
  useSelfFetch
} from "./chunk-L4LAAA5Q.js";
import {
  BlogCard,
  BlogCardSkeleton,
  CONTENT_REF_GROUPS,
  CaseStudyCard,
  CaseStudyCardSkeleton,
  CustomerInterviewCard,
  CustomerInterviewCardSkeleton,
  InvestorUpdateCard,
  InvestorUpdateCardSkeleton,
  Pagination,
  ProductReleaseCard,
  ProductReleaseCardSkeleton,
  ProgramCard,
  ProgramCardSkeleton,
  RoadmapCard,
  RoadmapCardSkeleton,
  buildListUrl,
  buildProductReleaseCardProps,
  canonicalContentRefType,
  extractItemId,
  extractItems,
  getContentRefLabelOrTitleCase,
  init_pagination,
  orderContentRefTypes
} from "./chunk-DTJ32U7J.js";
import {
  buildSuggestionUrl
} from "./chunk-NR535XIY.js";
import {
  OnboardingGuideCard,
  OnboardingGuideCardSkeleton,
  decideNewTab
} from "./chunk-HTR3ARN6.js";

// src/components/related-content/related-content-section.tsx
import { useEffect, useMemo, useRef, useState } from "react";
init_pagination();
import { jsx, jsxs } from "react/jsx-runtime";
function DefaultLinkPropsProvider({ href, targetPlatform, children }) {
  if (!href) return children(null);
  const newTab = decideNewTab({ href, targetPlatform, currentSource: "" });
  return children(
    newTab ? { href, target: "_blank", rel: "noopener noreferrer" } : { href }
  );
}
function defaultResolveHref(ref) {
  return { href: ref.url || null, targetPlatform: ref.targetPlatform ?? null };
}
function renderSkeletonForType(type, size, adminCampaignCard) {
  const legacySize = size === "sm" ? "sm" : "default";
  switch (type) {
    case "blog_post_existing":
      return /* @__PURE__ */ jsx(BlogCardSkeleton, { size: legacySize });
    case "case_study":
      return /* @__PURE__ */ jsx(CaseStudyCardSkeleton, { size: legacySize });
    case "customer_interview":
      return /* @__PURE__ */ jsx(CustomerInterviewCardSkeleton, { size: legacySize });
    case "product_release":
      return /* @__PURE__ */ jsx(ProductReleaseCardSkeleton, { size: size === "sm" ? "sm" : "lg" });
    case "podcast":
    case "webinar":
    case "event":
      return /* @__PURE__ */ jsx(ProgramCardSkeleton, { size: legacySize });
    case "investor_update":
      return /* @__PURE__ */ jsx(InvestorUpdateCardSkeleton, { size: legacySize });
    case "onboarding_guide":
      return /* @__PURE__ */ jsx(OnboardingGuideCardSkeleton, { size: size === "sm" ? "sm" : "catalog" });
    case "marketing_campaign":
      return adminCampaignCard ? /* @__PURE__ */ jsx(adminCampaignCard.Skeleton, { size: legacySize }) : null;
    case "roadmap_item":
    case "delivery_item":
    case "internal_task":
      return /* @__PURE__ */ jsx(RoadmapCardSkeleton, { size: legacySize });
    default:
      return null;
  }
}
function CardForType({
  type,
  item,
  size,
  href,
  targetPlatform,
  linkProps,
  extras,
  adminCampaignCard
}) {
  const legacySize = size === "sm" ? "sm" : "default";
  const placeholderUrl = extras?.buildOgPlaceholderUrl?.(item?.title ?? "") ?? void 0;
  const anchorAttrs = linkProps ? { target: linkProps.target, rel: linkProps.rel } : {};
  switch (type) {
    case "blog_post_existing":
      return /* @__PURE__ */ jsx(BlogCard, { post: item, size: legacySize, href, targetPlatform, placeholderUrl, ...anchorAttrs });
    case "case_study":
      return /* @__PURE__ */ jsx(CaseStudyCard, { study: item, size: legacySize, href, targetPlatform, placeholderUrl, ...anchorAttrs });
    case "customer_interview":
      return /* @__PURE__ */ jsx(CustomerInterviewCard, { interview: item, size: legacySize, href, targetPlatform, placeholderUrl, ...anchorAttrs });
    case "product_release": {
      const releaseSize = size === "sm" ? "sm" : "lg";
      const buildReleaseProps = extras?.buildProductReleaseCardProps ?? buildProductReleaseCardProps;
      const releaseProps = buildReleaseProps(item);
      return /* @__PURE__ */ jsx(
        ProductReleaseCard,
        {
          size: releaseSize,
          title: item.title,
          summary: item.summary,
          version: item.version,
          ...releaseProps,
          anchorProps: linkProps ?? void 0
        }
      );
    }
    case "podcast":
      return extras?.programConfigs?.podcast ? /* @__PURE__ */ jsx(ProgramCard, { config: extras.programConfigs.podcast, item, size: legacySize, href, targetPlatform, placeholderUrl, ...anchorAttrs }) : null;
    case "webinar":
      return extras?.programConfigs?.webinar ? /* @__PURE__ */ jsx(ProgramCard, { config: extras.programConfigs.webinar, item, size: legacySize, href, targetPlatform, placeholderUrl, ...anchorAttrs }) : null;
    case "event":
      return extras?.programConfigs?.event ? /* @__PURE__ */ jsx(ProgramCard, { config: extras.programConfigs.event, item, size: legacySize, href, targetPlatform, placeholderUrl, ...anchorAttrs }) : null;
    case "investor_update":
      return /* @__PURE__ */ jsx(InvestorUpdateCard, { update: item, size: legacySize, href, targetPlatform, placeholderUrl, ...anchorAttrs });
    case "onboarding_guide":
      return /* @__PURE__ */ jsx(OnboardingGuideCard, { guide: item, size: size === "sm" ? "sm" : "catalog", href, targetPlatform, placeholderUrl, ...anchorAttrs });
    case "marketing_campaign":
      return adminCampaignCard ? /* @__PURE__ */ jsx(adminCampaignCard.Card, { campaign: item }) : null;
    case "roadmap_item":
    case "delivery_item":
    case "internal_task":
      return /* @__PURE__ */ jsx(
        RoadmapCard,
        {
          item,
          href: href ?? "",
          targetPlatform,
          userVote: null,
          onVote: () => {
          },
          size: legacySize,
          cardType: type,
          ...anchorAttrs
        }
      );
    default:
      return null;
  }
}
function useGroupItems(type, refs, buildUrl) {
  const ids = refs.map((r) => r.id);
  const url = ids.length > 0 ? buildUrl(type, ids) : null;
  const { data, isLoading } = useSelfFetch(url);
  const items = data != null ? extractItems(data) : null;
  return { items, isLoading };
}
function gridClassFor(columns) {
  return columns === 3 ? "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6" : "grid grid-cols-1 sm:grid-cols-2 gap-6";
}
function resolveGroupConfig(type) {
  return CONTENT_REF_GROUPS[type] ?? {
    label: type,
    order: 999,
    layout: "grid",
    gridSize: "default"
  };
}
var GROUP_PAGE_SIZE = 12;
function ContentGroup({
  type,
  refs,
  columns,
  buildUrl,
  resolveHref,
  LinkProvider,
  extras,
  adminCampaignCard,
  heading
}) {
  const { items, isLoading } = useGroupItems(type, refs, buildUrl);
  const config = resolveGroupConfig(type);
  const isListLayout = config.layout === "list";
  const cardSize = config.gridSize;
  const [page, setPage] = useState(1);
  const refsKey = refs.map((r) => r.id).join("|");
  const prevRefsKeyRef = useRef(refsKey);
  useEffect(() => {
    if (prevRefsKeyRef.current !== refsKey) {
      prevRefsKeyRef.current = refsKey;
      setPage(1);
    }
  }, [refsKey]);
  const totalGroupPages = Math.max(1, Math.ceil(refs.length / GROUP_PAGE_SIZE));
  const safePage = Math.min(page, totalGroupPages);
  const visibleGroupRefs = refs.length > GROUP_PAGE_SIZE ? refs.slice((safePage - 1) * GROUP_PAGE_SIZE, safePage * GROUP_PAGE_SIZE) : refs;
  const groupPagination = totalGroupPages > 1 ? /* @__PURE__ */ jsx(Pagination, { currentPage: safePage, totalPages: totalGroupPages, onPageChange: setPage }) : null;
  if (isLoading && !items) {
    const skeletons = visibleGroupRefs.map((r) => /* @__PURE__ */ jsx("div", { children: renderSkeletonForType(type, cardSize, adminCampaignCard) }, r.id));
    return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
      heading,
      isListLayout ? /* @__PURE__ */ jsx("div", { className: "space-y-4", children: skeletons }) : /* @__PURE__ */ jsx("div", { className: gridClassFor(columns), children: skeletons })
    ] });
  }
  if (!items || items.length === 0) return null;
  const itemById = new Map(
    items.map((it) => [extractItemId(type, it) ?? String(it?.id), it])
  );
  const cards = visibleGroupRefs.map((contentRef) => {
    const itemId = String(contentRef.id);
    const item = itemById.get(itemId);
    if (!item) return null;
    const resolved = resolveHref(contentRef);
    const href = resolved.href ?? "";
    const targetPlatform = resolved.targetPlatform ?? contentRef.targetPlatform ?? null;
    return /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(LinkProvider, { href: href || null, targetPlatform, children: (linkProps) => /* @__PURE__ */ jsx(
      CardForType,
      {
        type,
        item,
        size: cardSize,
        href,
        targetPlatform,
        linkProps,
        extras,
        adminCampaignCard
      }
    ) }) }, itemId);
  }).filter(Boolean);
  if (cards.length === 0) {
    if (groupPagination) {
      return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
        heading,
        groupPagination
      ] });
    }
    return null;
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-4", children: [
    heading,
    isListLayout ? /* @__PURE__ */ jsx("div", { className: "space-y-4", children: cards }) : /* @__PURE__ */ jsx("div", { className: gridClassFor(columns), children: cards }),
    groupPagination
  ] });
}
function RelatedContentSection({
  contentRefs,
  entityType,
  entityId,
  authorId,
  minResults,
  sameTypeMinResults,
  includeTypes,
  initialItems,
  title = "Related Content",
  columns = 2,
  excludeTypes,
  apiBaseUrl = "",
  extras,
  resolveHref = defaultResolveHref,
  buildListUrl: buildListUrl2,
  LinkProvider = DefaultLinkPropsProvider,
  adminCampaignCard
}) {
  const suggestionsDisabled = includeTypes?.length === 0;
  const typeFilterParams = {
    types: includeTypes !== void 0 ? includeTypes.join(",") : void 0,
    excludeTypes: excludeTypes && excludeTypes.length > 0 ? excludeTypes.join(",") : void 0
  };
  const authorUrl = contentRefs === void 0 && authorId && !suggestionsDisabled ? buildSuggestionUrl("/api/related-content", {
    apiBaseUrl,
    extraParams: { authorId, ...typeFilterParams }
  }) : null;
  const suggestUrl = authorUrl ?? (contentRefs === void 0 && entityType && entityId !== void 0 && entityId !== null && entityId !== "" && !suggestionsDisabled ? buildSuggestionUrl("/api/related-content", {
    apiBaseUrl,
    entityType,
    entityId,
    count: minResults,
    extraParams: {
      sameTypeCount: sameTypeMinResults !== void 0 ? String(sameTypeMinResults) : void 0,
      ...typeFilterParams
    }
  }) : null);
  const initialData = useMemo(
    // An explicitly disabled rail (includeTypes: []) must ignore SSR-hydrated
    // refs too — otherwise useSelfFetch(null, {initialData}) keeps serving
    // initialItems and the "nothing participates" contract silently breaks.
    () => !suggestionsDisabled && initialItems ? { refs: initialItems } : void 0,
    [initialItems, suggestionsDisabled]
  );
  const { data } = useSelfFetch(suggestUrl, { initialData });
  const effectiveBuildListUrl = useMemo(
    () => buildListUrl2 ?? ((type, ids) => buildListUrl(type, ids, apiBaseUrl)),
    [buildListUrl2, apiBaseUrl]
  );
  const refs = contentRefs ?? data?.refs ?? [];
  const exclude = new Set(excludeTypes || []);
  const visibleRefs = exclude.size > 0 ? refs.filter((r) => !exclude.has(r.type)) : refs;
  if (!visibleRefs.length) return null;
  const grouped = {};
  for (const ref of visibleRefs) {
    if (!grouped[ref.type]) grouped[ref.type] = [];
    grouped[ref.type].push(ref);
  }
  let orderedTypes = orderContentRefTypes(Object.keys(grouped));
  if (entityType) {
    const canonicalEntityType = canonicalContentRefType(entityType);
    const sameType = orderedTypes.filter((t) => canonicalContentRefType(t) === canonicalEntityType);
    if (sameType.length > 0) {
      orderedTypes = [...sameType, ...orderedTypes.filter((t) => canonicalContentRefType(t) !== canonicalEntityType)];
    }
  }
  return /* @__PURE__ */ jsxs("div", { className: "space-y-8", children: [
    /* @__PURE__ */ jsx("h2", { className: "text-2xl font-bold text-ods-text-primary", children: title }),
    orderedTypes.map((type) => /* @__PURE__ */ jsx(
      ContentGroup,
      {
        type,
        refs: grouped[type],
        columns,
        buildUrl: effectiveBuildListUrl,
        resolveHref,
        LinkProvider,
        extras,
        adminCampaignCard,
        heading: /* @__PURE__ */ jsx("h3", { className: "font-['Azeret_Mono'] text-[14px] font-semibold uppercase text-ods-text-secondary tracking-wider", children: getContentRefLabelOrTitleCase(type) })
      },
      type
    ))
  ] });
}

export {
  GROUP_PAGE_SIZE,
  RelatedContentSection
};
//# sourceMappingURL=chunk-KUYYJ2XM.js.map