import type { Product } from 'brainerce';
<% if (i18nEnabled) { %>import { getMessages, defaultLocale } from '@/i18n';<% } else { %>import { defaultLocale, messages } from '@/i18n';<% } %>

type FaqStrings = Record<string, string>;

<% if (i18nEnabled) { %>async function getFaqStrings(locale: string): Promise<FaqStrings> {
  return ((await getMessages(locale)).faq ?? {}) as FaqStrings;
}<% } else { %>async function getFaqStrings(_locale: string): Promise<FaqStrings> {
  return ((messages as Record<string, unknown>).faq ?? {}) as FaqStrings;
}<% } %>

interface ProductFaqSectionProps {
  product: Product;
  locale?: string;
}

/**
 * Visible product Q&A — the extractable question/answer format AI answer
 * engines cite. The SAME pairs are emitted as FAQPage JSON-LD by
 * <ProductJsonLd> (both read product.faq, so they can never drift). Server
 * component on purpose: the pairs must be in the initial HTML payload — AI
 * crawlers don't run JavaScript. Content inside a closed <details> is still
 * present in the HTML, so the accordion costs nothing for extraction.
 */
export async function ProductFaqSection({
  product,
  locale = defaultLocale,
}: ProductFaqSectionProps) {
  const pairs = (product.faq ?? []).filter((item) => item?.q && item?.a);
  if (pairs.length === 0) return null;
  const t = await getFaqStrings(locale);

  return (
    <section className="mx-auto max-w-7xl px-4 py-10 sm:px-6 lg:px-8">
      <h2 className="mb-6 text-2xl font-semibold">{t.title ?? 'Frequently asked questions'}</h2>
      <div className="divide-y rounded-xl border">
        {pairs.map((item) => (
          <details key={item.q} className="px-5 py-4">
            <summary className="cursor-pointer text-base font-medium">{item.q}</summary>
            <p className="mt-2 text-sm leading-relaxed opacity-80">{item.a}</p>
          </details>
        ))}
      </div>
    </section>
  );
}
