// Global variables

// Main function to load and display all geofences
function allGeofences() {
    $(".crud_section").html("");

    // Modern loading skeleton
    var loadingHTML = `
        <div class="geofences-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>
    `;

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

    var url = serverURL + "geofences?size=1000";

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

            // Calculate statistics
            const totalGeofences = data.length;
            const routes = data.filter(g => g.route === true).length;
            const stations = data.filter(g => g.station === true).length;
            const hotspots = data.filter(g => g.hotspot === true).length;
            const totalDeviceAssignments = data.reduce((sum, g) => sum + (g.deviceCount || 0), 0);

            var html = `
            <div class="geofences-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; flex-wrap: wrap;">
                            <h1 style="margin: 0; font-size: 28px; font-weight: 600; color: #1a1f36; display: flex; align-items: center; gap: 12px;">
                                <i class="fas fa-draw-polygon" style="color: #000;"></i>
                                Geofence Management
                            </h1>
                            <span style="background: #f0f2f5; color: #1a1f36; padding: 6px 14px; border-radius: 40px; font-size: 14px; font-weight: 500;">
                                ${totalGeofences} Total
                            </span>
                        </div>
                        <div style="display: flex; gap: 12px; flex-wrap: wrap;">
                            <button onclick="exportGeofences()" 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 (responsive grid) -->
                <div class="stats-grid" style="display: grid; gap: 20px; margin-bottom: 24px; grid-template-columns: repeat(5, 1fr);">
                    <!-- Total Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                        <div style="width: 56px; height: 56px; background: #f0f2f5; border-radius: 14px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-globe" style="font-size: 24px; color: #000;"></i>
                        </div>
                        <div>
                            <div style="font-size: 14px; color: #5b677c; margin-bottom: 4px;">Total Geofences</div>
                            <div style="font-size: 32px; font-weight: 700; color: #1a1f36;">${totalGeofences}</div>
                        </div>
                    </div>

                    <!-- Routes Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                        <div style="width: 56px; height: 56px; background: #dbeafe; border-radius: 14px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-route" style="font-size: 24px; color: #3b82f6;"></i>
                        </div>
                        <div>
                            <div style="font-size: 14px; color: #5b677c; margin-bottom: 4px;">Routes</div>
                            <div style="font-size: 32px; font-weight: 700; color: #3b82f6;">${routes}</div>
                        </div>
                    </div>

                    <!-- Stations Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                        <div style="width: 56px; height: 56px; background: #dcfce7; border-radius: 14px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-map-marker-alt" style="font-size: 24px; color: #22c55e;"></i>
                        </div>
                        <div>
                            <div style="font-size: 14px; color: #5b677c; margin-bottom: 4px;">Stations</div>
                            <div style="font-size: 32px; font-weight: 700; color: #22c55e;">${stations}</div>
                        </div>
                    </div>

                    <!-- Hotspots Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                        <div style="width: 56px; height: 56px; background: #fee2e2; border-radius: 14px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-fire" style="font-size: 24px; color: #ef4444;"></i>
                        </div>
                        <div>
                            <div style="font-size: 14px; color: #5b677c; margin-bottom: 4px;">Hotspots</div>
                            <div style="font-size: 32px; font-weight: 700; color: #ef4444;">${hotspots}</div>
                        </div>
                    </div>

                    <!-- Assignments Card -->
                    <div style="background: #ffffff; border-radius: 16px; padding: 20px; box-shadow: 0 2px 8px rgba(0,0,0,0.04); border: 1px solid #eaeef2; display: flex; align-items: center; gap: 16px;">
                        <div style="width: 56px; height: 56px; background: #f3e8ff; border-radius: 14px; display: flex; align-items: center; justify-content: center;">
                            <i class="fas fa-link" style="font-size: 24px; color: #a855f7;"></i>
                        </div>
                        <div>
                            <div style="font-size: 14px; color: #5b677c; margin-bottom: 4px;">Assignments</div>
                            <div style="font-size: 32px; font-weight: 700; color: #a855f7;">${totalDeviceAssignments}</div>
                        </div>
                    </div>
                </div>

                <!-- Filter Chips (if any) can go here -->

                <!-- 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; min-width: 200px;">
                        <i class="fas fa-search" style="position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #94a3b8;"></i>
                        <input type="text" id="geofenceSearch" placeholder="Search by name, description, or type..." style="width: 100%; padding: 12px 12px 12px 40px; border: 1px solid #eaeef2; border-radius: 40px; font-size: 14px; outline: none; transition: all 0.2s;">
                    </div>
                    <div style="display: flex; gap: 12px; flex-wrap: wrap;">
                        <select id="pageSize" style="padding: 8px 16px; border: 1px solid #eaeef2; border-radius: 40px; background: white; font-size: 14px; outline: none;">
                            <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="refreshGeofencesTable()" style="width: 40px; height: 40px; border: 1px solid #eaeef2; border-radius: 50%; background: white; cursor: pointer; transition: all 0.2s;">
                            <i class="fas fa-sync-alt"></i>
                        </button>
                    </div>
                </div>

                <!-- Geofences Table (Responsive wrapper) -->
                <div style="background: #ffffff; border-radius: 16px; border: 1px solid #eaeef2; overflow: hidden; box-shadow: 0 2px 8px rgba(0,0,0,0.04);">
                    <div style="overflow-x: auto; -webkit-overflow-scrolling: touch;">
                        <table class="geofences-table" id="geofencetableview" style="width: 100%; border-collapse: collapse; min-width: 800px;">
                            <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;">Name & Type</th>
                                    <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Geometry</th>
                                    <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Color</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;">Details</th>
                                    <th style="padding: 16px; text-align: left; font-weight: 600; color: #1a1f36;">Created</th>
                                    <th style="padding: 16px; text-align: center; font-weight: 600; color: #1a1f36;">Actions</th>
                                </tr>
                            </thead>
                            <tbody id="geofenceTableBody">
            `;

            data.forEach((item, i) => {
                // Determine type
                let type = 'Regular';
                let typeIcon = 'fa-draw-polygon';
                let typeColor = '#64748b';
                if (item.route === true) { type = 'Route'; typeIcon = 'fa-route'; typeColor = '#3b82f6'; }
                else if (item.station === true) { type = 'Station'; typeIcon = 'fa-map-marker-alt'; typeColor = '#22c55e'; }
                else if (item.hotspot === true) { type = 'Hotspot'; typeIcon = 'fa-fire'; typeColor = '#ef4444'; }

                // Geometry type
                const geometryType = item.fenceType || 'N/A';
                
                // Status
                const isActive = item.isActive === true;
                
                // Format dates
                const createdDate = item.createdAt ? new Date(item.createdAt).toLocaleDateString() : 'N/A';
                const timeAgo = item.updatedAt ? timeSince(new Date(item.updatedAt)) : 'N/A';

                // Additional details string
                let details = [];
                if (item.stationType && item.stationType !== 'BUS_STOP') details.push(`Type: ${item.stationType}`);
                if (item.assignedRouteIds && item.assignedRouteIds.length > 0) details.push(`Routes: ${item.assignedRouteIds.length}`);
                if (item.deviceCount > 0) details.push(`Devices: ${item.deviceCount}`);
                const detailsText = details.join(' • ') || '—';

                html += `
                <tr data-id="${item.id}" 
                    data-type="${type.toLowerCase()}" 
                    data-active="${isActive}"
                    style="border-bottom: 1px solid #eaeef2; transition: background 0.2s;">
                    
                    <td style="padding: 16px;">
                        <input type="checkbox" class="row-checkbox" data-id="${item.id}" style="width: 18px; height: 18px; cursor: pointer;">
                    </td>

                    <td style="padding: 16px; color: #5b677c;">${i + 1}</td>

                    <td style="padding: 16px;">
                        <div style="display: flex; align-items: center; gap: 12px;">
                            <div style="width: 40px; height: 40px; background: ${typeColor}20; border-radius: 10px; display: flex; align-items: center; justify-content: center;">
                                <i class="fas ${typeIcon}" style="color: ${typeColor};"></i>
                            </div>
                            <div>
                                <div style="font-weight: 600; color: #1a1f36;" class="geofence-name">${item.name || 'Unnamed'}</div>
                                <div style="font-size: 12px; color: #5b677c;">${type}</div>
                            </div>
                        </div>
                    </td>

                    <td style="padding: 16px;">
                        <span style="background: #f0f2f5; padding: 4px 8px; border-radius: 40px; font-size: 12px; color: #1a1f36;">
                            ${geometryType}
                        </span>
                    </td>

                    <td style="padding: 16px;">
                        <div style="display: flex; align-items: center; gap: 8px;">
                            <div style="width: 24px; height: 24px; background: ${item.colorHex || '#3b82f6'}; border-radius: 6px; border: 2px solid #eaeef2;"></div>
                            <span style="font-size: 12px; color: #5b677c; font-family: monospace;">${item.colorHex || '#3b82f6'}</span>
                        </div>
                    </td>

                    <td style="padding: 16px;">
                        <span style="display: inline-flex; align-items: center; gap: 6px; padding: 4px 10px; background: ${isActive ? '#e8f5e9' : '#fee2e2'}; border-radius: 40px; font-size: 12px; font-weight: 500; color: ${isActive ? '#2e7d32' : '#dc2626'}; width: fit-content;">
                            <span style="width: 8px; height: 8px; border-radius: 50%; background: ${isActive ? '#2e7d32' : '#dc2626'};"></span>
                            ${isActive ? 'Active' : 'Inactive'}
                        </span>
                    </td>

                    <td style="padding: 16px;">
                        <div style="font-size: 12px; color: #1a1f36;">
                            ${item.description ? item.description.substring(0, 50) + (item.description.length > 50 ? '...' : '') : '—'}
                            ${detailsText !== '—' ? `<div style="color: #5b677c; margin-top: 4px; font-size: 11px;">${detailsText}</div>` : ''}
                        </div>
                    </td>

                    <td style="padding: 16px;">
                        <div>
                            <div style="font-size: 12px; color: #1a1f36;">${createdDate}</div>
                            <div style="font-size: 11px; color: #94a3b8;">${timeAgo}</div>
                        </div>
                    </td>

                    <td style="padding: 16px; text-align: center;">
                        <div class="action-dropdown" style="position: relative; display: inline-block;">
                            <button onclick="toggleGeofenceMenu('${item.id}')" style="width: 36px; height: 36px; border: 1px solid #eaeef2; border-radius: 8px; background: white; cursor: pointer; transition: all 0.2s;">
                                <i class="fas fa-ellipsis-v" style="color: #5b677c;"></i>
                            </button>
                            <div id="menu_${item.id}" style="display: none; position: absolute; right: 0; top: 45px; width: 220px; 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;">Actions</span>
                                </div>
                                <div style="padding: 8px;">
                                    <button onclick='viewGeofenceDetails(${JSON.stringify(item).replace(/'/g, "\\'")})' 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" style="width: 18px;"></i> View Details
                                    </button>
                                    <button onclick='getDevicesInsideGeofence(${item.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: #0891b2;">
                                        <i class="fas fa-map-pin" style="width: 18px;"></i> Devices Inside
                                    </button>
                                    <button onclick='editGeofence(${item.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" style="width: 18px;"></i> Edit
                                    </button>
                                    <button onclick='assignToRoute(${item.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-link" style="width: 18px;"></i> Assign to Route
                                    </button>
                                    <div style="height: 1px; background: #eaeef2; margin: 8px 0;"></div>
                                    <button onclick='viewOnMap(${item.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: #3b82f6;">
                                        <i class="fas fa-map-marked-alt" style="width: 18px;"></i> Show on Map
                                    </button>
                                    <div style="height: 1px; background: #eaeef2; margin: 8px 0;"></div>
                                    <button onclick='deleteGeofence(${item.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: #dc2626;">
                                        <i class="fas fa-trash" style="width: 18px;"></i> Delete
                                    </button>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
                `;
            });

            html += `
                            </tbody>
                        </table>
                    </div> <!-- end scroll wrapper -->
                </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; flex-wrap: wrap; gap: 12px;">
                    <div style="color: #5b677c;">
                        <span id="selectedCount">0</span> items selected
                    </div>
                    <div class="table-pagination" id="tablePagination"></div>
                </div>

                <style>
                    /* Filter chip active state (if used) */
                    .filter-chip.active {
                        background: #000 !important;
                        color: white !important;
                        border-color: #000 !important;
                    }
                    
                    /* Table row hover */
                    .geofences-table tbody tr:hover {
                        background: #f8fafc;
                        cursor: pointer;
                    }
                    
                    /* Action button hover */
                    .action-dropdown button:hover {
                        background: #f0f2f5;
                    }
                    
                    /* Dropdown menu item hover */
                    .action-menu button:hover {
                        background: #f8fafc;
                    }
                    
                    /* Stats grid responsiveness */
                    @media (max-width: 1200px) {
                        .stats-grid {
                            grid-template-columns: repeat(3, 1fr) !important;
                        }
                    }
                    @media (max-width: 768px) {
                        .stats-grid {
                            grid-template-columns: repeat(2, 1fr) !important;
                        }
                        .stats-grid > div {
                            padding: 12px !important;
                        }
                        .stats-grid > div div:first-child {
                            width: 40px !important;
                            height: 40px !important;
                        }
                        .stats-grid > div div:first-child i {
                            font-size: 18px !important;
                        }
                        .stats-grid > div > div:last-child div:first-of-type {
                            font-size: 12px !important;
                        }
                        .stats-grid > div > div:last-child div:last-of-type {
                            font-size: 24px !important;
                        }
                    }
                    @media (max-width: 480px) {
                        .stats-grid {
                            grid-template-columns: 1fr !important;
                        }
                    }
                    
                    /* General responsive adjustments */
                    @media (max-width: 768px) {
                        .geofences-container {
                            padding: 12px !important;
                        }
                        h1 {
                            font-size: 22px !important;
                        }
                        .filter-chip {
                            padding: 6px 12px !important;
                            font-size: 13px !important;
                        }
                        /* Ensure action dropdowns don't go off-screen on mobile */
                        .action-dropdown > div[id^="menu_"] {
                            right: auto !important;
                            left: 50% !important;
                            transform: translateX(-50%);
                            top: 50px !important;
                        }
                    }
                    @media (max-width: 480px) {
                        .action-dropdown > div[id^="menu_"] {
                            left: 0 !important;
                            transform: none;
                            right: auto;
                        }
                    }
                </style>
            </div>
            `;

            $(".tab_geofences").html(html);

            // Initialize DataTable with responsive option
            const table = $('#geofencetableview').DataTable({
                responsive: true,
                dom: 'rtip',
                pageLength: 10,
                lengthMenu: [[10, 25, 50, 100], [10, 25, 50, 100]],
                order: [[1, 'asc']],
                columnDefs: [
                    { orderable: false, targets: [0, 8] }
                ],
                initComplete: function() {
                    $('.dataTables_paginate').css({
                        'display': 'flex',
                        'gap': '4px',
                        'flex-wrap': 'wrap'
                    });
                    $('.paginate_button').css({
                        'padding': '6px 12px',
                        'border': '1px solid #eaeef2',
                        'border-radius': '8px',
                        'background': 'white',
                        'cursor': 'pointer'
                    });
                }
            });

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

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

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

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

            function updateSelectedCount() {
                const count = $(".row-checkbox:checked").length;
                $("#selectedCount").text(count);
            }

            // Close dropdowns when clicking outside
            $(document).on('click', function(e) {
                if (!$(e.target).closest('.action-dropdown').length) {
                    $('[id^="menu_"]').hide();
                }
            });

            // Make filter functions globally available (if you have filter chips)
            window.applyGeofenceFilter = function(filter) {
                $('.filter-chip').removeClass('active');
                $(`.filter-chip[data-filter="${filter}"]`).addClass('active');
                
                if (filter === 'all') {
                    table.column(2).search('').draw();
                } else {
                    table.column(2).search(filter, true, false).draw();
                }
            };

            window.refreshGeofencesTable = function() {
                allGeofences();
            };
        },
        error: function(xhr, status, error) {
            console.error("Error loading geofences:", error);
            $(".tab_geofences").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; margin-bottom: 16px;"></i>
                    <h3 style="color: #1a1f36; margin-bottom: 8px;">Failed to load geofences</h3>
                    <p style="color: #5b677c; margin-bottom: 20px;">${error}</p>
                    <button onclick="allGeofences()" style="padding: 10px 24px; background: #000; color: white; border: none; border-radius: 10px; cursor: pointer;">
                        <i class="fas fa-sync-alt"></i> Retry
                    </button>
                </div>
            `);
        }
    });
}

// Helper function for time ago
function timeSince(date) {
    const seconds = Math.floor((new Date() - date) / 1000);
    let interval = seconds / 31536000;
    if (interval > 1) return Math.floor(interval) + ' years ago';
    interval = seconds / 2592000;
    if (interval > 1) return Math.floor(interval) + ' months ago';
    interval = seconds / 86400;
    if (interval > 1) return Math.floor(interval) + ' days ago';
    interval = seconds / 3600;
    if (interval > 1) return Math.floor(interval) + ' hours ago';
    interval = seconds / 60;
    if (interval > 1) return Math.floor(interval) + ' minutes ago';
    return 'just now';
}

// Geofence-specific action menu
function toggleGeofenceMenu(geofenceId) {
    $('[id^="menu_"]').hide();
    $(`#menu_${geofenceId}`).toggle();
}

