"use client";

import { useEffect, useMemo, useState } from "react";
import { Chip } from "@/components/life/Controls";
import { LifeNotice, LifeSkeleton } from "@/components/life/LifeStatus";
import Icon from "@/components/ui/Icon";
import { useFaqsStore } from "@/store/services";

const label = (s: string) => s.charAt(0).toUpperCase() + s.slice(1);

/** FAQ accordion on native <details>, so keyboard and screen readers work without extra code. Topic chips come from the data. */
export default function FaqList() {
  const store = useFaqsStore();
  const [scope, setScope] = useState<string | null>(null);

  useEffect(() => {
    if (store.status === "idle") void store.load();
  }, [store.status, store.load]);

  const scopes = useMemo(() => [...new Set(store.items.map((f) => f.scope))], [store.items]);
  const shown = store.items.filter((f) => !scope || f.scope === scope);
  const loading = store.status === "idle" || store.status === "loading";

  return (
    <div className="lf">
      {scopes.length > 1 && (
        <div className="lf-group sv-tools" role="group" aria-label="Topic">
          <Chip pressed={!scope} onClick={() => setScope(null)}>
            All topics
          </Chip>
          {scopes.map((s) => (
            <Chip key={s} pressed={scope === s} onClick={() => setScope(scope === s ? null : s)}>
              {label(s)}
            </Chip>
          ))}
        </div>
      )}

      <LifeNotice status={store.status} error={store.error} hasFallback={false} onRetry={() => void store.load()} />

      {loading && store.items.length === 0 ? (
        <LifeSkeleton />
      ) : (
        <div className="sv-faq">
          {shown.map((f) => (
            <details key={f.id}>
              <summary>
                <span>{f.question}</span>
                <Icon name="expand_more" />
              </summary>
              <p>{f.answer}</p>
            </details>
          ))}
        </div>
      )}
    </div>
  );
}
