"use client";

import { useState } from 'react';
import { motion } from 'framer-motion';
import type { FaqQuestion } from '../../types/api/faq';

interface FAQHomeProps {
  faqs: FaqQuestion[];
  title?: string;
  maxItems?: number;
}

export const FAQHome = ({
  faqs: faqsData,
  title = "",
  maxItems,
}: FAQHomeProps) => {
  const faqs = Array.isArray(faqsData) ? faqsData : [];
  const displayFaqs = maxItems ? faqs.slice(0, maxItems) : faqs;
  
  const [openIndex, setOpenIndex] = useState<number | null>(null);

  return (
    <section>
      <div className="mx-auto max-w-3xl px-4 md:px-8">
        <div className="mb-12 text-center">
          <h2 className="font-display text-4xl font-normal text-fg-primary md:text-5xl">
            {title}
          </h2>
        </div>

        {displayFaqs.length > 0 ? (
          <div className="space-y-4">
            {displayFaqs.map((faq, i: number) => {
              const isOpen = openIndex === i;
              const answer = faq.answer_markdown?.replace(/[#*\[\]()]/g, '').trim() || '';
              
              return (
                <div key={faq.id} className="border-b border-secondary">
                  <button
                    onClick={() => setOpenIndex(isOpen ? null : i)}
                    className="flex w-full items-center justify-between py-4 text-left"
                  >
                    <h3 className="font-display text-xl font-normal text-fg-primary">
                      {faq.question}
                    </h3>
                    <span className="ml-4 text-fg-primary">
                      {isOpen ? '−' : '+'}
                    </span>
                  </button>
                  <motion.div
                    initial={false}
                    animate={{
                      height: isOpen ? 'auto' : 0,
                      opacity: isOpen ? 1 : 0,
                    }}
                    transition={{
                      duration: 0.3,
                      ease: [0.4, 0.0, 0.2, 1],
                    }}
                    style={{ overflow: 'hidden' }}
                  >
                    <div className="pb-4">
                      <p className="font-body text-base leading-relaxed text-tertiary whitespace-pre-line">
                        {answer}
                      </p>
                    </div>
                  </motion.div>
                </div>
              );
            })}
          </div>
        ) : (
          <div className="text-center py-12">
            <p className="font-body text-base text-tertiary">No FAQs available</p>
          </div>
        )}
      </div>
    </section>
  );
};

import { registerThemeVariant } from '../../lib/component-registry';
registerThemeVariant('faq-home', 'aman', FAQHome);
