/**
 * War room — AJAX polling (reliable on WordPress admin; SSE is not used).
 */
(function ($) {
    'use strict';

    var pollTimer = null;

    function ajaxUrl() {
        if (typeof newsai_vars !== 'undefined' && newsai_vars.ajax_url) {
            return newsai_vars.ajax_url;
        }
        return typeof window.ajaxurl === 'string' ? window.ajaxurl : '';
    }

    function nonce() {
        return typeof newsai_vars !== 'undefined' ? newsai_vars.nonce : '';
    }

    function setStatus(text, live) {
        var $status = $('#nros-war-room-status');
        var $dot = $('.nros-war-room__dot');
        if ($status.length) {
            $status.text(text);
        }
        if ($dot.length) {
            $dot.toggleClass('is-live', !!live);
        }
    }

    function applySnapshot(snap, html) {
        var $room = $('#nros-war-room');
        var $grid = $('#nros-war-room-grid');
        if (!$grid.length) {
            return;
        }
        if ($room.hasClass('nros-war-room--compact')) {
            if (!snap || typeof snap !== 'object') {
                return;
            }
            $room.find('[data-metric="tasks_open"]').text(String(snap.tasks_open || 0));
            $room.find('[data-metric="tasks_overdue"]').text(String(snap.tasks_overdue || 0));
            var arts = Array.isArray(snap.recent_articles) ? snap.recent_articles : [];
            var $ul = $room.find('.nros-war-room__list');
            if ($ul.length) {
                $ul.empty();
                if (!arts.length) {
                    $ul.append('<li class="nros-war-room__empty">—</li>');
                } else {
                    arts.slice(0, 3).forEach(function (art) {
                        var title = art && art.title ? String(art.title) : '';
                        var url = art && art.url ? String(art.url) : '#';
                        var when = art && art.when ? String(art.when) : '';
                        var $li = $('<li/>');
                        $li.append($('<a/>', { href: url, target: '_blank', rel: 'noopener noreferrer', text: title }));
                        $li.append($('<span/>', { text: when }));
                        $ul.append($li);
                    });
                }
            }
            return;
        }
        if (html) {
            $grid.html(html);
            return;
        }
        if (!snap || typeof snap !== 'object') {
            return;
        }
        ['published', 'gsc_clicks', 'tasks_open', 'tasks_overdue'].forEach(function (key) {
            var val = snap[key];
            if (typeof val === 'undefined') {
                return;
            }
            $grid.find('[data-metric="' + key + '"]').text(String(val));
        });
    }

    function pollSnapshot(days) {
        var url = ajaxUrl();
        if (!url) {
            setStatus('Offline', false);
            return;
        }
        $.get(url, {
            action: 'newsai_warroom_snapshot',
            nonce: nonce(),
            days: days
        }).done(function (resp) {
            if (resp && resp.success && resp.data) {
                applySnapshot(resp.data.snapshot, resp.data.html);
                setStatus('Live', true);
            } else {
                setStatus('Update failed', false);
            }
        }).fail(function () {
            setStatus('Update failed', false);
        });
    }

    function stopPolling() {
        if (pollTimer) {
            window.clearInterval(pollTimer);
            pollTimer = null;
        }
    }

    function initWarRoom() {
        var $room = $('#nros-war-room');
        if (!$room.length) {
            return;
        }
        var days = parseInt($room.attr('data-days'), 10) || 30;
        var live = String($room.attr('data-live') || '') === '1';
        if (!live) {
            setStatus('Demo', false);
            return;
        }
        setStatus('Updating…', false);
        pollSnapshot(days);
        pollTimer = window.setInterval(function () {
            pollSnapshot(days);
        }, 30000);
        $(window).on('beforeunload', stopPolling);
    }

    $(function () {
        initWarRoom();
    });
}(jQuery));
