import type { StoreSiteBlock } from "@alqove/api-client";
import { blockData, list, str } from "../block-data";
import { SectionHeading, StorefrontSection } from "../section";

interface FaqItem {
  question?: string;
  answer?: string;
}

/** Native <details> so the accordion works before (and without) hydration. */
export function FaqBlock({ block }: { block: StoreSiteBlock }) {
  const data = blockData(block);
  const heading = str(data, "heading") ?? "Frequently asked";

  const items = list<FaqItem>(data, "items").filter(
    (item): item is { question: string; answer: string } =>
      typeof item?.question === "string" &&
      item.question.trim() !== "" &&
      typeof item?.answer === "string" &&
      item.answer.trim() !== "",
  );

  if (items.length === 0) return null;

  return (
    <StorefrontSection>
      <div className="max-w-2xl">
        <SectionHeading>{heading}</SectionHeading>
        <div className="divide-y" style={{ borderColor: "var(--sf-border)" }}>
          {items.map((item, i) => (
            <details key={i} className="group py-4">
              <summary className="cursor-pointer list-none text-base font-medium marker:hidden">
                <span className="flex items-center justify-between gap-4">
                  {item.question}
                  <span
                    aria-hidden="true"
                    className="shrink-0 transition-transform group-open:rotate-45"
                    style={{ color: "var(--sf-muted)" }}
                  >
                    +
                  </span>
                </span>
              </summary>
              <p
                className="mt-3 whitespace-pre-line text-sm leading-relaxed"
                style={{ color: "var(--sf-muted)" }}
              >
                {item.answer}
              </p>
            </details>
          ))}
        </div>
      </div>
    </StorefrontSection>
  );
}
