"use client";

import { useEffect, useState } from "react";
import { ChevronDown } from "lucide-react";
import { cn } from "@/lib/utils";
import { api } from "@/lib/api";

interface FaqItem {
  id: string;
  question: string;
  answer: string;
  order: number;
  showOnHomepage: boolean;
}

export function FAQSection() {
  const [items, setItems] = useState<FaqItem[]>([]);
  const [openIndex, setOpenIndex] = useState<number | null>(null);

  useEffect(() => {
    api.getFaqs().catch(() => []).then((data) => {
      if (Array.isArray(data)) setItems(data);
    });
  }, []);

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

  return (
    <section id="faq" className="py-24 px-8">
      <div className="max-w-3xl mx-auto">
        <h2 className="text-4xl font-black mb-16 text-center">
          Frequently Asked Questions
        </h2>

        <div className="space-y-4">
          {items.map((item, i) => {
            const isOpen = openIndex === i;

            return (
              <div
                key={item.id}
                className="bg-surface-container-low rounded-xl overflow-hidden"
              >
                <button
                  onClick={() => setOpenIndex(isOpen ? null : i)}
                  className="w-full flex items-center justify-between p-6 text-left"
                >
                  <span className="text-lg font-bold pr-4">{item.question}</span>
                  <ChevronDown
                    size={20}
                    className={cn(
                      "shrink-0 text-primary transition-transform duration-200",
                      isOpen && "rotate-180"
                    )}
                  />
                </button>

                <div
                  className={cn(
                    "grid transition-all duration-200",
                    isOpen ? "grid-rows-[1fr]" : "grid-rows-[0fr]"
                  )}
                >
                  <div className="overflow-hidden">
                    <p className="px-6 pb-6 text-on-surface-variant leading-relaxed">
                      {item.answer}
                    </p>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}
