"use client";
import {
  useSelfFetch
} from "./chunk-L4LAAA5Q.js";
import {
  ChevronButton,
  buildSuggestionUrl,
  scrollElementIntoView,
  serializeJsonLd
} from "./chunk-T2URJAX2.js";
import {
  SECTION_HEADING_CLASS
} from "./chunk-OO4ZGDRO.js";
import {
  cn,
  init_cn
} from "./chunk-XTCBRQN2.js";

// src/components/faq/faq-section.tsx
import { useCallback as useCallback2, useEffect as useEffect2, useMemo, useState as useState2 } from "react";

// src/components/faq-accordion.tsx
import { useRef, useState, useEffect, useCallback } from "react";
init_cn();
import { jsx, jsxs } from "react/jsx-runtime";
var useMeasuredHeight = (isOpen) => {
  const ref = useRef(null);
  const [maxHeight, setMaxHeight] = useState("0px");
  const measure = useCallback(() => {
    if (ref.current) {
      const height = ref.current.scrollHeight;
      setMaxHeight(`${height}px`);
    }
  }, []);
  useEffect(() => {
    if (isOpen) {
      measure();
    } else {
      setMaxHeight("0px");
    }
  }, [isOpen, measure]);
  return { ref, maxHeight };
};
function FaqAccordion({ items, defaultOpenIds = [] }) {
  const [openSet, setOpenSet] = useState(new Set(defaultOpenIds));
  const toggle = (id) => {
    setOpenSet((prev) => {
      const next = new Set(prev);
      if (next.has(id)) next.delete(id);
      else next.add(id);
      return next;
    });
  };
  return /* @__PURE__ */ jsx("div", { className: "rounded-3xl border border-ods-border divide-y divide-ods-border bg-ods-card overflow-hidden", children: items.map((item) => {
    const isOpen = openSet.has(item.id);
    const { ref, maxHeight } = useMeasuredHeight(isOpen);
    return /* @__PURE__ */ jsxs(
      "div",
      {
        className: cn("group transition-colors hover:bg-[#1E1E1E]", isOpen ? "bg-ods-bg" : "bg-transparent"),
        children: [
          /* @__PURE__ */ jsxs(
            "div",
            {
              role: "button",
              tabIndex: 0,
              onClick: () => toggle(item.id),
              onKeyDown: (e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  toggle(item.id);
                }
              },
              "aria-expanded": isOpen,
              className: "flex w-full items-center justify-between px-6 md:px-8 py-6 text-left focus:outline-none transition-colors cursor-pointer",
              children: [
                /* @__PURE__ */ jsx("div", { className: "min-w-0 pr-4", children: /* @__PURE__ */ jsx("h3", { children: item.question }) }),
                /* @__PURE__ */ jsx("div", { className: "flex-shrink-0", children: /* @__PURE__ */ jsx(
                  ChevronButton,
                  {
                    "aria-label": isOpen ? "Collapse question" : "Expand question",
                    size: "md",
                    isExpanded: isOpen,
                    backgroundColor: "transparent",
                    borderColor: "#3A3A3A"
                  }
                ) })
              ]
            }
          ),
          /* @__PURE__ */ jsx(
            "div",
            {
              style: { maxHeight, transition: "max-height 0.35s ease-in-out, opacity 0.35s ease-in-out", opacity: isOpen ? 1 : 0 },
              className: "overflow-hidden group-hover:bg-[#1E1E1E]/30",
              children: /* @__PURE__ */ jsx("div", { ref, className: "px-6 md:px-8 pb-6 text-ods-text-primary text-h4", children: item.answer })
            }
          )
        ]
      },
      item.id
    );
  }) });
}

// src/components/faq/faq-section.tsx
init_cn();

