jQuery(document).ready(function () {
    const slimstatNotificationButtons = document.querySelectorAll('.js-slimstat-open-notification');
    const slimstatSidebar = document.querySelector('.slimstat-notification-sidebar');
    const slimstatOverlay = document.querySelector('.slimstat-notification-sidebar__overlay');
    const body = document.body;
    const tabs = document.querySelectorAll('.slimstat-notification-sidebar__tab');
    const slimstatCloseNotificationMenu = document.querySelector('.slimstat-notification-sidebar__close');
    const slimstatReloadNotifications = document.querySelector('.slimstat-notification-sidebar__reload');
    const tabPanes = document.querySelectorAll('.slimstat-notification-sidebar__tab-pane');
    const dismissAllBtn = document.querySelector(".slimstat-notification-sidebar__dismiss-all");

    // Toggle notification menu
    if (tabs.length > 0 && tabPanes.length > 0) {
        tabs.forEach(function (tab) {
            tab.addEventListener('click', function () {
                tabs.forEach(function (t) {
                    t.classList.remove('slimstat-notification-sidebar__tab--active');
                });
                tabPanes.forEach(function (pane) {
                    pane.classList.remove('slimstat-notification-sidebar__tab-pane--active');
                });

                const targetTab = tab.getAttribute('data-tab');
                tab.classList.add('slimstat-notification-sidebar__tab--active');
                document.getElementById(targetTab).classList.add('slimstat-notification-sidebar__tab-pane--active');
            });
        });
    }

    if (slimstatNotificationButtons.length > 0 && slimstatSidebar && slimstatOverlay) {
        const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
        document.documentElement.style.setProperty('--scrollbar-width', `${scrollbarWidth}px`);

        slimstatNotificationButtons.forEach(function (button) {
            button.addEventListener('click', function (e) {
                e.preventDefault();
                slimstatSidebar.classList.toggle('is-active');
                slimstatOverlay.classList.toggle('is-active');
                setTimeout(() => {
                    body.classList.toggle('slimstat-no-scroll');
                }, 250);
            });
        });

        slimstatOverlay.addEventListener('click', function () {
            slimstatSidebar.classList.remove('is-active');
            slimstatOverlay.classList.remove('is-active');
            setTimeout(() => {
                body.classList.remove('slimstat-no-scroll');
            }, 250);
        });
        if (slimstatCloseNotificationMenu) {
            slimstatCloseNotificationMenu.addEventListener('click', function () {
                slimstatSidebar.classList.remove('is-active');
                slimstatOverlay.classList.remove('is-active');
                body.classList.remove('slimstat-no-scroll');
            });
        }

        if (slimstatReloadNotifications) {
            slimstatReloadNotifications.addEventListener('click', function () {
                if (slimstatReloadNotifications.classList.contains('is-loading')) {
                    return;
                }

                slimstatReloadNotifications.classList.add('is-loading');

                jQuery.ajax({
                    url: slimstat_admin.ajax_url,
                    type: 'GET',
                    dataType: 'json',
                    data: {
                        'slimstat_nonce': slimstat_admin.nonce,
                        'action': 'slimstat_refresh_notifications'
                    },
                    timeout: 60000,
                    success: function (response) {
                        slimstatReloadNotifications.classList.remove('is-loading');

                        if (response.success) {
                            jQuery('#tab-1 .slimstat-notification-sidebar__cards').html(response.data.inbox_html);
                            jQuery('#tab-2 .slimstat-notification-sidebar__cards').html(response.data.dismissed_html);

                            updateDismissAllVisibility();
                            checkEmptyNotifications();
                            updateNotificationBadge();
                        }
                    },
                    error: function () {
                        slimstatReloadNotifications.classList.remove('is-loading');
                    }
                });
            });
        }

    }

    const updateDismissAllVisibility = () => {
        const activeTab = document.querySelector(".slimstat-notification-sidebar__tab--active");
        if (!activeTab) {
            return;
        }

        if (activeTab.dataset.tab === "tab-2") {
            if (dismissAllBtn) dismissAllBtn.style.display = "none";
        } else {
            const activeCards = document.querySelectorAll(
                ".slimstat-notification-sidebar__cards--active .slimstat-notification-sidebar__card:not(.slimstat-notification-sidebar__no-card)"
            );
            const hasNotifications = activeCards.length > 0;
            if (dismissAllBtn) dismissAllBtn.style.display = hasNotifications ? "inline-flex" : "none";
        }
    };

    const updateNotificationBadge = () => {
        // Count unread notifications (those in inbox tab)
        let inboxCards = jQuery('#tab-1 .slimstat-notification-sidebar__card:not(.slimstat-notification-sidebar__no-card)');
        let notificationBell = jQuery('.slimstat-notifications');
        let notificationBadge = jQuery('.notification-badge');

        if (inboxCards.length === 0) {
            // No unread notifications - remove badge and 'has-items' class
            notificationBell.removeClass('slimstat-notifications--has-items');
            notificationBadge.hide();
        } else {
            // Has unread notifications - show badge and add 'has-items' class
            notificationBell.addClass('slimstat-notifications--has-items');
            if (notificationBadge.length === 0) {
                // Create badge if it doesn't exist
                notificationBell.find('.dashicons-bell').after('<span class="notification-badge"></span>');
            } else {
                notificationBadge.show();
            }
        }
    };

    const checkEmptyNotifications = () => {
        let notificationsHasItems = jQuery('.slimstat-notifications--has-items');
        let helpNotification = jQuery('.slimstat-help__notification');
        let activeCards = jQuery('.slimstat-notification-sidebar__tab-pane--active .slimstat-notification-sidebar__card:not(.slimstat-notification-sidebar__no-card)');
        let noCardMessages = jQuery('.slimstat-notification-sidebar__tab-pane--active .slimstat-notification-sidebar__no-card');
        let noCardMessage = noCardMessages.first();

        if (activeCards.length === 0) {
            // If no active cards, show the empty state
            if (noCardMessage.length === 0) {
                // Create empty state if it doesn't exist
                let activeTabPane = jQuery('.slimstat-notification-sidebar__tab-pane--active .slimstat-notification-sidebar__cards');
                let tabName = jQuery('.slimstat-notification-sidebar__tab--active').text().toLowerCase();
                let emptyStateHtml = `
                    <div class="slimstat-notification-sidebar__card slimstat-notification-sidebar__no-card">
                        <div class="slimstat-notification-sidebar__card-body">
                            <svg width="37" height="37" viewBox="0 0 37 37" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <path d="M27.7802 17.2238V18.1917C27.7802 19.1322 28.181 20.5659 28.6435 21.3676L30.4164 24.3122C31.4339 26.008 30.6168 28.2126 28.7514 28.8292C22.1068 31.0492 14.9381 31.0492 8.29351 28.8292C6.28934 28.1509 5.53393 26.1313 6.62851 24.3122L8.40143 21.3676C8.87934 20.5659 9.28018 19.1322 9.28018 18.1917V13.7363C9.28018 8.63341 13.4273 4.48633 18.5302 4.48633C21.7261 4.48633 24.5571 6.12898 26.2203 8.6117" stroke="#56585A" stroke-width="1.59483" stroke-miterlimit="10" stroke-linecap="round"/>
                                <path d="M21.3829 4.93273C20.905 4.79398 20.4116 4.68607 19.9029 4.6244C18.4229 4.4394 17.0045 4.54732 15.6787 4.93273C16.1258 3.7919 17.2358 2.99023 18.5308 2.99023C19.8258 2.99023 20.9358 3.7919 21.3829 4.93273Z" stroke="#56585A" stroke-width="1.59483" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
                                <path d="M23 30C23 32.2 20.975 34 18.5 34C17.27 34 16.13 33.5467 15.32 32.8267C14.51 32.1067 14 31.0933 14 30" stroke="#56585A" stroke-width="1.59483" stroke-miterlimit="10"/>
                                <path d="M31.8096 8.29405H33.9093L31.2355 10.9199C31.0033 11.148 30.9334 11.4909 31.0593 11.7891C31.1844 12.0873 31.4815 12.2811 31.8096 12.2811H35.8695C36.3185 12.2811 36.6814 11.9239 36.6814 11.4837C36.6814 11.0435 36.3185 10.6863 35.8695 10.6863H33.7697L36.4435 8.0604C36.6758 7.83234 36.7456 7.48946 36.6197 7.19122C36.4947 6.89299 36.1975 6.69922 35.8695 6.69922H31.8096C31.3605 6.69922 30.9976 7.05646 30.9976 7.49663C30.9976 7.93681 31.3605 8.29405 31.8096 8.29405ZM21.6992 20.2541C21.4296 19.9024 20.9197 19.8331 20.5624 20.0978C20.2052 20.3634 20.1337 20.8633 20.4041 21.215C20.547 21.4008 21.3289 22.329 22.676 22.329C22.9131 22.329 24.1376 22.2756 24.9496 21.2126C25.2183 20.8601 25.1461 20.361 24.788 20.0962C24.4283 19.8315 23.92 19.9024 23.6512 20.2557C23.2899 20.7286 22.7012 20.7342 22.6768 20.7342C22.0776 20.7342 21.7155 20.2732 21.7008 20.2533L21.6992 20.2541ZM16.6674 20.097C16.3077 19.8323 15.7994 19.9032 15.5306 20.2565C15.1693 20.7294 14.5806 20.7349 14.5562 20.7349C13.957 20.7349 13.5949 20.274 13.5802 20.2541C13.3099 19.9024 12.8007 19.8331 12.4435 20.0978C12.0862 20.3634 12.0148 20.8633 12.2851 21.215C12.4281 21.4008 13.21 22.329 14.5571 22.329C14.7942 22.329 16.0186 22.2756 16.8306 21.2126C17.0994 20.8601 17.0271 20.361 16.669 20.0962L16.6674 20.097ZM29.3119 11.1783C29.1869 10.8801 28.8897 10.6863 28.5617 10.6863H26.1257C25.6767 10.6863 25.3138 11.0435 25.3138 11.4837C25.3138 11.9239 25.6767 12.2811 26.1257 12.2811H26.6015L25.5517 13.3122C25.3194 13.5402 25.2496 13.8831 25.3755 14.1814C25.5005 14.4796 25.7977 14.6734 26.1257 14.6734H28.5617C29.0107 14.6734 29.3736 14.3161 29.3736 13.8759C29.3736 13.4358 29.0107 13.0785 28.5617 13.0785H28.0858L29.1357 12.0475C29.368 11.8194 29.4378 11.4765 29.3119 11.1783Z" fill="#56585A"/>
                            </svg>
                            <h2 class="slimstat-notification-sidebar__card-content">You are up to date!</h2>
                            <p class="slimstat-notification-sidebar__card-content">
                                No notifications in your ${tabName}.
                            </p>
                        </div>
                    </div>
                `;
                activeTabPane.append(emptyStateHtml);
            } else {
                noCardMessage.css('display', 'flex');
            }
            helpNotification.hide();
            notificationsHasItems.removeClass('slimstat-notifications--has-items');
        } else {
            noCardMessage.hide();
        }
        if (noCardMessages.length > 1) {
            noCardMessages.last().hide();
        }

        // Update the badge status
        updateNotificationBadge();
    }

    tabs.forEach(tab => {
        tab.addEventListener("click", function () {
            tabs.forEach(t => t.classList.remove("slimstat-notification-sidebar__tab--active"));
            this.classList.add("slimstat-notification-sidebar__tab--active");
            updateDismissAllVisibility();
            checkEmptyNotifications();
        });
    });

    updateDismissAllVisibility();
    checkEmptyNotifications();
    updateNotificationBadge();

    jQuery(document).on('click', "a.slimstat-notification-sidebar__dismiss, a.slimstat-notification-sidebar__dismiss-all", function (e) {
        e.preventDefault();
        let $this = jQuery(this);
        let notificationId = '';

        if ($this.hasClass('slimstat-notification-sidebar__dismiss')) {
            notificationId = $this.data('notification-id');
        }

        if ($this.hasClass('slimstat-notification-sidebar__dismiss-all')) {
            notificationId = 'all';
        }


        if (notificationId === 'all') {
            jQuery('.slimstat-notification-sidebar__cards--active .slimstat-notification-sidebar__card:not(.slimstat-notification-sidebar__no-card)').each(function () {
                let $card = jQuery(this);

                jQuery('.slimstat-notification-sidebar__cards--dismissed').prepend($card.clone().hide().fadeIn(300));

                $card.fadeOut(300, function () {
                    jQuery(this).remove();
                    checkEmptyNotifications();
                    updateNotificationBadge();
                });
            });
        } else {
            let $card = $this.closest('.slimstat-notification-sidebar__card');

            jQuery('.slimstat-notification-sidebar__cards--dismissed').prepend($card.clone().hide().fadeIn(300));

            $card.fadeOut(300, function () {
                jQuery(this).remove();
                checkEmptyNotifications();
                updateNotificationBadge();
            });

        }
        updateDismissAllVisibility();

        jQuery('.slimstat-notification-sidebar__cards--dismissed .slimstat-notification-sidebar__no-card').remove();

        let params = {
            'slimstat_nonce': slimstat_admin.nonce,
            'action': 'slimstat_dismiss_notification',
            'notification_id': notificationId
        }

        jQuery.ajax({
            url: slimstat_admin.ajax_url,
            type: 'GET',
            dataType: 'json',
            data: params,
            timeout: 30000,
            success: function ({data, success}) {
                if (!success) {
                    console.log(data);
                } else {
                    // Ensure badge is updated after successful dismissal
                    updateNotificationBadge();
                }
            },
            error: function (xhr, status, error) {
                console.log(error);
            }
        });
    });
});