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;
}

/**
 * DESIGN ME — visible product Q&A.
 *
 * Two things here are behaviour, not styling, and must survive a redesign:
 *
 * 1. Keep it a SERVER component (no 'use client'). The pairs have to be in the
 *    initial HTML payload — AI answer engines cite this extractable Q&A format
 *    and do not run JavaScript. Content inside a closed <details> is still in
 *    the HTML, so an accordion costs nothing for extraction.
 * 2. Render the same pairs <ProductJsonLd> emits as FAQPage JSON-LD. Both read
 *    `product.faq`, so they cannot drift — unless you stop rendering them, at
 *    which point the structured data describes content that is not on the page.
 *
 * Style it however you like; drop the <details> for a custom accordion if you
 * prefer, as long as the text ships in the server-rendered HTML.
 */
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>
      <h2>{t.title ?? 'Frequently asked questions'}</h2>
      <div>
        {pairs.map((item) => (
          <details key={item.q}>
            <summary>{item.q}</summary>
            <p>{item.a}</p>
          </details>
        ))}
      </div>
    </section>
  );
}
