<x-layouts::front :title="__('about || Faqs', ['app' => config('app.name')])">
    <div class="">
        <x-hero-static title="Frequently Asked Questions"
            description="Find clear answers to common questions about our services, account options, security, and support. We're here to help you every step of the way."
              badge="Faqs"
    badgeIcon="question-mark-circle" />

        <div x-data="faqApp()" class="max-w-5xl mx-auto px-4 sm:px-6 lg:px-0 py-14 fade-in-up">

            <!-- Heading -->
            <h1 class="text-4xl font-bold text-gray-900 dark:text-white mb-10 text-center">
                Frequently Asked Questions
            </h1>

            <style>
                .no-scrollbar::-webkit-scrollbar {
                    display: none;
                }

                .no-scrollbar {
                    -ms-overflow-style: none;
                    scrollbar-width: none;
                }
            </style>

            {{-- Search --}}
            <div class="mb-10">
                <x-flux::input type="search" icon="magnifying-glass" placeholder="Search FAQs..." x-model="query"
                    @input.debounce.250ms="currentPage = 1" />
            </div>

            <!-- Category Tabs (Scrollable Pills) -->
            <div class="mb-10">
                <div class="relative">

                    <!-- Fade edges -->
                    <div
                        class="pointer-events-none absolute left-0 top-0 h-full w-10 bg-linear-to-r from-white dark:from-gray-950 to-transparent z-10">
                    </div>
                    <div
                        class="pointer-events-none absolute right-0 top-0 h-full w-10 bg-linear-to-l from-white dark:from-gray-950 to-transparent z-10">
                    </div>

                    <div
                        class="flex gap-2 overflow-x-auto no-scrollbar px-2 py-2 rounded-2xl
                                bg-gray-50 dark:bg-gray-900/40
                                border border-gray-200 dark:border-gray-800">

                        <!-- All -->
                        <button @click="setCategory('all')"
                            :class="activeCategory === 'all'
                                ? 'bg-sky-600 text-white shadow'
                                : 'bg-white dark:bg-gray-950 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-900'"
                            class="shrink-0 px-4 py-2 rounded-xl text-sm font-semibold transition">
                            All
                        </button>

                        <!-- Categories -->
                        <template x-for="cat in categories" :key="cat">
                            <button @click="setCategory(cat)"
                                :class="activeCategory === cat
                                    ? 'bg-sky-600 text-white shadow'
                                    : 'bg-white dark:bg-gray-950 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-900'"
                                class="shrink-0 px-4 py-2 rounded-xl text-sm font-semibold transition whitespace-nowrap">
                                <span x-text="cat"></span>
                            </button>
                        </template>
                    </div>
                </div>
            </div>

            {{-- FAQ List --}}
            <template x-for="faq in paginatedFaqs()" :key="faqKey(faq)">
                <div
                    class="mb-5 bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-xl shadow-sm hover:shadow-md transition-all duration-300 overflow-hidden">

                    <button @click="toggleFaq(faq)"
                        class="w-full text-left p-6 flex justify-between items-center hover:bg-sky-50 dark:hover:bg-gray-800 transition-colors duration-200">

                        <div class="pr-6">
                            <!-- Category label -->
                            <div class="mb-1">
                                <span
                                    class="inline-flex items-center px-2 py-0.5 rounded-lg text-xs font-semibold
                                           bg-sky-100 text-sky-800
                                           dark:bg-sky-900/40 dark:text-sky-300">
                                    <span x-text="faq.category"></span>
                                </span>
                            </div>

                            <span x-html="highlight(faq.question)"
                                class="font-semibold text-gray-800 dark:text-gray-100">
                            </span>
                        </div>

                        <!-- Closed icon -->
                        <svg x-show="openedKey !== faqKey(faq)" x-cloak xmlns="http://www.w3.org/2000/svg"
                            class="h-5 w-5 text-sky-600 dark:text-sky-400 transition" fill="none"
                            viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M19 9l-7 7-7-7" />
                        </svg>

                        <!-- Open icon -->
                        <svg x-show="openedKey === faqKey(faq)" x-cloak xmlns="http://www.w3.org/2000/svg"
                            class="h-5 w-5 text-sky-600 dark:text-sky-400 transform rotate-180 transition"
                            fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                                d="M19 9l-7 7-7-7" />
                        </svg>
                    </button>

                    <!-- Smooth collapse -->
                    <div x-collapse x-show="openedKey === faqKey(faq)" x-cloak>
                        <div
                            class="px-6 pb-6 pt-2 bg-sky-50/50 dark:bg-gray-800/60 text-gray-700 dark:text-gray-300 border-t border-gray-100 dark:border-gray-700">
                            <div x-html="highlight(faq.answer)"></div>
                        </div>
                    </div>
                </div>
            </template>

            <!-- Empty state -->
            <div x-show="filteredFaqs.length === 0" x-cloak
                class="text-center py-14 text-gray-600 dark:text-gray-300">
                <p class="text-lg font-semibold">No FAQs found.</p>
                <p class="text-sm mt-2">Try changing the category or adjusting your search.</p>
            </div>

      {{-- Modern Smart Pagination --}}
