<div>
    <div class="flex items-center justify-between mb-6">
        <h1 class="text-xl sm:text-2xl font-bold text-gray-800">{{ __('الفواتير') }}</h1>
        <div class="flex items-center gap-2">
            <a href="{{ route('export.invoices', array_filter(['status' => $status ?? '', 'search' => $search ?? ''])) }}"
               class="inline-flex items-center gap-2 px-3 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 text-sm 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 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>
                {{ __('تصدير CSV') }}
            </a>
            @can('invoices.create')
            <a href="{{ route('invoices.wizard') }}" wire:navigate
               class="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 text-sm 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>
                {{ __('إنشاء فاتورة') }}
            </a>
            @endcan
        </div>
    </div>

    {{-- Payment Summary Panel --}}
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-4">

        {{-- Controls row --}}
        <div class="flex flex-wrap items-center gap-2 mb-4">
            <span class="text-sm font-semibold text-gray-700">{{ __('ملخص المدفوعات') }}</span>

            {{-- Date presets --}}
            @php
                $presets = ['today' => 'اليوم', 'this_week' => 'هذا الأسبوع', 'this_month' => 'هذا الشهر', 'last_month' => 'الشهر الماضي', 'this_year' => 'هذا العام'];
                $presetStarts = [
                    'today'      => now()->toDateString(),
                    'this_week'  => now()->startOfWeek()->toDateString(),
                    'this_month' => now()->startOfMonth()->toDateString(),
                    'last_month' => now()->subMonthNoOverflow()->startOfMonth()->toDateString(),
                    'this_year'  => now()->startOfYear()->toDateString(),
                ];
            @endphp
            @foreach($presets as $preset => $presetLabel)
            @php $active = ($summaryFrom === $presetStarts[$preset]); @endphp
            <button type="button" wire:click="setSummaryPreset('{{ $preset }}')"
                    class="px-2.5 py-1 text-xs rounded-full border transition-colors {{ $active ? 'bg-blue-600 text-white border-blue-600' : 'bg-gray-50 text-gray-600 border-gray-200 hover:border-blue-300 hover:text-blue-600' }}">
                {{ $presetLabel }}
            </button>
            @endforeach

            {{-- Custom range --}}
            <input type="date" wire:model.live="summaryFrom" dir="ltr"
                   class="text-xs border border-gray-300 rounded-lg px-2 py-1 focus:ring-2 focus:ring-blue-400 focus:border-blue-400">
            <span class="text-gray-400 text-xs">—</span>
            <input type="date" wire:model.live="summaryTo" dir="ltr"
                   class="text-xs border border-gray-300 rounded-lg px-2 py-1 focus:ring-2 focus:ring-blue-400 focus:border-blue-400">

            {{-- Method selector --}}
            <div class="flex items-center gap-1.5 me-auto">
                <span class="text-xs text-gray-500">{{ __('مقارنة:') }}</span>
                <select wire:model.live="primaryMethod"
                        class="text-xs border border-gray-300 rounded-lg px-2 py-1 focus:ring-2 focus:ring-blue-400 focus:border-blue-400 bg-white">
                    @foreach($methodOptions as $val => $lbl)
                    <option value="{{ $val }}">{{ $lbl }}</option>
                    @endforeach
                </select>
                <span class="text-xs text-gray-500">{{ __('مقابل الباقي') }}</span>
            </div>
        </div>

        {{-- Comparison cards --}}
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-3 mb-4" wire:loading.class="opacity-50">
            {{-- Primary method card --}}
            @php
                $methodColors = [
                    'cash' => ['bg' => 'bg-green-50', 'border' => 'border-green-200', 'text' => 'text-green-700', 'amount' => 'text-green-800', 'badge' => 'bg-green-100 text-green-700'],
                    'card' => ['bg' => 'bg-blue-50', 'border' => 'border-blue-200', 'text' => 'text-blue-700', 'amount' => 'text-blue-800', 'badge' => 'bg-blue-100 text-blue-700'],
                    'bank_transfer' => ['bg' => 'bg-indigo-50', 'border' => 'border-indigo-200', 'text' => 'text-indigo-700', 'amount' => 'text-indigo-800', 'badge' => 'bg-indigo-100 text-indigo-700'],
                    'wallet' => ['bg' => 'bg-purple-50', 'border' => 'border-purple-200', 'text' => 'text-purple-700', 'amount' => 'text-purple-800', 'badge' => 'bg-purple-100 text-purple-700'],
                    'online' => ['bg' => 'bg-cyan-50', 'border' => 'border-cyan-200', 'text' => 'text-cyan-700', 'amount' => 'text-cyan-800', 'badge' => 'bg-cyan-100 text-cyan-700'],
                    'cheque' => ['bg' => 'bg-amber-50', 'border' => 'border-amber-200', 'text' => 'text-amber-700', 'amount' => 'text-amber-800', 'badge' => 'bg-amber-100 text-amber-700'],
                    'other' => ['bg' => 'bg-gray-50', 'border' => 'border-gray-200', 'text' => 'text-gray-600', 'amount' => 'text-gray-700', 'badge' => 'bg-gray-100 text-gray-600'],
                ];
                $pc = $methodColors[$primaryMethod] ?? $methodColors['other'];
                $primaryLabel = $methodOptions[$primaryMethod] ?? $primaryMethod;
                $primaryPct = $grandTotal > 0 ? round($primaryTotal / $grandTotal * 100) : 0;
                $otherPct   = 100 - $primaryPct;
            @endphp
            <div class="rounded-xl border {{ $pc['border'] }} {{ $pc['bg'] }} p-4">
                <div class="flex items-center justify-between mb-2">
                    <span class="text-sm font-semibold {{ $pc['text'] }}">{{ $primaryLabel }}</span>
                    <span class="text-xs px-2 py-0.5 rounded-full {{ $pc['badge'] }}">{{ $primaryPct }}%</span>
                </div>
                <p class="text-2xl font-bold {{ $pc['amount'] }}" dir="ltr">
                    {{ number_format($primaryTotal / 100, 2) }}
                    <span class="text-base font-medium">{{ __('ج.م') }}</span>
                </p>
                <p class="text-xs {{ $pc['text'] }} mt-1 opacity-75">{{ $primaryCount }} {{ __('مدفوعة') }}</p>
            </div>

            {{-- Divider / vs --}}
            <div class="hidden sm:flex flex-col items-center justify-center">
                <div class="w-px flex-1 bg-gray-200"></div>
                <span class="text-xs font-bold text-gray-400 py-2 px-3 bg-white border border-gray-200 rounded-full">VS</span>
                <div class="w-px flex-1 bg-gray-200"></div>
            </div>

            {{-- Other methods card --}}
            <div class="rounded-xl border border-gray-200 bg-gray-50 p-4">
                <div class="flex items-center justify-between mb-2">
                    <span class="text-sm font-semibold text-gray-600">{{ __('باقي الطرق') }}</span>
                    <span class="text-xs px-2 py-0.5 rounded-full bg-gray-200 text-gray-600">{{ $otherPct }}%</span>
                </div>
                <p class="text-2xl font-bold text-gray-700" dir="ltr">
                    {{ number_format($otherTotal / 100, 2) }}
                    <span class="text-base font-medium">{{ __('ج.م') }}</span>
                </p>
                <p class="text-xs text-gray-500 mt-1">{{ $otherCount }} {{ __('مدفوعة') }}</p>
            </div>
        </div>

        {{-- Full breakdown bar --}}
        @php
            $maxBreakdown = $breakdown->max('total') ?: 1;
        @endphp
        <div class="border-t border-gray-100 pt-3" wire:loading.class="opacity-50">
            <p class="text-xs font-medium text-gray-500 mb-2">{{ __('تفصيل كل الطرق') }}</p>
            <div class="grid grid-cols-2 sm:grid-cols-4 gap-x-4 gap-y-2">
                @foreach($breakdown->sortByDesc('total') as $method)
                @if($method['total'] > 0)
                @php
                    $mc = $methodColors[$method['value']] ?? $methodColors['other'];
                    $barPct = round($method['total'] / $maxBreakdown * 100);
                    $barColors = [
                        'cash' => '#16a34a', 'card' => '#2563eb', 'bank_transfer' => '#4f46e5',
                        'wallet' => '#9333ea', 'online' => '#0891b2', 'cheque' => '#d97706', 'other' => '#6b7280',
                    ];
                    $barColor = $barColors[$method['value']] ?? '#6b7280';
                @endphp
                <div>
                    <div class="flex items-center justify-between text-xs mb-0.5">
                        <span class="font-medium {{ $mc['text'] }}">{{ $method['label'] }}</span>
                        <span class="text-gray-500" dir="ltr">{{ number_format($method['total'] / 100, 2) }}</span>
                    </div>
                    <div class="h-1.5 rounded-full bg-gray-100 overflow-hidden">
                        <div class="h-full rounded-full" style="width: {{ $barPct }}%; background-color: {{ $barColor }};"></div>
                    </div>
                    <p class="text-xs text-gray-400 mt-0.5">{{ $method['count'] }} {{ __('مدفوعة') }}</p>
                </div>
                @endif
                @endforeach
                @if($breakdown->every(fn($m) => $m['total'] === 0))
                <p class="col-span-4 text-xs text-gray-400 text-center py-2">{{ __('لا توجد مدفوعات في هذه الفترة') }}</p>
                @endif
            </div>
        </div>

        {{-- Grand total --}}
        <div class="flex items-center justify-between mt-3 pt-3 border-t border-gray-100">
            <span class="text-sm text-gray-500">{{ __('إجمالي المدفوعات') }}</span>
            <span class="text-base font-bold text-gray-800" dir="ltr">
                {{ number_format($grandTotal / 100, 2) }} {{ __('ج.م') }}
            </span>
        </div>
    </div>

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

    {{-- Filters --}}
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 p-4 mb-4">
        <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
            <div class="sm:col-span-2">
                <input type="text" wire:model.live.debounce.300ms="search"
                       placeholder="{{ __('بحث برقم الفاتورة أو اسم العميل...') }}"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
            </div>
            <select wire:model.live="status" class="px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500">
                <option value="">{{ __('كل الحالات') }}</option>
                @foreach($statusOptions as $value => $label)
                <option value="{{ $value }}">{{ $label }}</option>
                @endforeach
            </select>
        </div>
    </div>

    {{-- Table --}}
    <div class="bg-white rounded-xl shadow-sm border border-gray-200 overflow-hidden">
        <div wire:loading.class="opacity-50 pointer-events-none">
            <table class="w-full text-sm">
                <thead class="bg-gray-50 border-b border-gray-200">
                    <tr>
                        <th class="px-4 py-3 text-start font-medium text-gray-600">{{ __('رقم الفاتورة') }}</th>
                        <th class="px-4 py-3 text-start font-medium text-gray-600">{{ __('العميل') }}</th>
                        <th class="px-4 py-3 text-center font-medium text-gray-600">{{ __('الإجمالي') }}</th>
                        <th class="px-4 py-3 text-center font-medium text-gray-600">{{ __('المدفوع') }}</th>
                        <th class="px-4 py-3 text-center font-medium text-gray-600">{{ __('المتبقي') }}</th>
                        <th class="px-4 py-3 text-center font-medium text-gray-600">{{ __('الحالة') }}</th>
                        <th class="px-4 py-3 text-center font-medium text-gray-600">{{ __('تاريخ الإصدار') }}</th>
                        <th class="px-4 py-3 text-center font-medium text-gray-600">{{ __('إجراءات') }}</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-100">
                    @forelse($invoices as $invoice)
                    <tr class="hover:bg-gray-50">
                        <td class="px-4 py-3 font-mono text-gray-600" dir="ltr">
                            {{ $invoice->number ?? '—' }}
                        </td>
                        <td class="px-4 py-3">
                            @php
                                $displayName = $invoice->contact_name
                                    ?? $invoice->billable?->person?->name_ar
                                    ?? $invoice->billable?->name_ar
                                    ?? '—';
                            @endphp
                            @if($invoice->billable_type === 'App\\Domain\\Participant\\Models\\Participant' && $invoice->billable)
                            <a href="{{ route('participants.show', $invoice->billable) }}" wire:navigate class="text-blue-600 hover:text-blue-800 hover:underline font-medium">{{ $displayName }}</a>
                            @else
                            <span class="font-medium text-gray-800">{{ $displayName }}</span>
                            @endif
                        </td>
                        <td class="px-4 py-3 text-center font-medium" dir="ltr">
                            {{ number_format($invoice->total_amount / 100, 2) }} {{ __('ج.م') }}
                        </td>
                        <td class="px-4 py-3 text-center text-green-600" dir="ltr">
                            {{ number_format($invoice->paid_amount / 100, 2) }} {{ __('ج.م') }}
                        </td>
                        <td class="px-4 py-3 text-center text-red-600" dir="ltr">
                            {{ number_format($invoice->due_amount / 100, 2) }} {{ __('ج.م') }}
                        </td>
                        <td class="px-4 py-3 text-center">
                            @php
                                $statusValue = $invoice->status->value ?? $invoice->status;
                                $statusColors = [
                                    'draft' => 'gray',
                                    'pending' => 'yellow',
                                    'awaiting_approval' => 'amber',
                                    'sent' => 'blue',
                                    'partially_paid' => 'amber',
                                    'paid' => 'green',
                                    'overpaid' => 'emerald',
                                    'overdue' => 'red',
                                    'cancelled' => 'gray',
                                    'refunded' => 'purple',
                                    'partially_refunded' => 'violet',
                                    'written_off' => 'slate',
                                    'disputed' => 'orange',
                                ];
                                $color = $statusColors[$statusValue] ?? 'gray';
                            @endphp
                            <span class="px-2 py-0.5 text-xs bg-{{ $color }}-100 text-{{ $color }}-700 rounded-full">
                                {{ $invoice->status->label() }}
                            </span>
                        </td>
                        <td class="px-4 py-3 text-center text-gray-600" dir="ltr">
                            {{ $invoice->issue_date?->format('Y-m-d') }}
                        </td>
                        <td class="px-4 py-3 text-center space-x-2 space-x-reverse">
                            @can('invoices.view')
                            <a href="{{ route('invoices.show', $invoice) }}" wire:navigate
                               class="text-blue-600 hover:text-blue-800 text-sm">{{ __('عرض') }}</a>
                            @endcan
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="8" class="px-4 py-12 text-center">
                            <div class="flex flex-col items-center">
                                <svg class="w-12 h-12 text-gray-300 mb-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/>
                                </svg>
                                <p class="text-gray-500 text-sm">{{ __('لا توجد فواتير') }}</p>
                                @can('invoices.create')
                                <a href="{{ route('invoices.wizard') }}" wire:navigate
                                   class="mt-2 text-blue-600 hover:text-blue-800 text-sm font-medium">
                                    {{ __('إنشاء أول فاتورة') }}
                                </a>
                                @endcan
                            </div>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        @if($invoices->hasPages())
        <div class="px-4 py-3 border-t border-gray-200">
            {{ $invoices->links() }}
        </div>
        @endif
    </div>
</div>
