@extends('layouts.navigation')

@section('content')
    <div class="main-content">

        <!-- Top Nav -->
        <div class="top-nav">
            <h2><i class="fas fa-shopping-cart me-2" style="color:#0a9a73;"></i> Orders Management</h2>
            <div class="user-profile">
                <div class="user-info">
                    <div class="user-name">{{ auth()->user()->name }}</div>
                    <div class="user-role">Administrator</div>
                </div>
                <img src="https://ui-avatars.com/api/?name={{ urlencode(auth()->user()->name) }}&background=0a9a73&color=fff"
                    alt="User">
                <form method="POST" action="{{ route('logout') }}" style="margin:0;">
                    @csrf
                    <button type="submit" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Logout</button>
                </form>
            </div>
        </div>

        <div class="dashboard-content">

            @if (session('success'))
                <div class="alert alert-success alert-dismissible fade show mb-4">
                    <i class="fas fa-check-circle me-2"></i>{{ session('success') }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            @endif

            <!-- Stats -->
            <div class="stats-row mb-4">
                <div class="stat-card">
                    <div class="stat-header">
                        <div>
                            <div class="stat-title">Total Orders</div>
                            <div class="stat-value">{{ $stats['total'] }}</div>
                        </div>
                        <div class="stat-icon blue"><i class="fas fa-shopping-cart"></i></div>
                    </div>
                </div>
                <div class="stat-card orange">
                    <div class="stat-header">
                        <div>
                            <div class="stat-title">Pending Review</div>
                            <div class="stat-value">{{ $stats['payment_submitted'] }}</div>
                        </div>
                        <div class="stat-icon orange"><i class="fas fa-search"></i></div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-header">
                        <div>
                            <div class="stat-title">In Progress</div>
                            <div class="stat-value">{{ $stats['processing'] + $stats['shipped'] }}</div>
                        </div>
                        <div class="stat-icon green"><i class="fas fa-cogs"></i></div>
                    </div>
                </div>
                <div class="stat-card">
                    <div class="stat-header">
                        <div>
                            <div class="stat-title">Completed</div>
                            <div class="stat-value">{{ $stats['completed'] }}</div>
                        </div>
                        <div class="stat-icon purple"><i class="fas fa-check-circle"></i></div>
                    </div>
                </div>
            </div>

            <!-- Filters -->
            <div class="chart-card mb-4">
                <form method="GET" action="{{ route('admin.orders') }}" class="row g-3 align-items-end">
                    <div class="col-md-4">
                        <label class="form-label fw-bold" style="font-size:13px;">Search</label>
                        <input type="text" name="search" class="form-control" placeholder="Order ID, name, email..."
                            value="{{ request('search') }}">
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-bold" style="font-size:13px;">Status</label>
                        <select name="status" class="form-select">
                            <option value="">All Statuses</option>
                            @foreach ([
            'pending' => 'Pending',
            'payment_submitted' => 'Payment Submitted',
            'processing' => 'Processing',
            'shipped' => 'Shipped',
            'in_transit' => 'In Transit',
            'out_for_delivery' => 'Out for Delivery',
            'delivered' => 'Delivered',
            'completed' => 'Completed',
            'cancelled' => 'Cancelled',
            'refunded' => 'Refunded',
        ] as $val => $label)
                                <option value="{{ $val }}" {{ request('status') === $val ? 'selected' : '' }}>
                                    {{ $label }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label fw-bold" style="font-size:13px;">Payment Method</label>
                        <select name="payment_method" class="form-select">
                            <option value="">All Methods</option>
                            <option value="crypto" {{ request('payment_method') === 'crypto' ? 'selected' : '' }}>Crypto
                            </option>
                            <option value="gift_card" {{ request('payment_method') === 'gift_card' ? 'selected' : '' }}>
                                Gift
                                Card</option>
                        </select>
                    </div>
                    <div class="col-md-2 d-flex gap-2">
                        <button type="submit" class="btn btn-sm w-100 fw-bold" style="background:#0a9a73;color:#fff;">
                            <i class="fas fa-search me-1"></i> Filter
                        </button>
                        <a href="{{ route('admin.orders') }}" class="btn btn-sm btn-outline-secondary w-100">Clear</a>
                    </div>
                </form>
            </div>

            <!-- Orders Table -->
            <div class="chart-card">
                <div class="chart-header d-flex justify-content-between align-items-center">
                    <h3 class="chart-title">All Orders</h3>
                    <span class="text-muted" style="font-size:13px;">{{ $orders->total() }} orders found</span>
                </div>

                @if ($orders->isEmpty())
                    <div class="text-center py-5 text-muted">
                        <i class="fas fa-inbox fa-3x mb-3" style="color:#ddd;"></i>
                        <p>No orders found.</p>
                    </div>
                @else
                    <div class="table-responsive">
                        <table class="table table-hover align-middle" style="font-size:14px;">
                            <thead style="background:#f8f9fa;">
                                <tr>
                                    <th>Order</th>
                                    <th>Customer</th>
                                    <th>Payment</th>
                                    <th>Total</th>
                                    <th>Status</th>
                                    <th>Date</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach ($orders as $order)
                                    <tr>
                                        <td>
                                            <div style="font-weight:700;color:#1a1a2e;">#{{ $order->id }}</div>
                                            <small class="text-muted">{{ $order->items->count() }} item(s)</small>
                                        </td>
                                        <td>
                                            <div style="font-weight:600;">{{ $order->first_name }} {{ $order->last_name }}
                                            </div>
                                            <small class="text-muted">{{ $order->email }}</small>
                                        </td>
                                        <td>
                                            @if ($order->payment_method === 'crypto')
                                                <span class="pay-badge"
                                                    style="background:rgba(247,147,26,0.15);color:#f7931a;">
                                                    <i class="fab fa-bitcoin me-1"></i>Crypto
                                                </span>
                                            @else
                                                <span class="pay-badge"
                                                    style="background:rgba(10,154,115,0.15);color:#0a9a73;">
                                                    <i class="fas fa-gift me-1"></i>Gift Card
                                                </span>
                                            @endif
                                        </td>
                                        <td><strong style="color:#0a9a73;">${{ number_format($order->total, 2) }}</strong>
                                        </td>
                                        <td>
                                            <span class="o-status-badge status-{{ $order->status }}">
                                                {{ ucfirst(str_replace('_', ' ', $order->status)) }}
                                            </span>
                                        </td>
                                        <td style="color:#666;font-size:13px;">{{ $order->created_at->format('M d, Y') }}
                                        </td>
                                        <td>
                                            <button class="view-order-btn" data-order-id="{{ $order->id }}"
                                                title="View & Manage Order">
                                                <i class="fas fa-eye me-1"></i> Manage
                                            </button>
                                        </td>
                                    </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                    <div class="mt-3">{{ $orders->withQueryString()->links() }}</div>
                @endif
            </div>
        </div>
    </div>

    <!-- ═══════════════════════════════════════════════════════════
             ORDER DETAIL + TRACKING UPDATE MODAL (combined)
        ═══════════════════════════════════════════════════════════ -->
    <div class="modal fade" id="orderModal" tabindex="-1">
        <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-scrollable">
            <div class="modal-content" style="border-radius:16px;border:none;overflow:hidden;">

                <!-- Header -->
                <div class="modal-header" style="background:#1a1a2e;border:none;padding:18px 25px;">
                    <div>
                        <h5 class="modal-title text-white mb-0">
                            <i class="fas fa-receipt me-2" style="color:#0a9a73;"></i>
                            Order <span id="modal-order-id" style="color:#0a9a73;"></span>
                        </h5>
                        <small id="modal-customer-name" style="color:#95a5a6;font-size:13px;"></small>
                    </div>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>

                <!-- Tabs -->
                <div style="background:#1a1a2e;padding:0 25px;">
                    <ul class="nav" id="orderModalTabs" role="tablist" style="border:none;gap:4px;">
                        <li class="nav-item" role="presentation">
                            <button class="modal-tab active" data-bs-toggle="tab" data-bs-target="#tab-details"
                                type="button" role="tab">
                                <i class="fas fa-receipt me-1"></i> Order Details
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="modal-tab" data-bs-toggle="tab" data-bs-target="#tab-payment" type="button"
                                role="tab">
                                <i class="fas fa-credit-card me-1"></i> Payment Proof
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="modal-tab" data-bs-toggle="tab" data-bs-target="#tab-tracking" type="button"
                                role="tab">
                                <i class="fas fa-map-marker-alt me-1"></i> Tracking History
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="modal-tab update-tab" data-bs-toggle="tab" data-bs-target="#tab-update"
                                type="button" role="tab">
                                <i class="fas fa-edit me-1"></i> Update Status
                            </button>
                        </li>
                    </ul>
                </div>

                <div class="modal-body p-0">
                    <div class="tab-content">

                        <!-- ── Tab 1: Order Details ── -->
                        <div class="tab-pane fade show active p-4" id="tab-details">
                            <div id="details-body">
                                <div class="text-center py-5">
                                    <i class="fas fa-spinner fa-spin fa-2x" style="color:#0a9a73;"></i>
                                </div>
                            </div>
                        </div>

                        <!-- ── Tab 2: Payment Proof ── -->
                        <div class="tab-pane fade p-4" id="tab-payment">
                            <div id="payment-body">
                                <div class="text-center py-5">
                                    <i class="fas fa-spinner fa-spin fa-2x" style="color:#0a9a73;"></i>
                                </div>
                            </div>
                        </div>

                        <!-- ── Tab 3: Tracking History ── -->
                        <div class="tab-pane fade p-4" id="tab-tracking">
                            <div id="tracking-body">
                                <div class="text-center py-5">
                                    <i class="fas fa-spinner fa-spin fa-2x" style="color:#0a9a73;"></i>
                                </div>
                            </div>
                        </div>

                        <!-- ── Tab 4: Update Status ── -->
                        <div class="tab-pane fade p-4" id="tab-update">
                            <form id="updateTrackingForm" method="POST">
                                @csrf
                                @method('PUT')

                                <h6 class="fw-bold mb-1" style="color:#1a1a2e;">Current Status</h6>
                                <div id="current-status-display" class="mb-4"></div>

                                <!-- Status Grid -->
                                <h6 class="fw-bold mb-3" style="color:#1a1a2e;">
                                    <i class="fas fa-exchange-alt me-2" style="color:#0a9a73;"></i>Select New Status
                                </h6>
                                @php
                                    $statuses = [
                                        [
                                            'value' => 'pending',
                                            'label' => 'Pending',
                                            'icon' => 'fa-clock',
                                            'bg' => '#fff3cd',
                                            'color' => '#856404',
                                        ],
                                        [
                                            'value' => 'payment_submitted',
                                            'label' => 'Payment Submitted',
                                            'icon' => 'fa-search',
                                            'bg' => '#cce5ff',
                                            'color' => '#004085',
                                        ],
                                        [
                                            'value' => 'processing',
                                            'label' => 'Processing',
                                            'icon' => 'fa-cogs',
                                            'bg' => '#e8f4fd',
                                            'color' => '#2980b9',
                                        ],
                                        [
                                            'value' => 'shipped',
                                            'label' => 'Shipped',
                                            'icon' => 'fa-box',
                                            'bg' => '#d1ecf1',
                                            'color' => '#0c5460',
                                        ],
                                        [
                                            'value' => 'in_transit',
                                            'label' => 'In Transit',
                                            'icon' => 'fa-shipping-fast',
                                            'bg' => '#fff0d4',
                                            'color' => '#d68000',
                                        ],
                                        [
                                            'value' => 'out_for_delivery',
                                            'label' => 'Out for Delivery',
                                            'icon' => 'fa-motorcycle',
                                            'bg' => '#e8d5ff',
                                            'color' => '#6f42c1',
                                        ],
                                        [
                                            'value' => 'delivered',
                                            'label' => 'Delivered',
                                            'icon' => 'fa-check-circle',
                                            'bg' => '#d4edda',
                                            'color' => '#155724',
                                        ],
                                        [
                                            'value' => 'completed',
                                            'label' => 'Completed',
                                            'icon' => 'fa-star',
                                            'bg' => '#d4edda',
                                            'color' => '#155724',
                                        ],
                                        [
                                            'value' => 'cancelled',
                                            'label' => 'Cancelled',
                                            'icon' => 'fa-times-circle',
                                            'bg' => '#f8d7da',
                                            'color' => '#721c24',
                                        ],
                                        [
                                            'value' => 'refunded',
                                            'label' => 'Refunded',
                                            'icon' => 'fa-undo',
                                            'bg' => '#f5f5f5',
                                            'color' => '#555555',
                                        ],
                                    ];
                                @endphp
                                <div class="row g-2 mb-4">
                                    @foreach ($statuses as $s)
                                        <div class="col-md-4 col-6">
                                            <label class="status-opt w-100"
                                                style="--bg:{{ $s['bg'] }};--clr:{{ $s['color'] }};">
                                                <input type="radio" name="status" value="{{ $s['value'] }}"
                                                    style="display:none;">
                                                <i class="fas {{ $s['icon'] }} me-2"></i>{{ $s['label'] }}
                                            </label>
                                        </div>
                                    @endforeach
                                </div>
                                <div id="status-error" class="text-danger mb-3" style="display:none;font-size:13px;">
                                    <i class="fas fa-exclamation-circle me-1"></i> Please select a status.
                                </div>

                                <!-- Location -->
                                <div class="mb-3">
                                    <label class="form-label fw-bold">
                                        <i class="fas fa-map-marker-alt me-1 text-danger"></i> Location / Route Update
                                    </label>
                                    <input type="text" name="location" class="form-control"
                                        placeholder="e.g. Departed Lagos Warehouse, Arrived Abuja facility...">
                                    <small class="text-muted">Visible to the customer on their tracking page.</small>
                                </div>

                                <!-- Note -->
                                <div class="mb-3">
                                    <label class="form-label fw-bold">
                                        <i class="fas fa-comment-alt me-1" style="color:#0a9a73;"></i> Note to Customer
                                    </label>
                                    <textarea name="note" class="form-control" rows="3"
                                        placeholder="e.g. Your order has been verified and is being packed..."></textarea>
                                </div>

                                <!-- Estimated Delivery -->
                                <div class="mb-4">
                                    <label class="form-label fw-bold">
                                        <i class="fas fa-calendar-check me-1" style="color:#0a9a73;"></i> Estimated
                                        Delivery Date
                                    </label>
                                    <input type="date" name="estimated_delivery" class="form-control"
                                        min="{{ now()->addDay()->format('Y-m-d') }}">
                                    <small class="text-muted">Leave blank to keep the existing estimate.</small>
                                </div>

                                <div class="d-flex gap-3">
                                    <button type="submit" class="btn fw-bold px-5 py-2"
                                        style="background:#0a9a73;color:#fff;border-radius:8px;">
                                        <i class="fas fa-save me-2"></i> Save Tracking Update
                                    </button>
                                    <button type="button" class="btn btn-outline-secondary px-4"
                                        data-bs-dismiss="modal">
                                        Cancel
                                    </button>
                                </div>
                            </form>
                        </div>

                    </div>
                </div>
            </div>
        </div>
    </div>

    <style>
        /* ── Status Badges ─────────────────────────────────────────────────── */
        .o-status-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 700;
            white-space: nowrap;
        }

        .status-pending {
            background: #fff3cd;
            color: #856404;
        }

        .status-payment_submitted {
            background: #cce5ff;
            color: #004085;
        }

        .status-processing {
            background: #e8f4fd;
            color: #2980b9;
        }

        .status-shipped {
            background: #d1ecf1;
            color: #0c5460;
        }

        .status-in_transit {
            background: #fff0d4;
            color: #d68000;
        }

        .status-out_for_delivery {
            background: #e8d5ff;
            color: #6f42c1;
        }

        .status-delivered {
            background: #d4edda;
            color: #155724;
        }

        .status-completed {
            background: #d4edda;
            color: #155724;
        }

        .status-cancelled {
            background: #f8d7da;
            color: #721c24;
        }

        .status-refunded {
            background: #f5f5f5;
            color: #555555;
        }

        /* ── Table Buttons ─────────────────────────────────────────────────── */
        .pay-badge {
            padding: 4px 10px;
            border-radius: 20px;
            font-size: 12px;
            font-weight: 700;
        }

        .view-order-btn {
            background: #1a1a2e;
            color: #fff;
            border: none;
            padding: 7px 16px;
            border-radius: 8px;
            font-size: 13px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s;
        }

        .view-order-btn:hover {
            background: #0a9a73;
        }

        /* ── Modal Tabs ────────────────────────────────────────────────────── */
        .modal-tabs {
            border: none;
            gap: 4px;
        }

        .modal-tab {
            display: inline-block;
            color: rgba(255, 255, 255, 0.75);
            padding: 12px 18px;
            font-size: 13px;
            font-weight: 600;
            border: none;
            border-bottom: 3px solid transparent;
            background: transparent;
            text-decoration: none;
            transition: all 0.2s;
            cursor: pointer;
        }

        .modal-tab:hover {
            color: #fff;
            background: rgba(255, 255, 255, 0.08);
        }

        .modal-tab.active {
            color: #fff;
            border-bottom-color: #0a9a73;
            background: rgba(10, 154, 115, 0.15);
        }

        .modal-tab.update-tab {
            color: #7ee8c8;
        }

        .modal-tab.update-tab.active {
            color: #0a9a73;
            border-bottom-color: #0a9a73;
            background: rgba(10, 154, 115, 0.15);
        }

        /* ── Status Options ────────────────────────────────────────────────── */
        .status-opt {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 11px 8px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 600;
            border: 2px solid transparent;
            background: var(--bg);
            color: var(--clr);
            transition: all 0.2s;
            user-select: none;
        }

        .status-opt:hover {
            border-color: var(--clr);
            transform: translateY(-1px);
            box-shadow: 0 3px 8px rgba(0, 0, 0, 0.1);
        }

        .status-opt.active {
            border-color: var(--clr);
            box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.1);
        }

        /* ── Detail Sections ───────────────────────────────────────────────── */
        .d-section {
            background: #f8f9fa;
            border-radius: 10px;
            border: 1px solid #eee;
            padding: 18px;
            height: 100%;
        }

        .d-label {
            font-size: 11px;
            font-weight: 700;
            color: #999;
            text-transform: uppercase;
            letter-spacing: .5px;
            margin-bottom: 3px;
        }

        .proof-img {
            max-height: 200px;
            border-radius: 8px;
            border: 2px solid #eee;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .proof-img:hover {
            transform: scale(1.02);
        }

        /* ── Tracking Timeline ─────────────────────────────────────────────── */
        .t-line {
            position: relative;
            padding-left: 30px;
        }

        .t-line::before {
            content: '';
            position: absolute;
            left: 10px;
            top: 0;
            bottom: 0;
            width: 2px;
            background: #e8e8e8;
        }

        .t-step {
            position: relative;
            padding-bottom: 24px;
        }

        .t-step:last-child {
            padding-bottom: 0;
        }

        .t-dot {
            position: absolute;
            left: -26px;
            top: 3px;
            width: 15px;
            height: 15px;
            border-radius: 50%;
            background: #e8e8e8;
            border: 3px solid #fff;
            box-shadow: 0 0 0 2px #e8e8e8;
            z-index: 1;
        }

        .t-dot.done {
            background: #0a9a73;
            box-shadow: 0 0 0 3px rgba(10, 154, 115, 0.2);
        }
    </style>

    @push('scripts')
        <script>
            const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
            let currentOrderId = null;

            // ── Open Modal ────────────────────────────────────────────────────────────────
            document.querySelectorAll('.view-order-btn').forEach(btn => {
                btn.addEventListener('click', function() {
                    currentOrderId = this.dataset.orderId;

                    document.getElementById('modal-order-id').textContent = '#' + currentOrderId;
                    document.getElementById('modal-customer-name').textContent = '';

                    // Reset all tab bodies to loading
                    ['details-body', 'payment-body', 'tracking-body'].forEach(id => {
                        document.getElementById(id).innerHTML =
                            '<div class="text-center py-5"><i class="fas fa-spinner fa-spin fa-2x" style="color:#0a9a73;"></i></div>';
                    });

                    // Reset update form
                    document.getElementById('updateTrackingForm').action =
                        `/admin/orders/${currentOrderId}/tracking`;
                    document.getElementById('status-error').style.display = 'none';
                    document.querySelectorAll('.status-opt').forEach(o => {
                        o.classList.remove('active');
                        o.querySelector('input').checked = false;
                    });
                    document.querySelector('[name="location"]').value = '';
                    document.querySelector('[name="note"]').value = '';
                    document.querySelector('[name="estimated_delivery"]').value = '';

                    // Activate first tab manually
                    document.querySelectorAll('.modal-tab').forEach(t => t.classList.remove('active'));
                    document.querySelectorAll('.tab-pane').forEach(p => {
                        p.classList.remove('show', 'active');
                    });
                    document.querySelector('[data-bs-target="#tab-details"]').classList.add('active');
                    document.getElementById('tab-details').classList.add('show', 'active');

                    // Show modal — get existing instance or create new one
                    const modalEl = document.getElementById('orderModal');
                    const existingModal = bootstrap.Modal.getInstance(modalEl);
                    if (existingModal) {
                        existingModal.show();
                    } else {
                        new bootstrap.Modal(modalEl).show();
                    }

                    // Fetch data
                    fetch(`/admin/orders/${currentOrderId}`, {
                            headers: {
                                'Accept': 'application/json',
                                'X-CSRF-TOKEN': csrfToken
                            }
                        })
                        .then(r => {
                            if (!r.ok) throw new Error('HTTP ' + r.status);
                            return r.json();
                        })
                        .then(data => {
                            document.getElementById('modal-customer-name').textContent =
                                data.first_name + ' ' + data.last_name + ' — ' + data.email;
                            renderDetails(data);
                            renderPayment(data);
                            renderTracking(data);
                            renderCurrentStatus(data.status);
                        })
                        .catch(err => {
                            document.getElementById('details-body').innerHTML =
                                `<div class="alert alert-danger"><i class="fas fa-exclamation-circle me-2"></i>Failed to load: ${err.message}</div>`;
                        });
                });
            });

            // ── Render: Order Details Tab ─────────────────────────────────────────────────
            function renderDetails(o) {
                const rows = o.items.map(i => `
        <tr>
            <td>${i.product_name}</td>
            <td class="text-center">${i.quantity}</td>
            <td class="text-end">$${parseFloat(i.price).toFixed(2)}</td>
            <td class="text-end"><strong>$${parseFloat(i.subtotal).toFixed(2)}</strong></td>
        </tr>`).join('');

                document.getElementById('details-body').innerHTML = `
        <div class="row g-4">
            <div class="col-md-5">
                <div class="d-section">
                    <h6 class="fw-bold mb-3" style="color:#1a1a2e;"><i class="fas fa-user me-2" style="color:#0a9a73;"></i>Customer & Shipping</h6>
                    <div class="fw-bold">${o.first_name} ${o.last_name}</div>
                    <div class="text-muted" style="font-size:13px;">${o.email}</div>
                    <div class="text-muted" style="font-size:13px;">${o.phone}</div>
                    <hr class="my-2">
                    <div style="font-size:13px;color:#555;line-height:1.9;">
                        ${o.address}${o.address2 ? ', '+o.address2 : ''}<br>
                        ${o.city}${o.state ? ', '+o.state : ''} ${o.zip ?? ''}<br>
                        ${o.country}
                    </div>
                    ${o.notes ? `<div class="mt-2 p-2 rounded" style="background:#fff3cd;font-size:12px;"><i class="fas fa-sticky-note me-1"></i>${o.notes}</div>` : ''}
                    <hr class="my-2">
                    <div style="font-size:12px;color:#666;">
                        <i class="fas fa-truck me-1"></i>
                        ${o.shipping_type === 'shipping_discrete' ? 'Discrete Shipping' : 'Non-Discrete Shipping'}
                        — <strong>$${parseFloat(o.shipping_cost).toFixed(2)}</strong>
                    </div>
                </div>
            </div>
            <div class="col-md-7">
                <div class="d-section">
                    <h6 class="fw-bold mb-3" style="color:#1a1a2e;"><i class="fas fa-box me-2" style="color:#0a9a73;"></i>Order Items</h6>
                    <table class="table table-sm mb-0" style="font-size:13px;">
                        <thead><tr>
                            <th>Product</th><th class="text-center">Qty</th>
                            <th class="text-end">Price</th><th class="text-end">Subtotal</th>
                        </tr></thead>
                        <tbody>${rows}</tbody>
                        <tfoot style="border-top:2px solid #dee2e6;">
                            <tr><td colspan="3" class="text-end text-muted">Subtotal</td><td class="text-end">$${parseFloat(o.subtotal).toFixed(2)}</td></tr>
                            <tr><td colspan="3" class="text-end text-muted">Shipping</td><td class="text-end">$${parseFloat(o.shipping_cost).toFixed(2)}</td></tr>
                            <tr><td colspan="3" class="text-end fw-bold">Total</td>
                                <td class="text-end fw-bold" style="color:#0a9a73;font-size:16px;">$${parseFloat(o.total).toFixed(2)}</td></tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>`;
            }

            // ── Render: Payment Proof Tab ─────────────────────────────────────────────────
            function renderPayment(o) {
                let html = '';
                if (o.payment_method === 'crypto') {
                    if (o.payment_screenshot || o.transaction_id) {
                        html = `<div class="row g-4">
                ${o.payment_screenshot ? `
                                <div class="col-12">
                                    <div class="d-label">Payment Screenshot</div>
                                    <a href="/storage/${o.payment_screenshot}" target="_blank">
                                        <img src="/storage/${o.payment_screenshot}" class="proof-img" alt="Proof">
                                    </a>
                                    <div class="mt-2"><a href="/storage/${o.payment_screenshot}" target="_blank" class="btn btn-sm btn-outline-secondary"><i class="fas fa-external-link-alt me-1"></i> Open Full Size</a></div>
                                </div>` : ''}
                ${o.transaction_id ? `
                                <div class="col-12">
                                    <div class="d-label">Transaction ID / Hash</div>
                                    <code style="background:#f4f4f4;padding:10px 14px;border-radius:8px;display:block;word-break:break-all;font-size:13px;">${o.transaction_id}</code>
                                </div>` : ''}
            </div>`;
                    } else {
                        html =
                            `<div class="text-center py-4 text-muted"><i class="fas fa-image fa-3x mb-3" style="color:#ddd;"></i><p>No payment proof submitted yet.</p></div>`;
                    }
                } else {
                    if (o.gift_card_code || o.gift_card_photo) {
                        html = `<div class="row g-4">
                ${o.gift_card_photo ? `
                                <div class="col-12">
                                    <div class="d-label">Card Photo</div>
                                    <a href="/storage/${o.gift_card_photo}" target="_blank">
                                        <img src="/storage/${o.gift_card_photo}" class="proof-img" alt="Card">
                                    </a>
                                    <div class="mt-2"><a href="/storage/${o.gift_card_photo}" target="_blank" class="btn btn-sm btn-outline-secondary"><i class="fas fa-external-link-alt me-1"></i> Open Full Size</a></div>
                                </div>` : ''}
                <div class="col-md-6">
                    <div class="d-section">
                        <div class="d-label">Brand</div>
                        <div class="fw-bold fs-6">${o.gift_card_brand ?? '—'}</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="d-section">
                        <div class="d-label">Card Value</div>
                        <div class="fw-bold fs-6 text-success">$${o.gift_card_value ?? '—'}</div>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="d-section">
                        <div class="d-label">Card Code / Claim Code</div>
                        <code style="font-size:14px;word-break:break-all;">${o.gift_card_code ?? '—'}</code>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="d-section">
                        <div class="d-label">PIN</div>
                        <code style="font-size:14px;">${o.gift_card_pin ?? '—'}</code>
                    </div>
                </div>
                ${o.gift_card_notes ? `
                                <div class="col-12">
                                    <div class="d-label">Customer Notes</div>
                                    <div style="font-size:14px;">${o.gift_card_notes}</div>
                                </div>` : ''}
            </div>`;
                    } else {
                        html =
                            `<div class="text-center py-4 text-muted"><i class="fas fa-gift fa-3x mb-3" style="color:#ddd;"></i><p>No gift card details submitted yet.</p></div>`;
                    }
                }
                document.getElementById('payment-body').innerHTML = html;
            }

            // ── Render: Tracking History Tab ──────────────────────────────────────────────
            function renderTracking(o) {
                if (!o.tracking || !o.tracking.length) {
                    document.getElementById('tracking-body').innerHTML =
                        `<div class="text-center py-4 text-muted"><i class="fas fa-map-marker-alt fa-3x mb-3" style="color:#ddd;"></i><p>No tracking updates yet.</p></div>`;
                    return;
                }
                const items = o.tracking.map(t => `
        <div class="t-step">
            <div class="t-dot done"></div>
            <div class="ms-1">
                <div class="d-flex align-items-center gap-2 mb-1">
                    <span class="o-status-badge status-${t.status}">${t.status.replace(/_/g,' ')}</span>
                    <span style="font-size:11px;color:#999;"><i class="far fa-clock me-1"></i>${t.created_at}</span>
                </div>
                ${t.location ? `<div style="font-size:13px;font-weight:600;"><i class="fas fa-map-marker-alt me-1 text-danger"></i>${t.location}</div>` : ''}
                ${t.note     ? `<div style="font-size:13px;color:#555;margin-top:3px;background:#f0faf7;padding:6px 10px;border-left:3px solid #0a9a73;border-radius:0 6px 6px 0;">${t.note}</div>` : ''}
                ${t.estimated_delivery ? `<div style="font-size:12px;color:#0a9a73;margin-top:3px;font-weight:600;"><i class="fas fa-calendar-check me-1"></i>Est. Delivery: ${t.estimated_delivery}</div>` : ''}
            </div>
        </div>`).join('');

                document.getElementById('tracking-body').innerHTML = `
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h6 class="fw-bold mb-0" style="color:#1a1a2e;">${o.tracking.length} update(s)</h6>

        </div>
         <div class="t-line">${items}</div>`;
            }

            // ── Render: Current Status in Update Tab ──────────────────────────────────────
            function renderCurrentStatus(status) {
                document.getElementById('current-status-display').innerHTML =
                    `<span class="o-status-badge status-${status}" style="font-size:14px;padding:7px 18px;">
            ${status.replace(/_/g,' ').replace(/\b\w/g, l => l.toUpperCase())}
        </span>`;

                // Pre-select the current status radio
                document.querySelectorAll('.status-opt').forEach(opt => {
                    const radio = opt.querySelector('input');
                    if (radio.value === status) {
                        radio.checked = true;
                        opt.classList.add('active');
                    }
                });
            }

            // ── Status option click ───────────────────────────────────────────────────────
            document.querySelectorAll('.status-opt').forEach(opt => {
                opt.addEventListener('click', function() {
                    document.querySelectorAll('.status-opt').forEach(o => o.classList.remove('active'));
                    this.classList.add('active');
                    document.getElementById('status-error').style.display = 'none';
                });
            });

            // ── Form submit ───────────────────────────────────────────────────────────────
            document.getElementById('updateTrackingForm').addEventListener('submit', function(e) {
                if (!document.querySelector('.status-opt.active input')) {
                    e.preventDefault();
                    document.getElementById('status-error').style.display = 'block';
                    document.getElementById('status-error').scrollIntoView({
                        behavior: 'smooth',
                        block: 'center'
                    });
                }
            });
        </script>
    @endpush

@endsection