<div x-show="totalPages() > 1" x-cloak class="flex justify-center mt-12 space-x-2">

    <!-- Previous -->
    <button @click="prevPage()" :disabled="currentPage === 1"
        class="px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-700 text-gray-600 dark:text-gray-300 disabled:opacity-40 hover:bg-sky-50 dark:hover:bg-gray-800 transition">
        Prev
    </button>

    <!-- Page Numbers -->
    <template x-for="page in smartPageList()" :key="page + '-' + currentPage">
        <button 
            x-show="page !== '…'"
            @click="goToPage(page)"
            :class="{
                'bg-sky-600 text-white border-sky-600 shadow-sm': currentPage === page,
                'bg-white dark:bg-gray-900 text-gray-700 dark:text-gray-300 border-gray-300 dark:border-gray-700 hover:bg-sky-50 dark:hover:bg-gray-800': currentPage !== page
            }"
            class="px-4 py-2 rounded-lg border transition-all duration-200"
            x-text="page">
        </button>

        <!-- Ellipsis -->
        <span x-show="page === '…'" class="px-3 py-2 text-gray-400 select-none">…</span>
    </template>

    <!-- Next -->
    <button @click="nextPage()" :disabled="currentPage === totalPages()"
        class="px-4 py-2 rounded-lg border border-gray-300 dark:border-gray-700 text-gray-600 dark:text-gray-300 disabled:opacity-40 hover:bg-sky-50 dark:hover:bg-gray-800 transition">
        Next
    </button>
</div>

        </div>

        <script>
            function faqApp() {
                return {
                    query: '',
                    currentPage: 1,
                    perPage: 10,
                    activeCategory: 'all',

                    // The ONLY open FAQ at any time
                    openedKey: null,

                    // Load from config
                    faqs: @json(config('faqs')),

                    init() {
                        this.shuffleFaqs();

                        // Open first FAQ by default
                        this.$nextTick(() => {
                            this.openFirstFaqIfNeeded();
                        });

                        /**
                         * IMPORTANT:
                         * Remember open FAQ while searching.
                         * If the currently opened FAQ disappears from filtered results,
                         * auto-open the first available FAQ.
                         */
                        this.$watch('query', () => {
                            this.currentPage = 1;
                            this.$nextTick(() => this.ensureOpenedFaqStillVisible());
                        });
                    },

                    faqKey(faq) {
                        return `${faq.category}__${faq.question}`;
                    },

                    toggleFaq(faq) {
                        const key = this.faqKey(faq);

                        // if clicking same one, close it
                        if (this.openedKey === key) {
                            this.openedKey = null;
                            return;
                        }

                        // otherwise open it (and closes any previous automatically)
                        this.openedKey = key;
                    },

                    openFirstFaqIfNeeded() {
                        if (this.openedKey) return;

                        const first = this.paginatedFaqs()[0];
                        if (first) this.openedKey = this.faqKey(first);
                    },

                    ensureOpenedFaqStillVisible() {
                        if (!this.openedKey) {
                            this.openFirstFaqIfNeeded();
                            return;
                        }

                        const visibleKeys = this.paginatedFaqs().map(f => this.faqKey(f));

                        // if current opened is not visible, open the first
                        if (!visibleKeys.includes(this.openedKey)) {
                            const first = this.paginatedFaqs()[0];
                            this.openedKey = first ? this.faqKey(first) : null;
                        }
                    },

                    get categories() {
                        const cats = [...new Set(this.faqs.map(f => f.category).filter(Boolean))];
                        return cats.sort((a, b) => a.localeCompare(b));
                    },

                    setCategory(cat) {
                        this.activeCategory = cat;
                        this.currentPage = 1;

                        // reset open when changing category
                        this.openedKey = null;

                        this.$nextTick(() => {
                            this.openFirstFaqIfNeeded();
                        });
                    },

                    smartPageList() {
    const total = this.totalPages();
    const current = this.currentPage;
    const delta = 2; // pages around current

    let pages = [];
    let l;

    for (let i = 1; i <= total; i++) {
        if (i === 1 || i === total || (i >= current - delta && i <= current + delta)) {
            pages.push(i);
        } else if (l && i - l === 2) {
            pages.push(l + 1);
        } else if (l && i - l > 2) {
            pages.push('…');
        }
        l = i;
    }

    // Remove duplicate ellipses
    return pages.filter((v, i, a) => !(v === '…' && a[i-1] === '…'));
},


                    get filteredFaqs() {
                        let list = this.faqs;

                        // Category filter
                        if (this.activeCategory !== 'all') {
                            list = list.filter(f => f.category === this.activeCategory);
                        }

                        // Search filter
                        if (this.query) {
                            const q = this.query.toLowerCase();
                            list = list.filter(f =>
                                (f.question || '').toLowerCase().includes(q) ||
                                (f.answer || '').toLowerCase().includes(q)
                            );
                        }

                        return list;
                    },

                    shuffleFaqs() {
                        this.faqs = this.faqs
                            .map(f => ({ ...f, _rand: Math.random() }))
                            .sort((a, b) => a._rand - b._rand)
                            .map(({ _rand, ...f }) => f);
                    },

                    paginatedFaqs() {
                        const start = (this.currentPage - 1) * this.perPage;
                        return this.filteredFaqs.slice(start, start + this.perPage);
                    },

                    totalPages() {
                        return Math.ceil(this.filteredFaqs.length / this.perPage);
                    },

                    goToPage(page) {
                        this.currentPage = page;

                        // when switching pages, open first faq on that page
                        this.openedKey = null;

                        this.$nextTick(() => {
                            this.openFirstFaqIfNeeded();
                        });

                        window.scrollTo({
                            top: 0,
                            behavior: 'smooth'
                        });
                    },

                    nextPage() {
                        if (this.currentPage < this.totalPages()) this.goToPage(this.currentPage + 1);
                    },

                    prevPage() {
                        if (this.currentPage > 1) this.goToPage(this.currentPage - 1);
                    },

                    highlight(text) {
                        if (!this.query) return text;

                        const query = this.query.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
                        const regex = new RegExp(`(${query})`, 'gi');

                        return (text || '').replace(regex, (_, match) => {
                            return `<span class="bg-yellow-200 dark:bg-yellow-400/30 rounded px-1">${match}</span>`;
                        });
                    }
                }
            }
        </script>
    </div>
</x-layouts::front>
