import { Fragment, isValidElement, type ReactNode } from "react";

import { logger } from "@/lib/logger";
import { faqSchema } from "@/lib/schema";

import JsonLd from "./JsonLd";

function visibleText(node: ReactNode): string {
  if (node == null || typeof node === "boolean") return "";
  if (typeof node === "string" || typeof node === "number") return String(node);
  if (Array.isArray(node)) return node.map(visibleText).join(" ");
  if (
    isValidElement<{ children?: ReactNode }>(node) &&
    (typeof node.type === "string" || node.type === Fragment)
  ) {
    return visibleText(node.props.children);
  }
  logger.warn("FAQ structured data cannot read this answer's visible text");
  return "";
}

export default function FaqSchema({
  items,
}: {
  items: readonly { question: string; answer: ReactNode }[];
}) {
  return <JsonLd data={faqSchema(items.map(({ question, answer }) => ({
    question,
    answer: visibleText(answer),
  })))} />;
}