// NEW FUNCTION: Get all devices inside a geofence
function getDevicesInsideGeofence(geofenceId) {
    if (!geofenceId) return;
    
    // Close the menu
    $(`#menu_${geofenceId}`).hide();
    
    // Show loading
    Swal.fire({
        title: 'Loading Devices',
        html: 'Fetching devices inside geofence...',
        allowOutsideClick: false,
        didOpen: () => {
            Swal.showLoading();
        }
    });
    
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + `geofence-monitoring/geofence/${geofenceId}/devices-inside`, true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
    xhr.setRequestHeader('Content-Type', 'application/json');
    
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status >= 200 && xhr.status < 300) {
                const devices = JSON.parse(xhr.responseText);
                displayDevicesInsideGeofence(devices, geofenceId);
            } else {
                let errorMsg = 'Failed to fetch devices inside geofence';
                try {
                    const errorData = JSON.parse(xhr.responseText);
                    errorMsg = errorData.message || errorMsg;
                } catch (e) {}
                
                Swal.fire({
                    title: 'Error!',
                    text: errorMsg,
                    icon: 'error',
                    confirmButtonColor: '#000',
                    background: '#ffffff',
                    color: '#1a1f36'
                });
            }
        }
    };
    
    xhr.send();
}

// Display devices inside geofence in a modal
function displayDevicesInsideGeofence(devices, geofenceId) {
    if (!devices || devices.length === 0) {
        Swal.fire({
            title: 'No Devices Found',
            html: `<div style="text-align: center; padding: 20px;">
                <i class="fas fa-info-circle" style="font-size: 48px; color: #94a3b8; margin-bottom: 16px;"></i>
                <p style="color: #5b677c; margin: 0;">No devices are currently inside this geofence.</p>
            </div>`,
            confirmButtonColor: '#000',
            background: '#ffffff',
            color: '#1a1f36'
        });
        return;
    }
    
    // Build devices table HTML
    let devicesHtml = `
        <div style="max-height: 500px; overflow-y: auto;">
            <div style="background: #f8fafc; padding: 12px; border-radius: 8px; margin-bottom: 16px;">
                <span style="font-weight: 600; color: #1a1f36;">Total Devices: ${devices.length}</span>
            </div>
            <table style="width: 100%; border-collapse: collapse; font-size: 13px;">
                <thead>
                    <tr style="background: #f1f5f9; border-bottom: 2px solid #e2e8f0;">
                        <th style="padding: 12px; text-align: left;">Device Name</th>
                        <th style="padding: 12px; text-align: left;">Serial/IMEI</th>
                        <th style="padding: 12px; text-align: left;">Status</th>
                        <th style="padding: 12px; text-align: left;">Vehicle</th>
                        <th style="padding: 12px; text-align: left;">Last Seen</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    devices.forEach(device => {
        const lastSeen = device.lastSeen ? new Date(device.lastSeen).toLocaleString() : 'N/A';
        const online = device.online === true;
        const active = device.active === true;
        
        devicesHtml += `
            <tr style="border-bottom: 1px solid #e2e8f0;">
                <td style="padding: 12px;">
                    <div style="font-weight: 500;">${device.name || 'Unnamed'}</div>
                    <div style="font-size: 11px; color: #64748b;">ID: ${device.deviceId || 'N/A'}</div>
                </td>
                <td style="padding: 12px;">
                    <div>${device.serialNumber || 'N/A'}</div>
                    <div style="font-size: 11px; color: #64748b;">${device.imei || ''}</div>
                </td>
                <td style="padding: 12px;">
                    <span style="display: inline-block; width: 8px; height: 8px; border-radius: 50%; background: ${online ? '#22c55e' : '#94a3b8'}; margin-right: 6px;"></span>
                    ${online ? 'Online' : 'Offline'}
                    <br>
                    <span style="font-size: 11px; color: ${active ? '#22c55e' : '#ef4444'};">
                        ${active ? 'Active' : 'Inactive'}
                    </span>
                </td>
                <td style="padding: 12px;">
                    ${device.vehicle ? `
                        <div>${device.vehicle.make || ''} ${device.vehicle.model || ''}</div>
                        <div style="font-size: 11px; color: #64748b;">${device.vehicle.plateNumber || ''}</div>
                    ` : 'No Vehicle'}
                </td>
                <td style="padding: 12px;">
                    <div>${lastSeen}</div>
                </td>
            </tr>
        `;
    });
    
    devicesHtml += `
                </tbody>
            </table>
        </div>
    `;
    
    // Get geofence name for the title
    const geofenceName = $(`tr[data-id="${geofenceId}"] .geofence-name`).text() || `Geofence #${geofenceId}`;
    
    Swal.fire({
        title: `Devices Inside: ${geofenceName}`,
        html: devicesHtml,
        width: '900px',
        confirmButtonText: 'Close',
        confirmButtonColor: '#000',
        background: '#ffffff',
        color: '#1a1f36'
    });
}

