import Link from "next/link";
import { readFile, readdir } from "node:fs/promises";
import { join } from "node:path";
import matter from "gray-matter";

export default async function FaqIndexPage() {
  // Dynamically read all FAQ markdown files
  const root = process.cwd();
  const faqDir = join(root, "content", "pt", "perguntas");
  
  let files: string[] = [];
  try {
    files = await readdir(faqDir);
    files = files.filter((f) => f.endsWith(".md")).sort();
  } catch {
    files = [];
  }

  const entries: { slug: string; title: string; readTime?: string; intendedFor?: string }[] = [];
  for (const f of files) {
    const raw = await readFile(join(faqDir, f));
    const { data } = matter(raw.toString());
    entries.push({
      slug: f.replace(/\.md$/, ""),
      title: String(data.title ?? "FAQ"),
      readTime: data.readTime as string | undefined,
      intendedFor: data.intendedFor as string | undefined,
    });
  }

  return (
    <section aria-labelledby="faq-title">
      <h1 id="faq-title" className="text-2xl font-bold">Perguntas Frequentes</h1>
      <ul className="mt-4 space-y-3">
        {entries.map((e) => (
          <li key={e.slug} className="border p-3">
            <Link href={`/pt/perguntas/${e.slug}`} className="underline font-semibold">{e.title}</Link>
            {e.readTime && <span className="ml-2">• {e.readTime}</span>}
            {e.intendedFor && <span className="ml-2">• {e.intendedFor}</span>}
          </li>
        ))}
      </ul>
    </section>
  );
}