// src/components/faq/json-ld.ts
var DEFAULT_NAME = "Frequently Asked Questions";
var DEFAULT_DESCRIPTION = "Answers to common questions.";
function baseFaqSchema(opts = {}) {
  return {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    name: opts.name ?? DEFAULT_NAME,
    description: opts.description ?? DEFAULT_DESCRIPTION,
    ...opts.url ? { url: opts.url } : {}
  };
}
function buildFaqJsonLdFromFaqs(faqs, opts = {}) {
  return {
    ...baseFaqSchema(opts),
    mainEntity: faqs.map((faq) => ({
      "@type": "Question",
      name: faq.question,
      acceptedAnswer: {
        "@type": "Answer",
        text: faq.answer
      }
    }))
  };
}

// src/components/faq/faq-section.tsx
import { Fragment, jsx as jsx2, jsxs as jsxs2 } from "react/jsx-runtime";
var DEFAULT_HEADING_TEXT = "Frequently Asked Questions";
function buildFaqsUrl(entityType, entityId, minResults, apiBaseUrl = "") {
  return buildSuggestionUrl("/api/faqs", { apiBaseUrl, entityType, entityId, count: minResults });
}
function sectionSlug(section) {
  return "faq-" + section.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
}
function groupFaqsBySection(faqs) {
  const order = [];
  const byName = /* @__PURE__ */ new Map();
  let uncategorized = null;
  for (const faq of faqs) {
    const item = { id: faq.id, question: faq.question, answer: faq.answer };
    const name = faq.section?.trim();
    if (!name) {
      if (!uncategorized) uncategorized = { section: null, slug: null, items: [] };
      uncategorized.items.push(item);
      continue;
    }
    let group = byName.get(name);
    if (!group) {
      group = { section: name, slug: sectionSlug(name), items: [] };
      byName.set(name, group);
      order.push(name);
    }
    group.items.push(item);
  }
  const groups = order.map((name) => byName.get(name));
  if (uncategorized) groups.push(uncategorized);
  return groups;
}
var FAQ_NAV_HEADER_OFFSET = 96;
function GroupedFaqList({
  groups,
  categoryHeadingAs
}) {
  const CategoryHeading = categoryHeadingAs;
  const navGroups = useMemo(() => groups.filter((g) => g.slug), [groups]);
  const [activeSlug, setActiveSlug] = useState2(navGroups[0]?.slug ?? null);
  const slugKey = navGroups.map((g) => g.slug).join("|");
  useEffect2(() => {
    if (navGroups.length < 2) return;
    const tops = /* @__PURE__ */ new Map();
    const observer = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) {
          const id = entry.target.id;
          if (entry.isIntersecting) tops.set(id, entry.boundingClientRect.top);
          else tops.delete(id);
        }
        let bestId = null;
        let bestTop = Number.POSITIVE_INFINITY;
        for (const [id, top] of tops) {
          if (top < bestTop) {
            bestTop = top;
            bestId = id;
          }
        }
        if (bestId) setActiveSlug(bestId);
      },
      { rootMargin: `-${FAQ_NAV_HEADER_OFFSET}px 0px -55% 0px`, threshold: 0 }
    );
    for (const group of navGroups) {
      const el = group.slug ? document.getElementById(group.slug) : null;
      if (el) observer.observe(el);
    }
    return () => observer.disconnect();
  }, [slugKey]);
  const handleJump = useCallback2(
    (e, slug) => {
      e.preventDefault();
      setActiveSlug(slug);
      scrollElementIntoView(document.getElementById(slug), {
        headerOffset: FAQ_NAV_HEADER_OFFSET
      });
      if (typeof history !== "undefined") history.replaceState(null, "", `#${slug}`);
    },
    []
  );
  return /* @__PURE__ */ jsxs2("div", { className: "space-y-8", children: [
    navGroups.length > 1 && /* @__PURE__ */ jsx2("nav", { "aria-label": "FAQ categories", className: "flex flex-wrap gap-2", children: navGroups.map((group) => {
      const isActive = group.slug === activeSlug;
      return /* @__PURE__ */ jsx2(
        "a",
        {
          href: `#${group.slug}`,
          "aria-current": isActive ? "true" : void 0,
          onClick: (e) => handleJump(e, group.slug),
          className: cn(
            "rounded-full border px-4 py-2 text-sm font-medium font-['DM_Sans'] transition-colors",
            isActive ? "border-ods-text-primary bg-ods-card text-ods-text-primary" : "border-ods-border bg-ods-card text-ods-text-secondary hover:border-ods-text-secondary hover:text-ods-text-primary"
          ),
          children: group.section
        },
        group.slug
      );
    }) }),
    /* @__PURE__ */ jsx2("div", { className: "space-y-10", children: groups.map((group) => /* @__PURE__ */ jsxs2(
      "section",
      {
        id: group.slug ?? void 0,
        className: "scroll-mt-24 space-y-4",
        children: [
          group.section && /* @__PURE__ */ jsx2(CategoryHeading, { className: SECTION_HEADING_CLASS, children: group.section }),
          /* @__PURE__ */ jsx2(FaqAccordion, { items: group.items })
        ]
      },
      group.slug ?? "faq-uncategorized"
    )) })
  ] });
}
function FaqSkeleton() {
  return /* @__PURE__ */ jsxs2("div", { className: "space-y-8 animate-pulse", children: [
    /* @__PURE__ */ jsx2("div", { className: "h-12 md:h-14 w-2/3 rounded bg-ods-border" }),
    /* @__PURE__ */ jsx2("div", { className: "rounded-3xl border border-ods-border overflow-hidden bg-ods-card divide-y divide-ods-border w-full", children: Array.from({ length: 8 }).map((_, idx) => /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between px-6 md:px-8 py-6", children: [
      /* @__PURE__ */ jsx2("div", { className: "h-6 w-5/6 rounded bg-ods-border" }),
      /* @__PURE__ */ jsx2("div", { className: "h-10 w-10 rounded-md bg-ods-border" })
    ] }, idx)) })
  ] });
}
function FaqSection({
  initialFaqs,
  entityType,
  entityId,
  heading,
  emitJsonLd = false,
  jsonLd,
  className,
  minResults,
  apiBaseUrl = ""
}) {
  const url = buildFaqsUrl(entityType, entityId, minResults, apiBaseUrl);
  const initialData = useMemo(
    () => initialFaqs ? { faqs: initialFaqs } : void 0,
    [initialFaqs]
  );
  const { data, isLoading, error } = useSelfFetch(url, { initialData });
  const faqs = data?.faqs ?? [];
  const groups = useMemo(() => faqs.length > 0 ? groupFaqsBySection(faqs) : [], [faqs]);
  const headingNode = heading === void 0 ? /* @__PURE__ */ jsx2("h2", { className: SECTION_HEADING_CLASS, children: DEFAULT_HEADING_TEXT }) : heading;
  if (error) return null;
  if (!isLoading && faqs.length === 0) return null;
  if (isLoading && faqs.length === 0) {
    return /* @__PURE__ */ jsx2("div", { className, children: /* @__PURE__ */ jsx2(FaqSkeleton, {}) });
  }
  const schema = emitJsonLd ? buildFaqJsonLdFromFaqs(faqs, jsonLd) : null;
  return /* @__PURE__ */ jsxs2(Fragment, { children: [
    /* @__PURE__ */ jsxs2("section", { className: className ?? "space-y-10", children: [
      headingNode,
      /* @__PURE__ */ jsx2(GroupedFaqList, { groups, categoryHeadingAs: heading === null ? "h2" : "h3" })
    ] }),
    schema && /* @__PURE__ */ jsx2(
      "script",
      {
        type: "application/ld+json",
        dangerouslySetInnerHTML: { __html: serializeJsonLd(schema) }
      }
    )
  ] });
}

export {
  FaqAccordion,
  FaqSection
};
//# sourceMappingURL=chunk-CYMMGPPV.js.map