// Action functions
function addNewGeofence() {
    window.location.href = 'mapviewgeo.html';
}

function exportGeofences() {
    alert('Export functionality coming soon!');
}

function viewGeofenceDetails(item) {
    Swal.fire({
        title: 'Geofence Details',
        html: `
            <div style="text-align: left; max-height: 400px; overflow-y: auto;">
                <pre style="background: #f8fafc; padding: 16px; border-radius: 8px; font-size: 12px;">${JSON.stringify(item, null, 2)}</pre>
            </div>
        `,
        confirmButtonColor: '#000',
        background: '#ffffff',
        color: '#1a1f36',
        width: '600px'
    });
}

function editGeofence(id) {
    Swal.fire({
        title: 'Edit Geofence',
        text: `Edit functionality for geofence ${id} will be implemented here.`,
        icon: 'info',
        confirmButtonColor: '#000',
        background: '#ffffff',
        color: '#1a1f36'
    });
}

function viewOnMap(id) {
    Swal.fire({
        title: 'View on Map',
        text: `Showing geofence ${id} on map.`,
        icon: 'info',
        confirmButtonColor: '#000',
        background: '#ffffff',
        color: '#1a1f36'
    });
}

// Load routes for assignment dropdown
function loadRoutesForAssignment() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + 'geofences/routes?size=500', true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText);
                const contentdata = data.content || [];
                
                let option = '<option selected value="">-Select Route-</option>';
                
                if (Array.isArray(contentdata) && contentdata.length > 0) {
                    for (let i = 0; i < contentdata.length; i++) {
                        option += `<option value="${contentdata[i].id}">${contentdata[i].name}</option>`;
                    }
                }
                
                $("#selectPrRoute").html(option);
            } else {
                console.error('Error loading routes:', xhr.responseText);
                showNotification('Failed to load routes', 'error');
            }
        }
    };
    xhr.send();
}

