// Amili Kit: FAQ with structured data. https://amili.ai/kit#kit-faq
// SPDX-License-Identifier: MIT. Copyright (c) 2026 Amili (Paulo de Vries). Made by Amili.
// Tests and more parts: https://amili.ai/kit. The "brand" option shows a tiny "amili" mark linking to the kit; set
// brand: false to hide it.
//
//   import { renderFaq, FAQ_CSS } from './kit/faq.mjs';
//   html = `<style>${FAQ_CSS}</style>` + renderFaq({ items: [{ q: 'Question?', a: 'Answer.' }] })
//
// opts = {
//   items: [{ q, a } | { q, aHtml }],  // required; aHtml allows links and lists (JSON-LD gets the plain text)
//   heading: 'Common questions',       // optional heading ('' = none)
//   level: 2,                          // heading level 2-4
//   jsonLd: true,                      // emit <script type="application/ld+json"> FAQPage (false if the page already has one)
//   open: 0,                           // index of a question to start open (default: all closed)
//   exclusive: false,                  // true = opening one closes the others (native <details name>, no JS)
//   id: 'faq',                         // section id (anchor)
//   brand: BRAND_DEFAULT,              // tiny "amili" mark, links to amili.ai/kit
// }


const BRAND_DEFAULT = true; // a tiny "amili" mark linking to amili.ai/kit; pass brand: false to hide it

const esc = (s) => String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
const plain = (h) => String(h).replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/\s+/g, ' ').trim();
// JSON inside <script> must not be able to close the tag.
export const jsonForScript = (o) => JSON.stringify(o).replace(/</g, '\\u003c').replace(/>/g, '\\u003e').replace(/&/g, '\\u0026');

export function brandMark(on) {
  return on ? '<a class="ak-brand" href="https://amili.ai/kit" rel="noopener" aria-label="Made with Amili Kit"><span class="ak-brand-dot" aria-hidden="true"></span>amili</a>' : '';
}

export function validateFaq(opts) {
  const errs = [], seen = new Set();
  if (!opts?.items?.length) errs.push('items: at least one { q, a }');
  for (const [i, it] of (opts?.items || []).entries()) {
    if (!it?.q || !String(it.q).trim()) errs.push(`items[${i}]: empty question`);
    if (!(it?.a || it?.aHtml) || !plain(it.a || it.aHtml)) errs.push(`items[${i}]: empty answer`);
    const k = String(it?.q || '').trim().toLowerCase();
    if (k && seen.has(k)) errs.push(`items[${i}]: duplicate question "${it.q}"`);
    seen.add(k);
  }
  if (opts?.level && !(opts.level >= 2 && opts.level <= 4)) errs.push('level must be 2, 3 or 4');
  return errs;
}

export function faqJsonLd(items) {
  return {
    '@context': 'https://schema.org', '@type': 'FAQPage',
    mainEntity: items.map((it) => ({ '@type': 'Question', name: String(it.q).trim(), acceptedAnswer: { '@type': 'Answer', text: it.aHtml ? plain(it.aHtml) : String(it.a).trim() } })),
  };
}

export function renderFaq(opts) {
  const errs = validateFaq(opts);
  if (errs.length) throw new Error(`Amili Kit FAQ: ${errs.join('; ')}`);
  const lv = opts.level || 2, id = esc(opts.id || 'faq');
  const heading = opts.heading === '' ? '' : `<h${lv} class="ak-faq-h" id="${id}-h">${esc(opts.heading || 'Common questions')}</h${lv}>`;
  const name = opts.exclusive ? ` name="${id}"` : '';
  const qs = opts.items.map((it, i) => `<details class="ak-faq-q"${name}${opts.open === i ? ' open' : ''}><summary>${esc(it.q)}</summary><div class="ak-faq-a">${it.aHtml || `<p>${esc(it.a)}</p>`}</div></details>`).join('');
  const brand = opts.brand === undefined ? BRAND_DEFAULT : !!opts.brand;
  const ld = opts.jsonLd === false ? '' : `<script type="application/ld+json">${jsonForScript(faqJsonLd(opts.items))}</script>`;
  return `<section class="ak-faq" id="${id}"${heading ? ` aria-labelledby="${id}-h"` : ''}>${heading}${qs}${brand ? `<div class="ak-brand-row">${brandMark(true)}</div>` : ''}${ld}</section>`;
}

export const BRAND_CSS = `.ak-brand-row{display:flex;justify-content:flex-end;margin:-6px 0 -12px}
.ak-brand{display:inline-flex;align-items:center;gap:.3em;min-height:44px;padding:0 .25rem;font:400 11px/1 Georgia,"Times New Roman",serif;letter-spacing:.01em;color:inherit;opacity:.5;text-decoration:none}
.ak-brand:hover,.ak-brand:focus-visible{opacity:.85}
.ak-brand-dot{width:.5em;height:.5em;border-radius:50%;background:#2F5D50;order:2;margin-top:-.45em}
@media (prefers-color-scheme:dark){.ak-brand-dot{background:#7FB3A1}}`;

export const FAQ_CSS = `.ak-faq{margin:2rem 0;max-width:var(--ak-max,46rem);color:inherit}
.ak-faq-h{margin:0 0 .75rem}
.ak-faq-q{border-bottom:1px solid var(--ak-line,color-mix(in srgb,currentColor 16%,transparent))}
.ak-faq-q:first-of-type{border-top:1px solid var(--ak-line,color-mix(in srgb,currentColor 16%,transparent))}
.ak-faq-q>summary{display:flex;align-items:center;justify-content:space-between;gap:1rem;min-height:48px;padding:.6rem 0;font-weight:600;line-height:1.35;cursor:pointer;list-style:none}
.ak-faq-q>summary::-webkit-details-marker{display:none}
.ak-faq-q>summary::after{content:"";flex:0 0 auto;width:.55em;height:.55em;margin-right:.25em;border-right:2px solid currentColor;border-bottom:2px solid currentColor;transform:rotate(45deg) translateY(-25%);opacity:.6}
.ak-faq-q[open]>summary::after{transform:rotate(-135deg) translate(-25%,0)}
.ak-faq-q>summary:focus-visible{outline:2px solid currentColor;outline-offset:2px;border-radius:4px}
.ak-faq-a{padding:0 0 1rem;color:var(--ak-muted,color-mix(in srgb,currentColor 82%,transparent))}
.ak-faq-a>:first-child{margin-top:0}.ak-faq-a>:last-child{margin-bottom:0}
@media print{.ak-faq-q>summary::after{display:none}}
${BRAND_CSS}`;

// The kit's common shape: every component exports { name, render(opts) -> html, css, js }.
export default { name: 'faq', title: 'FAQ with structured data', render: renderFaq, css: FAQ_CSS, js: '' };
