"use client";

import { useState } from "react";

/**
 * The FAQ accordion.
 *
 * Markup matches the Blade templates exactly: `.accordion[data-accordion]`
 * containing alternating `h3.accordion__title > button[aria-expanded]` and
 * `.accordion__panel > .accordion__panel-inner`. The stylesheet animates the
 * panel's height, which is why the inner wrapper exists — it is the element with
 * the intrinsic height to measure against.
 *
 * Every answer is present in the server HTML regardless of open state, so the
 * content is indexable and the FAQPage schema the backend emits describes markup
 * that is actually there. Closed panels are hidden by CSS, not removed.
 *
 * `mark` is rendered only where the template renders it — `about_intro` has the
 * chevron span, the plain `accordion` block does not.
 */
export default function Accordion({
  items,
  withMark = false,
}: {
  items: Array<{ question: string; answer: string | null }>;
  withMark?: boolean;
}) {
  const [open, setOpen] = useState(0);

  if (!items || items.length === 0) {
    return null;
  }

  return (
    <div className="accordion" data-accordion>
      {items.map((item, index) => (
        <div key={index} style={{ display: "contents" }}>
          <h3 className="accordion__title">
            <button
              type="button"
              aria-expanded={open === index}
              onClick={() => setOpen(open === index ? -1 : index)}
            >
              {item.question}
              {withMark ? <span className="accordion__mark" /> : null}
            </button>
          </h3>
          <div className="accordion__panel" hidden={open !== index}>
            <div
              className="accordion__panel-inner"
              // Editor HTML, printed unescaped exactly as the Blade template
              // prints it.
              dangerouslySetInnerHTML={{ __html: item.answer ?? "" }}
            />
          </div>
        </div>
      ))}
    </div>
  );
}
