<script lang="ts">
  import { accordion } from '$lib/actions/accordion';
  import Icon from '$lib/components/ui/Icon.svelte';
  import type { FaqItem } from '$lib/types';

  export let title = 'FAQs';
  export let intro: string | undefined = undefined;
  export let faqs: FaqItem[];
  export let emitSchema = true;
  export let variant: 'panel' | 'plain' = 'panel';
  // When the host page supplies its own heading (e.g. to match a page-wide
  // section system), suppress the built-in one but keep the schema + list.
  export let showHeading = true;

  $: schemaJson = JSON.stringify({
    '@context': 'https://schema.org',
    '@type': 'FAQPage',
    mainEntity: faqs.map((faq) => ({
      '@type': 'Question',
      name: faq.question,
      acceptedAnswer: {
        '@type': 'Answer',
        text: faq.answer
      }
    }))
  });
</script>

<svelte:head>
  {#if emitSchema && faqs.length}
    {@html `<script type="application/ld+json">${schemaJson}<` + `/script>`}
  {/if}
</svelte:head>

<div class:faq-section-plain={variant === 'plain'} class="faq-section">
  {#if showHeading}
    <h2 class="faq-section-heading">
      <span class="faq-section-icon"><Icon name="fas fa-circle-question" /></span>
      {title}
    </h2>
    {#if intro}
      <p class="faq-section-intro">{intro}</p>
    {/if}
  {/if}
  <div use:accordion class="faq">
    {#each faqs as faq}
      <details>
        <summary>{faq.question}</summary>
        <p>{faq.answer}</p>
      </details>
    {/each}
  </div>
</div>

<style>
  .faq-section-icon {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 40px;
    height: 40px;
    margin-right: 10px;
    border-radius: 12px;
    background: var(--gw-green);
    box-shadow: 0 10px 22px rgba(33, 48, 33, 0.16);
    vertical-align: middle;
  }

  .faq-section-icon :global(.icon) {
    color: var(--yellow);
    font-size: 16px;
  }

  .faq-section-heading {
    margin: 0 0 14px;
  }

  .faq-section-intro {
    margin: 0 0 18px;
    color: #5b6067;
    font-size: 16px;
    line-height: 1.6;
  }

  @media (max-width: 768px) {
    .faq-section-icon {
      display: none;
    }

    .faq-section-heading {
      text-align: left;
      white-space: normal;
      overflow-wrap: anywhere;
      text-wrap: balance;
      font-size: clamp(22px, 5.6vw, 26px);
      line-height: 1.18;
    }

    .faq summary,
    .faq details p {
      text-align: left;
    }
  }
</style>
