var userObj = JSON.parse(localStorage.getItem('userObj'));

let currentAttendId = null;
let currentAttendBtn = null;

let notificationsCache = [];
let currentPage = 0;
const pageSize = 9;

/* PRIORITY ORDER */
const PRIORITY_ORDER = {
    CRITICAL: 1,
    HIGH: 2,
    MEDIUM: 3,
    LOW: 4
};

/* ================= LOAD ================= */
loadNotificationData();

function loadNotificationData() {

    $(".crud_section").html(`
        <div class="ui segment" style="height:600px">
            <div class="ui active inverted dimmer">
                <div class="ui text loader">Loading</div>
            </div>
        </div>
    `);

    

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

            if (!response.content || response.content.length === 0) {
                $(".crud_section").html(
                    `<div class="no-notifications">No notifications available</div>`
                );
                return;
            }

            notificationsCache = response.content.sort((a, b) => {
                const p1 = PRIORITY_ORDER[a.priority] || 99;
                const p2 = PRIORITY_ORDER[b.priority] || 99;
                if (p1 !== p2) return p1 - p2;
                return new Date(b.createdAt) - new Date(a.createdAt);
            });

            currentPage = 0;
            renderNotificationsPage();
        },
        error: function () {
            $(".crud_section").html(
                `<div class="error-box">Failed to load notifications</div>`
            );
        }
    });
}

