<x-admin-layout
    active="products"
    :title="__('products.title')"
    :crumbs="[
        ['label' => __('admin.shell.brand_sub')],
        ['label' => __('products.crumb_parent')],
        ['label' => __('products.title')],
    ]">

    <div class="page-wide" x-data="productsPage()">

        {{-- ── Page header (mirrors design-system/admin/Products.html) ── --}}
        <div class="page-header mb-4">
            <div>
                <h1 class="page-title">{{ __('products.title') }}</h1>
                <p class="page-sub">
                    {{ __('products.list.header_sub', ['count' => $products->count()]) }}
                </p>
            </div>
            <div class="flex flex-wrap items-center gap-2">
                <div class="dropdown" x-data="dropdown">
                    <button type="button"
                            class="pos-btn pos-btn-sm pos-btn-ghost"
                            @click="toggle()"
                            :aria-expanded="open">
                        <x-icon name="download" class="w-4 h-4" />
                        {{ __('products.actions.export') }}
                        <x-icon name="chevron" class="w-4 h-4" />
                    </button>
                    <div class="dropdown-panel"
                         x-show="open"
                         x-cloak
                         @click.outside="close()"
                         @keydown.escape.window="close()">
                        <a href="{{ route('admin.products.export', ['format' => 'csv']) }}"
                           class="dropdown-item"
                           @click="close()">
                            <span class="dropdown-item-label">{{ __('products.actions.export_csv') }}</span>
                        </a>
                        <a href="{{ route('admin.products.export', ['format' => 'xlsx']) }}"
                           class="dropdown-item"
                           @click="close()">
                            <span class="dropdown-item-label">{{ __('products.actions.export_xlsx') }}</span>
                        </a>
                    </div>
                </div>

                <a href="{{ route('admin.products.import') }}"
                   class="pos-btn pos-btn-sm pos-btn-ghost">
                    <x-icon name="archive" class="w-4 h-4" />
                    {{ __('products.actions.import') }}
                </a>

                <a href="{{ route('admin.products.create') }}" class="pos-btn pos-btn-sm pos-btn-primary">
                    <x-icon name="plus" class="w-4 h-4" />
                    {{ __('products.actions.new') }}
                </a>
            </div>
        </div>

        <x-admin.summary-cards :cards="$summaryCards" />

        @if ($products->isEmpty())
            <div class="card card-pad-0">
                <div class="dt-empty">
                    <span class="dt-empty-icon"><x-icon name="box" class="w-5 h-5" /></span>
                    <div class="dt-empty-title">{{ __('products.list.empty_title') }}</div>
                    <div class="dt-empty-sub">{{ __('products.list.empty_sub') }}</div>
                </div>
            </div>
        @else
            {{-- ── Toolbar row ─────────────────────────────────────── --}}
            <div class="prod-toolbar mb-3">
                <div class="prod-toolbar-end">
                    <button type="button"
                            class="pos-btn pos-btn-sm pos-btn-ghost"
                            :disabled="_dtRefreshing"
                            @click="dtRefresh()"
                            :title="@js(__('products.list.refresh'))">
                        <span class="inline-flex" :class="{ 'animate-spin': _dtRefreshing }">
                            <x-icon name="refresh" class="w-4 h-4" />
                        </span>
                    </button>

                    <span class="prod-toolbar-count">
                        <span x-text="visibleCount"></span>
                        {{ __('products.list.of') }}
                        <span>{{ $products->count() }}</span>
                    </span>

                    <div class="seg" role="tablist" aria-label="{{ __('products.list.view_label') }}">
                        <button type="button"
                                role="tab"
                                :aria-selected="view === 'table'"
                                :class="{ 'is-active': view === 'table' }"
                                @click="view = 'table'">
                            <x-icon name="list" class="w-3.5 h-3.5" />
                            {{ __('products.list.view_table') }}
                        </button>
                        <button type="button"
                                role="tab"
                                :aria-selected="view === 'grid'"
                                :class="{ 'is-active': view === 'grid' }"
                                @click="view = 'grid'">
                            <x-icon name="dashboard" class="w-3.5 h-3.5" />
                            {{ __('products.list.view_grid') }}
                        </button>
                    </div>
                </div>
            </div>

            {{-- ── Filter bar (shared — applies to both table + grid views) ── --}}
            <div class="inv-filter inv-filter--boxed mb-3">
                {{-- Search --}}
                <label class="field inv-filter-search">
                    <span class="field-label">{{ __('table.search_label') }}</span>
                    <div class="inv-search">
                        <span class="inv-search-icon"><x-icon name="search" class="w-4 h-4" /></span>
                        <input type="search"
                               x-model.debounce.150ms="search"
                               placeholder="{{ __('products.list.search_placeholder') }}"
                               class="pos-input">
                    </div>
                </label>

                {{-- Category --}}
                <label class="field flex-none basis-[200px]">
                    <span class="field-label">{{ __('products.list.col_category') }}</span>
                    <select class="pos-input"
                            x-data="enhancedSelect()"
                            x-model="categoryFilter"
                            x-effect="ts && ts.setValue(categoryFilter)">
                        <option value="all">{{ __('products.list.filter_cat_all') }}</option>
                        @foreach ($filterCategories as $c)
                            <option value="{{ $c->id }}">{{ $c->name }}</option>
                        @endforeach
                    </select>
                </label>

                {{-- Type --}}
                <label class="field inv-filter-select">
                    <span class="field-label">{{ __('products.list.col_type') }}</span>
                    <select class="pos-input"
                            x-data="enhancedSelect()"
                            x-model="typeFilter"
                            x-effect="ts && ts.setValue(typeFilter)">
                        <option value="all">{{ __('products.list.filter_type_all') }}</option>
                        <option value="simple">{{ __('products.list.type_simple') }}</option>
                        <option value="variant">{{ __('products.list.type_variant') }}</option>
                        <option value="kit">{{ __('products.list.type_kit') }}</option>
                    </select>
                </label>

                {{-- Status --}}
                <label class="field inv-filter-select">
                    <span class="field-label">{{ __('products.list.col_status') }}</span>
                    <select class="pos-input"
                            x-data="enhancedSelect()"
                            x-model="activeFilter"
                            x-effect="ts && ts.setValue(activeFilter)">
                        <option value="all">{{ __('products.list.filter_status_all') }}</option>
                        <option value="active">{{ __('products.list.filter_status_active') }}</option>
                        <option value="inactive">{{ __('products.list.filter_status_inactive') }}</option>
                    </select>
                </label>

                {{-- Featured --}}
                <label class="field inv-filter-select">
                    <span class="field-label">{{ __('products.list.featured') }}</span>
                    <select class="pos-input"
                            x-data="enhancedSelect()"
                            x-model="featuredFilter"
                            x-effect="ts && ts.setValue(featuredFilter)">
                        <option value="all">{{ __('products.list.filter_featured_all') }}</option>
                        <option value="featured">{{ __('products.list.filter_featured_only') }}</option>
                    </select>
                </label>

                {{-- Reset --}}
                <button type="button"
                        class="inv-filter-reset"
                        @click="resetFilters()">
                    <x-icon name="x" class="w-3.5 h-3.5" />
                    <span>{{ __('table.filter_reset') }}</span>
                </button>
            </div>

            {{-- ── Table view ──────────────────────────────────────── --}}
            <div x-show="view === 'table'">
                <x-admin.data-table :show-search="false" :show-toolbar="false">
                    <div class="dt-scroll">
                    <table class="dt-table">
                        <thead>
                            <tr>
                                <th class="dt-th-sort"
                                    @click="sortBy('name')"
                                    :class="{ 'is-sorted-asc': sortDirFor('name') === 'asc', 'is-sorted-desc': sortDirFor('name') === 'desc' }">
                                    {{ __('products.list.col_name') }}
                                    <span class="dt-th-sort-arrow" aria-hidden="true"></span>
                                </th>
                                <th class="dt-th-sort"
                                    @click="sortBy('sku')"
                                    :class="{ 'is-sorted-asc': sortDirFor('sku') === 'asc', 'is-sorted-desc': sortDirFor('sku') === 'desc' }">
                                    {{ __('products.list.col_sku') }}
                                    <span class="dt-th-sort-arrow" aria-hidden="true"></span>
                                </th>
                                <th class="dt-th-sort"
                                    @click="sortBy('category')"
                                    :class="{ 'is-sorted-asc': sortDirFor('category') === 'asc', 'is-sorted-desc': sortDirFor('category') === 'desc' }">
                                    {{ __('products.list.col_category') }}
                                    <span class="dt-th-sort-arrow" aria-hidden="true"></span>
                                </th>
                                <th class="dt-th-sort"
                                    @click="sortBy('type')"
                                    :class="{ 'is-sorted-asc': sortDirFor('type') === 'asc', 'is-sorted-desc': sortDirFor('type') === 'desc' }">
                                    {{ __('products.list.col_type') }}
                                    <span class="dt-th-sort-arrow" aria-hidden="true"></span>
                                </th>
                                <th class="num dt-th-sort"
                                    @click="sortBy('price')"
                                    :class="{ 'is-sorted-asc': sortDirFor('price') === 'asc', 'is-sorted-desc': sortDirFor('price') === 'desc' }">
                                    {{ __('products.list.col_price') }}
                                    <span class="dt-th-sort-arrow" aria-hidden="true"></span>
                                </th>
                                <th class="num dt-th-sort"
                                    @click="sortBy('cost')"
                                    :class="{ 'is-sorted-asc': sortDirFor('cost') === 'asc', 'is-sorted-desc': sortDirFor('cost') === 'desc' }">
                                    {{ __('products.list.col_cost') }}
                                    <span class="dt-th-sort-arrow" aria-hidden="true"></span>
                                </th>
                                <th class="num dt-th-sort"
                                    @click="sortBy('margin')"
                                    :class="{ 'is-sorted-asc': sortDirFor('margin') === 'asc', 'is-sorted-desc': sortDirFor('margin') === 'desc' }">
                                    {{ __('products.list.col_margin') }}
                                    <span class="dt-th-sort-arrow" aria-hidden="true"></span>
                                </th>
                                <th class="dt-th-sort"
                                    @click="sortBy('active')"
                                    :class="{ 'is-sorted-asc': sortDirFor('active') === 'asc', 'is-sorted-desc': sortDirFor('active') === 'desc' }">
                                    {{ __('products.list.col_status') }}
                                    <span class="dt-th-sort-arrow" aria-hidden="true"></span>
                                </th>
                                <th>{{ __('products.list.col_actions') }}</th>
                            </tr>
                        </thead>
                        <tbody>
                            @foreach ($products as $p)
                                <tr data-dt-row
                                    data-dt-product-id="{{ $p->id }}"
                                    data-dt-name="{{ $p->name }}"
                                    data-dt-sku="{{ $p->sku }}"
                                    data-dt-category="{{ optional($p->category)->name }}"
                                    data-dt-category-id="{{ $p->category_id }}"
                                    data-dt-brand="{{ optional($p->brand)->name }}"
                                    data-dt-type="{{ $p->type }}"
                                    data-dt-price="{{ $p->selling_price }}"
                                    data-dt-cost="{{ $p->cost_price }}"
                                    data-dt-margin="{{ $p->selling_price > 0 ? round((($p->selling_price - $p->cost_price) / $p->selling_price) * 100) : 0 }}"
                                    data-dt-active="{{ $p->is_active ? '1' : '0' }}"
                                    data-dt-featured="{{ $p->is_featured ? '1' : '0' }}"
                                    class="prod-row"
                                    @click="window.location.href = {{ \Illuminate\Support\Js::from(route('admin.products.edit', $p)) }}">
                                    <td>
                                        <div class="prod-name-cell">
                                            <span class="prod-thumb" aria-hidden="true">
                                                @if ($p->image_url)
                                                    <img src="{{ $p->image_url }}" alt="" onerror="this.style.display='none'; this.nextElementSibling.style.display='inline-flex'">
                                                    <span class="prod-thumb-letter hidden">{{ \Illuminate\Support\Str::upper(\Illuminate\Support\Str::substr($p->name, 0, 1)) }}</span>
                                                @else
                                                    <span class="prod-thumb-letter">{{ \Illuminate\Support\Str::upper(\Illuminate\Support\Str::substr($p->name, 0, 1)) }}</span>
                                                @endif
                                            </span>
                                            <div>
                                                <div class="prod-name">
                                                    <span>{{ $p->name }}</span>
                                                    {{-- Inline "Featured" pill — bound to reactive
                                                         `rowState[id].is_featured`. Mutating that
                                                         from the toggle button triggers Alpine to
                                                         re-render this binding in place. --}}
                                                    <span class="prod-featured-badge"
                                                          x-show="rowState[{{ $p->id }}]?.is_featured"
                                                          x-cloak>
                                                        {{ __('products.list.featured') }}
                                                    </span>
                                                </div>
                                                @if ($p->short_description)
                                                    <div class="prod-sub">{{ \Illuminate\Support\Str::limit($p->short_description, 80) }}</div>
                                                @endif
                                            </div>
                                        </div>
                                    </td>
                                    <td class="mono">{{ $p->sku }}</td>
                                    <td>
                                        @if ($p->category)
                                            <span class="prod-tag">{{ $p->category->name }}</span>
                                        @else
                                            <span class="prod-muted">{{ __('products.list.no_category') }}</span>
                                        @endif
                                    </td>
                                    <td>
                                        @php
                                            $typeCount = $p->type === 'variant' ? $p->variants_count
                                                : ($p->type === 'kit' ? $p->kit_items_count : null);
                                        @endphp
                                        <span class="prod-type-text is-{{ $p->type }}">
                                            {{ __('products.list.type_'.$p->type) }}@if ($typeCount) · {{ $typeCount }}@endif
                                        </span>
                                    </td>
                                    <td class="num tnum">{{ format_money($p->selling_price) }}</td>
                                    <td class="num tnum prod-muted">{{ format_money($p->cost_price) }}</td>
                                    {{-- Margin — computed client-side from the same data-dt-*
                                         attrs the sort + filter use. Color thresholds match
                                         the mockup (≥35% positive, <20% danger). --}}
                                    <td class="num tnum"
                                        :class="marginClass($el.closest('tr'))"
                                        x-text="marginPct($el.closest('tr')) + '%'"></td>
                                    <td>
                                        {{-- Status badge bound to reactive rowState — Alpine
                                             re-renders when the toggle button flips it. --}}
                                        <template x-if="rowState[{{ $p->id }}]?.is_active">
                                            <span class="prod-badge prod-badge-positive">{{ __('products.list.active') }}</span>
                                        </template>
                                        <template x-if="!rowState[{{ $p->id }}]?.is_active">
                                            <span class="prod-badge prod-badge-muted">{{ __('products.list.inactive') }}</span>
                                        </template>
                                    </td>
                                    <td>
                                        {{-- Quick-action buttons — featured star + status toggle.
                                             Both use @click.stop to prevent the row's click-to-edit.
                                             AJAX via productsPage.toggleField().

                                             `title` attribute gives a native tooltip with state-aware
                                             copy (e.g. "Click to feature" when off, "Featured — click
                                             to remove" when on). --}}
                                        <div class="prod-row-actions">
                                            <button type="button"
                                                    class="prod-fav-btn"
                                                    :class="{ 'is-on': rowState[{{ $p->id }}]?.is_featured }"
                                                    :aria-pressed="rowState[{{ $p->id }}]?.is_featured ? 'true' : 'false'"
                                                    :title="rowState[{{ $p->id }}]?.is_featured ? @js(__('products.list.tip_featured_on')) : @js(__('products.list.tip_featured_off'))"
                                                    :disabled="togglingIds.includes({{ $p->id }})"
                                                    @click.stop="toggleField({{ $p->id }}, 'is_featured')"
                                                    aria-label="{{ __('products.list.toggle_featured') }}">
                                                <x-icon name="star" class="w-4 h-4" />
                                            </button>

                                            <button type="button"
                                                    class="prod-status-btn"
                                                    :class="{ 'is-on': rowState[{{ $p->id }}]?.is_active }"
                                                    :aria-pressed="rowState[{{ $p->id }}]?.is_active ? 'true' : 'false'"
                                                    :title="rowState[{{ $p->id }}]?.is_active ? @js(__('products.list.tip_active_on')) : @js(__('products.list.tip_active_off'))"
                                                    :disabled="togglingIds.includes({{ $p->id }})"
                                                    @click.stop="toggleField({{ $p->id }}, 'is_active')"
                                                    aria-label="{{ __('products.list.toggle_active') }}">
                                                <span class="prod-status-thumb" aria-hidden="true"></span>
                                            </button>

                                            <x-admin.row-actions>
                                                <x-admin.row-action :href="route('admin.products.edit', $p)" icon="edit" :label="__('table.action.edit')" />
                                                <div class="row-action-sep"></div>
                                                <x-admin.row-action icon="trash" variant="danger" :label="__('products.actions.delete')"
                                                    @click="$store.confirm.show({
                                                        title:        {{ \Illuminate\Support\Js::from($p->name) }},
                                                        message:      {{ \Illuminate\Support\Js::from(__('products.actions.delete_confirm')) }},
                                                        intent:       'danger',
                                                        confirmLabel: {{ \Illuminate\Support\Js::from(__('products.actions.delete')) }},
                                                        cancelLabel:  {{ \Illuminate\Support\Js::from(__('products.actions.cancel')) }},
                                                        onConfirm:    () => $deleteForm({{ \Illuminate\Support\Js::from(route('admin.products.destroy', $p)) }}),
                                                    })" />
                                            </x-admin.row-actions>
                                        </div>
                                    </td>
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                    </div>
                </x-admin.data-table>
            </div>

            {{-- ── Grid view ───────────────────────────────────────── --}}
            {{-- Grid cards carry the same `data-dt-row` + data-dt-* set as
                 the table rows. The productsPage factory overrides
                 `_dtCollect` to pick the right rows based on `view`, so
                 filters / search / sort / pagination apply identically
                 in both views. Only one view is visible at a time (the
                 other is x-show=false). --}}
            <div x-show="view === 'grid'" x-cloak>
                <div class="prod-grid">
                    @foreach ($products as $p)
                        <a href="{{ route('admin.products.edit', $p) }}"
                           data-dt-row
                           data-dt-product-id="{{ $p->id }}"
                           data-dt-name="{{ $p->name }}"
                           data-dt-sku="{{ $p->sku }}"
                           data-dt-category="{{ optional($p->category)->name }}"
                           data-dt-category-id="{{ $p->category_id }}"
                           data-dt-brand="{{ optional($p->brand)->name }}"
                           data-dt-type="{{ $p->type }}"
                           data-dt-price="{{ $p->selling_price }}"
                           data-dt-cost="{{ $p->cost_price }}"
                           data-dt-margin="{{ $p->selling_price > 0 ? round((($p->selling_price - $p->cost_price) / $p->selling_price) * 100) : 0 }}"
                           data-dt-active="{{ $p->is_active ? '1' : '0' }}"
                           data-dt-featured="{{ $p->is_featured ? '1' : '0' }}"
                           class="prod-card">
                            <div class="prod-card-img">
                                @if ($p->image_url)
                                    <img src="{{ $p->image_url }}" alt="" onerror="this.style.display='none'; this.nextElementSibling.style.display='flex'">
                                    <div class="prod-card-letter hidden">{{ \Illuminate\Support\Str::upper(\Illuminate\Support\Str::substr($p->name, 0, 1)) }}</div>
                                @else
                                    <div class="prod-card-letter">{{ \Illuminate\Support\Str::upper(\Illuminate\Support\Str::substr($p->name, 0, 1)) }}</div>
                                @endif
                            </div>
                            <div class="prod-card-body">
                                <div class="prod-card-head">
                                    <div class="prod-card-name">{{ $p->name }}</div>
                                    {{-- Grid-card badge mirrors the table's state — bound to
                                         the reactive rowState so the toggle button updates
                                         this card in place even when the user switches view. --}}
                                    <template x-if="!rowState[{{ $p->id }}]?.is_active">
                                        <span class="prod-badge prod-badge-muted">{{ __('products.list.inactive') }}</span>
                                    </template>
                                    <template x-if="rowState[{{ $p->id }}]?.is_active && rowState[{{ $p->id }}]?.is_featured">
                                        <span class="prod-badge prod-badge-positive">{{ __('products.list.featured') }}</span>
                                    </template>
                                </div>
                                <div class="prod-card-meta">
                                    <span class="prod-card-sku mono">{{ $p->sku }}</span>
                                    @php
                                        $typeCount = $p->type === 'variant' ? $p->variants_count
                                            : ($p->type === 'kit' ? $p->kit_items_count : null);
                                    @endphp
                                    <span class="prod-type-badge is-{{ $p->type }}">
                                        {{ __('products.list.type_'.$p->type) }}@if ($typeCount) · {{ $typeCount }}@endif
                                    </span>
                                </div>
                                <div class="prod-card-foot">
                                    <span class="prod-card-price tnum">{{ format_money($p->selling_price) }}</span>
                                    <span class="prod-card-cost tnum prod-muted">
                                        {{ __('products.list.cost_short') }}
                                        {{ format_money($p->cost_price) }}
                                    </span>
                                </div>
                            </div>
                        </a>
                    @endforeach
                </div>
                {{-- Infinite-scroll sentinel: when it nears the viewport the
                     grid reveals another batch of cards (see products-page.js). --}}
                <div x-ref="gridSentinel" class="prod-grid-sentinel" aria-hidden="true"></div>
            </div>
        @endif
    </div>
</x-admin-layout>
