/**
 * Themis notification polling and browser notification support.
 *
 * Polls the notification count endpoint at a configurable interval
 * and updates the notification bell badge. Optionally triggers
 * browser desktop notifications for new items.
 *
 * Configuration (via data attributes on <body> or inline script):
 *   data-notification-poll-interval="60"  (seconds, 0 to disable)
 *   data-notification-count-url="/themis/notifications/count/"
 *   data-browser-notifications="true"
 */
(function () {
    "use strict";

    var badge = document.getElementById("themis-notification-badge");
    var bell = document.getElementById("themis-notification-bell");

    // No bell = notifications not enabled, bail out
    if (!bell) return;

    var body = document.body;
    var pollInterval = parseInt(body.getAttribute("data-notification-poll-interval") || "60", 10);
    var countUrl = body.getAttribute("data-notification-count-url") || "/themis/notifications/count/";
    var browserNotificationsEnabled = body.getAttribute("data-browser-notifications") === "true";
    var lastCount = parseInt((badge && badge.textContent.trim()) || "0", 10);

    /**
     * Request browser notification permission if enabled and not yet granted.
     */
    function requestNotificationPermission() {
        if (browserNotificationsEnabled &&
            "Notification" in window &&
            Notification.permission === "default") {
            Notification.requestPermission();
        }
    }

    /**
     * Show a browser desktop notification.
     */
    function showBrowserNotification(count, previousCount) {
        if (!browserNotificationsEnabled) return;
        if (!("Notification" in window)) return;
        if (Notification.permission !== "granted") return;
        if (count <= previousCount) return;

        var newCount = count - previousCount;
        var noun = newCount === 1 ? "notification" : "notifications";

        try {
            new Notification("New Notifications", {
                body: "You have " + newCount + " new " + noun,
                icon: "/static/themis/img/notification-icon.png",
                tag: "themis-notifications",
            });
        } catch (e) {
            // Notification constructor may fail in some contexts
        }
    }

    /**
     * Update the badge count display.
     */
    function updateBadge(count) {
        if (!badge) return;

        badge.textContent = count;
        if (count > 0) {
            badge.classList.remove("hidden");
        } else {
            badge.classList.add("hidden");
        }
    }

    /**
     * Poll the server for the current unread notification count.
     */
    function pollNotificationCount() {
        fetch(countUrl, {
            credentials: "same-origin",
            headers: {
                "X-Requested-With": "XMLHttpRequest",
            },
        })
        .then(function (response) {
            if (!response.ok) return null;
            return response.json();
        })
        .then(function (data) {
            if (!data || typeof data.count !== "number") return;

            var newCount = data.count;
            updateBadge(newCount);

            // Show browser notification if count increased
            if (newCount > lastCount) {
                showBrowserNotification(newCount, lastCount);
            }

            lastCount = newCount;
        })
        .catch(function () {
            // Silently ignore polling errors
        });
    }

    // Request permission on load if browser notifications are enabled
    requestNotificationPermission();

    // Start polling if interval > 0
    if (pollInterval > 0) {
        setInterval(pollNotificationCount, pollInterval * 1000);
    }
})();
