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

    @php
        // Row-state snapshot for the Alpine factory — currently just
        // `is_active` for the inline toggle (mirrors customers).
        $rowsForJs = $suppliers->map(fn ($s) => [
            'id'        => $s->id,
            'is_active' => (bool) $s->is_active,
        ])->values();
    @endphp

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

                @can('create', App\Models\Supplier::class)
                    <a href="{{ route('admin.suppliers.create') }}" class="pos-btn pos-btn-sm pos-btn-primary">
                        <x-icon name="plus" class="w-4 h-4" />
                        {{ __('suppliers.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">{{ __('suppliers.list.title', ['count' => $suppliers->count()]) }}</div>
                <x-admin.dt-toolbar-actions />
            </div>
            {{-- Filters submit over AJAX (no full-page reload): each 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.suppliers.index') }}" class="inv-filter"
                  x-ref="filterForm" @submit.prevent="applyFilters()">
                <label class="field inv-filter-select">
                    <span class="field-label">{{ __('suppliers.columns.status') }}</span>
                    <select name="status" class="pos-input" x-data="enhancedSelect()" @change="applyFilters()">
                        <option value="active"   @selected($filters['status'] === 'active')>{{ __('suppliers.filter.status_active') }}</option>
                        <option value="inactive" @selected($filters['status'] === 'inactive')>{{ __('suppliers.filter.status_inactive') }}</option>
                        <option value="all"      @selected($filters['status'] === 'all')>{{ __('suppliers.filter.status_all') }}</option>
                    </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="{{ __('suppliers.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 ($suppliers->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">{{ __('suppliers.empty_state.title') }}</div>
                    <div class="dt-empty-sub">{{ __('suppliers.empty_state.sub') }}</div>
                </div>
            @else
                <div class="dt-scroll">
                <table class="dt-table">
                    <thead>
                        <tr>
                            <th>{{ __('suppliers.columns.code') }}</th>
                            <th>{{ __('suppliers.columns.name') }}</th>
                            <th>{{ __('suppliers.columns.contact_person') }}</th>
                            <th>{{ __('suppliers.columns.phone') }}</th>
                            <th>{{ __('suppliers.columns.city') }}</th>
                            <th class="num">{{ __('suppliers.columns.outstanding') }}</th>
                            <th>{{ __('suppliers.columns.status') }}</th>
                            <th class="dt-actions-col"><span class="sr-only">{{ __('suppliers.columns.actions') }}</span></th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($suppliers as $s)
                            <tr class="prod-row" data-dt-row
                                data-dt-name="{{ $s->name }}"
                                data-dt-id="{{ $s->id }}"
                                data-dt-active="{{ $s->is_active ? 1 : 0 }}"
                                @click="window.location.href = {{ \Illuminate\Support\Js::from(route('admin.suppliers.edit', $s)) }}">
                                <td class="mono">{{ $s->code }}</td>
                                <td>
                                    {{-- Name + business-name sub-line. Mirrors the Stores
                                         row layout: bold name on top, muted secondary
                                         line below. Long business names (e.g. "OfficeKart
                                         Wholesale LLP") used to render as a wrapping pill
                                         that broke the column. --}}
                                    <div class="store-row-id">
                                        <div class="store-row-name-line">
                                            <span class="store-row-name">{{ $s->name }}</span>
                                        </div>
                                        @if ($s->business_name)
                                            <span class="store-row-code">{{ $s->business_name }}</span>
                                        @endif
                                    </div>
                                </td>
                                <td>{{ $s->contact_person ?: '—' }}</td>
                                <td class="mono">{{ $s->phone ? \App\Support\PhoneFormatter::pretty($s->phone) : '—' }}</td>
                                <td>{{ $s->city ?: '—' }}</td>
                                <td class="num tnum">{{ format_money($s->outstanding_balance) }}</td>
                                <td>
                                    <span class="prod-badge"
                                          :class="rowState[{{ $s->id }}]?.is_active ? 'prod-badge-positive' : 'prod-badge-muted'"
                                          x-text="rowState[{{ $s->id }}]?.is_active
                                                    ? @js(__('suppliers.badges.active'))
                                                    : @js(__('suppliers.badges.inactive'))"></span>
                                </td>
                                <td>
                                    <div class="prod-row-actions">
                                        @can('update', $s)
                                            <button type="button"
                                                    class="prod-status-btn"
                                                    :class="{ 'is-on': rowState[{{ $s->id }}]?.is_active }"
                                                    :aria-pressed="rowState[{{ $s->id }}]?.is_active ? 'true' : 'false'"
                                                    :title="rowState[{{ $s->id }}]?.is_active ? @js(__('suppliers.actions.tip_active_on')) : @js(__('suppliers.actions.tip_active_off'))"
                                                    :disabled="togglingIds.includes({{ $s->id }})"
                                                    @click.stop="toggleActive({{ $s->id }})"
                                                    aria-label="{{ __('suppliers.actions.toggle_active') }}">
                                                <span class="prod-status-thumb" aria-hidden="true"></span>
                                            </button>
                                        @endcan
                                        <x-admin.row-actions>
                                            @can('view', $s)
                                                <x-admin.row-action :href="route('admin.suppliers.show', $s)" icon="eye" :label="__('suppliers.actions.view')" />
                                            @endcan
                                            @can('update', $s)
                                                <x-admin.row-action :href="route('admin.suppliers.edit', $s)" icon="edit" :label="__('table.action.edit')" />
                                            @endcan
                                            @can('delete', $s)
                                                <div class="row-action-sep"></div>
                                                <x-admin.row-action icon="trash" variant="danger" :label="__('suppliers.actions.delete')"
                                                    @click="
                                                        const btn = $event.currentTarget;
                                                        $store.confirm.show({
                                                            title: {{ \Illuminate\Support\Js::from(__('suppliers.confirm_delete.title', ['name' => $s->name])) }},
                                                            message: {{ \Illuminate\Support\Js::from(__('suppliers.confirm_delete.message')) }},
                                                            intent: 'danger',
                                                            confirmLabel: {{ \Illuminate\Support\Js::from(__('suppliers.confirm_delete.confirm')) }},
                                                            onConfirm: () => $deleteRow({{ \Illuminate\Support\Js::from(route('admin.suppliers.destroy', $s)) }}, btn),
                                                        })
                                                    " />
                                            @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>
