// ==================== T1 / GATEPASS MANAGEMENT ====================
// Global variables (assume userObj and serverURL are defined elsewhere)
// serverURL = "https://demo2.bsl.co.ke/api/v1/"

// Main function to load and display all T1 declarations
function allT1(filter = 'all') {
    $(".crud_section").html("");

    // Modern loading skeleton (same as before)
    var loadingHTML = `
        <div class="t1-container" style="padding: 24px; background: #ffffff; min-height: 100vh;">
            <div class="loading-skeleton">
                <div style="height: 60px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 12px; margin-bottom: 20px;"></div>
                <div style="display: grid; grid-template-columns: repeat(4, 1fr); gap: 20px; margin-bottom: 24px;">
                    ${Array(4).fill().map(() => '<div style="height: 100px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 16px;"></div>').join('')}
                </div>
                <div style="height: 400px; background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%); background-size: 200% 100%; animation: loading 1.5s infinite; border-radius: 16px;"></div>
            </div>
        </div>
        <style>
            @keyframes loading {
                0% { background-position: 200% 0; }
                100% { background-position: -200% 0; }
            }
        </style>
    `;

    $(".crud_section").html(loadingHTML);

    // Get all active T1 declarations
    let url = serverURL + "customs/t1";

    $.ajax({
        url: url,
        type: 'GET',
        dataType: "json",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json",
        },
        async: true,
        success: function(res) {
            // Response is an array directly
            let data = res || [];

            // Apply client‑side filter if needed
            if (filter !== 'all') {
                if (filter === 'IN_TRANSIT' || filter === 'COMPLETED' || filter === 'CANCELLED') {
                    data = data.filter(t1 => t1.status === filter);
                } else if (filter === 'withDevice') {
                    data = data.filter(t1 => t1.device && t1.device.deviceId);
                } else if (filter === 'withoutDevice') {
                    data = data.filter(t1 => !t1.device || !t1.device.deviceId);
                } else if (filter === 'online') {
                    data = data.filter(t1 => t1.device && t1.device.online === true);
                } else if (filter === 'offline') {
                    data = data.filter(t1 => t1.device && t1.device.online === false);
                }
            }

            // Calculate statistics for cards
            const total = data.length;
            const inTransit = data.filter(t1 => t1.status === 'IN_TRANSIT').length;
            const completed = data.filter(t1 => t1.status === 'COMPLETED').length;
            const cancelled = data.filter(t1 => t1.status === 'CANCELLED').length;
            const withDevice = data.filter(t1 => t1.device && t1.device.deviceId).length;
            const withoutDevice = total - withDevice;
            const onlineDevices = data.filter(t1 => t1.device && t1.device.online === true).length;
            const offlineDevices = data.filter(t1 => t1.device && t1.device.online === false).length;

            var html = `
            <div class="t1-container" style="padding: 24px; background: #ffffff; min-height: 100vh; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
                
                <!-- Header Section -->
                <div style="background: #ffffff; border-radius: 16px; padding: 24px; margin-bottom: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2;">
                    <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
                        <div style="display: flex; align-items: center; gap: 16px;">
                            <h1 style="margin: 0; font-size: 28px; font-weight: 600; color: #1a1f36; display: flex; align-items: center; gap: 12px;">
                                <i class="fas fa-file-alt" style="color: #000;"></i>
                                T1 / Gatepass Management
                            </h1>
                            <span style="background: #f0f2f5; color: #1a1f36; padding: 6px 14px; border-radius: 40px; font-size: 14px; font-weight: 500;">
                                ${total} Total
                            </span>
                        </div>
                        <div style="display: flex; gap: 12px;">
                            <button onclick="exportT1()" style="display: flex; align-items: center; gap: 8px; padding: 10px 20px; background: #ffffff; color: #1a1f36; border: 1px solid #d0d5dd; border-radius: 10px; font-weight: 500; cursor: pointer; transition: all 0.2s;">
                                <i class="fas fa-download"></i> Export
                            </button>
                        </div>
                    </div>
                </div>

                <!-- Statistics Cards - Single Responsive Row -->
                <div style="display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 16px; margin-bottom: 24px;">
                    
                    <!-- Total Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center;">
                        <div style="width: 40px; height: 40px; background: #f0f2f5; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-file-alt" style="font-size: 20px; color: #000;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #1a1f36;" id="stat-total">${total}</div>
                        <div style="font-size: 12px; color: #5b677c;">Total T1s</div>
                    </div>

                    <!-- In Transit Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center; cursor: pointer;" onclick="allT1('IN_TRANSIT')">
                        <div style="width: 40px; height: 40px; background: #e3f2fd; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-truck" style="font-size: 20px; color: #1976d2;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #1976d2;">${inTransit}</div>
                        <div style="font-size: 12px; color: #5b677c;">In Transit</div>
                    </div>

                    <!-- Completed Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center; cursor: pointer;" onclick="allT1('COMPLETED')">
                        <div style="width: 40px; height: 40px; background: #e8f5e9; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-check-circle" style="font-size: 20px; color: #2e7d32;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #2e7d32;">${completed}</div>
                        <div style="font-size: 12px; color: #5b677c;">Completed</div>
                    </div>

                    <!-- Cancelled Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center; cursor: pointer;" onclick="allT1('CANCELLED')">
                        <div style="width: 40px; height: 40px; background: #fee2e2; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-ban" style="font-size: 20px; color: #dc2626;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #dc2626;">${cancelled}</div>
                        <div style="font-size: 12px; color: #5b677c;">Cancelled</div>
                    </div>

                    <!-- With Device Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center; cursor: pointer;" onclick="allT1('withDevice')">
                        <div style="width: 40px; height: 40px; background: #fff3e0; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-microchip" style="font-size: 20px; color: #ed6c02;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #ed6c02;">${withDevice}</div>
                        <div style="font-size: 12px; color: #5b677c;">With Device</div>
                    </div>

                    <!-- Without Device Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center; cursor: pointer;" onclick="allT1('withoutDevice')">
                        <div style="width: 40px; height: 40px; background: #f3e5f5; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-microchip-slash" style="font-size: 20px; color: #9c27b0;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #9c27b0;">${withoutDevice}</div>
                        <div style="font-size: 12px; color: #5b677c;">No Device</div>
                    </div>

                    <!-- Online Devices Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center; cursor: pointer;" onclick="allT1('online')">
                        <div style="width: 40px; height: 40px; background: #e8f5e9; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-wifi" style="font-size: 20px; color: #2e7d32;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #2e7d32;">${onlineDevices}</div>
                        <div style="font-size: 12px; color: #5b677c;">Online</div>
                    </div>

                    <!-- Offline Devices Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 16px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; text-align: center; cursor: pointer;" onclick="allT1('offline')">
                        <div style="width: 40px; height: 40px; background: #fee2e2; border-radius: 10px; display: flex; align-items: center; justify-content: center; margin: 0 auto 8px;">
                            <i class="fas fa-power-off" style="font-size: 20px; color: #dc2626;"></i>
                        </div>
                        <div style="font-size: 20px; font-weight: 700; color: #dc2626;">${offlineDevices}</div>
                        <div style="font-size: 12px; color: #5b677c;">Offline</div>
                    </div>
                </div>

                <!-- Filter Chips (based on status and other attributes) -->
                <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-bottom: 20px; border: 1px solid #eaeef2; display: flex; gap: 8px; flex-wrap: wrap;">
                    <button class="filter-chip ${filter === 'all' ? 'active' : ''}" data-filter="all" onclick="allT1('all')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${filter === 'all' ? '#000' : 'white'}; color: ${filter === 'all' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px; display: inline-flex; align-items: center; gap: 6px;">
                        <i class="fas fa-list"></i> All
                    </button>
                    <button class="filter-chip ${filter === 'IN_TRANSIT' ? 'active' : ''}" data-filter="IN_TRANSIT" onclick="allT1('IN_TRANSIT')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${filter === 'IN_TRANSIT' ? '#1976d2' : 'white'}; color: ${filter === 'IN_TRANSIT' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px;">
                        <i class="fas fa-truck"></i> In Transit
                    </button>
                    <button class="filter-chip ${filter === 'COMPLETED' ? 'active' : ''}" data-filter="COMPLETED" onclick="allT1('COMPLETED')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${filter === 'COMPLETED' ? '#2e7d32' : 'white'}; color: ${filter === 'COMPLETED' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px;">
                        <i class="fas fa-check-circle"></i> Completed
                    </button>
                    <button class="filter-chip ${filter === 'CANCELLED' ? 'active' : ''}" data-filter="CANCELLED" onclick="allT1('CANCELLED')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${filter === 'CANCELLED' ? '#dc2626' : 'white'}; color: ${filter === 'CANCELLED' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px;">
                        <i class="fas fa-ban"></i> Cancelled
                    </button>
                    <button class="filter-chip ${filter === 'withDevice' ? 'active' : ''}" data-filter="withDevice" onclick="allT1('withDevice')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${filter === 'withDevice' ? '#ed6c02' : 'white'}; color: ${filter === 'withDevice' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px;">
                        <i class="fas fa-microchip"></i> With Device
                    </button>
                    <button class="filter-chip ${filter === 'withoutDevice' ? 'active' : ''}" data-filter="withoutDevice" onclick="allT1('withoutDevice')" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: ${filter === 'withoutDevice' ? '#9c27b0' : 'white'}; color: ${filter === 'withoutDevice' ? 'white' : '#1a1f36'}; cursor: pointer; font-size: 14px;">
                        <i class="fas fa-microchip-slash"></i> No Device
                    </button>
                </div>

                <!-- Search and Controls -->
                <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-bottom: 20px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 16px;">
                    <div style="position: relative; flex: 1; max-width: 400px;">
                        <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #94a3b8;"></i>
                        <input type="text" id="t1Search" placeholder="Search by T1 number, truck, consignee..." style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid #eaeef2; border-radius: 40px; font-size: 14px; outline: none;">
                    </div>
                    <div style="display: flex; gap: 12px;">
                        <select id="pageSize" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: white; font-size: 14px;">
                            <option value="10">10 per page</option>
                            <option value="25">25 per page</option>
                            <option value="50">50 per page</option>
                            <option value="100">100 per page</option>
                        </select>
                        <button onclick="allT1('${filter}')" style="width: 40px; height: 40px; border: 1px solid #eaeef2; border-radius: 50%; background: white; cursor: pointer;">
                            <i class="fas fa-sync-alt"></i>
                        </button>
                    </div>
                </div>

                <!-- T1 Table -->
                <div style="background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: inherit; box-shadow: 0 2px 8px rgba(0,0,0,0.04);">
                    <table class="t1-table" id="t1tableview" style="width: 100%; border-collapse: collapse; min-width: 1400px;">
                        <thead>
                            <tr style="background: #f8fafc; border-bottom: 2px solid #eaeef2;">
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36; width: 40px;">
                                    <input type="checkbox" id="selectAll" style="width: 18px; height: 18px; cursor: pointer;">
                                </th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">#</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">T1 Number</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Consignor</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Consignee</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Truck / Trailer</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Route</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Device</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Status</th>
                                <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Last Update</th>
                                <th style="padding: 16px; text-align: center; font-weight: 600; color: #1a1f36;">Actions</th>
                            </tr>
                        </thead>
                        <tbody id="t1TableBody">
            `;

            data.forEach((t1, i) => {
                const deviceStatus = t1.device ? 
                    (t1.device.online ? 
                        '<span style="color: #10b981;"><i class="fas fa-circle"></i> Online</span>' : 
                        '<span style="color: #ef4444;"><i class="fas fa-circle"></i> Offline</span>') : 
                    '<span style="color: #94a3b8;">Not assigned</span>';
                
                const statusBadge = t1.status === 'IN_TRANSIT' ? 
                    '<span style="background: #e3f2fd; color: #1976d2; padding: 4px 8px; border-radius: 30px; font-size: 12px;"><i class="fas fa-truck"></i> In Transit</span>' : 
                    t1.status === 'COMPLETED' ? 
                    '<span style="background: #e8f5e9; color: #2e7d32; padding: 4px 8px; border-radius: 30px; font-size: 12px;"><i class="fas fa-check-circle"></i> Completed</span>' : 
                    t1.status === 'CANCELLED' ? 
                    '<span style="background: #fee2e2; color: #dc2626; padding: 4px 8px; border-radius: 30px; font-size: 12px;"><i class="fas fa-ban"></i> Cancelled</span>' : 
                    `<span style="background: #f1f5f9; color: #1a1f36; padding: 4px 8px; border-radius: 30px; font-size: 12px;">${t1.status}</span>`;

                html += `
                <tr data-t1-id="${t1.id}" data-t1-number="${t1.t1Number}" style="border-bottom: 1px solid #eaeef2;">
                    <td style="padding: 16px;">
                        <input type="checkbox" class="row-checkbox" data-id="${t1.id}" style="width: 18px; height: 18px; cursor: pointer;">
                    </td>
                    <td style="padding: 16px; color: #5b677c;">${i + 1}</td>
                    <td style="padding: 16px; font-weight: 600; color: #1a1f36;">${t1.t1Number}</td>
                    <td style="padding: 16px;">
                        <div><strong>${t1.consignorName || 'N/A'}</strong></div>
                        <div style="font-size: 12px; color: #5b677c;">TIN: ${t1.consignorTin || 'N/A'}</div>
                    </td>
                    <td style="padding: 16px;">
                        <div><strong>${t1.consigneeName || 'N/A'}</strong></div>
                        <div style="font-size: 12px; color: #5b677c;">${t1.consigneeCountry || ''}</div>
                    </td>
                    <td style="padding: 16px;">
                        <div><i class="fas fa-truck"></i> ${t1.truckRegistrationNumber || 'N/A'}</div>
                        <div style="font-size: 12px; color: #5b677c;">Trailer: ${t1.trailerNumber || 'N/A'}</div>
                    </td>
                    <td style="padding: 16px;">
                        <div>${t1.origin || ''} → ${t1.destination || ''}</div>
                        <div style="font-size: 12px; color: #5b677c;">Exit: ${t1.exitPoint || 'N/A'}</div>
                    </td>
                    <td style="padding: 16px;">
                        ${t1.device ? 
                            `<div><strong>${t1.device.serialNumber || t1.device.name || 'Device'}</strong></div>
                             <div style="font-size: 12px;">${deviceStatus}</div>` : 
                            '<span style="color: #94a3b8;">No device</span>'}
                    </td>
                    <td style="padding: 16px;">
                        ${statusBadge}
                        <div style="font-size: 12px; margin-top: 4px;">${t1.trackingStatus || ''}</div>
                    </td>
                    <td style="padding: 16px; color: #5b677c; font-size: 13px;">
                        <div>${t1.lastPositionUpdate ? new Date(t1.lastPositionUpdate).toLocaleString() : 'N/A'}</div>
                        <div style="font-size: 11px;">Updated: ${t1.updatedAt ? new Date(t1.updatedAt).toLocaleString() : ''}</div>
                    </td>
                    <td style="padding: 16px; text-align: center;">
                        <div class="action-dropdown" style="position: relative; display: inline-block;">
                            <button onclick="toggleT1ActionMenu(${t1.id})" style="width: 36px; height: 36px; border: 1px solid #eaeef2; border-radius: 8px; background: white; cursor: pointer;">
                                <i class="fas fa-ellipsis-v" style="color: #5b677c;"></i>
                            </button>
                            <div id="t1_menu_${t1.id}" style="display: none; position: absolute; right: 0; top: 45px; width: 260px; background: white; border-radius: 12px; box-shadow: 0 4px 20px rgba(0,0,0,0.1); border: 1px solid #eaeef2; z-index: 1000;">
                                <div style="padding: 12px; border-bottom: 1px solid #eaeef2;">
                                    <span style="font-weight: 600; color: #1a1f36;">T1 Actions</span>
                                </div>
                                <div style="padding: 8px;">
                                    <button onclick='viewT1Details(${t1.id})' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-eye"></i> View Details
                                    </button>
                                    <button onclick='editT1(${t1.id})' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #1a1f36;">
                                        <i class="fas fa-edit"></i> Edit from SYDONIA
                                    </button>
                                    <button onclick='updateT1Status(${t1.id}, "${t1.t1Number}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #f97316;">
                                        <i class="fas fa-sync-alt"></i> Update Status
                                    </button>
                                    <button onclick='updateTrackingStatus(${t1.id}, "${t1.t1Number}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #3b82f6;">
                                        <i class="fas fa-map-marker-alt"></i> Update Tracking Status
                                    </button>
                                    <div style="height: 1px; background: #eaeef2; margin: 8px 0;"></div>
                                    ${!t1.device ? 
                                        `<button onclick='assignDeviceToT1(${t1.id}, "${t1.t1Number}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #10b981;">
                                            <i class="fas fa-microchip"></i> Assign Device
                                        </button>` : 
                                        `<button onclick='unassignDeviceFromT1(${t1.id}, "${t1.t1Number}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #f97316;">
                                            <i class="fas fa-microchip-slash"></i> Unassign Device
                                        </button>`
                                    }
                                    <button onclick='updateSeal(${t1.id}, "${t1.t1Number}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #8b5cf6;">
                                        <i class="fas fa-lock"></i> Update Seal
                                    </button>
                                    <div style="height: 1px; background: #eaeef2; margin: 8px 0;"></div>
                                    <button onclick='confirmT1Arrival(${t1.id}, "${t1.t1Number}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #2e7d32;">
                                        <i class="fas fa-flag-checkered"></i> Confirm Arrival
                                    </button>
                                    <button onclick='cancelT1(${t1.id}, "${t1.t1Number}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #dc2626;">
                                        <i class="fas fa-ban"></i> Cancel T1
                                    </button>
                                    <button onclick='viewJourneyStatus(${t1.id}, "${t1.t1Number}")' style="width: 100%; padding: 10px; text-align: left; background: none; border: none; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; color: #64748b;">
                                        <i class="fas fa-road"></i> Journey Status
                                    </button>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
                `;
            });

            html += `
                        </tbody>
                    </table>
                </div>

                <!-- Table Footer -->
                <div style="background: #ffffff; border-radius: 12px; padding: 16px; margin-top: 20px; border: 1px solid #eaeef2; display: flex; justify-content: space-between; align-items: center;">
                    <div style="color: #5b677c;">
                        <span id="selectedCount">0</span> items selected
                    </div>
                    <div class="table-pagination" id="tablePagination"></div>
                </div>

                <style>
                    .filter-chip.active { background: #000 !important; color: white !important; border-color: #000 !important; }
                    .t1-table tbody tr:hover { background: #f8fafc; cursor: pointer; }
                    .action-dropdown button:hover { background: #f0f2f5; }
                </style>
            </div>
            `;

            $(".crud_section").html(html);

            // Initialize DataTable
            const table = $('#t1tableview').DataTable({
                dom: 'rtip',
                pageLength: 10,
                lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
                order: [[1, 'asc']],
                columnDefs: [
                    { orderable: false, targets: [0, 10] }
                ]
            });

            // Search
            $('#t1Search').off('keyup').on('keyup', function() {
                table.search(this.value).draw();
            });

            // Page size
            $('#pageSize').off('change').on('change', function() {
                table.page.len(this.value).draw();
            });

            // Select All
            $("#selectAll").off("click").on("click", function() {
                $(".row-checkbox").prop("checked", this.checked);
                updateSelectedCount();
            });

            $(document).off("change", ".row-checkbox").on("change", ".row-checkbox", function() {
                updateSelectedCount();
                const total = $(".row-checkbox").length;
                const checked = $(".row-checkbox:checked").length;
                $("#selectAll").prop("checked", total === checked);
            });

            function updateSelectedCount() {
                $("#selectedCount").text($(".row-checkbox:checked").length);
            }
        },
        error: function(xhr, status, error) {
            console.error("Error loading T1 declarations:", error);
            $(".crud_section").html(`
                <div style="padding: 40px; text-align: center; background: white; border-radius: 16px; margin: 24px;">
                    <i class="fas fa-exclamation-triangle" style="font-size: 48px; color: #dc2626;"></i>
                    <h3 style="color: #1a1f36;">Failed to load T1 declarations</h3>
                    <p style="color: #5b677c;">${error}</p>
                    <button onclick="allT1()" style="padding: 10px 24px; background: #000; color: white; border: none; border-radius: 10px;">
                        <i class="fas fa-sync-alt"></i> Retry
                    </button>
                </div>
            `);
        }
    });
}

