@extends('layouts.admin')

@section('title', 'Orders')

@section('content')
@php
    $perPageValue = (int) ($perPage ?? request('per_page', 10));
    $baseExceptStatus = request()->except(['status', 'payment_status', 'filter', 'shipment_status', 'page']);
    $dateFilterOptions = [
        '' => 'All Time',
        'today' => 'Today',
        'yesterday' => 'Yesterday',
        'last_7_days' => 'Last 7 Days',
        'last_month' => 'Last Month',
        'last_year' => 'Last Year',
        'custom' => 'Custom Range',
    ];
    $currentDateFilter = (string) request('date_filter', '');
    $currentDateLabel = $dateFilterOptions[$currentDateFilter] ?? 'All Time';
    if ($currentDateFilter === 'custom' && (request('date_from') || request('date_to'))) {
        $currentDateLabel = trim((request('date_from') ?: '…') . ' to ' . (request('date_to') ?: '…'));
    }
@endphp

<div class="orders-index-page tw-migrated space-y-3">
<div class="admin-page-header">
    <div class="d-flex justify-content-between align-items-center w-100">
        <div>
            <h1 class="admin-page-title">Orders Management</h1>
            <p class="admin-page-subtitle">Manage and track customer orders</p>
        </div>
    </div>
</div>

