{{--
    Theme preset grid — see App\Filament\Forms\Components\PresetPicker.

    Mini cards are painted from each preset's REAL swatches (sidebar, page
    surface, primary button, accent, login panel), so what the landlord picks
    is exactly what the tenant's app will look like. Search, group chips and
    pagination are client-side Alpine; selecting a card pushes the key into
    the form state with a DEFERRED `$wire.$set()` (it rides along with the
    next server request — the section save — instead of round-tripping on
    every pick) and announces `preview:change`, which the preview bridge
    listens for to repaint the live previews client-side.
--}}
@php
    $statePath = $getStatePath();
    $wireModel = $applyStateBindingModifiers('wire:model');
    $selectedKey = $getState();
    $pageSize = 12;
@endphp

<x-dynamic-component :component="$getFieldWrapperView()" :field="$field">
    <div
        x-data="{
            search: '',
            group: 'All',
            page: 1,
            selected: @js($selectedKey),
            pageSize: @js($pageSize),

            filtered() {
                const q = this.search.trim().toLowerCase();
                return @js($presets).filter((p) =>
                    (this.group === 'All' || p.group === this.group) &&
                    (q === '' || p.name.toLowerCase().includes(q))
                );
            },

            totalPages() {
                return Math.max(1, Math.ceil(this.filtered().length / this.pageSize));
            },

            pageItems() {
                const safe = Math.min(this.page, this.totalPages());
                return this.filtered().slice((safe - 1) * this.pageSize, safe * this.pageSize);
            },

            setGroup(group) {
                this.group = group;
                this.page = 1;
            },

            select(key) {
                this.selected = key;
                // Deferred: no request on its own — the pick rides along with
                // the next commit (the section save), like every other field on
                // the tab. The bridge repaints the previews from `selected`
                // directly, so it never waits on the server.
                $wire.$set(@js($statePath), key, false);
                window.dispatchEvent(new CustomEvent('preview:change'));
            },
        }"
        data-preview-bind="theme.preset"
        data-preview-value="selected"
        class="fi-preset-picker space-y-4"
    >
        {{-- ── Search + group chips ──────────────────────────────────── --}}
        <div class="flex flex-wrap items-center gap-2">
            <div class="relative">
                <x-filament::icon icon="heroicon-m-magnifying-glass" class="pointer-events-none absolute inset-y-0 start-2.5 my-auto h-3.5 w-3.5 text-gray-400 dark:text-gray-500" />
                <input
                    type="search"
                    x-model="search"
                    x-on:input="page = 1"
                    placeholder="Search presets…"
                    class="fi-input h-8 w-44 rounded-lg border-gray-300 ps-8 text-xs dark:bg-gray-800"
                >
            </div>

            <div class="flex flex-wrap gap-1.5">
                <template x-for="g in @js($groups)" :key="g">
                    <button
                        type="button"
                        x-on:click="setGroup(g)"
                        class="rounded-full border px-2.5 py-1 text-xs transition"
                        :class="group === g
                            ? 'border-primary-500 bg-primary-500/10 text-primary-600 dark:text-primary-400'
                            : 'border-gray-300 text-gray-500 hover:border-primary-400 hover:text-gray-900 dark:border-white/10 dark:hover:text-gray-200'"
                        x-text="g"
                    ></button>
                </template>
            </div>
        </div>

        {{-- ── Preset cards ──────────────────────────────────────────── --}}
        <template x-if="pageItems().length === 0">
            <p class="rounded-lg border border-dashed border-gray-300 py-8 text-center text-sm text-gray-500 dark:border-white/10">
                No presets match “<span x-text="search"></span>”.
            </p>
        </template>

        <div class="grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-4">
            <template x-for="preset in pageItems()" :key="preset.key">
                <button
                    type="button"
                    x-on:click="select(preset.key)"
                    :aria-pressed="selected === preset.key"
                    class="group overflow-hidden rounded-lg border-2 text-start transition"
                    :class="selected === preset.key
                        ? 'border-primary-500 ring-2 ring-primary-500/30'
                        : 'border-gray-200 hover:border-primary-400 dark:border-white/10 dark:hover:border-primary-500/50'"
                >
                    <div class="flex h-20">
                        {{-- sidebar strip --}}
                        <div class="flex w-7 shrink-0 flex-col items-center gap-1.5 py-2.5" :style="{ background: preset.swatches.sidebar }">
                            <span class="h-1.5 w-1.5 rounded-full" :style="{ background: preset.swatches.sidebar_accent }"></span>
                            <span class="h-1.5 w-1.5 rounded-full opacity-70" :style="{ background: preset.swatches.sidebar_accent }"></span>
                            <span class="h-1.5 w-1.5 rounded-full opacity-40" :style="{ background: preset.swatches.sidebar_accent }"></span>
                        </div>
                        {{-- page surface --}}
                        <div class="flex flex-1 flex-col justify-between p-2.5" :style="{ background: preset.swatches.background }">
                            <div class="rounded p-1.5" :style="{ background: preset.swatches.card }">
                                <div class="h-1.5 w-3/4 rounded-full" :style="{ background: preset.swatches.foreground, opacity: 0.75 }"></div>
                                <div class="mt-1 h-1.5 w-1/2 rounded-full" :style="{ background: preset.swatches.foreground, opacity: 0.35 }"></div>
                            </div>
                            <div class="flex items-center gap-1.5">
                                <span class="h-3.5 w-9 rounded" :style="{ background: preset.swatches.primary }"></span>
                                <span class="h-3.5 w-3.5 rounded" :style="{ background: preset.swatches.accent }"></span>
                                <span class="ms-auto h-3.5 w-3.5 rounded-full border border-black/10" :style="{ background: preset.swatches.panel }"></span>
                            </div>
                        </div>
                    </div>
                    <div class="flex items-center justify-between border-t px-2.5 py-1.5" :style="{ background: preset.swatches.card, borderColor: preset.swatches.sidebar }">
                        <span class="truncate text-xs font-medium" :style="{ color: preset.swatches.foreground }" x-text="preset.name"></span>
                        <template x-if="selected === preset.key">
                            <x-filament::icon icon="heroicon-m-check" x-bind:style="'color: ' + preset.swatches.primary" class="h-3.5 w-3.5 shrink-0" />
                        </template>
                    </div>
                </button>
            </template>
        </div>

        {{-- ── Pagination ────────────────────────────────────────────── --}}
        <div x-show="totalPages() > 1" class="flex items-center justify-between border-t border-gray-100 pt-3 dark:border-white/10">
            <p class="text-xs text-gray-500 dark:text-gray-400">
                Page <span x-text="Math.min(page, totalPages())"></span> of <span x-text="totalPages()"></span> · <span x-text="filtered().length"></span> presets
            </p>
            <div class="flex gap-1.5">
                <button
                    type="button"
                    x-on:click="page = Math.max(1, page - 1)"
                    x-bind:disabled="page <= 1"
                    class="flex h-7 w-7 items-center justify-center rounded-md border border-gray-300 text-gray-500 transition hover:bg-gray-50 disabled:opacity-40 dark:border-white/10 dark:hover:bg-white/5"
                >
                    <x-filament::icon icon="heroicon-m-chevron-left" class="h-3.5 w-3.5" />
                </button>
                <button
                    type="button"
                    x-on:click="page = Math.min(totalPages(), page + 1)"
                    x-bind:disabled="page >= totalPages()"
                    class="flex h-7 w-7 items-center justify-center rounded-md border border-gray-300 text-gray-500 transition hover:bg-gray-50 disabled:opacity-40 dark:border-white/10 dark:hover:bg-white/5"
                >
                    <x-filament::icon icon="heroicon-m-chevron-right" class="h-3.5 w-3.5" />
                </button>
            </div>
        </div>
    </div>
</x-dynamic-component>
