@php
    use App\Domain\Financial\Enums\AllocationType;
    use App\Domain\Financial\Enums\TaxMode;
@endphp

<div>
    {{-- ───────────────────────────────────────────── header --}}
    <div class="flex flex-col sm:flex-row sm:items-start justify-between gap-3 mb-4">
        <div>
            <h1 class="text-xl sm:text-2xl font-bold text-gray-800">{{ __('توجيه الإيرادات') }}</h1>
            <p class="text-sm text-gray-500 mt-1">
                {{ __('كل مبلغ يُحصَّل في النظام، وإلى أي حساب في شجرة الحسابات يذهب.') }}
            </p>
        </div>
        <a href="{{ route('financial.overview') }}" wire:navigate
           class="inline-flex items-center gap-1 text-sm text-gray-600 hover:text-gray-800 shrink-0">
            <svg class="w-4 h-4 rtl:rotate-180" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 17l-5-5m0 0l5-5m-5 5h12"/></svg>
            {{ __('النظرة المالية') }}
        </a>
    </div>

    @if(session('success'))
        <div class="mb-4 p-3 bg-green-50 border border-green-200 rounded-lg text-green-800 text-sm">{{ session('success') }}</div>
    @endif
    @if(session('error'))
        <div class="mb-4 p-3 bg-red-50 border border-red-200 rounded-lg text-red-700 text-sm">{{ session('error') }}</div>
    @endif

    {{-- ───────────────────────────────────────────── how it works --}}
    <div class="mb-5 rounded-xl border border-blue-200 bg-blue-50/60 p-4">
        <div class="flex items-start gap-3">
            <svg class="w-5 h-5 text-blue-600 shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
            </svg>
            <div class="text-sm text-blue-900 leading-relaxed">
                <p class="font-semibold mb-1">{{ __('كيف يُقرأ التوزيع') }}</p>
                <p>
                    {{ __('لكل مصدر إيراد قاعدة واحدة. القاعدة تخصم الضريبة أولاً — لأن الضريبة المحصَّلة مستحقة لمصلحة الضرائب وليست إيراداً — ثم توزّع الصافي على السطور بالترتيب:') }}
                    <span class="font-semibold">{{ __('المبالغ الثابتة، ثم النسب، ثم سطر «الباقي» يأخذ ما تبقى.') }}</span>
                </p>
                <p class="mt-1">
                    {{ __('يمكن تخصيص قاعدة لصنف بعينه (منتج، برنامج، إيفنت) فتسبق القاعدة الافتراضية له وحده. القيود المُرحَّلة سابقاً لا تتغير — القاعدة تسري على ما يُحصَّل بعد الحفظ.') }}
                </p>
            </div>
        </div>
    </div>

    {{-- ───────────────────────────────────────────── sources --}}
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div class="overflow-x-auto">
            <table class="min-w-full text-sm">
                <thead class="bg-gray-50 text-gray-500 text-xs">
                    <tr>
                        <th class="px-4 py-3 text-start font-medium">{{ __('مصدر الإيراد') }}</th>
                        <th class="px-4 py-3 text-start font-medium">{{ __('يذهب إلى') }}</th>
                        <th class="px-4 py-3 text-start font-medium">{{ __('الضريبة') }}</th>
                        <th class="px-4 py-3 text-start font-medium">{{ __('المحصَّل تاريخياً') }}</th>
                        <th class="px-4 py-3 text-start font-medium"></th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    @foreach($sources as $row)
                        @php
                            $source = $row['source'];
                            $mapping = $row['mapping'];
                            $inactive = ! $mapping || ! $mapping->is_active;
                        @endphp
                        <tr class="hover:bg-gray-50/70 align-top">
                            <td class="px-4 py-3">
                                <div class="font-semibold text-gray-800">{{ $source->label() }}</div>
                                <div class="text-xs text-gray-500 mt-0.5 max-w-md leading-relaxed">{{ $source->description() }}</div>
                                @if($row['overrides']->isNotEmpty())
                                    <div class="mt-1.5 text-xs text-indigo-700">
                                        {{ __('تخصيصات لأصناف بعينها:') }} {{ $row['overrides']->count() }}
                                    </div>
                                @endif
                            </td>

                            <td class="px-4 py-3">
                                @if($inactive)
                                    <span class="inline-flex items-center gap-1 px-2 py-1 rounded-md bg-gray-100 text-gray-600 text-xs">
                                        {{ __('غير مفعَّلة — يُطبَّق السلوك المدمج') }}
                                    </span>
                                @else
                                    <div class="flex flex-col gap-1">
                                        @foreach($mapping->lines as $line)
                                            <div class="inline-flex items-center gap-2 text-xs">
                                                <span class="px-1.5 py-0.5 rounded bg-gray-100 text-gray-700 font-medium shrink-0" dir="ltr">{{ $line->shareLabel() }}</span>
                                                <svg class="w-3 h-3 text-gray-400 shrink-0 rtl:rotate-180" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 7l5 5m0 0l-5 5m5-5H6"/></svg>
                                                <span class="text-gray-700">
                                                    <span class="font-mono text-gray-500" dir="ltr">{{ $line->account?->code }}</span>
                                                    {{ $line->account?->name_ar ?: $line->account?->name }}
                                                </span>
                                            </div>
                                        @endforeach
                                    </div>
                                @endif
                            </td>

                            <td class="px-4 py-3">
                                @if($mapping && $mapping->tax_mode !== TaxMode::None)
                                    <span class="inline-flex items-center px-2 py-1 rounded-md bg-amber-50 text-amber-800 border border-amber-200 text-xs font-medium" dir="ltr">
                                        {{ rtrim(rtrim(number_format($mapping->taxRatePercent(), 2), '0'), '.') }}%
                                    </span>
                                    <div class="text-[11px] text-gray-500 mt-1">{{ $mapping->tax_mode->label() }}</div>
                                    <div class="text-[11px] text-gray-500">
                                        <span class="font-mono" dir="ltr">{{ $mapping->taxAccount?->code }}</span>
                                        {{ $mapping->taxAccount?->name_ar }}
                                    </div>
                                @else
                                    <span class="text-xs text-gray-400">{{ __('بدون') }}</span>
                                @endif
                            </td>

                            <td class="px-4 py-3">
                                @if($row['volume']['count'] > 0)
                                    <div class="font-semibold text-gray-800" dir="ltr">{{ format_money($row['volume']['total']) }}</div>
                                    <div class="text-xs text-gray-500">{{ $row['volume']['count'] }} {{ __('بند') }}</div>
                                @else
                                    <span class="text-xs text-gray-400">{{ __('لا يوجد بعد') }}</span>
                                @endif
                            </td>

                            <td class="px-4 py-3 text-end">
                                <button type="button" wire:click="editRule('{{ $source->value }}')"
                                        wire:loading.attr="disabled"
                                        class="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg border border-gray-300 text-gray-700 hover:bg-gray-50 text-xs font-medium disabled:opacity-50">
                                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
                                    {{ $canManage ? __('تعديل') : __('عرض') }}
                                </button>
                            </td>
                        </tr>

                        @foreach($row['overrides'] as $override)
                            <tr class="bg-indigo-50/30">
                                <td class="px-4 py-2 ps-10">
                                    <div class="text-xs text-indigo-900 font-medium">
                                        {{ __('تخصيص:') }}
                                        {{ $row['scopeNames'][$override->scope_id] ?? __('صنف محذوف') }}
                                    </div>
                                </td>
                                <td class="px-4 py-2">
                                    <div class="flex flex-col gap-0.5">
                                        @foreach($override->lines as $line)
                                            <div class="text-xs text-gray-700">
                                                <span class="font-medium" dir="ltr">{{ $line->shareLabel() }}</span>
                                                <span class="text-gray-400">→</span>
                                                <span class="font-mono text-gray-500" dir="ltr">{{ $line->account?->code }}</span>
                                                {{ $line->account?->name_ar }}
                                            </div>
                                        @endforeach
                                    </div>
                                </td>
                                <td class="px-4 py-2 text-xs text-gray-500">
                                    {{ $override->tax_mode === TaxMode::None ? __('بدون') : rtrim(rtrim(number_format($override->taxRatePercent(), 2), '0'), '.') . '%' }}
                                </td>
                                <td class="px-4 py-2"></td>
                                <td class="px-4 py-2 text-end">
                                    <button type="button"
                                            wire:click="editRule('{{ $source->value }}', {{ (int) $override->scope_id }})"
                                            class="text-xs text-indigo-700 hover:underline">{{ __('تعديل') }}</button>
                                </td>
                            </tr>
                        @endforeach
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>

    {{-- ───────────────────────────────────────────── editor --}}
    @if($editingSource)
        @php $editingEnum = \App\Domain\Financial\Enums\RevenueSource::from($editingSource); @endphp

        <div class="fixed inset-0 z-50 overflow-y-auto bg-black/50" wire:key="editor-{{ $editingSource }}-{{ $scopeId ?? 0 }}">
            <div class="min-h-full flex items-start justify-center p-3 sm:p-6">
                <div class="bg-gray-50 rounded-2xl shadow-xl w-full max-w-6xl">

                    {{-- editor header --}}
                    <div class="flex items-start justify-between gap-3 p-4 sm:p-5 bg-white rounded-t-2xl border-b border-gray-200">
                        <div>
                            <h2 class="text-lg font-bold text-gray-800">{{ $editingEnum->label() }}</h2>
                            @if($scopeLabel)
                                <p class="text-xs text-indigo-700 mt-0.5">{{ __('قاعدة خاصة بـ') }} «{{ $scopeLabel }}» {{ __('وحده') }}</p>
                            @else
                                <p class="text-xs text-gray-500 mt-0.5">{{ __('القاعدة الافتراضية لهذا المصدر') }}</p>
                            @endif
                        </div>
                        <button type="button" wire:click="closeEditor"
                                class="flex items-center justify-center w-8 h-8 rounded-lg text-gray-400 hover:text-gray-600 hover:bg-gray-100" aria-label="{{ __('إغلاق') }}">
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
                        </button>
                    </div>

                    <div class="grid grid-cols-1 lg:grid-cols-5 gap-4 p-4 sm:p-5">

                        {{-- ── left: the rule ────────────────────────────── --}}
                        <div class="lg:col-span-3 space-y-4">

                            {{-- active --}}
                            <div class="bg-white rounded-xl border border-gray-200 p-4">
                                <label class="flex items-start gap-3 cursor-pointer">
                                    {{-- Every control on this screen renders its own value server-side.
                                         Livewire would otherwise only apply it once its JavaScript
                                         initialises, and a select that shows "اختر الحساب…" for a rule
                                         that in fact points at 4010 is the one mistake this screen
                                         cannot afford to make. --}}
                                    <input type="checkbox" wire:model.live="isActive" @checked($isActive) @disabled(! $canManage)
                                           class="mt-0.5 rounded border-gray-300 text-green-600 focus:ring-green-500">
                                    <span>
                                        <span class="text-sm font-medium text-gray-800">{{ __('القاعدة مفعَّلة') }}</span>
                                        <span class="block text-xs text-gray-500 mt-0.5">
                                            {{ __('إيقافها يعيد هذا المصدر للسلوك المدمج في النظام دون حذف ما كتبته.') }}
                                        </span>
                                    </span>
                                </label>
                            </div>

                            {{-- tax --}}
                            <div class="bg-white rounded-xl border border-gray-200 p-4">
                                <h3 class="text-sm font-semibold text-gray-800 mb-1">{{ __('المعالجة الضريبية') }}</h3>
                                <p class="text-xs text-gray-500 mb-3">
                                    {{ __('تُخصم الضريبة من المبلغ قبل التوزيع، وتُرحَّل لحساب التزامات — لا لحساب إيراد.') }}
                                </p>

                                <div class="grid grid-cols-1 sm:grid-cols-3 gap-2">
                                    @foreach(TaxMode::cases() as $mode)
                                        <label class="cursor-pointer">
                                            <input type="radio" wire:model.live="taxMode" value="{{ $mode->value }}"
                                                   @checked($taxMode === $mode->value) class="peer sr-only" @disabled(! $canManage)>
                                            <div class="peer-checked:ring-2 peer-checked:ring-amber-500 peer-checked:border-amber-500 peer-checked:bg-amber-50 h-full p-3 rounded-lg border-2 border-gray-200 hover:border-amber-300 transition-all">
                                                <div class="text-xs font-semibold text-gray-800">{{ $mode->label() }}</div>
                                                <div class="text-[11px] text-gray-500 mt-1 leading-snug">{{ $mode->hint() }}</div>
                                            </div>
                                        </label>
                                    @endforeach
                                </div>

                                @if($taxMode !== TaxMode::None->value)
                                    <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 mt-3 pt-3 border-t border-gray-100">
                                        <div>
                                            <label class="block text-xs text-gray-600 mb-1">{{ __('النسبة %') }}</label>
                                            <input type="number" wire:model.live.debounce.500ms="taxRateDisplay" dir="ltr" step="0.01" min="0" max="100"
                                                   value="{{ $taxRateDisplay }}" @disabled(! $canManage)
                                                   class="w-full rounded-lg border-gray-300 text-sm py-2">
                                            <p class="text-[11px] text-gray-400 mt-1">{{ __('القيمة المضافة في مصر 14% — وبعض الخدمات 10% أو معفاة.') }}</p>
                                        </div>
                                        <div>
                                            <label class="block text-xs text-gray-600 mb-1">{{ __('حساب الضريبة') }}</label>
                                            <select wire:model.live="taxAccountId" @disabled(! $canManage)
                                                    class="w-full rounded-lg border-gray-300 text-sm py-2">
                                                <option value="">{{ __('اختر حساباً…') }}</option>
                                                @foreach($taxAccounts as $account)
                                                    <option value="{{ $account->id }}" @selected((int) $taxAccountId === (int) $account->id)>{{ $account->code }} — {{ $account->name_ar ?: $account->name }}</option>
                                                @endforeach
                                            </select>
                                            <p class="text-[11px] text-gray-400 mt-1">{{ __('حسابات الالتزامات فقط.') }}</p>
                                        </div>
                                    </div>
                                @endif
                            </div>

                            {{-- lines --}}
                            <div class="bg-white rounded-xl border border-gray-200 p-4">
                                <div class="flex items-center justify-between mb-1">
                                    <h3 class="text-sm font-semibold text-gray-800">{{ __('توزيع الصافي على الحسابات') }}</h3>
                                    @can('revenue_routing.manage')
                                        <button type="button" wire:click="$toggle('showAccountForm')"
                                                class="text-xs text-gray-600 hover:text-gray-800 hover:underline">
                                            {{ __('+ حساب جديد في شجرة الحسابات') }}
                                        </button>
                                    @endcan
                                </div>
                                <p class="text-xs text-gray-500 mb-3">
                                    {{ __('الترتيب المحاسبي ثابت: المبالغ الثابتة أولاً، ثم النسب من الصافي، ثم «الباقي».') }}
                                </p>

                                @if($showAccountForm)
                                    <div class="mb-3 p-3 rounded-lg bg-gray-50 border border-gray-200">
                                        <div class="grid grid-cols-1 sm:grid-cols-4 gap-2">
                                            <div>
                                                <label class="block text-[11px] text-gray-600 mb-1">{{ __('رقم الحساب') }}</label>
                                                <input type="text" wire:model="newAccountCode" dir="ltr" placeholder="4070"
                                                       class="w-full rounded-lg border-gray-300 text-sm py-1.5">
                                                @error('newAccountCode') <p class="text-red-500 text-[11px] mt-0.5">{{ $message }}</p> @enderror
                                            </div>
                                            <div class="sm:col-span-2">
                                                <label class="block text-[11px] text-gray-600 mb-1">{{ __('اسم الحساب') }}</label>
                                                <input type="text" wire:model="newAccountName" placeholder="{{ __('مثال: رسوم إدارية') }}"
                                                       class="w-full rounded-lg border-gray-300 text-sm py-1.5">
                                                @error('newAccountName') <p class="text-red-500 text-[11px] mt-0.5">{{ $message }}</p> @enderror
                                            </div>
                                            <div>
                                                <label class="block text-[11px] text-gray-600 mb-1">{{ __('النوع') }}</label>
                                                <select wire:model="newAccountType" class="w-full rounded-lg border-gray-300 text-sm py-1.5">
                                                    <option value="revenue" @selected($newAccountType === 'revenue')>{{ __('إيراد') }}</option>
                                                    <option value="liability" @selected($newAccountType === 'liability')>{{ __('التزام') }}</option>
                                                    <option value="equity" @selected($newAccountType === 'equity')>{{ __('حقوق ملكية') }}</option>
                                                </select>
                                            </div>
                                        </div>
                                        <div class="flex gap-2 mt-2">
                                            <button type="button" wire:click="createAccount" wire:loading.attr="disabled"
                                                    class="px-3 py-1.5 rounded-lg bg-gray-800 text-white text-xs font-medium disabled:opacity-50">
                                                <span wire:loading.remove wire:target="createAccount">{{ __('إنشاء') }}</span>
                                                <span wire:loading wire:target="createAccount">{{ __('جارٍ…') }}</span>
                                            </button>
                                            <button type="button" wire:click="$set('showAccountForm', false)"
                                                    class="px-3 py-1.5 rounded-lg border border-gray-300 text-gray-600 text-xs">{{ __('إلغاء') }}</button>
                                        </div>
                                    </div>
                                @endif

                                <div class="space-y-2">
                                    @foreach($lines as $i => $line)
                                        <div class="grid grid-cols-12 gap-2 items-start" wire:key="line-{{ $i }}">
                                            <div class="col-span-12 sm:col-span-5">
                                                <select wire:model.live="lines.{{ $i }}.account_id" @disabled(! $canManage)
                                                        class="w-full rounded-lg border-gray-300 text-sm py-2">
                                                    <option value="">{{ __('اختر الحساب…') }}</option>
                                                    @foreach($accounts as $account)
                                                        <option value="{{ $account->id }}" @selected((int) ($line['account_id'] ?? 0) === (int) $account->id)>{{ $account->code }} — {{ $account->name_ar ?: $account->name }}</option>
                                                    @endforeach
                                                </select>
                                            </div>

                                            <div class="col-span-5 sm:col-span-3">
                                                <select wire:model.live="lines.{{ $i }}.allocation_type" @disabled(! $canManage)
                                                        class="w-full rounded-lg border-gray-300 text-sm py-2">
                                                    @foreach(AllocationType::cases() as $type)
                                                        <option value="{{ $type->value }}" @selected(($line['allocation_type'] ?? '') === $type->value)>{{ $type->label() }}</option>
                                                    @endforeach
                                                </select>
                                            </div>

                                            <div class="col-span-5 sm:col-span-3">
                                                @if(($line['allocation_type'] ?? '') === AllocationType::Remainder->value)
                                                    <div class="text-xs text-gray-500 py-2.5 px-2 rounded-lg bg-gray-50 border border-gray-200 text-center">
                                                        {{ __('ما تبقى') }}
                                                    </div>
                                                @else
                                                    <div class="relative">
                                                        <input type="number" wire:model.live.debounce.500ms="lines.{{ $i }}.value"
                                                               dir="ltr" step="0.01" min="0" @disabled(! $canManage)
                                                               value="{{ $line['value'] ?? '' }}"
                                                               class="w-full rounded-lg border-gray-300 text-sm py-2 pe-10"
                                                               placeholder="0.00">
                                                        <span class="absolute inset-y-0 end-2 flex items-center text-[11px] text-gray-400 pointer-events-none">
                                                            {{ ($line['allocation_type'] ?? '') === AllocationType::Percentage->value ? '%' : __('ج.م') }}
                                                        </span>
                                                    </div>
                                                @endif
                                            </div>

                                            <div class="col-span-2 sm:col-span-1 flex justify-end">
                                                @can('revenue_routing.manage')
                                                    <button type="button" wire:click="removeLine({{ $i }})"
                                                            class="w-9 h-9 flex items-center justify-center rounded-lg text-gray-400 hover:text-red-600 hover:bg-red-50"
                                                            aria-label="{{ __('حذف السطر') }}">
                                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
                                                    </button>
                                                @endcan
                                            </div>
                                        </div>
                                    @endforeach
                                </div>

                                @can('revenue_routing.manage')
                                    <button type="button" wire:click="addLine"
                                            class="mt-3 inline-flex items-center gap-1 text-sm text-green-700 hover:text-green-800 font-medium">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                                        {{ __('إضافة سطر توزيع') }}
                                    </button>
                                @endcan
                            </div>

                            {{-- notes --}}
                            <div class="bg-white rounded-xl border border-gray-200 p-4">
                                <label class="block text-xs text-gray-600 mb-1">{{ __('ملاحظة للمراجع') }}</label>
                                <textarea wire:model="notes" rows="2" @disabled(! $canManage)
                                          class="w-full rounded-lg border-gray-300 text-sm"
                                          placeholder="{{ __('مثال: قرار الجمعية العمومية بتاريخ … بتخصيص 10% لصندوق التطوير') }}">{{ $notes }}</textarea>
                            </div>

                            {{-- overrides --}}
                            @if($editingEnum->supportsOverrides() && ! $scopeType)
                                <div class="bg-white rounded-xl border border-gray-200 p-4">
                                    <h3 class="text-sm font-semibold text-gray-800 mb-1">{{ __('تخصيص لصنف بعينه') }}</h3>
                                    <p class="text-xs text-gray-500 mb-3">
                                        {{ __('قاعدة تخص صنفاً واحداً وتسبق القاعدة الافتراضية له — مثل رسوم القيد التي يجب أن تذهب لحساب مستقل.') }}
                                    </p>

                                    @can('revenue_routing.manage')
                                        @if(! $showOverridePicker)
                                            <button type="button" wire:click="openOverridePicker"
                                                    class="inline-flex items-center gap-1 text-sm text-indigo-700 hover:text-indigo-800 font-medium">
                                                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"/></svg>
                                                {{ __('إضافة تخصيص') }}
                                            </button>
                                        @else
                                            <input type="text" wire:model.live.debounce.300ms="overrideSearch"
                                                   class="w-full rounded-lg border-gray-300 text-sm py-2 mb-2"
                                                   placeholder="{{ __('ابحث بالاسم…') }}">
                                            <div class="max-h-56 overflow-y-auto divide-y divide-gray-100 border border-gray-200 rounded-lg">
                                                @forelse($overrideCandidates as $candidate)
                                                    <button type="button" wire:click="chooseOverride({{ $candidate->id }})"
                                                            class="w-full text-start px-3 py-2 text-sm text-gray-700 hover:bg-indigo-50">
                                                        {{ $candidate->name_ar ?: $candidate->name }}
                                                    </button>
                                                @empty
                                                    <p class="px-3 py-3 text-xs text-gray-400">{{ __('لا توجد أصناف مطابقة') }}</p>
                                                @endforelse
                                            </div>
                                            <button type="button" wire:click="$set('showOverridePicker', false)"
                                                    class="mt-2 text-xs text-gray-500 hover:underline">{{ __('إلغاء') }}</button>
                                        @endif
                                    @endcan
                                </div>
                            @endif
                        </div>

                        {{-- ── right: the preview ────────────────────────── --}}
                        <div class="lg:col-span-2">
                            <div class="bg-white rounded-xl border border-gray-200 p-4 lg:sticky lg:top-4">
                                <h3 class="text-sm font-semibold text-gray-800 mb-1">{{ __('القيد الناتج') }}</h3>
                                <p class="text-xs text-gray-500 mb-3">
                                    {{ __('محسوب بنفس المحرك الذي يُرحِّل التحصيل فعلياً — لا محاكاة منفصلة.') }}
                                </p>

                                <label class="block text-xs text-gray-600 mb-1">{{ __('لو حصَّلنا الآن (ج.م)') }}</label>
                                <input type="number" wire:model.live.debounce.500ms="previewAmount" dir="ltr" step="0.01" min="0"
                                       value="{{ $previewAmount }}"
                                       class="w-full rounded-lg border-gray-300 text-sm py-2 mb-3">

                                @if($preview === null)
                                    <p class="text-xs text-gray-400 py-4 text-center">{{ __('أكمل السطور لعرض القيد') }}</p>
                                @elseif(isset($preview['error']))
                                    <div class="p-3 rounded-lg bg-red-50 border border-red-200 text-xs text-red-700">{{ $preview['error'] }}</div>
                                @else
                                    @php $allocation = $preview['allocation']; @endphp

                                    {{-- Laid out with flex and min-w-0 rather than a grid: an account
                                         name like "ضريبة القيمة المضافة المستحقة" is long, and in a
                                         narrow column a grid cell wraps it into four lines that push
                                         the figure out of alignment with the row above it. --}}
                                    <div class="rounded-lg border border-gray-200 overflow-hidden">
                                        <div class="flex items-center bg-gray-50 text-[11px] text-gray-500 font-medium">
                                            <div class="flex-1 px-2 py-1.5 text-start">{{ __('الحساب') }}</div>
                                            <div class="w-24 px-2 py-1.5 text-end">{{ __('مدين') }}</div>
                                            <div class="w-24 px-2 py-1.5 text-end">{{ __('دائن') }}</div>
                                        </div>

                                        {{-- the debit side: the money that arrived --}}
                                        <div class="flex items-center text-xs border-b border-gray-100 bg-green-50/40">
                                            <div class="flex-1 min-w-0 px-2 py-2 text-gray-800 font-medium truncate">{{ __('النقدية / البنك') }}</div>
                                            <div class="w-24 px-2 py-2 text-end font-semibold text-gray-900" dir="ltr">{{ format_money($allocation->gross) }}</div>
                                            <div class="w-24"></div>
                                        </div>

                                        @foreach($allocation->postings as $posting)
                                            <div class="flex items-center text-xs border-b border-gray-100 {{ $posting->isTax() ? 'bg-amber-50/50' : '' }}">
                                                <div class="flex-1 min-w-0 px-2 py-2 ps-5">
                                                    <div class="flex items-center gap-1.5">
                                                        <span class="font-mono text-gray-500 shrink-0" dir="ltr">{{ $posting->account->code }}</span>
                                                        <span class="text-gray-800 truncate" title="{{ $posting->account->name_ar ?: $posting->account->name }}">{{ $posting->account->name_ar ?: $posting->account->name }}</span>
                                                        @if($posting->isTax())
                                                            <span class="shrink-0 px-1 py-0.5 rounded bg-amber-100 text-amber-800 text-[10px]">{{ __('ضريبة') }}</span>
                                                        @endif
                                                    </div>
                                                </div>
                                                <div class="w-24"></div>
                                                <div class="w-24 px-2 py-2 text-end font-semibold text-gray-900" dir="ltr">{{ format_money($posting->amount) }}</div>
                                            </div>
                                        @endforeach

                                        <div class="flex items-center text-xs bg-gray-50 font-semibold">
                                            <div class="flex-1 min-w-0 px-2 py-2 text-gray-700">{{ __('الإجمالي') }}</div>
                                            <div class="w-24 px-2 py-2 text-end text-gray-900" dir="ltr">{{ format_money($allocation->gross) }}</div>
                                            <div class="w-24 px-2 py-2 text-end text-gray-900" dir="ltr">{{ format_money($allocation->totalPosted()) }}</div>
                                        </div>
                                    </div>

                                    <div class="mt-2 flex items-center gap-1.5 text-xs {{ $preview['balanced'] ? 'text-green-700' : 'text-red-700' }}">
                                        @if($preview['balanced'])
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>
                                            {{ __('القيد متوازن — المدين يساوي الدائن') }}
                                        @else
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01M5 19h14a2 2 0 001.84-2.75L13.74 4a2 2 0 00-3.48 0l-7.1 12.25A2 2 0 004.99 19z"/></svg>
                                            {{ __('القيد غير متوازن — لن يُسمح بالترحيل') }}
                                        @endif
                                    </div>

                                    @if($allocation->tax > 0)
                                        <div class="mt-2 text-[11px] text-gray-600 leading-relaxed">
                                            {{ __('صافي الإيراد') }} <span dir="ltr" class="font-semibold">{{ format_money($allocation->net) }}</span>
                                            · {{ __('ضريبة مستحقة') }} <span dir="ltr" class="font-semibold">{{ format_money($allocation->tax) }}</span>
                                        </div>
                                    @endif

                                    @foreach($allocation->warnings as $warning)
                                        <div class="mt-2 p-2 rounded-lg bg-amber-50 border border-amber-200 text-[11px] text-amber-800">{{ $warning }}</div>
                                    @endforeach
                                @endif
                            </div>
                        </div>
                    </div>

                    {{-- editor footer --}}
                    <div class="flex flex-col sm:flex-row sm:items-center justify-between gap-3 p-4 sm:p-5 bg-white rounded-b-2xl border-t border-gray-200">
                        <div>
                            @if($scopeType)
                                @can('revenue_routing.manage')
                                    <button type="button"
                                            wire:click="deleteOverride('{{ $editingSource }}', {{ (int) $scopeId }})"
                                            wire:confirm="{{ __('حذف هذا التخصيص وإعادة الصنف للقاعدة الافتراضية؟') }}"
                                            class="text-sm text-red-600 hover:text-red-700">
                                        {{ __('حذف التخصيص') }}
                                    </button>
                                @endcan
                            @endif
                        </div>

                        <div class="flex items-center gap-2">
                            <button type="button" wire:click="closeEditor"
                                    class="px-4 py-2 rounded-lg border border-gray-300 text-gray-700 text-sm hover:bg-gray-50">
                                {{ __('إغلاق') }}
                            </button>
                            @can('revenue_routing.manage')
                                <button type="button" wire:click="save" wire:loading.attr="disabled" wire:target="save"
                                        class="px-5 py-2 rounded-lg bg-green-600 text-white text-sm font-medium hover:bg-green-700 disabled:opacity-60 inline-flex items-center gap-2">
                                    <svg wire:loading wire:target="save" class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24">
                                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v4a4 4 0 00-4 4H4z"></path>
                                    </svg>
                                    <span wire:loading.remove wire:target="save">{{ __('حفظ القاعدة') }}</span>
                                    <span wire:loading wire:target="save">{{ __('جارٍ الحفظ…') }}</span>
                                </button>
                            @endcan
                        </div>
                    </div>
                </div>
            </div>
        </div>
    @endif
</div>
