// app/faq/page.tsx

"use client";

import { Loader2, MessageCircleQuestionMark } from 'lucide-react';
import { useEffect, useState } from 'react';
import { readJsonFile } from '../actions/jsonEditor';
import { FAQItem } from '../components/ui/FAQItem';
import { PageHeader } from '../components/ui/PageHeader';
import { SectionCard } from '../components/ui/SectionCard';

export default function FAQ() {
    const [openIndex, setOpenIndex] = useState<string | null>(null);
    const [faqData, setFaqData] = useState<any[]>([]);
    const [isLoading, setIsLoading] = useState(true);

    useEffect(() => {
        const loadFAQ = async () => {
            if (navigator.onLine) {
                const res = await readJsonFile('faq.json');
                if (res.success && res.data) {
                    setFaqData(res.data);
                    localStorage.setItem('kullaberg_faq_cache', JSON.stringify(res.data));
                }
            } else {
                const cachedData = localStorage.getItem('kullaberg_faq_cache');
                if (cachedData) setFaqData(JSON.parse(cachedData));
            }
            setIsLoading(false);
        };
        loadFAQ();
    }, []);

    const toggleQuestion = (index: string) => {
        setOpenIndex(openIndex === index ? null : index);
    };

    if (isLoading) return <div className="flex justify-center py-20"><Loader2 className="animate-spin text-slate-teal" size={40} /></div>;

    return (
        <div className="w-full animate-fade-in space-y-6">
            <PageHeader
                title="Vanliga Frågor (FAQ)"
                icon={MessageCircleQuestionMark}
                description="Använd den här guiden för att snabbt svara på turisternas vanligaste frågor."
            />

            <div className="columns-1 lg:columns-2 gap-4">
                {faqData.map((section, sIndex) => (
                    <SectionCard
                        key={sIndex}
                        title={section.category}
                        className="break-inside-avoid mb-4 inline-block w-full"
                    >
                        <div className="space-y-2">
                            {section.questions.map((item: any, qIndex: number) => {
                                const id = `${sIndex}-${qIndex}`;
                                return (
                                    <FAQItem
                                        key={id}
                                        id={id}
                                        question={item.q}
                                        answer={item.a}
                                        isOpen={openIndex === id}
                                        onToggle={toggleQuestion}
                                    />
                                );
                            })}
                        </div>
                    </SectionCard>
                ))}
            </div>
        </div>
    );
}