<div class="admin-content">
    <div class="admin-status-filters-card mb-2">
        <div class="orders-filter-toolbar">
            <div class="orders-filter-toolbar__sources">
                <span class="source-filter-label">Source</span>
                <div class="status-filter-pills-container source-pos">
                    @php
                        $sourceBaseParams = request()->except('source');
                        $sourceBaseUrl = route('admin.orders.index');
                    @endphp
                    <a href="{{ $sourceBaseParams ? $sourceBaseUrl . '?' . http_build_query($sourceBaseParams) : $sourceBaseUrl }}"
                       class="source-filter-pill pill-white source-pill {{ !request('source') ? 'active' : '' }}"
                       data-source="">
                        <i class="bi bi-layers"></i> All
                    </a>
                    <a href="{{ $sourceBaseUrl . '?' . http_build_query(array_merge($sourceBaseParams, ['source' => 'pos'])) }}"
                       class="source-filter-pill pill-white source-pill {{ request('source') == 'pos' ? 'active' : '' }}"
                       data-source="pos">
                        <i class="bi bi-shop"></i> POS
                    </a>
                    <a href="{{ $sourceBaseUrl . '?' . http_build_query(array_merge($sourceBaseParams, ['source' => 'online'])) }}"
                       class="source-filter-pill pill-white source-pill {{ request('source') == 'online' ? 'active' : '' }}"
                       data-source="online">
                        <i class="bi bi-globe"></i> Online
                    </a>
                    <a href="{{ $sourceBaseUrl . '?' . http_build_query(array_merge($sourceBaseParams, ['source' => 'pos_to_online'])) }}"
                       class="source-filter-pill pill-white source-pill {{ request('source') == 'pos_to_online' ? 'active' : '' }}"
                       data-source="pos_to_online">
                        <i class="bi bi-arrow-left-right"></i> POS to Online
                    </a>
                </div>
            </div>

            <form method="GET" action="{{ route('admin.orders.index') }}" class="orders-filter-toolbar__form">
                @if(request('per_page'))
                    <input type="hidden" name="per_page" value="{{ request('per_page') }}">
                @endif
                @if(request('source'))
                    <input type="hidden" name="source" value="{{ request('source') }}">
                @endif
                @if(request('status'))
                    <input type="hidden" name="status" value="{{ request('status') }}">
                @endif
                @if(request('payment_status'))
                    <input type="hidden" name="payment_status" value="{{ request('payment_status') }}">
                @endif
                @if(request('filter'))
                    <input type="hidden" name="filter" value="{{ request('filter') }}">
                @endif
                @if(request('shipment_status'))
                    <input type="hidden" name="shipment_status" value="{{ request('shipment_status') }}">
                @endif

                <div class="orders-filter-fields">
                    @if(isset($locations) && $locations->count())
                    <div class="orders-filter-field orders-filter-field--shop">
                        <label for="location_id" class="admin-form-label">Shop</label>
                        <select name="location_id" id="location_id" class="form-select admin-form-control" onchange="this.form.submit()">
                            @if(!empty($canViewAllShops))
                                <option value="all" @selected(($locationId ?? null) === null)>All shops</option>
                            @endif
                            @foreach($locations as $loc)
                                <option value="{{ $loc->id }}" @selected(($locationId ?? null) == $loc->id)>
                                    {{ $loc->name }}{{ $loc->type === 'warehouse' ? ' (WH)' : '' }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    @endif
                    <div class="orders-filter-field orders-filter-field--search">
                        <label for="search" class="admin-form-label">Search</label>
                        <input type="text"
                               name="search"
                               id="search"
                               class="form-control admin-form-control"
                               value="{{ request('search', request('order_id') ?? request('customer_phone') ?? request('awb_number')) }}"
                               placeholder="Order ID, phone, or AWB">
                    </div>
                    <div class="orders-filter-field orders-filter-field--date">
                        <label for="dateFilterTrigger" class="admin-form-label">Date</label>
                        <div class="dropdown orders-date-dropdown">
                            <button type="button"
                                    class="form-select admin-form-control orders-date-trigger text-start"
                                    id="dateFilterTrigger"
                                    data-bs-toggle="dropdown"
                                    data-bs-auto-close="outside"
                                    aria-expanded="false">
                                <i class="bi bi-calendar3"></i>
                                <span id="dateFilterLabel">{{ $currentDateLabel }}</span>
                            </button>
                            <div class="dropdown-menu dropdown-menu-end orders-date-popup" aria-labelledby="dateFilterTrigger">
                                <input type="hidden" name="date_filter" id="date_filter" value="{{ $currentDateFilter }}">
                                <div class="orders-date-popup__title">Date range</div>
                                <div class="orders-date-presets">
                                    @foreach($dateFilterOptions as $value => $label)
                                        <button type="button"
                                                class="orders-date-preset {{ $currentDateFilter === (string) $value ? 'active' : '' }}"
                                                data-value="{{ $value }}"
                                                data-label="{{ $label }}">
                                            {{ $label }}
                                        </button>
                                    @endforeach
                                </div>
                                <div class="row g-2 mt-2" id="ordersDateCustomFields" style="display: {{ $currentDateFilter === 'custom' ? 'flex' : 'none' }};">
                                    <div class="col-6" id="startDateDiv">
                                        <label for="date_from" class="admin-form-label">From</label>
                                        <input type="date" name="date_from" id="date_from" class="form-control admin-form-control" value="{{ request('date_from') }}">
                                    </div>
                                    <div class="col-6" id="endDateDiv">
                                        <label for="date_to" class="admin-form-label">To</label>
                                        <input type="date" name="date_to" id="date_to" class="form-control admin-form-control" value="{{ request('date_to') }}">
                                    </div>
                                </div>
                                <div class="d-flex gap-2 mt-3">
                                    <button type="submit" class="btn btn-primary btn-sm flex-grow-1">
                                        <i class="bi bi-funnel"></i> Filter
                                    </button>
                                    <a href="{{ route('admin.orders.index', ['per_page' => $perPageValue]) }}" title="Reset Filters" class="btn btn-outline-secondary btn-sm">
                                        <i class="bi bi-arrow-clockwise"></i>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="orders-filter-field orders-filter-field--actions">
                        <label class="admin-form-label">&nbsp;</label>
                        <div class="d-flex gap-2">
                            <button type="submit" class="btn btn-primary text-nowrap">
                                <i class="bi bi-funnel"></i> Filter
                            </button>
                            <a href="{{ route('admin.orders.index', ['per_page' => $perPageValue]) }}" title="Reset Filters" class="btn btn-outline-secondary">
                                <i class="bi bi-arrow-clockwise"></i>
                            </a>
                        </div>
                    </div>
                </div>
            </form>
        </div>

        <div class="status-filter-pills-container mt-3">
            <div class="status-filter-label w-100 mb-1">Status</div>
            <a href="{{ route('admin.orders.index', array_merge($baseExceptStatus, ['per_page' => $perPageValue])) }}"
               class="status-filter-pill pill-all {{ !request('status') && !request('payment_status') && !request('filter') ? 'active' : '' }}"
               data-filter-type="all">
               <i class="bi bi-layers"></i> All Orders ({{ $statusCounts['all_orders'] }})
            </a>
            <a href="{{ route('admin.orders.index', array_merge($baseExceptStatus, ['status' => 'awaiting_payment', 'per_page' => $perPageValue])) }}"
               class="status-filter-pill pill-yellow {{ request('status') == 'awaiting_payment' ? 'active' : '' }}"
               data-filter-type="status"
               data-filter-value="awaiting_payment">
               <i class="bi bi-credit-card"></i> Awaiting Payment ({{ $statusCounts['awaiting_payment'] }})
            </a>
            <a href="{{ route('admin.orders.index', array_merge($baseExceptStatus, ['status' => 'placed', 'per_page' => $perPageValue])) }}"
               class="status-filter-pill pill-purple {{ request('status') == 'placed' ? 'active' : '' }}"
               data-filter-type="status"
               data-filter-value="placed">
               <i class="bi bi-box"></i> Order Placed ({{ $statusCounts['order_placed'] }})
            </a>
            <a href="{{ route('admin.orders.index', array_merge($baseExceptStatus, ['status' => 'confirmed', 'per_page' => $perPageValue])) }}"
               class="status-filter-pill pill-blue {{ request('status') == 'confirmed' ? 'active' : '' }}"
               data-filter-type="status"
               data-filter-value="confirmed">
               <i class="bi bi-boxes"></i> Order Confirmed ({{ $statusCounts['order_confirmed'] }})
            </a>
            <a href="{{ route('admin.orders.index', array_merge($baseExceptStatus, ['status' => 'packed', 'per_page' => $perPageValue])) }}"
               class="status-filter-pill pill-white {{ request('status') == 'packed' ? 'active' : '' }}"
               data-filter-type="status"
               data-filter-value="packed">
               <i class="bi bi-archive"></i> Order Packed ({{ $statusCounts['order_packed'] }})
            </a>
            <a href="{{ route('admin.orders.index', array_merge($baseExceptStatus, ['status' => 'awaiting_pickup', 'per_page' => $perPageValue])) }}"
               class="status-filter-pill pill-white {{ request('status') == 'awaiting_pickup' ? 'active' : '' }}"
               data-filter-type="status"
               data-filter-value="awaiting_pickup">
               <i class="bi bi-truck"></i> Shipment Created ({{ $statusCounts['shipment_created'] }})
            </a>
            <a href="{{ route('admin.orders.index', array_merge($baseExceptStatus, ['status' => 'shipped', 'per_page' => $perPageValue])) }}"
               class="status-filter-pill pill-white {{ request('status') == 'shipped' ? 'active' : '' }}"
               data-filter-type="status"
               data-filter-value="shipped">
               <i class="bi bi-truck"></i> Shipped ({{ $statusCounts['shipped'] }})
            </a>
            <a href="{{ route('admin.orders.index', array_merge($baseExceptStatus, ['status' => 'delivery_failed', 'per_page' => $perPageValue])) }}"
               class="status-filter-pill pill-yellow {{ request('status') == 'delivery_failed' ? 'active' : '' }}"
               data-filter-type="status"
               data-filter-value="delivery_failed">
               <i class="bi bi-exclamation-triangle"></i> Delivery Failed ({{ $statusCounts['delivery_failed'] }})
            </a>
            <a href="{{ route('admin.orders.index', array_merge($baseExceptStatus, ['status' => 'delivered', 'per_page' => $perPageValue])) }}"
               class="status-filter-pill pill-green {{ request('status') == 'delivered' ? 'active' : '' }}"
               data-filter-type="status"
               data-filter-value="delivered">
               <i class="bi bi-check-circle"></i> Completed ({{ $statusCounts['completed'] }})
            </a>
            <a href="{{ route('admin.orders.index', array_merge($baseExceptStatus, ['status' => 'returned', 'per_page' => $perPageValue])) }}"
               class="status-filter-pill pill-red {{ request('status') == 'returned' ? 'active' : '' }}"
               data-filter-type="status"
               data-filter-value="returned">
               <i class="bi bi-arrow-return-left"></i> Returned ({{ $statusCounts['returned'] }})
            </a>
            <a href="{{ route('admin.orders.index', array_merge($baseExceptStatus, ['status' => 'lost', 'per_page' => $perPageValue])) }}"
               class="status-filter-pill pill-red {{ request('status') == 'lost' ? 'active' : '' }}"
               data-filter-type="status"
               data-filter-value="lost">
               <i class="bi bi-box-seam"></i> Lost ({{ $statusCounts['lost'] }})
            </a>
            <a href="{{ route('admin.orders.index', array_merge($baseExceptStatus, ['filter' => 'cancelled_failed', 'per_page' => $perPageValue])) }}"
               class="status-filter-pill pill-red {{ request('filter') == 'cancelled_failed' ? 'active' : '' }}"
               data-filter-type="filter"
               data-filter-value="cancelled_failed">
               <i class="bi bi-x-octagon"></i> Cancelled / Failed ({{ $statusCounts['cancelled_failed'] }})
            </a>
        </div>

        @if(!empty($showShipmentFilter) && !empty($shipmentStatusCounts))
        <div class="status-filter-pills-container mt-3">
            <div class="status-filter-label w-100 mb-1">Shipment Status</div>
            @php
                $shipmentBaseExcept = ['shipment_status', 'page'];
            @endphp
            <a href="{{ route('admin.orders.index', array_merge(request()->except($shipmentBaseExcept), ['per_page' => $perPageValue])) }}"
               class="status-filter-pill pill-all {{ !request('shipment_status') ? 'active' : '' }}">
               <i class="bi bi-layers"></i> All ({{ $shipmentStatusCounts['all'] ?? 0 }})
            </a>
            @foreach($shipmentStatusCounts as $normalizedKey => $count)
                @if($normalizedKey === 'all')
                    @continue
                @endif
                <a href="{{ route('admin.orders.index', array_merge(request()->except($shipmentBaseExcept), ['shipment_status' => $normalizedKey, 'per_page' => $perPageValue])) }}"
                   class="status-filter-pill pill-white {{ request('shipment_status') === $normalizedKey ? 'active' : '' }}">
                   <i class="bi bi-truck"></i> {{ ucwords($normalizedKey) }} ({{ $count }})
                </a>
            @endforeach
        </div>
        @endif
    </div>


    <!-- Orders Table -->
    <div class="admin-table-card">
        <div class="table-responsive">
            <table class="table admin-table">
                <thead>
                    <tr>
                        <th>Order ID</th>
                        <th>Customer</th>
                        <th>Date</th>
                        <th>Total</th>
                        <th>Status</th>
                        <th>Payment</th>
                        <th>Source</th>
                        <th>Shipping Details</th>
                        <th>Shipping Status</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($orders as $order)
                    <tr>
                        <td>
                            <span class="fw-bold" style="color: var(--admin-primary);">#{{ $order->id }}</span>
                        </td>
                        <td>
                            @php
                                $customerName = $order->user->name
                                    ?? data_get($order->address_snapshot, 'name')
                                    ?? 'Guest User';
                                $customerMobile = $order->user->mobile
                                    ?? data_get($order->address_snapshot, 'mobile')
                                    ?? data_get($order->address_snapshot, 'phone')
                                    ?? data_get($order->address_snapshot, 'contact')
                                    ?? 'N/A';
                                $avatarInitial = strtoupper(substr((string) $customerName, 0, 1));
                                if ($avatarInitial === '') {
                                    $avatarInitial = 'G';
                                }
                                $avatarColors = config('services.admin_ui.customer_avatar_colors', ['#2563EB', '#10B981', '#F59E0B', '#8B5CF6', '#EC4899', '#14B8A6']);
                                $avatarSeed = (string) ($order->user_id ?? $order->id);
                                $avatarIndex = (int) (sprintf('%u', crc32($avatarSeed)) % max(count($avatarColors), 1));
                                $avatarColor = $avatarColors[$avatarIndex] ?? '#2563EB';
                            @endphp
                            <div class="d-flex align-items-center">
                                <div class="me-2" style="width: 40px; height: 40px; min-width: 40px;">
                                    <div class="d-flex align-items-center justify-content-center text-white rounded-circle"
                                         style="width: 40px; height: 40px; font-size: 16px; font-weight: 600; background-color: {{ $avatarColor }};">
                                        {{ $avatarInitial }}
                                    </div>
                                </div>
                                <div>
                                    <div class="fw-medium">{{ $customerName }}</div>
                                    <small class="text-muted">{{ $customerMobile }}</small>
                                </div>
                            </div>
                        </td>
                        <td class="text-nowrap">
                            <div>{{ $order->created_at->format('M d, Y') }}</div>
                            <small class="text-muted">{{ $order->created_at->format('h:i A') }}</small>
                        </td>
                        <td>
                            <span class="fw-bold text-success">₹{{ number_format($order->total_payable, 2) }}</span>
                        </td>
                        <td>
                            @php
                                // All statuses use same default color
                                $statusClass = 'badge-modern-info';
                                if($order->status == 'delivered') $statusClass = 'badge-modern-success';
                                elseif($order->status == 'placed' || $order->status == 'awaiting_payment' || $order->status == 'awaiting_pickup') $statusClass = 'badge-modern-warning';
                                elseif($order->status == 'cancelled' || $order->status == 'returned' || $order->status == 'lost') $statusClass = 'badge-modern-danger';
                                elseif($order->status == 'delivery_failed') $statusClass = 'badge-modern-warning';
                                elseif($order->status == 'shipped') $statusClass = 'badge-modern-info';
                                elseif($order->status == 'confirmed') $statusClass = 'badge-modern-primary';
                            @endphp
                            <span class="badge-modern {{ $statusClass }}">
                                {{ ucfirst($order->status_label) }}
                            </span>
                        </td>
                        <td>
                            @php
                                $paymentClass = 'badge-modern-primary';
                                if($order->isCodOrder()) $paymentClass = 'badge-modern-info';
                                elseif($order->isAbandonedPayment()) $paymentClass = 'badge-modern-danger';
                                elseif($order->payment_status == 'paid') $paymentClass = 'badge-modern-success';
                                elseif($order->payment_status == 'failed') $paymentClass = 'badge-modern-danger';
                                elseif($order->payment_status == 'pending') $paymentClass = 'badge-modern-warning';
                            @endphp
                            <span class="badge-modern {{ $paymentClass }}">
                                @if($order->isCodOrder())
                                    <i class="bi bi-cash-coin"></i>
                                @elseif($order->isAbandonedPayment())
                                    <i class="bi bi-x-circle"></i>
                                @elseif($order->payment_status == 'paid')
                                    <i class="bi bi-check-circle"></i>
                                @elseif($order->payment_status == 'failed')
                                    <i class="bi bi-exclamation-triangle"></i>
                                @else
                                    <i class="bi bi-clock"></i>
                                @endif
                                {{ $order->getPaymentStatusDisplay() }}
                            </span>
                        </td>
                        <td>
                            @php
                                $source = $order->source ?? 'online';
                                $isPos = $source === 'pos';
                                $isPosToOnline = $source === 'pos_to_online';
                            @endphp
                            <span class="badge-modern {{ $isPosToOnline ? 'badge-modern-warning' : ($isPos ? 'badge-modern-info' : 'badge-modern-success') }}">
                                <i class="bi bi-{{ $isPosToOnline ? 'cart-check' : ($isPos ? 'shop' : 'globe') }}"></i>
                                {{ $isPosToOnline ? 'POS to Online' : ($isPos ? 'POS' : 'Online') }}
                            </span>
                        </td>
                        @php
                            $latestShipment = $order->shipments->sortByDesc('created_at')->first();
                            $shippingType = $latestShipment?->carrier?->name;
                            $awbNumber = $latestShipment?->tracking_id ?? $order->delhivery_awb ?? '—';
                            $shipmentStatus = $latestShipment?->status;
                        @endphp

                        <td>
                            @if($shippingType) <span class="text-muted">{{ $shippingType }}</span><br> @endif
                            <span class="font-monospace small text-muted">{{ $awbNumber }}</span>
                        </td>
                        <td>
                            @if($shipmentStatus)
                                @php
                                    $shipmentStatusClass = 'badge-modern-info';
                                    if (in_array($shipmentStatus, ['created', 'delivered'], true)) {
                                        $shipmentStatusClass = 'badge-modern-success';
                                    } elseif ($shipmentStatus === 'failed') {
                                        $shipmentStatusClass = 'badge-modern-danger';
                                    } elseif ($shipmentStatus === 'pending') {
                                        $shipmentStatusClass = 'badge-modern-warning';
                                    }
                                @endphp
                                <span class="badge-modern {{ $shipmentStatusClass }}">
                                    {{ ucwords($shipmentStatus) }}
                                </span>
                            @else
                                <span class="text-muted">—</span>
                            @endif
                        </td>
                        <td>
                            <div class="d-flex gap-2">
                                <a href="{{ route('admin.orders.show', $order) }}" 
                                    class="admin-action-btn admin-action-btn-sm" 
                                    style="background: #10b981; color: white; width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; padding: 0;"
                                    target="_blank"
                                    title="View">
                                    <i class="bi bi-eye"></i>
                                </a>
                                <a href="{{ route('admin.orders.invoice.print', $order) }}"
                                    class="admin-action-btn admin-action-btn-sm"
                                    style="background: #0f766e; color: white; width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; padding: 0;"
                                    target="_blank"
                                    title="Print Invoice">
                                    <i class="bi bi-printer"></i>
                                </a>
                                @if($order->status == 'awaiting_payment' || $order->status == 'placed' || $order->status == 'confirmed')
                                <!-- <a href="#" 
                                    class="admin-action-btn admin-action-btn-sm admin-btn-primary"
                                    style="background: #ef4444; height: -webkit-fill-available; color: white; width: 36px; height: 36px; display: flex; align-items: center; justify-content: center; padding: 0;"
                                    title="Cancel Order">
                                    <i class="bi bi-x-circle"></i>
                                </a> -->
                                @endif
                            </div>
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="10" class="text-center py-5">
                            <div class="empty-state">
                                <i class="bi bi-cart-x empty-state-icon"></i>
                                <h5 class="empty-state-title">No Orders Found</h5>
                                <p class="empty-state-description">No orders match your current filters. Try adjusting your search or filter criteria.</p>
                            </div>
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- Pagination - Right Aligned -->
            <div class="pagination-wrapper d-flex justify-content-between mt-4">

            <div class="align-items-center gap-2">
                    <label for="ordersPerPage" class="mb-0 small text-muted">Per page</label>
                    <form method="GET" action="{{ route('admin.orders.index') }}" class="d-inline">
                        @foreach(request()->except(['per_page', 'page']) as $key => $value)
                            @if(is_array($value))
                                @foreach($value as $item)
                                    <input type="hidden" name="{{ $key }}[]" value="{{ $item }}">
                                @endforeach
                            @else
                                <input type="hidden" name="{{ $key }}" value="{{ $value }}">
                            @endif
                        @endforeach
                        <select id="ordersPerPage" name="per_page" class="form-select form-select-sm" style="width: auto;" onchange="this.form.submit()">
                            @foreach(($allowedPerPage ?? [10, 20, 50, 100]) as $size)
                                <option value="{{ $size }}" {{ (int)($perPage ?? request('per_page', 10)) === (int)$size ? 'selected' : '' }}>{{ $size }}</option>
                            @endforeach
                        </select>
                        
                    </form>
                </div>
            <div class="d-flex justify-content-end align-items-center gap-3 flex-wrap">
                <div class="pagination-info-text">
                    Showing <strong>{{ $orders->firstItem() ?? 0 }}</strong>–<strong>{{ $orders->lastItem() ?? 0 }}</strong> 
                    of <strong>{{ $orders->total() }}</strong> orders
                </div>
                @if($orders->hasPages())
                <div class="pagination-controls">
                    {{ $orders->links('vendor.pagination.admin-categories') }}
                </div>
                @endif
            </div>
        </div>
    </div>
</div>
</div>

@push('styles')
<style>
.orders-index-page .admin-page-header {
    position: relative;
    margin-bottom: 0.35rem;
}

.orders-index-page .admin-page-title {
    font-family: var(--font-display, "Fraunces", serif);
    font-size: clamp(1.35rem, 1.1rem + 0.7vw, 1.75rem);
    letter-spacing: -0.02em;
}

.orders-index-page .orders-filter-toolbar {
    display: flex;
    flex-wrap: nowrap;
    align-items: flex-end;
    justify-content: space-between;
    gap: 0.75rem;
}

.orders-index-page .orders-filter-toolbar__sources {
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    gap: 0.25rem;
    flex: 0 0 auto;
}

.orders-index-page .orders-filter-toolbar .source-filter-label {
    font-weight: 600;
    color: #4b5563;
    font-size: 12px;
    letter-spacing: 0;
    text-transform: none;
    margin-bottom: 0;
    line-height: 1.2;
}

.orders-index-page .orders-filter-toolbar__form {
    flex: 0 1 auto;
    min-width: 0;
    margin-left: auto;
}

.orders-index-page .orders-filter-fields {
    display: flex;
    flex-wrap: nowrap;
    align-items: flex-end;
    justify-content: flex-end;
    gap: 0.5rem;
}

.orders-index-page .orders-filter-field {
    min-width: 0;
}

.orders-index-page .orders-filter-field--shop {
    flex: 0 1 140px;
}

.orders-index-page .orders-filter-field--search {
    flex: 0 1 180px;
    max-width: 180px;
}

.orders-index-page .orders-filter-field--date {
    flex: 0 0 150px;
}

.orders-index-page .orders-filter-field--actions {
    flex: 0 0 auto;
}

.orders-index-page .orders-filter-field--shop .form-select,
.orders-index-page .orders-filter-field--search .form-control,
.orders-index-page .orders-filter-field--date .orders-date-trigger {
    width: 100%;
}

@media (max-width: 1399.98px) {
    .orders-index-page .orders-filter-toolbar {
        flex-wrap: wrap;
        gap: 0.75rem;
    }

    .orders-index-page .orders-filter-toolbar__sources,
    .orders-index-page .orders-filter-toolbar__form {
        flex: 1 1 100%;
        width: 100%;
        margin-left: 0;
    }

    .orders-index-page .orders-filter-fields {
        justify-content: flex-end;
    }

    .orders-index-page .source-pos {
        flex-wrap: wrap;
        max-width: 100%;
    }
}

@media (max-width: 1024px) {
    .orders-index-page .orders-filter-field--shop {
        flex: 0 1 120px;
    }

    .orders-index-page .orders-filter-field--search {
        flex: 0 1 150px;
        max-width: 150px;
    }

    .orders-index-page .orders-filter-field--date {
        flex: 0 1 128px;
    }

    .orders-index-page .source-filter-pill i {
        display: none;
    }

    .orders-index-page .orders-date-popup {
        width: min(280px, calc(100vw - 2rem));
    }
}

@media (max-width: 767.98px) {
    .orders-index-page .orders-filter-fields {
        flex-wrap: wrap;
    }

    .orders-index-page .orders-filter-field--shop,
    .orders-index-page .orders-filter-field--search {
        flex: 1 1 calc(50% - 0.25rem);
        max-width: none;
    }

    .orders-index-page .orders-filter-field--date {
        flex: 1 1 calc(50% - 0.25rem);
    }

    .orders-index-page .orders-filter-field--actions {
        flex: 0 0 auto;
        margin-left: auto;
    }

    .orders-index-page .orders-filter-field--actions .admin-form-label {
        display: none;
    }
}

.orders-index-page .orders-date-dropdown {
    min-width: 0;
    width: 100%;
}

.orders-index-page .orders-date-trigger {
    display: inline-flex;
    align-items: center;
    gap: 0.4rem;
    min-width: 0;
    padding-right: 2rem;
    cursor: pointer;
}

.orders-index-page .orders-date-trigger span {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.orders-index-page .orders-date-popup {
    width: 280px;
    padding: 0.85rem;
    border-radius: 12px;
    border: 1px solid var(--admin-border-color, #e4e0d8);
    box-shadow: 0 10px 28px rgba(15, 23, 42, 0.12);
}

.orders-index-page .orders-date-popup__title {
    font-size: 0.72rem;
    font-weight: 650;
    letter-spacing: 0.05em;
    text-transform: uppercase;
    color: var(--color-text-muted, #6b7280);
    margin-bottom: 0.5rem;
}

.orders-index-page .orders-date-presets {
    display: flex;
    flex-wrap: wrap;
    gap: 0.35rem;
}

.orders-index-page .orders-date-preset {
    border: 1px solid var(--admin-border-color, #e5e7eb);
    background: #fff;
    color: #1f2937;
    border-radius: 999px;
    font-size: 0.75rem;
    font-weight: 550;
    padding: 0.28rem 0.6rem;
    line-height: 1.2;
    cursor: pointer;
}

.orders-index-page .orders-date-preset:hover {
    background: #f9fafb;
    border-color: #d1d5db;
}

.orders-index-page .orders-date-preset.active {
    background: var(--admin-primary);
    border-color: var(--admin-primary);
    color: #fff;
}

.orders-index-page .btn-primary,
.orders-index-page .btn-primary:hover,
.orders-index-page .btn-primary:focus,
.orders-index-page .btn-primary:focus-visible,
.orders-index-page .btn-primary:active,
.orders-index-page .btn-primary.active {
    background: var(--admin-primary) !important;
    border-color: transparent !important;
    box-shadow: none !important;
    transform: none !important;
    color: #fff !important;
}

.orders-index-page .source-pos {
    background-color: color-mix(in srgb, var(--color-bg, #f3f1ec) 80%, #fff);
    border-radius: 999px;
    padding: 0.2rem;
    display: inline-flex;
    flex-wrap: nowrap;
    gap: 0.2rem;
    width: fit-content;
    max-width: 100%;
}

.orders-index-page .admin-status-filters-card {
    background: var(--color-card, #ffffff);
    border-radius: var(--admin-border-radius, 16px);
    box-shadow: var(--admin-card-shadow);
    border: 1px solid var(--admin-border-color, #e4e0d8);
    padding: 1rem 1.1rem 1.15rem;
    margin-bottom: 0.75rem;
}

.orders-index-page .source-filter-label,
.orders-index-page .status-filter-label {
    font-weight: 650;
    color: var(--color-text-muted, #6b7280);
    font-size: 0.72rem;
    letter-spacing: 0.05em;
    text-transform: uppercase;
}

.orders-index-page .status-filter-pills-container {
    display: flex;
    flex-wrap: wrap;
    gap: 0.5rem;
    align-items: center;
}

.orders-index-page .status-filter-pill {
    display: inline-flex;
    align-items: center;
    gap: 0.35rem;
    padding: 0.4rem 0.7rem;
    border-radius: 999px;
    font-size: 0.78rem;
    font-weight: 550;
    text-decoration: none;
    transition: all 0.2s ease;
    cursor: pointer;
    border: 1px solid var(--admin-border-color, #E5E7EB);
    white-space: nowrap;
    background-color: #ffffff;
    color: #1F2937;
}

.orders-index-page .source-filter-pill {
    display: inline-flex;
    align-items: center;
    gap: 0.25rem;
    padding: 0.28rem 0.55rem;
    border-radius: 999px;
    font-size: 0.75rem;
    font-weight: 550;
    text-decoration: none;
    transition: all 0.2s ease;
    cursor: pointer;
    white-space: nowrap;
    color: #1F2937;
    border: 1px solid transparent;
}

.orders-index-page .status-filter-pill:hover {
    background-color: #F9FAFB;
    border-color: #D1D5DB;
    color: #111827;
}

.orders-index-page .status-filter-pill.pill-yellow.active {
    background-color: #FDE68A;
    border-color: #FBBF24;
    color: #78350F;
}

.orders-index-page .status-filter-pill.pill-purple.active {
    background-color: #DDD6FE;
    border-color: #A78BFA;
    color: #581C87;
}

.orders-index-page .status-filter-pill.pill-blue.active {
    background-color: #BFDBFE;
    border-color: #3B82F6;
    color: #1E3A8A;
}

.orders-index-page .status-filter-pill.pill-green.active {
    background-color: #A7F3D0;
    border-color: #10B981;
    color: #047857;
}

.orders-index-page .status-filter-pill.pill-red.active {
    background-color: #FECACA;
    border-color: #F87171;
    color: #7F1D1D;
}

.orders-index-page .source-filter-pill.pill-white.active,
.orders-index-page .status-filter-pill.pill-white.active {
    background-color: var(--admin-primary);
    border-color: var(--admin-primary);
    color: #ffffff;
}

.orders-index-page .status-filter-pill.pill-all.active {
    background-color: #F3F4F6;
    border-color: #9CA3AF;
    color: #111827;
}

.orders-index-page .admin-table-card {
    border: 1px solid var(--admin-border-color, #e4e0d8);
}

.orders-index-page .pagination-wrapper {
    padding: 1rem 1.1rem 1.15rem;
    border-top: 1px solid var(--admin-border-color, #e9ecef);
    display: flex;
    justify-content: space-between;
    gap: 1rem;
    flex-wrap: wrap;
}

.orders-index-page .pagination-info-text {
    font-size: 0.9rem;
    color: #4a5568;
    font-weight: 500;
    white-space: nowrap;
}

.orders-index-page .pagination-info-text strong {
    color: var(--admin-primary);
    font-weight: 700;
}

.orders-index-page .pagination-wrapper .pagination-controls .pagination {
    justify-content: flex-end !important;
    margin: 0 !important;
}

.orders-index-page .pagination-wrapper .pagination {
    display: flex;
    list-style: none;
    padding: 0;
}
</style>
@endpush

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Handle status pill clicks to preserve other filters (skip source pills - they use their own href)
    const statusPills = document.querySelectorAll('.status-filter-pill');
    
    statusPills.forEach(pill => {
        pill.addEventListener('click', function(e) {
            if (this.classList.contains('source-pill')) {
                return; // Source pills use their href as-is, don't modify
            }
            
            const filterType = this.getAttribute('data-filter-type');
            const filterValue = this.getAttribute('data-filter-value');
            
            // If it's "all", clear all filters
            if (filterType === 'all') {
                return; // Let the default link behavior work
            }
            
            // Build URL with current filters preserved
            const url = new URL(this.href);
            const currentParams = new URLSearchParams(window.location.search);
            
            // Preserve date_filter, source, and other filters
            if (currentParams.has('date_filter')) {
                url.searchParams.set('date_filter', currentParams.get('date_filter'));
            }
            if (currentParams.has('date_from')) {
                url.searchParams.set('date_from', currentParams.get('date_from'));
            }
            if (currentParams.has('date_to')) {
                url.searchParams.set('date_to', currentParams.get('date_to'));
            }
            if (currentParams.has('source')) {
                url.searchParams.set('source', currentParams.get('source'));
            }
            
            // Update the href to include preserved filters
            this.href = url.toString();
        });
    });

    function setDateFilterValue(value, label) {
        const hidden = document.getElementById('date_filter');
        const labelEl = document.getElementById('dateFilterLabel');
        const customFields = document.getElementById('ordersDateCustomFields');
        if (hidden) {
            hidden.value = value;
        }
        if (labelEl && label) {
            labelEl.textContent = label;
        }
        document.querySelectorAll('.orders-date-preset').forEach(function (btn) {
            btn.classList.toggle('active', btn.getAttribute('data-value') === value);
        });
        if (customFields) {
            customFields.style.display = value === 'custom' ? 'flex' : 'none';
        }
    }

    document.querySelectorAll('.orders-date-preset').forEach(function (btn) {
        btn.addEventListener('click', function () {
            setDateFilterValue(this.getAttribute('data-value'), this.getAttribute('data-label'));
        });
    });

    ['date_from', 'date_to'].forEach(function (id) {
        const input = document.getElementById(id);
        if (!input) {
            return;
        }
        input.addEventListener('change', function () {
            const fromVal = document.getElementById('date_from').value;
            const toVal = document.getElementById('date_to').value;
            const label = (fromVal || '…') + ' to ' + (toVal || '…');
            setDateFilterValue('custom', (fromVal || toVal) ? label : 'Custom Range');
        });
    });

    const dateDropdown = document.querySelector('.orders-date-dropdown');
    if (dateDropdown) {
        dateDropdown.addEventListener('hide.bs.dropdown', function (event) {
            if (document.activeElement && document.activeElement.type === 'date') {
                event.preventDefault();
            }
        });
    }
});
</script>
@endpush
@endsection