// Load stations for assignment dropdown
function loadStationsForAssignment() {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', API_BASE + 'geofences/stations?size=1000', true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
    xhr.setRequestHeader('Content-Type', 'application/json');

    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status >= 200 && xhr.status < 300) {
                const data = JSON.parse(xhr.responseText);
                const contentdata = data.content || [];
                
                let option = '<option selected value="">-Select Station-</option>';
                
                if (Array.isArray(contentdata) && contentdata.length > 0) {
                    for (let i = 0; i < contentdata.length; i++) {
                        option += `<option value="${contentdata[i].id}">${contentdata[i].name}</option>`;
                    }
                }
                
                $("#selectStation").html(option);
            } else {
                console.error('Error loading stations:', xhr.responseText);
                showNotification('Failed to load stations', 'error');
            }
        }
    };
    xhr.send();
}

// Assign station to route
function assignStationToRoute() {
    const stationId = $("#selectStation").val();
    const routeId = $("#selectPrRoute").val();
    
    if (!stationId) {
        showNotification('Please select a station', 'warning');
        return;
    }
    
    if (!routeId) {
        showNotification('Please select a route', 'warning');
        return;
    }
    
    const $btn = $("#assignStationToRoutes");
    const originalText = $btn.html();
    $btn.html('<i class="fas fa-spinner fa-spin"></i> Assigning...').prop('disabled', true);
    
    const xhr = new XMLHttpRequest();
    xhr.open('POST', API_BASE + `geofences/${stationId}/assign-to-route/${routeId}`, true);
    xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
    xhr.setRequestHeader('Content-Type', 'application/json');
    
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            $btn.html(originalText).prop('disabled', false);
            
            if (xhr.status >= 200 && xhr.status < 300) {
                showNotification('Station successfully assigned to route!', 'success');
                
                $("#selectStation").val('');
                $("#selectPrRoute").val('');
                
                if (typeof allGeofences === 'function') {
                    allGeofences();
                }
            } else {
                let errorMsg = 'Failed to assign station to route';
                try {
                    const errorData = JSON.parse(xhr.responseText);
                    errorMsg = errorData.message || errorMsg;
                } catch (e) {}
                showNotification(errorMsg, 'error');
            }
        }
    };
    
    xhr.send();
}