/* ================= RENDER PAGE ================= */
function renderNotificationsPage() {

    const start = currentPage * pageSize;
    const pageItems = notificationsCache.slice(start, start + pageSize);

    let html = `<div class="notifications-wrapper">`;

    pageItems.forEach(item => {

        const deviceBtn = item.deviceSerialNumber
            ? `<button class="btn-map"
                    onclick="openmap('${item.deviceSerialNumber}')">
                    📍 View on Map
               </button>`
            : `<span class="no-device">No device</span>`;

        html += `
        <div class="notification-card ${item.read ? '' : 'unread'}">

            <div class="notification-header">
                <span class="notification-title">${item.title}</span>
                <span class="notification-time">${formatDate(item.createdAt)}</span>
            </div>

            <div class="notification-body">
                ${item.message.replace(/\n/g, "<br>")}
            </div>

            <div class="notification-footer">
                <span class="priority ${item.priority.toLowerCase()}">
                    ${item.priority}
                </span>

                <div class="notification-actions">

                    ${
                        !item.read
                            ? `<button class="btn-read"
                                    onclick="markAsRead(${item.id}, this)">
                                    Mark Read
                               </button>`
                            : `<span class="read-label">Read</span>`
                    }

                    ${
                        !item.attended
                            ? `<button class="btn-attend"
                                    onclick="openAttendModal(${item.id}, this)">
                                    Attend
                               </button>`
                            : `<span class="attended-label">Attended</span>`
                    }
                </div>
            </div>
        </div>`;
    });

    html += renderPaginationControls();
    html += `</div>`;

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

/* ================= PAGINATION ================= */
function renderPaginationControls() {

    const totalPages = Math.ceil(notificationsCache.length / pageSize);
    if (totalPages <= 1) return "";

    return `
        <div class="pagination">
            <button ${currentPage === 0 ? "disabled" : ""}
                onclick="changePage(${currentPage - 1})">◀ Prev</button>

            <span class="page-info">
                Page ${currentPage + 1} of ${totalPages}
            </span>

            <button ${currentPage >= totalPages - 1 ? "disabled" : ""}
                onclick="changePage(${currentPage + 1})">Next ▶</button>
        </div>
    `;
}

function changePage(page) {
    currentPage = page;
    renderNotificationsPage();
}

/* ================= MAP ================= */
function viewDeviceOnMap(deviceSerialNumber) {

    if (typeof focusDevice !== "function") {
        
        
        openmap(deviceSerialNumber);


        return;
    }

    focusDevice(deviceSerialNumber);

    document
        .getElementById("all_devices_map")
        ?.scrollIntoView({ behavior: "smooth" });
}

let historyMap;
let historyPolyline;

function openmap(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 drawHistoryMap(data, deviceSn) {

    $("#historyMapModal").fadeIn(150);

    const pathCoords = data
        .filter(d => d.latitude && d.longitude)
        .map(d => ({ lat: d.latitude, lng: d.longitude }));

    const start = pathCoords[0];
    const end = pathCoords[pathCoords.length - 1];

    historyMap = new google.maps.Map(
        document.getElementById("historyMap"),
        {
            zoom: 14,
            center: end,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            //    mapTypeId: google.maps.MapTypeId.SATELLITE, // 👈 DEFAULT SATELLITE
                styles: [
                    {
                        featureType: "administrative.country",
                        elementType: "geometry.stroke",
                        stylers: [{ visibility: "on" }, { color: "#000" }, { weight: 2 }]
                    },
                    {
                        featureType: "administrative.province",
                        elementType: "geometry.stroke",
                        stylers: [{ visibility: "on" }, { weight: 1 }]
                    },
                    {
                        featureType: "road",
                        elementType: "geometry",
                        stylers: [{ color: "#E9E8E8" }]
                    },
                    {
                        featureType: "water",
                        elementType: "geometry",
                        stylers: [{ color: "#b7e3f4" }]
                    }
                ],
                gestureHandling: "greedy",
                zoomControl: true,
                streetViewControl: true,
                mapTypeControl: true,
                fullscreenControl: true



        }
    );

    /* PATH */
    historyPolyline = new google.maps.Polyline({
        path: pathCoords,
        geodesic: true,
        strokeColor: "#0d6efd",
        strokeOpacity: 0.9,
        strokeWeight: 4
    });

    historyPolyline.setMap(historyMap);

    /* START MARKER */
    new google.maps.Marker({
        position: start,
        map: historyMap,
        label: "S",
        icon: {
            url: "https://maps.google.com/mapfiles/ms/icons/green-dot.png"
        }
    });

    /* CURRENT MARKER */
    new google.maps.Marker({
        position: end,
        map: historyMap,
        label: "Now",
        icon: {
            url: "https://maps.google.com/mapfiles/ms/icons/red-dot.png"
        }
    });

    /* FIT */
    const bounds = new google.maps.LatLngBounds();
    pathCoords.forEach(p => bounds.extend(p));
    historyMap.fitBounds(bounds);
}


function closeHistoryMap() {
    $("#historyMapModal").fadeOut(150);
}

/* ================= ACTIONS ================= */
function openAttendModal(id, btn) {
    currentAttendId = id;
    currentAttendBtn = btn;
    $("#attendComments").val("");
    $("#attendModal").fadeIn(150);
}

function closeAttendModal() {
    $("#attendModal").fadeOut(150);
    currentAttendId = null;
    currentAttendBtn = null;
}

function submitAttend() {

    const comments = $("#attendComments").val().trim();
    if (!comments) return alert("Please enter comments");

    $.ajax({
        url: serverURL + "notifications/" + currentAttendId + "/attend",
        type: "POST",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json"
        },
        data: JSON.stringify({ comments }),
        success: function () {
            $(currentAttendBtn)
                .replaceWith(`<span class="attended-label">Attended</span>`);
            closeAttendModal();
        }
    });
}

function markAsRead(id, btn) {

    $.ajax({
        url: serverURL + "notifications/" + id + "/read",
        type: "POST",
        headers: {
            Authorization: "Bearer " + userObj.accessToken,
            "Content-Type": "application/json"
        },
        success: function () {
            $(btn).closest(".notification-card").removeClass("unread");
            $(btn).remove();
        }
    });
}

/* ================= UTILS ================= */
function formatDate(d) {
    return new Date(d).toLocaleString();
}
