(function ($) {
    'use strict';

    var intervalId = null;

    function refreshTraffic() {
        if (!$('#traffic-monitor-table').length) {
            return;
        }

        $.post(ultraguardTrafficMonitor.ajaxUrl, {
            action: 'ultraguard_traffic_get_logs',
            nonce: ultraguardTrafficMonitor.nonce,
            page: 1,
            limit: 25
        });
    }

    function maybeStartRefresh() {
        if (intervalId) {
            window.clearInterval(intervalId);
            intervalId = null;
        }

        if ($('input[name="traffic-monitor-live-refresh"]').is(':checked')) {
            intervalId = window.setInterval(refreshTraffic, ultraguardTrafficMonitor.refreshEvery || 10000);
        }
    }

    $(document).on('change', 'input[name="traffic-monitor-live-refresh"]', maybeStartRefresh);
    $(maybeStartRefresh);
})(jQuery);
