function homePage(){
$(".crud_section").html("");

    /***************************************************
 * GLOBALS
 ***************************************************/
var deviceMap;
var markers = {};
var infoWindows = {};
var geofenceHoverInfo = null;
var geocoder = new google.maps.Geocoder();

var devicesMaster = [];
var telemetryMap = {};
var moveIntervals = {};

var geofences = [];
var geofenceShapes = {
    hotspots: [],
    stations: [],
    routes: []
};

/***************************************************
 * INIT
 ***************************************************/



   buildLayout();
loadDevicesList();
loadTelemetryInitial();
setInterval(loadTelemetryRealtime, 5000);

/***************************************************
 * UI LAYOUT
 ***************************************************/
function buildLayout() {

    let html = `
        <div class="container-fluid">
            <div class="row g-1">

                <!-- LEFT: DEVICES -->
                <div class="col-lg-2">
                    <div class="card shadow-sm border-0 h-80">
                        <div class="card-header text-black fw-semibold">
                            Devices
                        </div>
                        <div class="card-body p-2 bg-light">
                            <div id="device_summary" class="mb-2 small fw-bold"></div>
                            <div id="device_list" style="max-height:750px; overflow-y:auto;"></div>
                        </div>
                    </div>
                </div>

                <!-- CENTER: MAP -->
                <div class="col-lg-8">
                    <div class="card shadow-sm border-0 h-80">
                        <div class="card-header text-black fw-semibold">
                            Live Map
                        </div>
                        <div id="all_devices_map" style="height:800px;"></div>
                    </div>
                </div>

                <!-- RIGHT: TABS -->
                <div class="col-lg-2">
                    <div class="card shadow-sm border-0 h-80">
                        <div class="card-header text-black fw-semibold">
                            Info Panel
                        </div>

                           <div class="p-2 border-bottom bg-light">
                                        <div class="fw-bold mb-2">Map Filters</div>

                                        <div class="form-check">
                                            <input class="form-check-input geofence-filter"
                                                type="checkbox" id="filter_hotspots" checked>
                                            <label class="form-check-label">Hotspots</label>
                                        </div>

                                        <div class="form-check">
                                            <input class="form-check-input geofence-filter"
                                                type="checkbox" id="filter_stations" checked>
                                            <label class="form-check-label">Stations</label>
                                        </div>

                                        <div class="form-check">
                                            <input class="form-check-input geofence-filter"
                                                type="checkbox" id="filter_routes" checked>
                                            <label class="form-check-label">Routes</label>
                                        </div>

                                        <button class="btn btn-sm btn-outline-primary mt-2 w-100"
                                                onclick="applyGeofenceFilters()">
                                            Apply Filter
                                        </button>


                                          <button class="btn btn-sm btn-outline-primary mt-2 w-100"
                                                onclick="openGeofences()">
                                            🟢 Monitoring
                                        </button>
                                    </div>

                                    
                    </div>
                </div>

            </div>
        </div>
    `;

    $(".tab_position").html(html);

    $(document).on("keydown", e => {
        if (e.key === "Escape") {
            closeAllInfoWindows();
            focusedDeviceSn = null;
            showAllMarkers();
        }
    });
}
function openGeofences() {
    window.location.href = "#app/multitracking"; // or modal
}


function applyGeofenceFilters() {

    const showHotspots = $("#filter_hotspots").is(":checked");
    const showStations = $("#filter_stations").is(":checked");
    const showRoutes = $("#filter_routes").is(":checked");

    toggleShapeGroup(geofenceShapes.hotspots, showHotspots);
    toggleShapeGroup(geofenceShapes.stations, showStations);
    toggleShapeGroup(geofenceShapes.routes, showRoutes);
}

function toggleShapeGroup(group, visible) {
    group.forEach(shape => {
        shape.setMap(visible ? deviceMap : null);
    });
}



/***************************************************
 * DEVICES
 ***************************************************/
function loadDevicesList() {
    controller.getAuthRequest(
        API_BASE + "devices/all",
        true,
        data => {
            devicesMaster = data || [];
            $("#device_list").empty();
            devicesMaster.forEach(createDeviceCard);
            updateDeviceSummary();
        }
    );
}

function createDeviceCard(d) {

    $("#device_list").append(`
        <div class="device-card"
             onclick="focusDevice('${d.serialNo}')">

            <!-- LEFT -->
            <div class="device-left">
                <div class="device-pin">
                    <i class="fa-solid fa-location-dot"></i>
                </div>

                <div class="device-text">
                    <div class="device-title">${d.serialNo}</div>
                    <div class="device-id">ID: ${d.serialNo}</div>
                </div>
            </div>

            <!-- RIGHT -->
            <div class="device-badge ${d.isOnline ? 'online' : 'offline'}">
                ${d.isOnline ? 'ONLINE' : 'OFFLINE'}
            </div>

        </div>
    `);
}

/***************************************************
 * TELEMETRY
 ***************************************************/
function loadTelemetryInitial() {
    controller.getAuthRequest(serverURL + "telemetry/latest", true, data => {

        if (!data?.length) return;

        data.forEach(d => telemetryMap[d.deviceSn] = d);

        const first = data.find(d => d.latitude && d.longitude);
        if (!first) return;

         deviceMap = new google.maps.Map(
            document.getElementById("all_devices_map"),
            {
                zoom: 16,
                center: { lat: first.latitude, lng: first.longitude },
                gestureHandling: "greedy",
                zoomControl: true,
                mapTypeControl: true
                
            }
        );


        geofenceHoverInfo = new google.maps.InfoWindow({ disableAutoPan: true });

        data.forEach(addOrUpdateMarker);
        loadGeofences();
    });
}

function loadTelemetryRealtime() {
    controller.getAuthRequest(serverURL + "telemetry/latest", true, data => {
        if (!data) return;
        data.forEach(d => {
            telemetryMap[d.deviceSn] = d;
            addOrUpdateMarker(d);
        });
    });
}

/***************************************************
 * MARKERS
 ***************************************************/
function addOrUpdateMarker(t) {

    if (!t.latitude || !t.longitude) return;

    if (!markers[t.deviceSn]) {

        markers[t.deviceSn] = new google.maps.Marker({
            map: deviceMap,
            position: { lat: t.latitude, lng: t.longitude }
        });

        infoWindows[t.deviceSn] = new google.maps.InfoWindow({
            content: buildInfoContent(t)
        });

        markers[t.deviceSn].addListener("click", () => {
            closeAllInfoWindows();
            infoWindows[t.deviceSn].open(deviceMap, markers[t.deviceSn]);
        });

    } else {
        smoothMoveMarker(t);
        infoWindows[t.deviceSn].setContent(buildInfoContent(t));
    }
}

/***************************************************
 * GEOFENCES
 ***************************************************/
function loadGeofences() {
    controller.getAuthRequest(
        API_BASE + "geofences?size=1000",
        true,
        res => {
            geofences = res?.content || [];
            drawGeofences();
        }
    );
}

function drawGeofences() {

    Object.values(geofenceShapes).flat().forEach(s => s.setMap(null));
    geofenceShapes = { hotspots: [], stations: [], routes: [] };

    geofences.forEach(f => {

        const name = f.name;
        const color = f.colorHex || "#3b82f6";

        /* HOTSPOT */
        if (f.hotspot) {
            const c = new google.maps.Circle({
                map: deviceMap,
                center: { lat: f.centerLat, lng: f.centerLng },
                radius: f.radiusMeters,
                fillColor: color,
                fillOpacity: 0.25,
                strokeColor: color,
                
            });

            attachGeofenceHover(c, {
                name,
                type: "Hotspot",
                description: f.description
            });
            c.set("name", name);

            geofenceShapes.hotspots.push(c);
        }

        /* STATION */
        if (f.station && f.coordinatesJson) {
            const p = new google.maps.Polygon({
                map: deviceMap,
                paths: JSON.parse(f.coordinatesJson),
                fillColor: color,
                fillOpacity: 0.25,
                strokeColor: color
            });

            attachGeofenceHover(p, {
                name,
                type: "Station",
                description: f.description
            });
            p.set("name", name);

            geofenceShapes.stations.push(p);
        }

        /* ROUTE */
        if (f.route && f.coordinatesJson) {
            const r = new google.maps.Polyline({
                map: deviceMap,
                path: JSON.parse(f.coordinatesJson),
                strokeColor: color,
                strokeWeight: 4
            });

            attachGeofenceHover(r, {
                name,
                type: "Route",
                description: f.description
            });

            r.set("name", name);

            geofenceShapes.routes.push(r);
        }
    });

        applyGeofenceFilters();

}

/***************************************************
 * GEOFENCE HOVER TOOLTIP
 ***************************************************/
function attachGeofenceHover(shape, meta) {

    shape.addListener("mouseover", e => {

        let position = e?.latLng;

        if (shape instanceof google.maps.Circle) {
            position = shape.getCenter();
        }

        if (shape instanceof google.maps.Polygon) {
            const bounds = new google.maps.LatLngBounds();
            shape.getPath().forEach(p => bounds.extend(p));
            position = bounds.getCenter();
        }

        geofenceHoverInfo.setContent(`
            <div class="geofence-hover-card">
                <div class="geofence-hover-title">
                    ${meta.name}
                </div>

                <div class="geofence-hover-type">
                    ${meta.type}
                </div>

                ${meta.description ? `
                    <div class="geofence-hover-desc">
                        ${meta.description}
                    </div>
                ` : ''}
            </div>
        `);

        geofenceHoverInfo.setPosition(position);
        geofenceHoverInfo.open(deviceMap);
    });

    shape.addListener("mouseout", () => {
        geofenceHoverInfo.close();
    });
}


/***************************************************
 * DEVICE ↔ GEOFENCE CHECK
 ***************************************************/
function getDeviceFenceStatus(latLng) {

    let result = { hotspot: null, station: null, route: null };

    geofenceShapes.hotspots.forEach(c => {
        if (
            google.maps.geometry.spherical
                .computeDistanceBetween(latLng, c.getCenter()) <= c.getRadius()
        ) result.hotspot = c.get("name");
    });

    geofenceShapes.stations.forEach(p => {
        if (google.maps.geometry.poly.containsLocation(latLng, p))
            result.station = p.get("name");
    });

    geofenceShapes.routes.forEach(r => {
        if (google.maps.geometry.poly.isLocationOnEdge(latLng, r, 0.00015))
            result.route = r.get("name");
    });

    return result;
}

/***************************************************
 * INFO WINDOW
 ***************************************************/
function buildInfoContent(d) {
    return `
        <div>
            <strong>${d.deviceName || d.deviceSn}</strong><hr>
            📍 ${d.latitude}, ${d.longitude}<br>
            🚗 ${d.speedKmh || 0} km/h
        </div>
    `;
}

/***************************************************
 * HELPERS
 ***************************************************/
function smoothMoveMarker(d) {
    const m = markers[d.deviceSn];
    const s = m.getPosition();
    const e = new google.maps.LatLng(d.latitude, d.longitude);
    let i = 0;

    clearInterval(moveIntervals[d.deviceSn]);
    moveIntervals[d.deviceSn] = setInterval(() => {
        i++;
        m.setPosition({
            lat: s.lat() + (e.lat() - s.lat()) * i / 20,
            lng: s.lng() + (e.lng() - s.lng()) * i / 20
        });
        if (i >= 20) clearInterval(moveIntervals[d.deviceSn]);
    }, 100);
}

function closeAllInfoWindows() {
    Object.values(infoWindows).forEach(iw => iw.close());
}

function focusDevice(sn) {
    const m = markers[sn];
    if (!m) return;
    deviceMap.panTo(m.getPosition());
    deviceMap.setZoom(18);
    closeAllInfoWindows();
    infoWindows[sn]?.open(deviceMap, m);



}


function showroutesassigned(deviceSerialNumber) {

    $.ajax({
        url: serverURL + "telemetry/device/" + deviceSerialNumber + "?page=0&size=10",
        type: "GET",
        dataType: "json",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json"
        },
        success: function (response) {

            if (!response.content || response.content.length < 2) {
                alert("Not enough data to draw path");
                return;
            }

            drawHistoryMap(response.content.reverse(), deviceSerialNumber);
        },
        error: function () {
            alert("Failed to load device history");
        }
    });
}


function updateDeviceSummary() {
    const total = devicesMaster.length;
    const online = devicesMaster.filter(d => d.isOnline).length;
    $("#device_summary").html(`Total: ${total} | Online: ${online} | Offline: ${total - online}`);
}

}