// Delete geofence (soft delete)
function deleteGeofence(id) {
    if (!id) return;
    
    Swal.fire({
        title: 'Delete Geofence?',
        text: 'This action will soft delete the geofence. You can restore it later if needed.',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#dc2626',
        cancelButtonColor: '#6b7280',
        confirmButtonText: 'Yes, delete it!',
        cancelButtonText: 'Cancel',
        background: '#ffffff',
        color: '#1a1f36'
    }).then((result) => {
        if (result.isConfirmed) {
            Swal.fire({
                title: 'Deleting...',
                html: 'Please wait',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            const xhr = new XMLHttpRequest();
            xhr.open('DELETE', API_BASE + `geofences/${id}`, true);
            xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
            xhr.setRequestHeader('Content-Type', 'application/json');
            
            xhr.onreadystatechange = function () {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        Swal.fire({
                            title: 'Deleted!',
                            text: 'Geofence has been soft deleted successfully.',
                            icon: 'success',
                            confirmButtonColor: '#000',
                            background: '#ffffff',
                            color: '#1a1f36'
                        }).then(() => {
                            if (typeof allGeofences === 'function') {
                                allGeofences();
                            }
                            $(`#menu_${id}`).hide();
                        });
                    } else {
                        let errorMsg = 'Failed to delete geofence';
                        try {
                            const errorData = JSON.parse(xhr.responseText);
                            errorMsg = errorData.message || errorMsg;
                        } catch (e) {}
                        
                        Swal.fire({
                            title: 'Error!',
                            text: errorMsg,
                            icon: 'error',
                            confirmButtonColor: '#000',
                            background: '#ffffff',
                            color: '#1a1f36'
                        });
                    }
                }
            };
            
            xhr.send();
        }
    });
}

