@props([
    'candidates'   => [],
    'selected'     => [],
    'branchName'   => null,
    'baseAmount'   => 0,
    'canRemove'    => true,
    'manualCap'    => 0,
    'manualReasons'=> [],
])

@php
    $grouped = collect($candidates)->groupBy('group_label');
    $pinned  = collect($candidates)->where('is_pinned', true)
                                   ->whereIn('state', ['applied','available','stacks','needs_approval'])
                                   ->take(4);
    $applied = collect($candidates)->whereIn('rule_id', $selected);
@endphp

{{-- One Alpine scope owns the open/closed + search state; Livewire owns the data. --}}
<div x-data="{ open: false, search: '', manual: false }" class="relative">

    <div class="flex items-center justify-between mb-2">
        <label class="text-sm font-semibold text-gray-800">{{ __('الخصومات') }}</label>
        @if($branchName)
            <span class="text-xs text-emerald-700 font-medium">{{ $branchName }}</span>
        @endif
    </div>

    {{-- Pinned quick buttons — the daily cases stay one tap --}}
    @if($pinned->isNotEmpty())
        <div class="flex flex-wrap gap-2 mb-2">
            @foreach($pinned as $pin)
                @php $isOn = in_array($pin['rule_id'], $selected); @endphp
                <button type="button"
                        wire:click="{{ $isOn ? 'removeDiscount' : 'applyDiscount' }}({{ $pin['rule_id'] }})"
                        wire:loading.attr="disabled"
                        class="inline-flex items-center gap-1.5 px-3 py-2 rounded-lg border-2 text-sm font-bold transition-colors
                               {{ $isOn ? 'bg-emerald-100 border-emerald-600 text-emerald-800'
                                        : 'bg-white border-gray-300 text-gray-700 hover:border-emerald-400' }}">
                    @if($pin['icon'])<x-ui.icon :name="$pin['icon']" class="w-4 h-4" />@endif
                    <span>{{ $pin['name'] }}</span>
                    @if($pin['value_label'])
                        <span dir="ltr" class="tabular-nums">{{ $pin['value_label'] }}</span>
                    @endif
                    @if($isOn)<x-ui.icon name="x-mark" class="w-3.5 h-3.5 opacity-60" />@endif
                </button>
            @endforeach
        </div>
    @endif

    {{-- The picker --}}
    <button type="button" @click="open = !open"
            class="w-full flex items-center justify-between gap-2 px-3 py-2.5 bg-white
                   border-2 border-emerald-500 rounded-lg text-sm font-semibold text-gray-700
                   focus:outline-none focus:ring-2 focus:ring-emerald-500">
        <span class="inline-flex items-center gap-1.5">
            <x-ui.icon name="magnifying-glass" class="w-4 h-4 text-gray-400" />
            {{ __('اختر خصم...') }}
        </span>
        <x-ui.icon name="chevron-down" class="w-4 h-4 text-emerald-600 transition-transform"
                   x-bind:class="open && 'rotate-180'" />
    </button>

    <div x-show="open" x-cloak @click.outside="open = false" x-transition
         class="mt-1 bg-white border border-gray-200 rounded-lg shadow-lg overflow-hidden max-h-80 overflow-y-auto">

        <div class="p-2 border-b border-gray-100 sticky top-0 bg-white">
            <input type="text" x-model="search" placeholder="{{ __('ابحث...') }}"
                   class="w-full px-3 py-1.5 border border-gray-200 rounded-lg text-sm focus:ring-2 focus:ring-emerald-500">
        </div>

        @if(count($candidates) === 0)
            <p class="px-3 py-6 text-center text-sm text-gray-400">
                {{ __('لا توجد خصومات متاحة لهذا الفرع') }}
            </p>
        @endif

        @foreach($grouped as $label => $rows)
            <div x-show="search === '' || @js($rows->pluck('name')->all()).some(n => n.includes(search))">
                <div class="px-3 pt-2 pb-1 text-xs font-bold text-gray-400">{{ $label }}</div>
                @foreach($rows as $row)
                    @php
                        $isOn     = in_array($row['rule_id'], $selected);
                        $blocked  = $row['state'] === 'blocked';
                        $approval = $row['state'] === 'needs_approval';
                    @endphp
                    <div data-row
                         x-show="search === '' || @js($row['name']).includes(search)"
                         class="border-t border-gray-50">
                        <button type="button"
                                @if(!$blocked) wire:click="{{ $isOn ? 'removeDiscount' : 'applyDiscount' }}({{ $row['rule_id'] }})" @endif
                                @if($blocked) disabled @endif
                                class="w-full flex items-center justify-between gap-3 px-3 py-2 text-sm text-start
                                       {{ $blocked ? 'text-gray-300 cursor-not-allowed'
                                          : ($isOn ? 'bg-emerald-50 text-emerald-800 font-bold'
                                          : ($approval ? 'text-amber-700 hover:bg-amber-50' : 'text-gray-700 hover:bg-gray-50')) }}">
                            <span class="flex items-center gap-1.5">
                                @if($isOn)
                                    <x-ui.icon name="check" class="w-4 h-4" />
                                @elseif($approval)
                                    <x-ui.icon name="exclamation-triangle" class="w-4 h-4" />
                                @elseif($blocked)
                                    <x-ui.icon name="no-symbol" class="w-4 h-4" />
                                @endif
                                @if($row['icon'])<x-ui.icon :name="$row['icon']" class="w-4 h-4" />@endif
                                <span>{{ $row['name'] }}</span>
                            </span>
                            <span dir="ltr" class="tabular-nums text-xs whitespace-nowrap">
                                {{ $row['value_label'] }}
                            </span>
                        </button>
                        @if($row['reason'])
                            <p class="px-3 pb-1.5 text-xs {{ $blocked ? 'text-gray-400' : 'text-amber-700' }}">
                                {{ $row['reason'] }}
                            </p>
                        @endif
                    </div>
                @endforeach
            </div>
        @endforeach

        {{-- Manual discount --}}
        @if($manualCap > 0)
            <div class="border-t border-gray-100 bg-gray-50 p-3">
                <button type="button" @click="manual = !manual"
                        class="text-sm font-bold text-amber-700 hover:text-amber-800">
                    <x-ui.icon name="hand-raised" class="w-4 h-4 inline-block align-text-bottom" />
                    {{ __('خصم استثنائي') }}
                    <span class="text-xs font-normal text-gray-500">
                        ({{ __('حتى') }} {{ $manualCap }}%)
                    </span>
                </button>

                <div x-show="manual" x-cloak class="mt-2 space-y-2">
                    <input type="number" step="0.01" min="0" dir="ltr"
                           wire:model.blur="manualDiscountAmount"
                           placeholder="{{ __('المبلغ بالجنيه') }}"
                           class="w-full px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-amber-500">

                    <select wire:model.live="manualDiscountReason"
                            class="w-full px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-amber-500">
                        <option value="">{{ __('سبب الخصم...') }}</option>
                        @foreach($manualReasons as $reason)
                            <option value="{{ $reason['value'] }}">{{ $reason['label'] }}</option>
                        @endforeach
                    </select>

                    <textarea wire:model.blur="manualDiscountNote" rows="2"
                              placeholder="{{ __('ملاحظة (مطلوبة لبعض الأسباب)') }}"
                              class="w-full px-3 py-1.5 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-amber-500"></textarea>

                    @error('manualDiscountAmount')
                        <p class="text-xs text-red-600">{{ $message }}</p>
                    @enderror
                </div>
            </div>
        @endif
    </div>

    {{-- What is actually applied --}}
    @if($applied->isNotEmpty())
        <div class="flex flex-wrap items-center gap-2 mt-3 pt-3 border-t border-dashed border-gray-200">
            <span class="text-xs text-gray-500 font-semibold">{{ __('المُطبق:') }}</span>
            @foreach($applied as $row)
                <span class="inline-flex items-center gap-1.5 px-3 py-1 rounded-full
                             bg-emerald-100 border-2 border-emerald-600 text-emerald-800 text-sm font-bold">
                    {{ $row['name'] }}
                    @if($row['value_label'])
                        <span dir="ltr" class="tabular-nums">{{ $row['value_label'] }}</span>
                    @endif
                    @if($canRemove)
                        <button type="button" wire:click="removeDiscount({{ $row['rule_id'] }})"
                                class="opacity-60 hover:opacity-100" title="{{ __('إلغاء') }}">
                            <x-ui.icon name="x-mark" class="w-3.5 h-3.5" />
                        </button>
                    @endif
                </span>
            @endforeach
        </div>
    @endif
</div>
