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

    @php
        // Row-state snapshot for the Alpine factory — currently just
        // `is_active` for the inline toggle. Adding fav/featured later
        // means another column here.
        $rowsForJs = $customers->map(fn ($c) => [
            'id'        => $c->id,
            'is_active' => (bool) $c->is_active,
        ])->values();
    @endphp

    <div class="page-wide"
         x-data="customersIndexPage({
             toggleUrlTemplate: '{{ route('admin.customers.toggle-active', ['customer' => '__ID__']) }}',
             rows:              {{ Js::from($rowsForJs) }},
         })">
        <div class="page-header mb-6">
            <div>
                <h1 class="page-title">{{ __('customers.title') }}</h1>
                <p class="page-sub">{{ __('customers.sub') }}</p>
            </div>
            <div class="flex 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" />
                        {{ __('customers.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.customers.export', ['format' => 'csv']) }}"
                           class="dropdown-item"
                           @click="close()">
                            <span class="dropdown-item-label">{{ __('customers.actions.export_csv') }}</span>
                        </a>
                        <a href="{{ route('admin.customers.export', ['format' => 'xlsx']) }}"
                           class="dropdown-item"
                           @click="close()">
                            <span class="dropdown-item-label">{{ __('customers.actions.export_xlsx') }}</span>
                        </a>
                    </div>
                </div>

                @can('create', App\Models\Customer::class)
                    <a href="{{ route('admin.customers.create') }}" class="pos-btn pos-btn-sm pos-btn-primary">
                        <x-icon name="plus" class="w-4 h-4" />
                        {{ __('customers.new') }}
                    </a>
                @endcan
            </div>
        </div>

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

        <div class="card card-pad-0">
            <div class="dt-toolbar">
                <div class="dt-toolbar-title">{{ __('customers.list.title', ['count' => $customers->count()]) }}</div>
                <x-admin.dt-toolbar-actions />
            </div>
            {{-- Filters submit over AJAX (no full-page reload): every change
                 calls applyFilters(), which updates the URL + swaps the table
                 region below. Reset clears the controls + reloads the region. --}}
            <form method="GET" action="{{ route('admin.customers.index') }}" class="inv-filter"
                  x-ref="filterForm" @submit.prevent="applyFilters()">
                <label class="field inv-filter-select">
                    <span class="field-label">{{ __('customers.columns.status') }}</span>
                    <select name="status" class="pos-input" x-data="enhancedSelect()" @change="applyFilters()">
                        <option value="active"   @selected($filters['status'] === 'active')>{{ __('customers.filter.status_active') }}</option>
                        <option value="inactive" @selected($filters['status'] === 'inactive')>{{ __('customers.filter.status_inactive') }}</option>
                        <option value="all"      @selected($filters['status'] === 'all')>{{ __('customers.filter.status_all') }}</option>
                    </select>
                </label>
                <label class="field inv-filter-select">
                    <span class="field-label">{{ __('customers.columns.group') }}</span>
                    <select name="group_id" class="pos-input" x-data="enhancedSelect()" @change="applyFilters()">
                        <option value="">{{ __('customers.filter.group_all') }}</option>
                        @foreach ($groups as $group)
                            <option value="{{ $group->id }}" @selected($filters['groupId'] === $group->id)>{{ $group->name }}</option>
                        @endforeach
                    </select>
                </label>
                <label class="field inv-filter-search">
                    <span class="field-label">&nbsp;</span>
                    <span class="inv-search">
                        <span class="inv-search-icon"><x-icon name="search" class="w-4 h-4" /></span>
                        <input type="search" name="q" value="{{ $filters['q'] }}" class="pos-input"
                               placeholder="{{ __('customers.filter.search') }}"
                               @input.debounce.400ms="applyFilters()"
                               @search="applyFilters()">
                    </span>
                </label>
                <button type="button" class="inv-filter-reset" @click="resetFilters()"
                        title="{{ __('table.filter_reset') }}">
                    <x-icon name="x" class="w-3.5 h-3.5" />
                    <span>{{ __('table.filter_reset') }}</span>
                </button>
            </form>

            <div data-customers-region x-ref="tableRegion">
            @if ($customers->isEmpty())
                <div class="dt-empty">
                    <span class="dt-empty-icon"><x-icon name="customers" class="w-5 h-5" /></span>
                    <div class="dt-empty-title">{{ __('customers.empty_state.title') }}</div>
                    <div class="dt-empty-sub">{{ __('customers.empty_state.sub') }}</div>
                </div>
            @else
                <div class="dt-scroll">
                <table class="dt-table">
                    <thead>
                        <tr>
                            <th>{{ __('customers.columns.code') }}</th>
                            <th>{{ __('customers.columns.name') }}</th>
                            <th>{{ __('customers.columns.phone') }}</th>
                            <th>{{ __('customers.columns.email') }}</th>
                            <th>{{ __('customers.columns.group') }}</th>
                            <th class="num">{{ __('customers.columns.outstanding') }}</th>
                            <th class="num">{{ __('customers.columns.credit') }}</th>
                            <th>{{ __('customers.columns.status') }}</th>
                            <th class="dt-actions-col"><span class="sr-only">{{ __('customers.columns.actions') }}</span></th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($customers as $c)
                            {{-- Row click → edit (system-wide convention).
                                 View / toggle / delete live in the single
                                 actions column. --}}
                            <tr class="prod-row" data-dt-row
                                data-dt-name="{{ $c->name }}"
                                data-dt-id="{{ $c->id }}"
                                data-dt-active="{{ $c->is_active ? 1 : 0 }}"
                                @click="window.location.href = {{ \Illuminate\Support\Js::from(route('admin.customers.edit', $c)) }}">
                                <td class="mono">{{ $c->code }}</td>
                                <td>
                                    <div class="store-row-name-line">
                                        <span class="store-row-name">{{ $c->name }}</span>
                                        @if ($c->is_business)
                                            <span class="prod-badge prod-badge-muted">{{ __('customers.badges.business') }}</span>
                                        @endif
                                    </div>
                                </td>
                                <td class="mono">{{ $c->phone ? \App\Support\PhoneFormatter::pretty($c->phone) : '—' }}</td>
                                <td>{{ $c->email ?: '—' }}</td>
                                <td>{{ $c->group?->name ?: '—' }}</td>
                                <td class="num tnum">{{ format_money($c->outstanding_balance) }}</td>
                                <td class="num tnum">{{ format_money($c->store_credit_balance) }}</td>
                                {{-- Status badge mirrors the live toggle state in the actions column —
                                     bound to `rowState[id].is_active` so it flips in sync when the
                                     toggle is clicked, without a server round-trip. --}}
                                <td>
                                    <span class="prod-badge"
                                          :class="rowState[{{ $c->id }}]?.is_active ? 'prod-badge-positive' : 'prod-badge-muted'"
                                          x-text="rowState[{{ $c->id }}]?.is_active
                                                    ? @js(__('customers.badges.active'))
                                                    : @js(__('customers.badges.inactive'))"></span>
                                </td>
                                <td>
                                    <div class="prod-row-actions">
                                        @can('update', $c)
                                            {{-- Status toggle — same component as Products. --}}
                                            <button type="button"
                                                    class="prod-status-btn"
                                                    :class="{ 'is-on': rowState[{{ $c->id }}]?.is_active }"
                                                    :aria-pressed="rowState[{{ $c->id }}]?.is_active ? 'true' : 'false'"
                                                    :title="rowState[{{ $c->id }}]?.is_active ? @js(__('customers.actions.tip_active_on')) : @js(__('customers.actions.tip_active_off'))"
                                                    :disabled="togglingIds.includes({{ $c->id }})"
                                                    @click.stop="toggleActive({{ $c->id }})"
                                                    aria-label="{{ __('customers.actions.toggle_active') }}">
                                                <span class="prod-status-thumb" aria-hidden="true"></span>
                                            </button>
                                        @endcan
                                        <x-admin.row-actions>
                                            @can('view', $c)
                                                <x-admin.row-action :href="route('admin.customers.show', $c)" icon="eye" :label="__('customers.actions.view')" />
                                            @endcan
                                            @can('update', $c)
                                                <x-admin.row-action :href="route('admin.customers.edit', $c)" icon="edit" :label="__('table.action.edit')" />
                                            @endcan
                                            @can('delete', $c)
                                                <div class="row-action-sep"></div>
                                                <x-admin.row-action icon="trash" variant="danger" :label="__('customers.actions.delete')"
                                                    @click="$store.confirm.show({
                                                        title: {{ \Illuminate\Support\Js::from(__('customers.confirm_delete.title', ['name' => $c->name])) }},
                                                        message: {{ \Illuminate\Support\Js::from(__('customers.confirm_delete.message')) }},
                                                        intent: 'danger',
                                                        confirmLabel: {{ \Illuminate\Support\Js::from(__('customers.confirm_delete.confirm')) }},
                                                        onConfirm: () => $deleteForm({{ \Illuminate\Support\Js::from(route('admin.customers.destroy', $c)) }}),
                                                    })" />
                                            @endcan
                                        </x-admin.row-actions>
                                    </div>
                                </td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
                </div>

                <x-admin.dt-pager />
            @endif
            </div>{{-- /data-customers-region --}}
        </div>
    </div>
</x-admin-layout>