// Enhanced assignToRoute function
function assignToRoute(geofenceId) {
    const row = $(`tr[data-id="${geofenceId}"]`);
    const typeCell = row.find('td:eq(2)').text().toLowerCase();
    
    if (!typeCell.includes('station')) {
        Swal.fire({
            title: 'Not a Station',
            text: 'Only stations can be assigned to routes.',
            icon: 'info',
            confirmButtonColor: '#000',
            background: '#ffffff',
            color: '#1a1f36'
        });
        return;
    }
    
    Swal.fire({
        title: 'Assign Station to Route',
        html: `
            <div style="text-align: left;">
                <div style="margin-bottom: 20px;">
                    <label style="display: block; margin-bottom: 8px; font-weight: 500; color: #1a1f36;">
                        Select Route
                    </label>
                    <select id="swal-route-select" style="width: 100%; padding: 10px; border: 1px solid #eaeef2; border-radius: 8px;">
                        <option value="">Loading routes...</option>
                    </select>
                </div>
                <div style="font-size: 13px; color: #5b677c; background: #f8fafc; padding: 10px; border-radius: 8px;">
                    <i class="fas fa-info-circle"></i> Station ID: ${geofenceId}
                </div>
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Assign',
        cancelButtonText: 'Cancel',
        confirmButtonColor: '#000',
        background: '#ffffff',
        color: '#1a1f36',
        didOpen: () => {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', API_BASE + 'geofences/routes?size=500', true);
            xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === XMLHttpRequest.DONE && xhr.status >= 200 && xhr.status < 300) {
                    const data = JSON.parse(xhr.responseText);
                    const routes = data.content || [];
                    
                    let options = '<option value="">-Select Route-</option>';
                    routes.forEach(route => {
                        options += `<option value="${route.id}">${route.name}</option>`;
                    });
                    
                    $('#swal-route-select').html(options);
                }
            };
            xhr.send();
        },
        preConfirm: () => {
            const routeId = $('#swal-route-select').val();
            if (!routeId) {
                Swal.showValidationMessage('Please select a route');
                return false;
            }
            return { stationId: geofenceId, routeId: routeId };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { stationId, routeId } = result.value;
            
            const xhr = new XMLHttpRequest();
            xhr.open('POST', API_BASE + `geofences/${stationId}/assign-to-route/${routeId}`, true);
            xhr.setRequestHeader('Authorization', 'Bearer ' + userObj.accessToken);
            
            xhr.onreadystatechange = function() {
                if (xhr.readyState === XMLHttpRequest.DONE) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        Swal.fire({
                            title: 'Success!',
                            text: 'Station assigned to route successfully.',
                            icon: 'success',
                            confirmButtonColor: '#000',
                            background: '#ffffff',
                            color: '#1a1f36'
                        }).then(() => {
                            if (typeof allGeofences === 'function') {
                                allGeofences();
                            }
                        });
                    } else {
                        Swal.fire({
                            title: 'Error!',
                            text: 'Failed to assign station to route.',
                            icon: 'error',
                            confirmButtonColor: '#000',
                            background: '#ffffff',
                            color: '#1a1f36'
                        });
                    }
                }
            };
            xhr.send();
        }
    });
}

// Show notification function
function showNotification(message, type = 'info') {
    const toast = Swal.mixin({
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 3000,
        timerProgressBar: true,
        didOpen: (toast) => {
            toast.addEventListener('mouseenter', Swal.stopTimer);
            toast.addEventListener('mouseleave', Swal.resumeTimer);
        }
    });
    
    toast.fire({
        icon: type,
        title: message
    });
}

// Initialize on document ready
$(document).ready(function() {
    if ($("#selectStation").length) {
        loadStationsForAssignment();
    }
    if ($("#selectPrRoute").length) {
        loadRoutesForAssignment();
    }
    
    $("#assignStationToRoutes").on("click", assignStationToRoute);
});