// Toggle action menu for T1
function toggleT1ActionMenu(t1Id) {
    $('[id^="t1_menu_"]').hide();
    $(`#t1_menu_${t1Id}`).toggle();
}

// ========== CRUD Operations ==========

// Create new T1 (POST /api/v1/customs/t1)
function addT1() {
    Swal.fire({
        title: 'Create New T1 / Gatepass',
        html: `
            <div style="text-align: left; max-height: 500px; overflow-y: auto; padding: 10px;">
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500;">T1 Number <span style="color: #db2828;">*</span></label>
                    <div style="position: relative;">
                        <i class="fas fa-barcode" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999;"></i>
                        <input id="t1Number" type="text" placeholder="e.g., BSL001" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid #ccc; border-radius: 4px;">
                    </div>
                </div>
                <div style="display: flex; gap: 10px;">
                    <div style="flex:1;">
                        <label>Consignor Name</label>
                        <input id="consignorName" class="swal2-input" placeholder="Consignor">
                    </div>
                    <div style="flex:1;">
                        <label>Consignor TIN</label>
                        <input id="consignorTin" class="swal2-input" placeholder="TIN">
                    </div>
                </div>
                <div style="display: flex; gap: 10px;">
                    <div style="flex:1;">
                        <label>Consignee Name</label>
                        <input id="consigneeName" class="swal2-input" placeholder="Consignee">
                    </div>
                    <div style="flex:1;">
                        <label>Consignee Country</label>
                        <input id="consigneeCountry" class="swal2-input" placeholder="Kenya">
                    </div>
                </div>
                <div style="display: flex; gap: 10px;">
                    <div style="flex:1;">
                        <label>Declarant Name</label>
                        <input id="declarantName" class="swal2-input" placeholder="Declarant">
                    </div>
                    <div style="flex:1;">
                        <label>Declarant TIN</label>
                        <input id="declarantTin" class="swal2-input" placeholder="TIN">
                    </div>
                </div>
                <div style="display: flex; gap: 10px;">
                    <div style="flex:1;">
                        <label>Truck Registration</label>
                        <input id="truckReg" class="swal2-input" placeholder="KDW 456 T">
                    </div>
                    <div style="flex:1;">
                        <label>Trailer Number</label>
                        <input id="trailerNo" class="swal2-input" placeholder="TR-9981">
                    </div>
                </div>
                <div style="display: flex; gap: 10px;">
                    <div style="flex:1;">
                        <label>Origin</label>
                        <input id="origin" class="swal2-input" placeholder="DMP Port">
                    </div>
                    <div style="flex:1;">
                        <label>Destination</label>
                        <input id="destination" class="swal2-input" placeholder="Galafi Border">
                    </div>
                </div>
                <div style="display: flex; gap: 10px;">
                    <div style="flex:1;">
                        <label>Exit Point</label>
                        <input id="exitPoint" class="swal2-input" placeholder="Galafi">
                    </div>
                    <div style="flex:1;">
                        <label>Cargo Type</label>
                        <input id="cargoType" class="swal2-input" placeholder="Transit">
                    </div>
                </div>
                <div style="display: flex; gap: 10px;">
                    <div style="flex:1;">
                        <label>Total Weight (kg)</label>
                        <input id="totalWeight" type="number" step="0.1" class="swal2-input" placeholder="1500.5">
                    </div>
                    <div style="flex:1;">
                        <label>Packages</label>
                        <input id="packages" type="number" class="swal2-input" placeholder="25">
                    </div>
                </div>
                <div>
                    <label>Goods Description</label>
                    <textarea id="goodsDesc" class="swal2-input" placeholder="Description of goods" rows="3"></textarea>
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Create T1',
        confirmButtonColor: '#000',
        preConfirm: () => {
            const t1Number = $('#t1Number').val();
            if (!t1Number) {
                Swal.showValidationMessage('T1 Number is required');
                return false;
            }
            return {
                t1Number: t1Number.trim(),
                consignorName: $('#consignorName').val() || null,
                consignorTin: $('#consignorTin').val() || null,
                consigneeName: $('#consigneeName').val() || null,
                consigneeCountry: $('#consigneeCountry').val() || null,
                declarantName: $('#declarantName').val() || null,
                declarantTin: $('#declarantTin').val() || null,
                truckRegistrationNumber: $('#truckReg').val() || null,
                trailerNumber: $('#trailerNo').val() || null,
                origin: $('#origin').val() || null,
                destination: $('#destination').val() || null,
                exitPoint: $('#exitPoint').val() || null,
                cargoType: $('#cargoType').val() || null,
                totalWeight: $('#totalWeight').val() ? parseFloat($('#totalWeight').val()) : null,
                numberOfPackages: $('#packages').val() ? parseInt($('#packages').val()) : null,
                goodsDescription: $('#goodsDesc').val() || null
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            createT1(result.value);
        }
    });
}

function createT1(data) {
    Swal.fire({ title: 'Creating...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
    $.ajax({
        url: serverURL + 'customs/t1',
        type: 'POST',
        contentType: 'application/json',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        data: JSON.stringify(data),
        success: () => {
            Swal.fire({ title: 'Success', text: 'T1 created', icon: 'success', confirmButtonColor: '#000' })
                .then(() => allT1());
        },
        error: (xhr) => {
            let msg = 'Creation failed';
            try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e) {}
            Swal.fire({ title: 'Error', text: msg, icon: 'error' });
        }
    });
}

// View details (GET /api/v1/customs/t1/{t1Number})
function viewT1Details(t1Id) {
    // Show loading
    Swal.fire({
        title: 'Loading T1 Details...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    // Get T1 number from row data attribute
    const t1Number = $(`tr[data-t1-id="${t1Id}"]`).data('t1-number');
    if (!t1Number) {
        Swal.fire({ title: 'Error', text: 'T1 number not found', icon: 'error' });
        return;
    }

    $.ajax({
        url: serverURL + 'customs/t1/' + t1Number,
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: (t1) => {
            Swal.close();

            // Helper to format dates
            const formatDate = (dateStr) => dateStr ? new Date(dateStr).toLocaleString() : 'N/A';

            // Determine status badge styles
            const statusBadge = t1.status === 'IN_TRANSIT' 
                ? '<span class="badge in-transit"><i class="fas fa-truck"></i> In Transit</span>'
                : t1.status === 'COMPLETED'
                ? '<span class="badge completed"><i class="fas fa-check-circle"></i> Completed</span>'
                : t1.status === 'CANCELLED'
                ? '<span class="badge cancelled"><i class="fas fa-ban"></i> Cancelled</span>'
                : t1.status === 'ARRIVED'
                ? '<span class="badge arrived"><i class="fas fa-flag-checkered"></i> Arrived</span>'
                : `<span class="badge default">${t1.status}</span>`;

            const trackingStatusBadge = t1.trackingStatus ? `<span class="badge tracking">${t1.trackingStatus}</span>` : '';

            // Device info
            const deviceInfo = t1.device 
                ? `<div><i class="fas fa-microchip"></i> <strong>${t1.device.serialNumber || t1.device.name}</strong> (${t1.device.online ? '<span style="color:#10b981;">Online</span>' : '<span style="color:#ef4444;">Offline</span>'})</div>`
                : '<span style="color:#94a3b8;">No device assigned</span>';

            // Location link
            const locationLink = (t1.currentLocation && t1.currentLocation.latitude && t1.currentLocation.longitude)
                ? `<a href="https://www.google.com/maps?q=${t1.currentLocation.latitude},${t1.currentLocation.longitude}" target="_blank" style="color:#3b82f6; text-decoration:none;">${t1.currentLocation.latitude.toFixed(6)}, ${t1.currentLocation.longitude.toFixed(6)}</a>`
                : 'N/A';

            const locationSpeed = t1.currentLocation ? ` (${t1.currentLocation.speedKph} km/h)` : '';

            const html = `
                <div class="t1-details-container">
                    <!-- Header with gradient -->
                    <div class="details-header">
                        <div class="header-icon">
                            <i class="fas fa-file-alt"></i>
                        </div>
                        <div class="header-title">
                            <h2>T1 Declaration</h2>
                            <div class="t1-number">${t1.t1Number}</div>
                        </div>
                        <div class="header-badges">
                            ${statusBadge}
                            ${trackingStatusBadge}
                        </div>
                    </div>

                    <!-- Two‑column layout -->
                    <div class="details-grid">
                        <!-- Left column: Consignor/Consignee -->
                        <div class="info-card">
                            <h3><i class="fas fa-user-tie"></i> Parties</h3>
                            <div class="info-row">
                                <span class="info-label">Consignor</span>
                                <span class="info-value">${t1.consignorName || 'N/A'} (TIN: ${t1.consignorTin || 'N/A'})</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">Consignee</span>
                                <span class="info-value">${t1.consigneeName || 'N/A'} (${t1.consigneeCountry || 'N/A'})</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">Declarant</span>
                                <span class="info-value">${t1.declarantName || 'N/A'} (${t1.declarantCountry || 'N/A'})</span>
                            </div>
                        </div>

                        <!-- Right column: Transport -->
                        <div class="info-card">
                            <h3><i class="fas fa-truck"></i> Transport</h3>
                            <div class="info-row">
                                <span class="info-label">Truck</span>
                                <span class="info-value">${t1.truckRegistrationNumber || 'N/A'}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">Trailer</span>
                                <span class="info-value">${t1.trailerNumber || 'N/A'}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">Route</span>
                                <span class="info-value">${t1.origin || 'N/A'} → ${t1.destination || 'N/A'}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">Exit Point</span>
                                <span class="info-value">${t1.exitPoint || 'N/A'}</span>
                            </div>
                        </div>
                    </div>

                    <!-- Second row: Cargo & Device -->
                    <div class="details-grid">
                        <div class="info-card">
                            <h3><i class="fas fa-boxes"></i> Cargo</h3>
                            <div class="info-row">
                                <span class="info-label">Description</span>
                                <span class="info-value">${t1.goodsDescription || 'N/A'}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">Weight</span>
                                <span class="info-value">${t1.totalWeight ? t1.totalWeight + ' kg' : 'N/A'}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">Packages</span>
                                <span class="info-value">${t1.numberOfPackages || 'N/A'}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">Cargo Type</span>
                                <span class="info-value">${t1.cargoType || 'N/A'}</span>
                            </div>
                        </div>

                        <div class="info-card">
                            <h3><i class="fas fa-microchip"></i> Device & Location</h3>
                            <div class="info-row">
                                <span class="info-label">Device</span>
                                <span class="info-value">${deviceInfo}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">Last Position</span>
                                <span class="info-value">${locationLink}${locationSpeed}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">Last Update</span>
                                <span class="info-value">${formatDate(t1.lastPositionUpdate)}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">Device Assigned</span>
                                <span class="info-value">${formatDate(t1.deviceAssignedAt)}</span>
                            </div>
                        </div>
                    </div>

                    <!-- Timeline / System Info -->
                    <div class="info-card system-info">
                        <h3><i class="fas fa-history"></i> Timeline</h3>
                        <div style="display: flex; gap: 20px; flex-wrap: wrap;">
                            <div><span class="info-label">Created</span> ${formatDate(t1.createdAt)}</div>
                            <div><span class="info-label">Updated</span> ${formatDate(t1.updatedAt)}</div>
                            <div><span class="info-label">Declaration Date</span> ${t1.declarationDate ? new Date(t1.declarationDate).toLocaleDateString() : 'N/A'}</div>
                        </div>
                    </div>

                    <!-- Action buttons -->
                    <div style="display: flex; gap: 10px; justify-content: flex-end; margin-top: 20px;">
                        <button onclick="window.open('https://www.google.com/maps?q=${t1.currentLocation?.latitude || 0},${t1.currentLocation?.longitude || 0}', '_blank')" class="map-btn" ${!t1.currentLocation ? 'disabled' : ''}>
                            <i class="fas fa-map-marked-alt"></i> View on Map
                        </button>
                        <button onclick="viewJourneyStatus(${t1.id}, '${t1.t1Number}')" class="journey-btn">
                            <i class="fas fa-road"></i> Journey Status
                        </button>
                    </div>
                </div>

                <style>
                    .t1-details-container {
                        text-align: left;
                        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                        max-height: 70vh;
                        overflow-y: auto;
                        padding: 5px;
                    }
                    .details-header {
                        display: flex;
                        align-items: center;
                        gap: 20px;
                        background: linear-gradient(135deg, #4b6af3 0%, #2c3e9e 100%);
                        margin: -20px -20px 20px -20px;
                        padding: 25px 30px;
                        border-radius: 20px 20px 0 0;
                        color: white;
                        flex-wrap: wrap;
                    }
                    .header-icon {
                        font-size: 48px;
                        color: rgba(255,255,255,0.8);
                    }
                    .header-title h2 {
                        margin: 0;
                        font-size: 24px;
                        font-weight: 600;
                    }
                    .t1-number {
                        font-size: 16px;
                        opacity: 0.9;
                        margin-top: 4px;
                    }
                    .header-badges {
                        display: flex;
                        gap: 8px;
                        flex-wrap: wrap;
                    }
                    .badge {
                        display: inline-flex;
                        align-items: center;
                        gap: 6px;
                        padding: 6px 14px;
                        border-radius: 30px;
                        font-size: 13px;
                        font-weight: 500;
                        background: rgba(255,255,255,0.2);
                        backdrop-filter: blur(5px);
                        border: 1px solid rgba(255,255,255,0.3);
                        color: white;
                    }
                    .badge.in-transit { background: #1976d2; }
                    .badge.completed { background: #2e7d32; }
                    .badge.cancelled { background: #dc2626; }
                    .badge.arrived { background: #2e7d32; }
                    .badge.default { background: #6b7280; }
                    .badge.tracking { background: #8b5cf6; }

                    .details-grid {
                        display: grid;
                        grid-template-columns: repeat(2, 1fr);
                        gap: 20px;
                        margin-bottom: 20px;
                    }
                    .info-card {
                        background: #f8fafc;
                        border-radius: 16px;
                        padding: 20px;
                        border: 1px solid #e2e8f0;
                    }
                    .info-card h3 {
                        margin: 0 0 15px 0;
                        font-size: 16px;
                        font-weight: 600;
                        color: #1e293b;
                        display: flex;
                        align-items: center;
                        gap: 8px;
                    }
                    .info-card h3 i {
                        color: #3b82f6;
                    }
                    .info-row {
                        display: flex;
                        justify-content: space-between;
                        padding: 8px 0;
                        border-bottom: 1px solid #e9eef2;
                    }
                    .info-row:last-child {
                        border-bottom: none;
                    }
                    .info-label {
                        font-size: 13px;
                        color: #64748b;
                        font-weight: 500;
                    }
                    .info-value {
                        font-size: 13px;
                        font-weight: 600;
                        color: #1e293b;
                        text-align: right;
                        word-break: break-word;
                    }
                    .system-info {
                        background: #f1f5f9;
                    }
                    .map-btn, .journey-btn {
                        padding: 10px 20px;
                        border: none;
                        border-radius: 30px;
                        font-weight: 500;
                        cursor: pointer;
                        display: inline-flex;
                        align-items: center;
                        gap: 8px;
                        transition: all 0.2s;
                    }
                    .map-btn {
                        background: #3b82f6;
                        color: white;
                    }
                    .map-btn:hover {
                        background: #2563eb;
                    }
                    .map-btn:disabled {
                        opacity: 0.5;
                        cursor: not-allowed;
                    }
                    .journey-btn {
                        background: #10b981;
                        color: white;
                    }
                    .journey-btn:hover {
                        background: #059669;
                    }
                    @media (max-width: 600px) {
                        .details-grid { grid-template-columns: 1fr; }
                        .details-header { flex-direction: column; text-align: center; }
                        .header-badges { margin-left: 0; }
                    }
                </style>
            `;

            Swal.fire({
                title: null,
                html: html,
                showCloseButton: true,
                showConfirmButton: false,
                background: '#ffffff',
                color: '#1a1f36',
                width: '900px',
                customClass: {
                    popup: 't1-details-popup'
                }
            });
        },
        error: () => Swal.fire({ title: 'Error', text: 'Could not fetch T1 details', icon: 'error' })
    });
}

// Edit T1 (PUT /api/v1/customs/t1/{t1Number})
function editT1(t1Id) {
    const t1Number = $(`tr[data-t1-id="${t1Id}"]`).data('t1-number');
    if (!t1Number) return Swal.fire('Error', 'T1 number not found', 'error');

    Swal.fire({ title: 'Loading...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
    $.ajax({
        url: serverURL + 'customs/t1/' + t1Number,
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: (t1) => {
            Swal.close();
            // Show edit form pre-filled (simplified – you can expand as needed)
            Swal.fire({
                title: 'Edit T1 (from SYDONIA)',
                html: `
                    <input id="editT1Number" class="swal2-input" value="${t1.t1Number}" readonly>
                    <input id="editConsignorName" class="swal2-input" value="${t1.consignorName || ''}" placeholder="Consignor Name">
                    <input id="editConsigneeName" class="swal2-input" value="${t1.consigneeName || ''}" placeholder="Consignee Name">
                    <input id="editTruckReg" class="swal2-input" value="${t1.truckRegistrationNumber || ''}" placeholder="Truck Reg">
                    <input id="editTrailer" class="swal2-input" value="${t1.trailerNumber || ''}" placeholder="Trailer Number">
                    <input id="editOrigin" class="swal2-input" value="${t1.origin || ''}" placeholder="Origin">
                    <input id="editDestination" class="swal2-input" value="${t1.destination || ''}" placeholder="Destination">
                `,
                showCancelButton: true,
                confirmButtonText: 'Update',
                preConfirm: () => {
                    return {
                        t1Number: $('#editT1Number').val(),
                        consignorName: $('#editConsignorName').val() || null,
                        consigneeName: $('#editConsigneeName').val() || null,
                        truckRegistrationNumber: $('#editTruckReg').val() || null,
                        trailerNumber: $('#editTrailer').val() || null,
                        origin: $('#editOrigin').val() || null,
                        destination: $('#editDestination').val() || null
                        // Add other fields as needed
                    };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    updateT1(t1Number, result.value);
                }
            });
        },
        error: () => Swal.fire('Error', 'Could not load T1', 'error')
    });
}

function updateT1(t1Number, data) {
    Swal.fire({ title: 'Updating...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
    $.ajax({
        url: serverURL + 'customs/t1/' + t1Number,
        type: 'PUT',
        contentType: 'application/json',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        data: JSON.stringify(data),
        success: () => {
            Swal.fire({ title: 'Success', text: 'T1 updated', icon: 'success' }).then(() => allT1());
        },
        error: (xhr) => {
            let msg = 'Update failed';
            try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e) {}
            Swal.fire({ title: 'Error', text: msg, icon: 'error' });
        }
    });
}

// Update T1 status (PUT /api/v1/customs/t1/{t1Number}/status)
function updateT1Status(t1Id, t1Number) {
    Swal.fire({
        title: 'Update T1 Status',
        input: 'select',
        inputOptions: {
            'IN_TRANSIT': 'In Transit',
            'COMPLETED': 'Completed',
            'CANCELLED': 'Cancelled'
        },
        inputPlaceholder: 'Select new status',
        showCancelButton: true,
        confirmButtonColor: '#f97316',
        preConfirm: (status) => {
            if (!status) {
                Swal.showValidationMessage('Please select a status');
                return false;
            }
            return status;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({ title: 'Updating...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
            $.ajax({
                url: serverURL + 'customs/t1/' + t1Number + '/status',
                type: 'PUT',
                contentType: 'application/json',
                headers: { Authorization: 'Bearer ' + userObj.accessToken },
                data: JSON.stringify({ status: result.value }),
                success: () => {
                    Swal.fire({ title: 'Success', text: 'Status updated', icon: 'success' }).then(() => allT1());
                },
                error: (xhr) => {
                    let msg = 'Update failed';
                    try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e) {}
                    Swal.fire({ title: 'Error', text: msg, icon: 'error' });
                }
            });
        }
    });
}

// Update tracking status (PUT /api/v1/customs/t1/{t1Number}/tracking-status)
function updateTrackingStatus(t1Id, t1Number) {
    Swal.fire({
        title: 'Update Tracking Status',
        input: 'text',
        inputLabel: 'New tracking status',
        inputPlaceholder: 'e.g., IN_TRANSIT, ARRIVED, etc.',
        showCancelButton: true,
        confirmButtonColor: '#3b82f6',
        preConfirm: (status) => {
            if (!status) {
                Swal.showValidationMessage('Status is required');
                return false;
            }
            return status;
        }
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({ title: 'Updating...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
            $.ajax({
                url: serverURL + 'customs/t1/' + t1Number + '/tracking-status',
                type: 'PUT',
                contentType: 'application/json',
                headers: { Authorization: 'Bearer ' + userObj.accessToken },
                data: JSON.stringify({ trackingStatus: result.value }),
                success: () => {
                    Swal.fire({ title: 'Success', text: 'Tracking status updated', icon: 'success' }).then(() => allT1());
                },
                error: (xhr) => {
                    let msg = 'Update failed';
                    try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e) {}
                    Swal.fire({ title: 'Error', text: msg, icon: 'error' });
                }
            });
        }
    });
}





// Assign device to T1 (POST /api/v1/customs/t1/assign-device)
function assignDeviceToT1(t1Id, t1Number) {
    // First fetch list of available devices (adjust endpoint as needed)
    Swal.fire({
        title: 'Loading devices...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    $.ajax({
        url: serverURL + 'devices/all', // Change to your actual endpoint for unassigned devices
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: function(devices) {
            Swal.close();

            if (!devices || devices.length === 0) {
                Swal.fire({
                    title: 'No Devices',
                    text: 'No available devices to assign',
                    icon: 'info',
                    confirmButtonColor: '#000'
                });
                return;
            }

            // Build dropdown options HTML
            let options = '<option value="">Select a device</option>';
            devices.forEach(device => {
                const displayName = device.serialNumber || device.name || `Device ${device.deviceId}`;
                options += `<option value="${device.deviceId}">${displayName} (ID: ${device.deviceId})</option>`;
            });

            Swal.fire({
                title: 'Assign Device to T1',
                html: `
                    <div style="text-align: left; max-height: 500px; overflow-y: auto; padding: 10px;">
                        <p style="margin-bottom: 15px; font-weight: 500; color: #1a1f36;">T1 Number: <span style="font-weight: 600; color: #000;">${t1Number}</span></p>
                        
                        <!-- Device Dropdown -->
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Device <span style="color: #db2828;">*</span></label>
                            <div style="position: relative; width: 100%;">
                                <i class="fas fa-microchip" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                                <select id="deviceSelect" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box; background: white; appearance: none; -webkit-appearance: none;">
                                    ${options}
                                </select>
                                <i class="fas fa-chevron-down" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;"></i>
                            </div>
                        </div>

                        <!-- Remarks (optional) -->
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Remarks</label>
                            <div style="position: relative; width: 100%;">
                                <i class="fas fa-sticky-note" style="position: absolute; left: 12px; top: 15px; color: #999; z-index: 1;"></i>
                                <textarea id="remarks" placeholder="Enter any remarks" rows="3" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; font-family: inherit; box-sizing: border-box; resize: vertical;"></textarea>
                            </div>
                        </div>
                    </div>

                    <style>
                        /* Form styles - matching device form */
                        input:focus, select:focus, textarea:focus {
                            border-color: #85b7d9 !important;
                            outline: 0 !important;
                            box-shadow: 0 0 0 2px rgba(33,133,208,.2) !important;
                        }
                        select {
                            cursor: pointer;
                        }
                        .swal2-popup {
                            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                        }
                        .swal2-title {
                            color: #1a1f36;
                        }
                    </style>
                `,
                showCancelButton: true,
                confirmButtonText: 'Assign Device',
                confirmButtonColor: '#10b981', // green for assign
                cancelButtonColor: '#64748b',
                background: '#ffffff',
                color: '#1a1f36',
                width: '700px',
                preConfirm: () => {
                    const deviceId = $('#deviceSelect').val();
                    const remarks = $('#remarks').val();
                    
                    if (!deviceId) {
                        Swal.showValidationMessage('Please select a device');
                        return false;
                    }
                    
                    return {
                        deviceId: parseInt(deviceId),
                        remarks: remarks ? remarks.trim() : null
                    };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    const { deviceId, remarks } = result.value;
                    const assignedBy = userObj.userId || 0; // adjust if your user object stores id differently

                    const payload = {
                        t1Number: t1Number,
                        deviceId: deviceId,
                        assignedBy: assignedBy,
                        remarks: remarks
                    };

                    Swal.fire({
                        title: 'Assigning...',
                        allowOutsideClick: false,
                        didOpen: () => Swal.showLoading()
                    });

                    $.ajax({
                        url: serverURL + 'customs/t1/assign-device',
                        type: 'POST',
                        contentType: 'application/json',
                        headers: { Authorization: 'Bearer ' + userObj.accessToken },
                        data: JSON.stringify(payload),
                        success: function() {
                            Swal.fire({
                                title: 'Success!',
                                text: 'Device assigned successfully',
                                icon: 'success',
                                confirmButtonColor: '#000',
                                background: '#ffffff',
                                color: '#1a1f36'
                            }).then(() => allT1());
                        },
                        error: function(xhr) {
                            let msg = 'Assignment failed';
                            try {
                                const resp = JSON.parse(xhr.responseText);
                                msg = resp.message || msg;
                            } catch (e) {
                                msg = xhr.statusText || msg;
                            }
                            Swal.fire({
                                title: 'Error',
                                text: msg,
                                icon: 'error',
                                confirmButtonColor: '#000',
                                background: '#ffffff',
                                color: '#1a1f36'
                            });
                        }
                    });
                }
            });
        },
        error: function(xhr) {
            Swal.close();
            let msg = 'Could not load devices';
            try {
                const resp = JSON.parse(xhr.responseText);
                msg = resp.message || msg;
            } catch (e) {}
            Swal.fire({
                title: 'Error',
                text: msg,
                icon: 'error',
                confirmButtonColor: '#000',
                background: '#ffffff',
                color: '#1a1f36'
            });
        }
    });
}

// Unassign device from T1 (POST /api/v1/customs/t1/{t1Number}/unassign-device)
function unassignDeviceFromT1(t1Id, t1Number) {
    Swal.fire({
        title: 'Unassign Device?',
        text: 'Are you sure you want to unassign the device from this T1?',
        icon: 'warning',
        // input: 'textarea',
        // inputLabel: 'Reason (optional)',
        showCancelButton: true,
        confirmButtonColor: '#f97316',
        confirmButtonText: 'Yes, unassign'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({ title: 'Unassigning...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
            $.ajax({
                url: serverURL + 'customs/t1/' + t1Number + '/unassign-device',
                type: 'POST',
                contentType: 'application/json',
                headers: { Authorization: 'Bearer ' + userObj.accessToken },
                data: result.value ? JSON.stringify({ reason: result.value }) : undefined,
                success: () => {
                    Swal.fire({ title: 'Success', text: 'Device unassigned', icon: 'success' }).then(() => allT1());
                },
                error: (xhr) => {
                    let msg = 'Unassignment failed';
                    try { msg = JSON.parse(xhr.responseText).message || msg; } catch(e) {}
                    Swal.fire({ title: 'Error', text: msg, icon: 'error' });
                }
            });
        }
    });
}

// Update seal (POST /api/v1/customs/api/t1/{t1Number}/update-seal)
function updateSeal(t1Id, t1Number) {
    // First fetch list of devices (all or unassigned – adjust endpoint as needed)
    Swal.fire({
        title: 'Loading devices...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    $.ajax({
        url: serverURL + 'devices/all', // Change to correct endpoint
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: function(devices) {
            Swal.close();

            if (!devices || devices.length === 0) {
                Swal.fire({
                    title: 'No Devices',
                    text: 'No devices available to use as seal number',
                    icon: 'info',
                    confirmButtonColor: '#000'
                });
                return;
            }

            // Build dropdown options using device serial number (or other identifier)
            let options = '<option value="">Select a device</option>';
            devices.forEach(device => {
                const serial = device.serialNumber || device.name || `Device ${device.deviceId}`;
                options += `<option value="${serial}">${serial} (ID: ${device.deviceId})</option>`;
            });

            Swal.fire({
                title: 'Update Seal Number',
                html: `
                    <div style="text-align: left; max-height: 500px; overflow-y: auto; padding: 10px;">
                        <p style="margin-bottom: 15px; font-weight: 500; color: #1a1f36;">T1 Number: <span style="font-weight: 600; color: #000;">${t1Number}</span></p>
                        
                        <!-- Device Dropdown (choose new seal number) -->
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Select Device (Seal Number) <span style="color: #db2828;">*</span></label>
                            <div style="position: relative; width: 100%;">
                                <i class="fas fa-microchip" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                                <select id="sealDeviceSelect" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box; background: white; appearance: none; -webkit-appearance: none;">
                                    ${options}
                                </select>
                                <i class="fas fa-chevron-down" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;"></i>
                            </div>
                            <small style="color: #64748b; display: block; margin-top: 4px;">The selected device's serial number will be used as the new seal number.</small>
                        </div>

                        <!-- Optional Remarks -->
                        <div style="margin-bottom: 15px;">
                            <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Remarks (optional)</label>
                            <div style="position: relative; width: 100%;">
                                <i class="fas fa-sticky-note" style="position: absolute; left: 12px; top: 15px; color: #999; z-index: 1;"></i>
                                <textarea id="remarks" placeholder="Enter any remarks" rows="3" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; font-family: inherit; box-sizing: border-box; resize: vertical;"></textarea>
                            </div>
                        </div>
                    </div>

                    <style>
                        input:focus, select:focus, textarea:focus {
                            border-color: #85b7d9 !important;
                            outline: 0 !important;
                            box-shadow: 0 0 0 2px rgba(33,133,208,.2) !important;
                        }
                        select {
                            cursor: pointer;
                        }
                        .swal2-popup {
                            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                        }
                        .swal2-title {
                            color: #1a1f36;
                        }
                    </style>
                `,
                showCancelButton: true,
                confirmButtonText: 'Update Seal',
                confirmButtonColor: '#8b5cf6',
                cancelButtonColor: '#64748b',
                background: '#ffffff',
                color: '#1a1f36',
                width: '700px',
                preConfirm: () => {
                    const sealNumber = $('#sealDeviceSelect').val();
                    if (!sealNumber) {
                        Swal.showValidationMessage('Please select a device');
                        return false;
                    }
                    const remarks = $('#remarks').val();
                    return {
                        sealNumber: sealNumber,
                        remarks: remarks ? remarks.trim() : null
                    };
                }
            }).then((result) => {
                if (result.isConfirmed) {
                    const { sealNumber, remarks } = result.value;

                    // Construct URL with query parameter
                    let url = `${serverURL}customs/api/t1/${t1Number}/update-seal?newSealNumber=${encodeURIComponent(sealNumber)}`;
                    // If remarks are to be sent, add as another param (adjust as needed)
                    // if (remarks) url += `&remarks=${encodeURIComponent(remarks)}`;

                    Swal.fire({
                        title: 'Updating...',
                        allowOutsideClick: false,
                        didOpen: () => Swal.showLoading()
                    });

                    $.ajax({
                        url: url,
                        type: 'POST', // or GET? Your example shows GET style but we'll keep POST as original
                        headers: { Authorization: 'Bearer ' + userObj.accessToken },
                        success: function() {
                            Swal.fire({
                                title: 'Success!',
                                text: 'Seal number updated successfully',
                                icon: 'success',
                                confirmButtonColor: '#000',
                                background: '#ffffff',
                                color: '#1a1f36'
                            }).then(() => allT1());
                        },
                        error: function(xhr) {
                            let msg = 'Update failed';
                            try {
                                const resp = JSON.parse(xhr.responseText);
                                msg = resp.message || msg;
                            } catch (e) {
                                msg = xhr.statusText || msg;
                            }
                            Swal.fire({
                                title: 'Error',
                                text: msg,
                                icon: 'error',
                                confirmButtonColor: '#000',
                                background: '#ffffff',
                                color: '#1a1f36'
                            });
                        }
                    });
                }
            });
        },
        error: function(xhr) {
            Swal.close();
            let msg = 'Could not load devices';
            try {
                const resp = JSON.parse(xhr.responseText);
                msg = resp.message || msg;
            } catch (e) {}
            Swal.fire({
                title: 'Error',
                text: msg,
                icon: 'error',
                confirmButtonColor: '#000',
                background: '#ffffff',
                color: '#1a1f36'
            });
        }
    });
}
// Confirm arrival (POST /api/v1/customs/t1/{t1Number}/arrival)
function confirmT1Arrival(t1Id, t1Number) {
    // First load ports and inspection statuses
    Promise.all([
        $.ajax({ url: serverURL + 'ports', headers: { Authorization: 'Bearer ' + userObj.accessToken } }),
        $.ajax({ url: serverURL + 'inspection-statuses', headers: { Authorization: 'Bearer ' + userObj.accessToken } })
    ]).then(([ports, inspectionStatuses]) => {
        // Build dropdown options
        let portOptions = '<option value="">Select a port</option>';
        ports.forEach(p => {
            portOptions += `<option value="${p.id}">${p.name} (${p.code})</option>`;
        });

        let statusOptions = '<option value="">None</option>';
        inspectionStatuses.forEach(s => {
            statusOptions += `<option value="${s.id}">${s.name} (${s.code})</option>`;
        });

        const hasFlatpickr = typeof flatpickr === 'function';

        Swal.fire({
            title: 'Confirm T1 Arrival',
            html: `
                <div style="text-align: left; max-height: 500px; overflow-y: auto; padding: 10px;">
                    <p style="margin-bottom: 15px; font-weight: 500; color: #1a1f36;">T1 Number: <span style="font-weight: 600; color: #000;">${t1Number}</span></p>
                    
                    <!-- Arrival Time (required) -->
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Arrival Time <span style="color: #db2828;">*</span></label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-calendar-alt" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input type="${hasFlatpickr ? 'text' : 'datetime-local'}" id="arrivalTime" placeholder="YYYY-MM-DDTHH:MM:SS" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                        <small style="color: #64748b; display: block; margin-top: 4px;">Format: YYYY-MM-DDTHH:MM:SS (e.g., 2025-03-12T14:30:00)</small>
                    </div>

                    <!-- Port (required) -->
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Port <span style="color: #db2828;">*</span></label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-ship" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <select id="portId" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box; background: white; appearance: none;">
                                ${portOptions}
                            </select>
                            <i class="fas fa-chevron-down" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;"></i>
                        </div>
                    </div>

                    <!-- Inspection Status (optional) -->
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Inspection Status</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-clipboard-check" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <select id="inspectionStatusId" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box; background: white; appearance: none;">
                                ${statusOptions}
                            </select>
                            <i class="fas fa-chevron-down" style="position: absolute; right: 12px; top: 50%; transform: translateY(-50%); color: #999; pointer-events: none;"></i>
                        </div>
                    </div>

                    <!-- Seal Status (optional) -->
                    <div style="margin-bottom: 15px;">
                        <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Seal Status (optional)</label>
                        <div style="position: relative; width: 100%;">
                            <i class="fas fa-lock" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                            <input type="text" id="sealStatus" placeholder="e.g., INTACT, BROKEN" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                        </div>
                    </div>
                </div>

                <style>
                    input:focus, select:focus {
                        border-color: #85b7d9 !important;
                        outline: 0 !important;
                        box-shadow: 0 0 0 2px rgba(33,133,208,.2) !important;
                    }
                    select { cursor: pointer; }
                    .swal2-popup { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; }
                    .swal2-title { color: #1a1f36; }
                </style>
            `,
            showCancelButton: true,
            confirmButtonText: 'Confirm Arrival',
            confirmButtonColor: '#10b981',
            cancelButtonColor: '#64748b',
            background: '#ffffff',
            color: '#1a1f36',
            width: '700px',
            didOpen: () => {
                if (hasFlatpickr) {
                    flatpickr("#arrivalTime", {
                        enableTime: true,
                        dateFormat: "Y-m-d\\TH:i:S",
                        time_24hr: true,
                        allowInput: true,
                        defaultDate: new Date()
                    });
                }
            },
            preConfirm: () => {
                const arrivalTime = $('#arrivalTime').val();
                const portId = $('#portId').val();
                const inspectionStatusId = $('#inspectionStatusId').val();
                const sealStatus = $('#sealStatus').val();

                if (!arrivalTime) {
                    Swal.showValidationMessage('Arrival time is required');
                    return false;
                }
                if (!portId) {
                    Swal.showValidationMessage('Please select a port');
                    return false;
                }

                let formattedArrivalTime = arrivalTime;
                if (!hasFlatpickr && arrivalTime && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(arrivalTime)) {
                    formattedArrivalTime = arrivalTime + ':00';
                }

                return {
                    t1Number: t1Number,
                    arrivalTime: formattedArrivalTime,
                    portId: parseInt(portId),
                    inspectionStatusId: inspectionStatusId ? parseInt(inspectionStatusId) : null,
                    sealStatus: sealStatus ? sealStatus.trim() : null
                };
            }
        }).then((result) => {
            if (result.isConfirmed) {
                Swal.fire({
                    title: 'Confirming Arrival...',
                    allowOutsideClick: false,
                    didOpen: () => Swal.showLoading()
                });

                $.ajax({
                    url: serverURL + 'customs/t1/arrival',
                    type: 'POST',
                    contentType: 'application/json',
                    headers: { Authorization: 'Bearer ' + userObj.accessToken },
                    data: JSON.stringify(result.value),
                    success: function() {
                        Swal.fire({
                            title: 'Success!',
                            text: 'Arrival confirmed successfully',
                            icon: 'success',
                            confirmButtonColor: '#000'
                        }).then(() => allT1());
                    },
                    error: function(xhr) {
                        let msg = 'Confirmation failed';
                        try {
                            const resp = JSON.parse(xhr.responseText);
                            msg = resp.message || msg;
                        } catch (e) {
                            msg = xhr.statusText || msg;
                        }
                        Swal.fire({
                            title: 'Error',
                            text: msg,
                            icon: 'error',
                            confirmButtonColor: '#000'
                        });
                    }
                });
            }
        });
    }).catch(() => {
        Swal.fire({
            title: 'Error',
            text: 'Could not load ports or inspection statuses',
            icon: 'error',
            confirmButtonColor: '#000'
        });
    });
}

// Cancel T1 (POST /api/v1/customs/t1/{t1Number}/cancel)
function cancelT1(t1Id, t1Number) {
    // Check if flatpickr is available and is a function
    const hasFlatpickr = typeof flatpickr === 'function';

    Swal.fire({
        title: 'Cancel T1 / Gatepass',
        html: `
            <div style="text-align: left; max-height: 500px; overflow-y: auto; padding: 10px;">
                <p style="margin-bottom: 15px; font-weight: 500; color: #1a1f36;">T1 Number: <span style="font-weight: 600; color: #000;">${t1Number}</span></p>
                
                <!-- Cancellation Time (optional) - placed first -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Cancellation Time (optional)</label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-calendar-alt" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #999; z-index: 1;"></i>
                        <input type="${hasFlatpickr ? 'text' : 'datetime-local'}" id="cancelTime" placeholder="YYYY-MM-DDTHH:MM:SS" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; box-sizing: border-box;">
                    </div>
                    <small style="color: #64748b; display: block; margin-top: 4px;">Format: YYYY-MM-DDTHH:MM:SS (e.g., 2025-03-12T14:30:00)</small>
                </div>

                <!-- Reason (required) -->
                <div style="margin-bottom: 15px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: 500; color: #1a1f36;">Reason <span style="color: #db2828;">*</span></label>
                    <div style="position: relative; width: 100%;">
                        <i class="fas fa-comment" style="position: absolute; left: 12px; top: 15px; color: #999; z-index: 1;"></i>
                        <textarea id="cancelReason" placeholder="Enter reason for cancellation" rows="3" style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid rgba(34,36,38,.15); border-radius: 4px; font-size: 14px; font-family: inherit; box-sizing: border-box; resize: vertical;"></textarea>
                    </div>
                </div>
            </div>

            <style>
                input:focus, textarea:focus {
                    border-color: #85b7d9 !important;
                    outline: 0 !important;
                    box-shadow: 0 0 0 2px rgba(33,133,208,.2) !important;
                }
                .swal2-popup {
                    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
                }
                .swal2-title {
                    color: #1a1f36;
                }
            </style>
        `,
        showCancelButton: true,
        confirmButtonText: 'Cancel T1',
        confirmButtonColor: '#dc2626', // red for cancel
        cancelButtonColor: '#64748b',
        background: '#ffffff',
        color: '#1a1f36',
        width: '700px',
        didOpen: () => {
            // Initialize flatpickr only if it's available as a function
            if (hasFlatpickr) {
                flatpickr("#cancelTime", {
                    enableTime: true,
                    dateFormat: "Y-m-d\\TH:i:S",
                    time_24hr: true,
                    allowInput: true,
                    defaultDate: new Date() // optionally prefill with current date/time
                });
            }
        },
        preConfirm: () => {
            // Validate reason
            const reason = $('#cancelReason').val();
            if (!reason) {
                Swal.showValidationMessage('Reason is required');
                return false;
            }

            // Get cancellation time
            let cancellationTime = $('#cancelTime').val();
            
            // If flatpickr is not used and the input is datetime-local, it returns YYYY-MM-DDTHH:MM
            // Append seconds if missing
            if (!hasFlatpickr && cancellationTime) {
                // Check if it matches pattern without seconds
                if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(cancellationTime)) {
                    cancellationTime += ':00';
                }
            }

            return {
                reason: reason.trim(),
                cancellationTime: cancellationTime || null // send null if empty
            };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { reason, cancellationTime } = result.value;

            // Build URL with query parameters
            let url = `${serverURL}customs/t1/${t1Number}/cancel?reason=${encodeURIComponent(reason)}`;
            if (cancellationTime) {
                url += `&cancellationTime=${encodeURIComponent(cancellationTime)}`;
            }

            Swal.fire({
                title: 'Cancelling...',
                allowOutsideClick: false,
                didOpen: () => Swal.showLoading()
            });

            $.ajax({
                url: url,
                type: 'POST', // Adjust if your API expects a different method
                headers: { Authorization: 'Bearer ' + userObj.accessToken },
                success: function() {
                    Swal.fire({
                        title: 'Success!',
                        text: 'T1 cancelled successfully',
                        icon: 'success',
                        confirmButtonColor: '#000',
                        background: '#ffffff',
                        color: '#1a1f36'
                    }).then(() => allT1());
                },
                error: function(xhr) {
                    let msg = 'Cancellation failed';
                    try {
                        const resp = JSON.parse(xhr.responseText);
                        msg = resp.message || msg;
                    } catch (e) {
                        msg = xhr.statusText || msg;
                    }
                    Swal.fire({
                        title: 'Error',
                        text: msg,
                        icon: 'error',
                        confirmButtonColor: '#000',
                        background: '#ffffff',
                        color: '#1a1f36'
                    });
                }
            });
        }
    });
}

// View journey status (GET /api/v1/customs/t1/{t1Number}/journey-status)
// Enhanced function to view T1 journey status with interactive map
function viewJourneyStatus(t1Id, t1Number) {
    Swal.fire({
        title: 'Loading Journey Status...',
        allowOutsideClick: false,
        didOpen: () => Swal.showLoading()
    });

    $.ajax({
        url: serverURL + 'customs/t1/' + t1Number + '/journey-status',
        type: 'GET',
        headers: { Authorization: 'Bearer ' + userObj.accessToken },
        success: (journey) => {
            Swal.close();

            // If no location data, show info message
            if (!journey.lastLatitude || !journey.lastLongitude) {
                Swal.fire({
                    title: 'No Location Data',
                    text: 'This T1 has no recent location information.',
                    icon: 'info',
                    confirmButtonColor: '#000'
                });
                return;
            }

            // Display the interactive map with journey data
            displayT1JourneyMap(t1Number, journey);
        },
        error: (xhr) => {
            let msg = 'Could not fetch journey status';
            try {
                const resp = JSON.parse(xhr.responseText);
                msg = resp.message || msg;
            } catch (e) {}
            Swal.fire({
                title: 'Error',
                text: msg,
                icon: 'error',
                confirmButtonColor: '#000'
            });
        }
    });
}

// Display interactive Google Map for T1 journey
function displayT1JourneyMap(t1Number, journey) {
    const latitude = journey.lastLatitude;
    const longitude = journey.lastLongitude;
    const timestamp = journey.lastLocationTimestamp ? new Date(journey.lastLocationTimestamp).toLocaleString() : 'N/A';
    const speed = journey.currentSpeed || 0;
    const odometer = journey.odometerReading ? journey.odometerReading.toFixed(1) : 'N/A';
    const esealStatus = journey.esealStatus || 'N/A';
    const battery = journey.batteryLevel !== null ? journey.batteryLevel + '%' : 'N/A';
    const journeyStatus = journey.journeyStatus || 'N/A';
    
    // Format location name if available
    const locationName = journey.lastLocationName || 'Unknown location';

    // Generate a unique ID for the map container
    const mapId = 't1_journey_map_' + Date.now();

    Swal.fire({
        title: `📍 T1 Journey: ${t1Number}`,
        html: `
            <div style="text-align: left;">
                <!-- Map Type Controls -->
                <div style="margin-bottom: 10px; display: flex; gap: 8px; flex-wrap: wrap; justify-content: center;">
                    <button id="btnRoadmap" class="map-type-btn active" onclick="setGoogleMapType('roadmap')" style="padding: 6px 12px; background: #000; color: white; border: none; border-radius: 20px; cursor: pointer; font-size: 12px; display: inline-flex; align-items: center; gap: 4px;">
                        <i class="fas fa-road"></i> Roadmap
                    </button>
                    <button id="btnSatellite" class="map-type-btn" onclick="setGoogleMapType('satellite')" style="padding: 6px 12px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 20px; cursor: pointer; font-size: 12px; display: inline-flex; align-items: center; gap: 4px;">
                        <i class="fas fa-satellite"></i> Satellite
                    </button>
                    <button id="btnHybrid" class="map-type-btn" onclick="setGoogleMapType('hybrid')" style="padding: 6px 12px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 20px; cursor: pointer; font-size: 12px; display: inline-flex; align-items: center; gap: 4px;">
                        <i class="fas fa-globe"></i> Hybrid
                    </button>
                    <button id="btnTerrain" class="map-type-btn" onclick="setGoogleMapType('terrain')" style="padding: 6px 12px; background: #f0f2f5; color: #1a1f36; border: none; border-radius: 20px; cursor: pointer; font-size: 12px; display: inline-flex; align-items: center; gap: 4px;">
                        <i class="fas fa-mountain"></i> Terrain
                    </button>
                </div>
                
                <!-- Map Container -->
                <div style="margin-bottom: 20px; border-radius: 12px; overflow: hidden; border: 1px solid #eaeef2; position: relative; height: 400px;">
                    <div id="${mapId}" style="height: 100%; width: 100%;"></div>
                    
                    <!-- Street View Button -->
                    <div style="position: absolute; bottom: 20px; right: 20px; z-index: 5;">
                        <button onclick="openStreetView(${latitude}, ${longitude})" 
                                style="width: 44px; height: 44px; background: white; border: none; border-radius: 50%; cursor: pointer; box-shadow: 0 2px 6px rgba(0,0,0,0.2); display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-street-view" style="color: #3b82f6; font-size: 20px;"></i>
                        </button>
                    </div>
                    
                    <!-- Location Info Overlay -->
                    <div style="position: absolute; top: 20px; left: 20px; z-index: 5; background: white; padding: 8px 12px; border-radius: 8px; box-shadow: 0 2px 6px rgba(0,0,0,0.2); font-size: 12px; border-left: 4px solid #3b82f6;">
                        <i class="fas fa-map-marker-alt" style="color: #3b82f6; margin-right: 5px;"></i>
                        <strong>${latitude.toFixed(6)}°, ${longitude.toFixed(6)}°</strong>
                    </div>
                    
                    <!-- Zoom Level Indicator -->
                    <div style="position: absolute; bottom: 20px; left: 20px; z-index: 5; background: white; padding: 4px 10px; border-radius: 20px; box-shadow: 0 2px 6px rgba(0,0,0,0.2); font-size: 11px;">
                        <i class="fas fa-search-plus"></i> <span id="zoomLevel">15</span>
                    </div>
                </div>
                
                <!-- Journey Details -->
                <div style="background: #f8fafc; padding: 16px; border-radius: 12px; margin-bottom: 15px;">
                    <h4 style="margin: 0 0 12px 0; color: #1a1f36; font-size: 16px;">🚚 Journey Details</h4>
                    <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 12px;">
                        <div>
                            <div style="font-size: 12px; color: #64748b;">T1 Number</div>
                            <div style="font-weight: 500;">${t1Number}</div>
                        </div>
                        <div>
                            <div style="font-size: 12px; color: #64748b;">Journey Status</div>
                            <div style="font-weight: 500;">${journeyStatus}</div>
                        </div>
                        <div>
                            <div style="font-size: 12px; color: #64748b;">eSeal ID</div>
                            <div style="font-weight: 500;">${journey.esealId || 'N/A'}</div>
                        </div>
                        <div>
                            <div style="font-size: 12px; color: #64748b;">eSeal Status</div>
                            <div style="font-weight: 500;">${esealStatus}</div>
                        </div>
                    </div>
                </div>

                <!-- Location & Telemetry -->
                <div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-bottom: 15px;">
                    <div style="background: #f1f5f9; padding: 12px; border-radius: 8px; text-align: center;">
                        <i class="fas fa-map-pin" style="color: #3b82f6; font-size: 18px; margin-bottom: 5px; display: block;"></i>
                        <div style="font-size: 20px; font-weight: 700; color: #1a1f36;">${latitude.toFixed(6)}</div>
                        <div style="font-size: 12px; color: #64748b;">Latitude</div>
                    </div>
                    <div style="background: #f1f5f9; padding: 12px; border-radius: 8px; text-align: center;">
                        <i class="fas fa-map-marker-alt" style="color: #3b82f6; font-size: 18px; margin-bottom: 5px; display: block;"></i>
                        <div style="font-size: 20px; font-weight: 700; color: #1a1f36;">${longitude.toFixed(6)}</div>
                        <div style="font-size: 12px; color: #64748b;">Longitude</div>
                    </div>
                    <div style="background: #f1f5f9; padding: 12px; border-radius: 8px; text-align: center;">
                        <i class="fas fa-clock" style="color: #3b82f6; font-size: 18px; margin-bottom: 5px; display: block;"></i>
                        <div style="font-size: 16px; font-weight: 600; color: #1a1f36;">${timestamp}</div>
                        <div style="font-size: 12px; color: #64748b;">Last Update</div>
                    </div>
                </div>
                
                <!-- Speed & Battery -->
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 15px;">
                    <div style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); padding: 15px; border-radius: 12px; color: white;">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <i class="fas fa-tachometer-alt" style="font-size: 24px;"></i>
                            <div>
                                <div style="font-size: 28px; font-weight: 700;">${speed} km/h</div>
                                <div style="font-size: 12px; opacity: 0.9;">Current Speed</div>
                            </div>
                        </div>
                    </div>
                    <div style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%); padding: 15px; border-radius: 12px; color: white;">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <i class="fas fa-battery-half" style="font-size: 24px;"></i>
                            <div>
                                <div style="font-size: 28px; font-weight: 700;">${battery}</div>
                                <div style="font-size: 12px; opacity: 0.9;">Battery Level</div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Additional Info -->
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 10px; margin-bottom: 15px;">
                    <div style="background: #ffffff; padding: 12px; border-radius: 8px; border: 1px solid #e2e8f0;">
                        <div style="font-size: 12px; color: #64748b;">Odometer Reading</div>
                        <div style="font-size: 18px; font-weight: 600; color: #1a1f36;">${odometer} km</div>
                    </div>
                    <div style="background: #ffffff; padding: 12px; border-radius: 8px; border: 1px solid #e2e8f0;">
                        <div style="font-size: 12px; color: #64748b;">Location</div>
                        <div style="font-size: 14px; font-weight: 500; color: #1a1f36;">${locationName}</div>
                    </div>
                </div>
                
                <!-- Action Buttons -->
                <div style="display: flex; gap: 10px; justify-content: center;">
                    <button onclick="window.open('https://www.google.com/maps?q=${latitude},${longitude}', '_blank')" 
                            style="flex: 1; padding: 12px; background: #3b82f6; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 500; display: flex; align-items: center; justify-content: center; gap: 8px;">
                        <i class="fas fa-external-link-alt"></i> Open in Google Maps
                    </button>
                    <button onclick="getDirections(${latitude}, ${longitude})" 
                            style="flex: 1; padding: 12px; background: #10b981; color: white; border: none; border-radius: 8px; cursor: pointer; font-weight: 500; display: flex; align-items: center; justify-content: center; gap: 8px;">
                        <i class="fas fa-directions"></i> Get Directions
                    </button>
                </div>
                
                <!-- Raw Data Toggle -->
                <div style="margin-top: 15px;">
                    <details style="background: #f8fafc; border-radius: 8px; padding: 12px;">
                        <summary style="color: #3b82f6; cursor: pointer; font-size: 13px; font-weight: 500;">
                            <i class="fas fa-code"></i> View Raw Journey Data
                        </summary>
                        <pre style="background: #1e293b; color: #e2e8f0; padding: 16px; border-radius: 8px; margin-top: 12px; overflow-x: auto; font-size: 11px;">${JSON.stringify(journey, null, 2)}</pre>
                    </details>
                </div>
            </div>
            
            <style>
                .map-type-btn.active { background: #000 !important; color: white !important; }
                .swal2-popup { width: 900px !important; }
                @media (max-width: 768px) {
                    .swal2-popup { width: 95% !important; }
                    div[style*="grid-template-columns: repeat(3, 1fr)"] { grid-template-columns: 1fr !important; }
                    div[style*="grid-template-columns: repeat(2, 1fr)"] { grid-template-columns: 1fr !important; }
                }
            </style>
        `,
        showConfirmButton: false,
        showCloseButton: true,
        background: '#ffffff',
        color: '#1a1f36',
        width: '900px',
        didOpen: () => {
            // Initialize Google Map
            initGoogleMap(mapId, latitude, longitude, `T1: ${t1Number}`);
        }
    });
}

// Export T1 list (similar to agent export)
function exportT1() {
    Swal.fire({
        title: 'Export T1',
        text: 'Choose format',
        icon: 'question',
        showCancelButton: true,
        confirmButtonText: 'CSV',
        cancelButtonText: 'JSON',
        confirmButtonColor: '#000'
    }).then((result) => {
        if (result.isConfirmed) {
            alert('CSV export coming soon!');
        } else if (result.dismiss === Swal.DismissReason.cancel) {
            const table = $('#t1tableview').DataTable();
            const data = table.data().toArray();
            const jsonStr = JSON.stringify(data, null, 2);
            const blob = new Blob([jsonStr], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `t1_export_${new Date().toISOString().slice(0,10)}.json`;
            a.click();
            URL.revokeObjectURL(url);
        }
    });
}

// Initialize on document ready
$(document).ready(function() {
    allT1();

    $(document).on('click', function(e) {
        if (!$(e.target).closest('.action-dropdown').length) {
            $('[id^="t1_menu_"]').hide();
        }
    });
});