$(document).ready(function () {

    let currentUserToken = null;
    let wsUrl = null;
    let ws;
    let notifications = [];
    const audio = document.getElementById('message-sound');

    $.ajax({
        url: '/engine/ajax/lib/notification/get_token.php', // Замените на ваш маршрут
        type: 'GET',
        data: { },
        dataType: 'json',
        success: function(response) {
            if (response.token !== false) {
                currentUserToken = response.token;
                wsUrl = response.ws_config.web_socket_url;
                connectToWebSocket();
            }
        },
        error: function(xhr) {
        }
    });

    $('.dropdown-toggle-notification').on('click', function () {
        const unreadIds = notifications
            .filter(n => n.status === 0)
            .map(n => n.id);

        if (unreadIds.length > 0) {
            // Отправляем на сервер запрос: пометить как прочитанные
            $.ajax({
                url: '/engine/ajax/lib/notification/mark_as_read.php',
                method: 'POST',
                data: { ids: unreadIds },
                dataType: 'json',
                success: function (response) {
                    
                    notifications = response;

                    const $dot = $('.dropdown-toggle .bullet-dot');

                    const unreadCount = notifications.filter(n => n.status === 0).length;

                    if ($dot.length) {
                        if (unreadCount > 0) {
                            $(".animation-blink").show();
                            $dot.text(unreadCount > 10 ? '10+' : unreadCount);
                        } else {
                            $(".animation-blink").hide().text('');
                        }
                    }
                }
            });
        }
    });


    function connectToWebSocket() {

        ws = new WebSocket(wsUrl + '?usr_token=' + currentUserToken);

        
        ws.onopen = function () {
            ws.send(JSON.stringify({
                type: 'notification',
                from_user_token: currentUserToken,
                action: "connect",
                globalLang: window.globalLang
            }));
        };

        ws.onmessage = function (event) {
            
            const data = JSON.parse(event.data);
            notifications = data.notifications
            if (data.type === "notification" && data.action === "connect" || data.type === "notification" && data.action === "send") {
                if (notifications === null) {
                    $(".animation-blink").hide();

                }
                const $list = $('#NotificationsDiv ul');
                const $dot = $('.dropdown-toggle .bullet-dot');

                $list.empty();

                if (notifications.length < 1) {
                    $list.append(`
                        <li class="pe-2 text-center text-muted py-5">
                            <div class="fs-6">Уведомлений нет</div>
                            <small class="text-secondary d-block">Вы в курсе всех событий</small>
                        </li>
                    `);
                }

                const unreadCount = notifications.filter(n => n.status === 0).length;

                if ($dot.length) {
                    if (unreadCount > 0) {
                        $(".animation-blink").show();
                        $dot.text(unreadCount > 10 ? '10+' : unreadCount);
                    } else {
                        $(".animation-blink").hide().text('');
                    }
                }


                // Перебираем уведомления и добавляем в список
                $.each(notifications, function (index, item) {
                    const time = new Date(item.created_at).toLocaleString('en-EN', {
                        day: 'numeric',
                        month: 'short',   // например, "May"
                        year: 'numeric',
                        hour: '2-digit',
                        minute: '2-digit',
                        second: '2-digit', // добавляем секунды
                        hour12: false      // отключаем 12-часовой формат (AM/PM), если нужно
                    });


                    const notificationItem = `
            <li class="pe-2" onclick="window.location.href = '${item.module_url}'">
                <a class="d-flex p-lg-3 p-2 rounded-3" href="javascript:void(0);">
                    <div class="avatar sm">
                        ${item.svg_ico}
                    </div>
                    <div class="flex-fill ms-3">
                        <span class="d-flex justify-content-between">
                            <small class="text-primary">${window.globalLang[item.module_type] || 'Уведомление'}</small>
                            <small class="text-muted">${time}</small>
                        </span>
                        <p class="mb-0 mt-1">${item.content}</p>
                    </div>
                </a>
            </li>
        `;
                    $list.append(notificationItem);
                });


                if (data.type === "notification" && data.action === "send") {
                    audio.play();
                    Push.create(window.globalLang[notifications[0]['module_type']], {
                        body: notifications[0]["content"],
                        icon: 'https://cdn-icons-png.flaticon.com/512/1827/1827349.png',
                        timeout: 5000,
                        onClick: function () {
                            window.location.href = notifications[0]['module_url'];
                            this.close();
                        }
                    });
                    const $list = $('#notificationList');

                    if (notifications.length > 0) {
                        const item = notifications[0];

                        $(".no-notifications").addClass("d-none");

                        const time = new Date(item.created_at).toLocaleString('en-EN', {
                            day: 'numeric',
                            month: 'short',
                            year: 'numeric',
                            hour: '2-digit',
                            minute: '2-digit',
                            second: '2-digit',
                            hour12: false
                        });

                        const notificationItem = `
                            <div class="card mb-3 notification-card shadow-sm">
                                <div class="card-body d-flex align-items-center gap-3">
                                    ${item.svg_ico}
                                    <div class="flex-grow-1">
                                        <h6 class="mb-1">${item.content}</h6>
                                        <p class="mb-0 notification-time">${time}</p>
                                    </div>
                                </div>
                            </div>
                        `;

                        $list.prepend(notificationItem);
                    }
                }

            }

        }

    }
});