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

    @php
        $rowsForJs = $terminals->map(fn ($t) => [
            'id'         => $t->id,
            'store_id'   => $t->store_id,
            'store_name' => $t->store?->name,
            'code'       => $t->code,
            'name'       => $t->name,
            'is_active'  => (bool) $t->is_active,
            'config'     => $t->default_printer_config['receipt_printer'] ?? null,
            'updated_at' => $t->updated_at?->diffForHumans(),
        ])->values();

        if ($errors->any()) {
            $editingId = old('editing_id') ? (int) old('editing_id') : null;
            $initial = [
                'mode'      => $editingId ? 'edit' : 'new',
                'id'        => $editingId,
                'store_id'  => old('store_id') ? (int) old('store_id') : null,
                'code'      => (string) old('code', ''),
                'name'      => (string) old('name', ''),
                'is_active' => (bool) old('is_active', false),
            ];
        } elseif ($selected) {
            $initial = [
                'mode'      => 'edit',
                'id'        => $selected->id,
                'store_id'  => $selected->store_id,
                'code'      => $selected->code,
                'name'      => $selected->name,
                'is_active' => (bool) $selected->is_active,
                'config'    => $selected->default_printer_config['receipt_printer'] ?? null,
            ];
        } elseif ($isNew) {
            $initial = ['mode' => 'new', 'id' => null, 'store_id' => null, 'code' => '', 'name' => '', 'is_active' => true];
        } else {
            $initial = null;
        }
    @endphp

    <div class="page-wide"
         x-data="terminalsPage({
             storeUrl:           '{{ route('admin.terminals.store') }}',
             updateUrlTemplate:  '{{ route('admin.terminals.update', ['terminal' => '__ID__']) }}',
             deleteUrlTemplate:  '{{ route('admin.terminals.destroy', ['terminal' => '__ID__']) }}',
             selectUrlTemplate:  '{{ route('admin.terminals.select', ['terminal' => '__ID__']) }}',
             clearSelectionUrl:  '{{ route('admin.terminals.clear-selection') }}',
             activeTerminalId:   {{ $activeTerminalId ?? 'null' }},
             rows:               {{ Js::from($rowsForJs) }},
             initial:            {{ Js::from($initial) }},
         })">

        <div class="page-header mb-6">
            <div>
                <h1 class="page-title">{{ __('terminals.title') }}</h1>
                <p class="page-sub">{{ __('terminals.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" />
                        {{ __('terminals.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.terminals.export', ['format' => 'csv']) }}"
                           class="dropdown-item" @click="close()">
                            <span class="dropdown-item-label">{{ __('terminals.actions.export_csv') }}</span>
                        </a>
                        <a href="{{ route('admin.terminals.export', ['format' => 'xlsx']) }}"
                           class="dropdown-item" @click="close()">
                            <span class="dropdown-item-label">{{ __('terminals.actions.export_xlsx') }}</span>
                        </a>
                    </div>
                </div>

                <button type="button" @click="openNew()" class="pos-btn pos-btn-sm pos-btn-primary">
                    <x-icon name="plus" class="w-4 h-4" />
                    {{ __('terminals.actions.new') }}
                </button>
            </div>
        </div>

        <div class="grid grid-cols-1 lg:grid-cols-[minmax(0,1fr)_360px] gap-5 items-start">
            @if ($terminals->isEmpty())
                <div class="card card-pad-0">
                    <div class="term-empty">
                        <span class="term-empty-icon"><x-icon name="pos" class="w-5 h-5" /></span>
                        <div class="term-empty-title">{{ __('terminals.list.empty_title') }}</div>
                        <div class="term-empty-sub">{{ __('terminals.list.empty_sub') }}</div>
                    </div>
                </div>
            @else
                <x-admin.data-table>
                    <x-slot:toolbarStart>
                        <div class="dt-toolbar-title">
                            {{ __('terminals.list.title') }} (<span x-text="rowCount">{{ $terminals->count() }}</span>)
                        </div>
                    </x-slot:toolbarStart>

                    <ul class="term-list">
                        @include('admin.terminals._list', ['terminals' => $terminals])
                    </ul>
                </x-admin.data-table>
            @endif

            <div class="card term-editor">
                <div class="term-editor-empty" x-show="isIdle" x-cloak>
                    <span class="term-editor-empty-icon"><x-icon name="pos" class="w-5 h-5" /></span>
                    <div class="term-editor-empty-title">{{ __('terminals.editor.empty_title') }}</div>
                    <div class="term-editor-empty-sub">{{ __('terminals.editor.empty_sub') }}</div>
                </div>

                <template x-if="!isIdle">
                    <div>
                        <div class="term-editor-head">
                            <span class="term-tile" aria-hidden="true"><x-icon name="pos" class="w-5 h-5" /></span>
                            <div>
                                <div class="term-editor-name"
                                     x-text="isEdit ? (form.name || @js(__('terminals.drawer.edit_title')))
                                                    : @js(__('terminals.drawer.new_title'))"></div>
                                <div class="term-editor-id">
                                    <template x-if="isEdit">
                                        <span>
                                            {{ __('terminals.drawer.edit_id') }}
                                            <span class="mono" x-text="form.id"></span>
                                            <template x-if="rowMeta?.updated_at">
                                                <span> · {{ __('terminals.drawer.edit_updated') }}
                                                    <span x-text="rowMeta.updated_at"></span>
                                                </span>
                                            </template>
                                        </span>
                                    </template>
                                    <template x-if="isNew">
                                        <span>{{ __('terminals.drawer.new_sub') }}</span>
                                    </template>
                                </div>
                            </div>
                        </div>

                        <form method="POST"
                              :action="formAction"
                              class="card-body"
                              novalidate
                              @submit.prevent="submitEditor($event)">
                            @csrf
                            <input type="hidden" name="_method" :value="isEdit ? 'PATCH' : 'POST'">
                            <input type="hidden" name="editing_id" :value="form.id || ''">

                            <div class="form-stack">
                                <label class="field">
                                    <span class="field-label is-required">{{ __('terminals.drawer.store') }}</span>
                                    <select name="store_id" x-model="form.store_id" class="pos-input">
                                        <option value="">{{ __('terminals.drawer.store_placeholder') }}</option>
                                        @foreach ($stores as $st)
                                            <option value="{{ $st->id }}">{{ $st->name }}</option>
                                        @endforeach
                                    </select>
                                </label>

                                <label class="field">
                                    <span class="field-label is-required">{{ __('terminals.drawer.name') }}</span>
                                    <input type="text" name="name" x-model="form.name" class="pos-input"
                                           placeholder="{{ __('terminals.drawer.name_placeholder') }}">
                                </label>

                                <label class="field">
                                    <span class="field-label">{{ __('terminals.drawer.code') }}</span>
                                    <input type="text" name="code" x-model="form.code" class="pos-input mono"
                                           maxlength="32" placeholder="{{ __('terminals.drawer.code_placeholder') }}">
                                    <span class="field-help">{{ __('terminals.drawer.code_help') }}</span>
                                </label>

                                <label class="field-toggle">
                                    <input type="hidden" name="is_active" value="0">
                                    <input type="checkbox" name="is_active" value="1" x-model="form.is_active">
                                    <span>{{ __('terminals.drawer.is_active') }}</span>
                                </label>
                            </div>

                            {{-- ── Hardware ────────────────────────────────
                                 Folded into default_printer_config JSON by
                                 TerminalRequest. Drives the cashier's print
                                 bridge for THIS terminal. --}}
                            <div class="term-hw">
                                <div class="term-hw-title">{{ __('terminals.hw.title') }}</div>

                                <div class="form-stack">
                                    <label class="field">
                                        <span class="field-label">{{ __('terminals.hw.mode') }}</span>
                                        <select name="printer_mode" x-model="form.printer_mode" class="pos-input">
                                            <option value="browser_print">{{ __('terminals.hw.mode_browser') }}</option>
                                            <option value="webusb">{{ __('terminals.hw.mode_webusb') }}</option>
                                            <option value="network">{{ __('terminals.hw.mode_network') }}</option>
                                            <option value="none">{{ __('terminals.hw.mode_none') }}</option>
                                        </select>
                                        <span class="field-help">{{ __('terminals.hw.mode_help') }}</span>
                                    </label>

                                    {{-- WebUSB pairing — only for thermal/WebUSB mode. --}}
                                    <div class="field" x-show="form.printer_mode === 'webusb'" x-cloak>
                                        <span class="field-label">{{ __('terminals.hw.pair') }}</span>
                                        <div class="term-hw-pair">
                                            <button type="button" class="pos-btn pos-btn-sm pos-btn-ghost"
                                                    @click="pairPrinter()">
                                                <x-icon name="printer" class="w-4 h-4" />
                                                {{ __('terminals.hw.pair_btn') }}
                                            </button>
                                            <span class="term-hw-paired mono"
                                                  x-text="form.webusb_label || @js(__('terminals.hw.not_paired'))"></span>
                                        </div>
                                        <input type="hidden" name="webusb_vendor_id"  :value="form.webusb_vendor_id || ''">
                                        <input type="hidden" name="webusb_product_id" :value="form.webusb_product_id || ''">
                                        <span class="field-help">{{ __('terminals.hw.pair_help') }}</span>
                                    </div>

                                    {{-- Paper + cut — for any real printer. --}}
                                    <label class="field" x-show="form.printer_mode !== 'none'" x-cloak>
                                        <span class="field-label">{{ __('terminals.hw.paper') }}</span>
                                        <select name="paper_width" x-model="form.paper_width" class="pos-input">
                                            <option value="58mm">58 mm</option>
                                            <option value="80mm">80 mm</option>
                                            <option value="a4">A4</option>
                                        </select>
                                    </label>

                                    <label class="field-toggle" x-show="form.printer_mode === 'webusb' || form.printer_mode === 'network'" x-cloak>
                                        <input type="hidden" name="cut_paper" value="0">
                                        <input type="checkbox" name="cut_paper" value="1" x-model="form.cut_paper">
                                        <span>{{ __('terminals.hw.cut') }}</span>
                                    </label>

                                    {{-- Cash drawer. --}}
                                    <label class="field-toggle">
                                        <input type="hidden" name="open_drawer_on_cash" value="0">
                                        <input type="checkbox" name="open_drawer_on_cash" value="1" x-model="form.open_drawer_on_cash">
                                        <span>{{ __('terminals.hw.drawer') }}</span>
                                    </label>

                                    <label class="field" x-show="form.open_drawer_on_cash" x-cloak>
                                        <span class="field-label">{{ __('terminals.hw.drawer_pin') }}</span>
                                        <select name="drawer_pin" x-model="form.drawer_pin" class="pos-input">
                                            <option value="2">{{ __('terminals.hw.drawer_pin_2') }}</option>
                                            <option value="5">{{ __('terminals.hw.drawer_pin_5') }}</option>
                                        </select>
                                        <span class="field-help">{{ __('terminals.hw.drawer_pin_help') }}</span>
                                    </label>
                                </div>
                            </div>

                            <div class="term-editor-actions">
                                <template x-if="isEdit">
                                    <button type="button"
                                            class="pos-btn pos-btn-sm pos-btn-danger"
                                            :disabled="submitting"
                                            @click="confirmDelete()">
                                        <x-icon name="trash" class="w-4 h-4" />
                                        {{ __('terminals.actions.delete') }}
                                    </button>
                                </template>
                                <template x-if="isNew"><span></span></template>

                                <div class="flex items-center gap-2">
                                    <button type="button"
                                            @click="closeEditor()"
                                            :disabled="submitting"
                                            class="pos-btn pos-btn-sm pos-btn-ghost">
                                        {{ __('terminals.actions.discard') }}
                                    </button>
                                    <button type="submit"
                                            class="pos-btn pos-btn-sm pos-btn-primary"
                                            :disabled="submitting">
                                        <svg x-show="submitting" x-cloak class="h-4 w-4 animate-spin"
                                             viewBox="0 0 24 24" fill="none" aria-hidden="true">
                                            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"/>
                                            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"/>
                                        </svg>
                                        <span x-text="
                                            submitting
                                                ? (isEdit ? @js(__('terminals.actions_extra.saving'))
                                                          : @js(__('terminals.actions_extra.creating')))
                                                : (isEdit ? @js(__('terminals.actions.save'))
                                                          : @js(__('terminals.actions.create')))
                                        "></span>
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </template>
            </div>
        </div>
    </div>
</x-admin-layout>
