'use client'

import { useState, useEffect } from 'react';
import styles from './FAQ.module.css';

interface FAQItem {
    q: string;
    a: string;
}

interface FAQProps {
    faqs: FAQItem[];
}

export default function FAQ({ faqs }: FAQProps) {
    const [openIndex, setOpenIndex] = useState<number | null>(0);

    useEffect(() => {
        if (faqs.length > 0) {
            const timer = setTimeout(() => {
                setOpenIndex(0);
            }, 100);
            return () => clearTimeout(timer);
        }
    }, [faqs.length]);

    const toggleFAQ = (index: number) => {
        setOpenIndex(openIndex === index ? null : index);
    };

    return (
        <div className={styles.faqSection}>
            <h3 className={styles.faqTitle}>FAQs</h3>
            <div className={styles.faqContainer}>
                {faqs.map((faq, index) => (
                    <div key={index} className={styles.faqItem}>
                        <button
                            className={`${styles.faqQuestion} ${openIndex === index ? styles.active : ''}`}
                            onClick={() => toggleFAQ(index)}
                        >
                            <span>{faq.q}</span>
                            <span className={styles.icon}>{openIndex === index ? '−' : '+'}</span>
                        </button>
                        <div className={`${styles.faqAnswer} ${openIndex === index ? styles.open : ''}`}>
                            <div
                                className={styles.faqContent}
                                dangerouslySetInnerHTML={{ __html: faq.a }}
                            />
                        </div>
                    </div>
                ))}
            </div>
        </div>
    );
}
