import Container from "@/components/Container/Container";
import Section from "@/components/Section/Section";
import FAQs from "@/components/FAQs/FAQs";
import { FAQPage, WithContext } from "schema-dts";

const FaqsBlock = (props: any) => {
  const faqs: { question: string; answer: string }[] = [];

  for (let i = 0; i < props.faq; i++) {
    const question = String(props[`faq_${i}_question`] || "").trim();
    const answer = String(props[`faq_${i}_answer`] || "").trim();

    if (!question || !answer) {
      continue;
    }

    faqs.push({ question, answer });
  }

  if (faqs.length < 1) return <></>;

  const faqJsonLd: WithContext<FAQPage> = {
    "@context": "https://schema.org",
    "@type": "FAQPage",
    mainEntity: faqs.map(({ question, answer }) => ({
      "@type": "Question",
      name: question,
      acceptedAnswer: {
        "@type": "Answer",
        text: answer,
      },
    })),
  };

  return (
    <Container id={props.anchor}>
      <Section gridArea="thin">
        <script
          type="application/ld+json"
          dangerouslySetInnerHTML={{ __html: JSON.stringify(faqJsonLd) }}
        />
        {props.title && <h4 className="h1">{props.title}</h4>}
        <FAQs faqs={faqs} />
      </Section>
    </Container>
  );
};

export default FaqsBlock;
