(function (window, document, $) {
  'use strict';

  if (!$) return;
  if (window.__noesiaSwaNewsAdminLoaded) return;
  window.__noesiaSwaNewsAdminLoaded = true;

  var modules = window.noesiaSwaAdminModules || (window.noesiaSwaAdminModules = {});
  var VIEW_KEY = 'noesia_swa_news_view_mode';
  var VIEW_MODES = ['panels', 'list', 'pulse', 'exclusive'];
  var CATEGORY_ACCENTS = {
    general: '#2563eb',
    business: '#0f766e',
    health: '#16a34a',
    economy: '#c2410c',
    politics: '#7c3aed',
    world: '#1d4ed8'
  };

  var state = {
    initialized: false,
    refreshId: 0,
    openTimer: null,
    fetching: false,
    lastFetchAt: 0,
    panelCache: {},
    tickerTimer: null,
    tickerIndex: 0,
    tickerItems: [],
    currentView: 'panels'
  };

  function vars() {
    return (window.noesia_admin_vars && typeof window.noesia_admin_vars === 'object') ? window.noesia_admin_vars : {};
  }

  function getOption(key, fallback) {
    var v = vars();
    if (v.options && Object.prototype.hasOwnProperty.call(v.options, key)) return v.options[key];
    return fallback;
  }

  function getLang() {
    var lang = String(getOption('news_language', 'en') || 'en').toLowerCase();
    return lang || 'en';
  }

  function getCountryFromLang(lang) {
    var map = { en: 'US', el: 'GR', fr: 'FR', de: 'DE', it: 'IT', es: 'ES' };
    return map[String(lang || 'en').toLowerCase()] || 'US';
  }

  function getCountry() {
    var explicit = String(getOption('news_country', '') || '').toUpperCase().replace(/[^A-Z]/g, '').slice(0, 2);
    if (explicit) return explicit;

    var weatherCountry = String(getOption('weather_country', '') || '').toUpperCase().replace(/[^A-Z]/g, '').slice(0, 2);
    if (weatherCountry) return weatherCountry;

    return getCountryFromLang(getLang());
  }

  function panelConfigs() {
    return [
      { key: 'general',  panel: 'general',  listId: 'noesia-swa-general-news',  countryId: 'noesia-swa-general-news-country',  topic: '',         query: '' },
      { key: 'business', panel: 'business', listId: 'noesia-swa-business-news', countryId: 'noesia-swa-business-news-country', topic: 'BUSINESS', query: '' },
      { key: 'health',   panel: 'health',   listId: 'noesia-swa-health-news',   countryId: 'noesia-swa-health-news-country',   topic: 'HEALTH',   query: '' },
      { key: 'economy',  panel: 'economy',  listId: 'noesia-swa-economy-news',  countryId: 'noesia-swa-economy-news-country',  topic: '',         query: '' },
      { key: 'politics', panel: 'politics', listId: 'noesia-swa-politics-news', countryId: 'noesia-swa-politics-news-country', topic: '',         query: '' },
      { key: 'world',    panel: 'world',    listId: 'noesia-swa-world-news',    countryId: 'noesia-swa-world-news-country',    topic: 'WORLD',    query: '' }
    ];
  }

  function normalizeView(view) {
    var safe = $.trim(String(view || 'panels')).toLowerCase();
    return VIEW_MODES.indexOf(safe) === -1 ? 'panels' : safe;
  }

  function getStore(key) {
    try { return window.localStorage.getItem(key); } catch (e) { return null; }
  }

  function setStore(key, value) {
    try { window.localStorage.setItem(key, value); } catch (e) {}
  }

  function escapeHtml(str) {
    return String(str || '')
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;');
  }

  function placeholderHtml(text) {
    return '<li class="noesia-swa-news-item noesia-swa-news-item--placeholder">' + escapeHtml(text) + '</li>';
  }

  function clearNewsCache() {
    state.refreshId += 1;
    state.fetching = false;
    state.lastFetchAt = 0;
    state.panelCache = {};
    state.tickerItems = [];
    state.tickerIndex = 0;
    stopTicker();
  }

  function ajaxFetchRss(config) {
    var v = vars();
    var ajaxUrl = v.ajax_url || '';
    var nonce = v.nonce || '';
    var lang = getLang();

    if (!ajaxUrl || !nonce) return $.Deferred().reject('missing_ajax').promise();

    var payload = {
      action: 'noesia_swa_fetch_news',
      nonce: nonce,
      lang: lang,
      country: getCountry(),
      panel: config && config.panel ? String(config.panel) : ''
    };

    if (config && config.topic) payload.topic = String(config.topic);
    if (config && config.query) payload.query = String(config.query);

    return $.ajax({
      url: ajaxUrl,
      method: 'POST',
      dataType: 'text',
      data: payload
    });
  }

  function parseRss(xmlText) {
    var items = [];
    if (!xmlText) return items;

    var doc;
    try {
      doc = (new window.DOMParser()).parseFromString(xmlText, 'text/xml');
    } catch (e) {
      return items;
    }

    var nodes = doc.getElementsByTagName('item');
    for (var i = 0; i < nodes.length; i++) {
      var item = nodes[i];
      var titleNode = item.getElementsByTagName('title')[0];
      var linkNode = item.getElementsByTagName('link')[0];
      var dateNode = item.getElementsByTagName('pubDate')[0];
      var sourceNode = item.getElementsByTagName('source')[0];

      var titleRaw = titleNode ? String(titleNode.textContent || '').trim() : '';
      var link = linkNode ? String(linkNode.textContent || '').trim() : '';
      if (!titleRaw || !link) continue;

      var source = '';
      var sourceUrl = '';
      if (sourceNode) {
        source = String(sourceNode.textContent || '').trim();
        if (sourceNode.getAttribute) sourceUrl = String(sourceNode.getAttribute('url') || '').trim();
      }

      var title = titleRaw;
      if (!source) {
        var parts = titleRaw.split(' - ');
        if (parts.length >= 2) {
          source = parts.slice(-1)[0];
          title = parts.slice(0, -1).join(' - ');
        }
      } else {
        var suffix = ' - ' + source;
        if (title.endsWith(suffix)) title = title.slice(0, -suffix.length).trim();
      }

      var pubDateMs = 0;
      if (dateNode) {
        var d = Date.parse(String(dateNode.textContent || '').trim());
        if (!window.isNaN(d)) pubDateMs = d;
      }

      items.push({
        title: title,
        link: link,
        source: source,
        sourceUrl: sourceUrl,
        pubDateMs: pubDateMs
      });
    }

    return items;
  }

  function pad2(n) {
    n = parseInt(n || 0, 10);
    return n < 10 ? '0' + n : String(n);
  }

  function isSameLocalDay(a, b) {
    return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
  }

  function formatWhen(ms, lang) {
    if (!ms) return '';
    var d = new Date(ms);
    if (window.isNaN(d.getTime())) return '';

    var now = new Date();
    var diffMs = Math.max(0, now.getTime() - d.getTime());
    var diffMin = Math.floor(diffMs / 60000);
    var diffHr = Math.floor(diffMs / 3600000);
    var isEl = (String(lang || '').toLowerCase() === 'el');

    if (diffMs < 60000) return isEl ? 'Τώρα' : 'Just now';
    if (diffMin < 60) return isEl ? (diffMin === 1 ? '1 λεπτό πριν' : diffMin + ' λεπτά πριν') : (diffMin === 1 ? '1 min ago' : diffMin + ' mins ago');
    if (diffHr < 6) return isEl ? (diffHr === 1 ? '1 ώρα πριν' : diffHr + ' ώρες πριν') : (diffHr === 1 ? '1 hour ago' : diffHr + ' hours ago');

    var hh = pad2(d.getHours());
    var mm = pad2(d.getMinutes());
    if (isSameLocalDay(now, d)) return (isEl ? 'Σήμερα, ' : 'Today, ') + hh + ':' + mm;

    var yest = new Date(now.getTime() - 86400000);
    if (isSameLocalDay(yest, d)) return (isEl ? 'Χθες, ' : 'Yesterday, ') + hh + ':' + mm;

    try {
      var locale = isEl ? 'el-GR' : undefined;
      var fmt = new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' });
      return fmt.format(d);
    } catch (e) {
      return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()) + ' ' + hh + ':' + mm;
    }
  }

  function renderSource(it, cls) {
    cls = cls || 'noesia-swa-news-source';
    if (!it.source) return '';
    if (it.sourceUrl) {
      return '<a class="' + cls + '" href="' + escapeHtml(it.sourceUrl) + '" target="_blank" rel="noopener noreferrer">' + escapeHtml(it.source) + '</a>';
    }
    return '<span class="' + cls + '">' + escapeHtml(it.source) + '</span>';
  }

  function renderMeta(it, lang, sourceClass, timeClass) {
    var when = formatWhen(it.pubDateMs, lang);
    var html = '<div class="noesia-swa-news-meta">';
    html += renderSource(it, sourceClass || 'noesia-swa-news-source');
    if (when) html += '<span class="' + (timeClass || 'noesia-swa-news-time-badge') + '">' + escapeHtml(when) + '</span>';
    html += '</div>';
    return html;
  }

  function renderPanelsHtml(items, lang) {
    var html = '';
    for (var i = 0; i < items.length && i < 8; i++) {
      var it = items[i];
      html += '<li class="noesia-swa-news-item">';
      html +=   '<div class="noesia-swa-news-item-inner">';
      html +=     '<a class="noesia-swa-news-link" href="' + escapeHtml(it.link) + '" target="_blank" rel="noopener noreferrer"><strong>' + escapeHtml(it.title) + '</strong></a>';
      html +=     renderMeta(it, lang, 'noesia-swa-news-source', 'noesia-swa-news-time-badge');
      html +=   '</div>';
      html += '</li>';
    }
    return html;
  }

  function renderListModeHtml(items, lang) {
    var html = '';
    for (var i = 0; i < items.length && i < 10; i++) {
      var it = items[i];
      html += '<li class="noesia-swa-news-list-row">';
      html +=   '<a class="noesia-swa-news-list-row-link" href="' + escapeHtml(it.link) + '" target="_blank" rel="noopener noreferrer">';
      html +=     '<span class="noesia-swa-news-list-row-index">' + pad2(i + 1) + '</span>';
      html +=     '<span class="noesia-swa-news-list-row-copy">';
      html +=       '<strong>' + escapeHtml(it.title) + '</strong>';
      html +=       renderMeta(it, lang, 'noesia-swa-news-source', 'noesia-swa-news-time-badge');
      html +=     '</span>';
      html +=   '</a>';
      html += '</li>';
    }
    return html;
  }

  function renderPulseHtml(items, lang, key) {
    var accent = CATEGORY_ACCENTS[key] || '#2563eb';
    var lead = items[0];
    var html = '<li class="noesia-swa-news-pulse-shell" style="--noesia-swa-news-accent:' + escapeHtml(accent) + ';">';
    html += '<div class="noesia-swa-news-pulse-hero">';
    html +=   '<div class="noesia-swa-news-pulse-kicker">Pulse</div>';
    html +=   '<a class="noesia-swa-news-pulse-link" href="' + escapeHtml(lead.link) + '" target="_blank" rel="noopener noreferrer">';
    html +=     '<strong>' + escapeHtml(lead.title) + '</strong>';
    html +=   '</a>';
    html +=   renderMeta(lead, lang, 'noesia-swa-news-source', 'noesia-swa-news-time-badge');
    html += '</div>';
    if (items.length > 1) {
      html += '<div class="noesia-swa-news-pulse-stack">';
      for (var i = 1; i < items.length && i < 6; i++) {
        var it = items[i];
        html += '<a class="noesia-swa-news-pulse-row" href="' + escapeHtml(it.link) + '" target="_blank" rel="noopener noreferrer">';
        html +=   '<span class="noesia-swa-news-pulse-row-index">' + pad2(i) + '</span>';
        html +=   '<span class="noesia-swa-news-pulse-row-copy">';
        html +=     '<span class="noesia-swa-news-pulse-row-title">' + escapeHtml(it.title) + '</span>';
        html +=     renderMeta(it, lang, 'noesia-swa-news-source', 'noesia-swa-news-time-badge');
        html +=   '</span>';
        html += '</a>';
      }
      html += '</div>';
    }
    html += '</li>';
    return html;
  }

  function renderExclusiveHtml(items, lang, key) {
    var accent = CATEGORY_ACCENTS[key] || '#2563eb';
    var lead = items[0];
    var html = '<li class="noesia-swa-news-exclusive-shell" style="--noesia-swa-news-accent:' + escapeHtml(accent) + ';">';
    html +=   '<a class="noesia-swa-news-exclusive-hero" href="' + escapeHtml(lead.link) + '" target="_blank" rel="noopener noreferrer">';
    html +=     '<span class="noesia-swa-news-exclusive-tag">Exclusive</span>';
    html +=     '<strong>' + escapeHtml(lead.title) + '</strong>';
    html +=     renderMeta(lead, lang, 'noesia-swa-news-source', 'noesia-swa-news-time-badge');
    html +=   '</a>';
    if (items.length > 1) {
      html += '<div class="noesia-swa-news-exclusive-groups">';
      for (var i = 1; i < items.length && i < 7; i++) {
        var it = items[i];
        html += '<a class="noesia-swa-news-exclusive-item" href="' + escapeHtml(it.link) + '" target="_blank" rel="noopener noreferrer">';
        html +=   '<span class="noesia-swa-news-exclusive-item-kicker">Story ' + pad2(i) + '</span>';
        html +=   '<span class="noesia-swa-news-exclusive-item-title">' + escapeHtml(it.title) + '</span>';
        html +=   renderMeta(it, lang, 'noesia-swa-news-source', 'noesia-swa-news-time-badge');
        html += '</a>';
      }
      html += '</div>';
    }
    html += '</li>';
    return html;
  }

  function renderPanel(listId, items, emptyText, key) {
    var $list = $('#' + listId);
    if (!$list.length) return;
    var lang = getLang();

    if (!items || !items.length) {
      $list.html(placeholderHtml(emptyText));
      return;
    }

    var mode = normalizeView(state.currentView);
    var html = '';
    if (mode === 'list') {
      html = renderListModeHtml(items, lang);
    } else if (mode === 'pulse') {
      html = renderPulseHtml(items, lang, key);
    } else if (mode === 'exclusive') {
      html = renderExclusiveHtml(items, lang, key);
    } else {
      html = renderPanelsHtml(items, lang);
    }

    $list.html(html);
  }

  function applyViewMode(view) {
    var safe = normalizeView(view);
    var $root = $('[data-noesia-swa-news-root="1"]');
    state.currentView = safe;
    setStore(VIEW_KEY, safe);
    if ($root.length) {
      $root.attr('data-noesia-swa-news-view', safe);
      $root.find('[data-noesia-swa-news-view-btn]').removeClass('is-active').attr('aria-pressed', 'false');
      $root.find('[data-noesia-swa-news-view-btn="' + safe + '"]').addClass('is-active').attr('aria-pressed', 'true');
    }
    renderCachedPanels();
  }

  function delay(ms) {
    return $.Deferred(function (d) { window.setTimeout(d.resolve, Math.max(0, ms || 0)); }).promise();
  }

  function renderDashboardMinimal() {
    var slotId = 'noesia-swa-dashboard-news-slot';
    var $slot = $('#' + slotId);
    if (!$slot.length) return;

    var lang = getLang();
    var cats = [
      { key: 'general', title: 'General' },
      { key: 'business', title: 'Business' },
      { key: 'health', title: 'Health' },
      { key: 'economy', title: 'Economy' }
    ];

    var html = '';
    html += '<div class="noesia-card noesia-swa-dash-news-card">';
    html +=   '<div class="noesia-swa-card-header"><div><h3>News Pulse</h3></div></div>';
    html +=   '<div class="noesia-swa-card-body"><div class="noesia-swa-dash-news-grid">';

    for (var c = 0; c < cats.length; c++) {
      var cat = cats[c];
      var items = (state.panelCache && state.panelCache[cat.key]) ? state.panelCache[cat.key] : [];
      html += '<div class="noesia-swa-dash-news-col">';
      html +=   '<div class="noesia-swa-dash-news-col-title">' + escapeHtml(cat.title) + '</div>';
      if (!items.length) {
        html += '<div class="noesia-swa-dash-news-empty">—</div>';
      } else {
        for (var i = 0; i < Math.min(items.length, 3); i++) {
          var it = items[i];
          var when = formatWhen(it.pubDateMs, lang);
          html += '<a class="noesia-swa-dash-news-item" href="' + escapeHtml(it.link) + '" target="_blank" rel="noopener noreferrer">';
          html +=   '<div class="noesia-swa-dash-news-title">' + escapeHtml(it.title) + '</div>';
          html +=   '<div class="noesia-swa-dash-news-meta">';
          if (it.source) html += '<span class="noesia-swa-dash-news-source">' + escapeHtml(it.source) + '</span>';
          if (when) html += '<span class="noesia-swa-dash-news-time">' + escapeHtml(when) + '</span>';
          html +=   '</div>';
          html += '</a>';
        }
      }
      html += '</div>';
    }

    html +=   '</div></div></div>';
    $slot.html(html);
  }

  function stopTicker() {
    if (state.tickerTimer) {
      window.clearInterval(state.tickerTimer);
      state.tickerTimer = null;
    }
  }

  function paintTicker() {
    var slotId = 'noesia-swa-morning-briefing-slot';
    var $slot = $('#' + slotId);
    if (!$slot.length) {
      stopTicker();
      return;
    }
    if (!state.tickerItems || !state.tickerItems.length) {
      $slot.html('<a class="noesia-swa-news-link" href="#" target="_blank" rel="noopener noreferrer"><strong>—</strong></a>');
      return;
    }

    var lang = getLang();
    var it = state.tickerItems[state.tickerIndex % state.tickerItems.length];
    state.tickerIndex += 1;
    var when = formatWhen(it.pubDateMs, lang);

    var a = '';
    a += '<a class="noesia-swa-news-link" href="' + escapeHtml(it.link) + '" target="_blank" rel="noopener noreferrer">';
    a +=   '<strong>' + escapeHtml(it.title) + '</strong>';
    if (it.source || when) {
      a += '<span class="noesia-swa-news-meta">';
      if (it.source) a += '<span class="noesia-swa-news-source">' + escapeHtml(it.source) + '</span>';
      if (when) a += '<span class="noesia-swa-news-time-badge">' + escapeHtml(when) + '</span>';
      a += '</span>';
    }
    a += '</a>';

    $slot.html(a);
  }

  function startTicker() {
    stopTicker();
    if (!$('#noesia-swa-morning-briefing-slot').length) return;
    state.tickerIndex = 0;
    paintTicker();
    state.tickerTimer = window.setInterval(paintTicker, 10000);
  }

  function renderCachedPanels() {
    var configs = panelConfigs();
    for (var i = 0; i < configs.length; i++) {
      var c = configs[i];
      if (state.panelCache && Object.prototype.hasOwnProperty.call(state.panelCache, c.key)) {
        renderPanel(c.listId, state.panelCache[c.key], 'News unavailable right now.', c.key);
      }
    }

    renderDashboardMinimal();

    if (!$('#noesia-swa-morning-briefing-slot').length) stopTicker();

    if (state.panelCache && state.panelCache.general && state.panelCache.general.length) {
      state.tickerItems = state.panelCache.general.slice(0, 10);
    } else {
      state.tickerItems = [];
    }
    startTicker();
  }

  function getPanelCacheSnapshot() {
    var snapshot = {};

    Object.keys(state.panelCache || {}).forEach(function (key) {
      snapshot[key] = Array.isArray(state.panelCache[key]) ? state.panelCache[key].slice() : [];
    });

    return snapshot;
  }

  function getMergedItems(limitPerPanel) {
    var perPanel = parseInt(limitPerPanel || 8, 10);
    var merged = [];

    if (!perPanel || perPanel < 1) {
      perPanel = 8;
    }

    panelConfigs().forEach(function (config) {
      var items = Array.isArray(state.panelCache[config.key]) ? state.panelCache[config.key].slice(0, perPanel) : [];
      items.forEach(function (item) {
        merged.push($.extend({ panel: config.key }, item || {}));
      });
    });

    merged.sort(function (left, right) {
      return (right.pubDateMs || 0) - (left.pubDateMs || 0);
    });

    return merged;
  }

  function refreshAll() {
    if (state.fetching) return false;

    var hasAny = (
      $('[data-noesia-swa-news-root="1"]').length ||
      $('#noesia-swa-dashboard-news-slot').length ||
      $('#noesia-swa-morning-briefing-slot').length ||
      $('#noesia-swa-general-news').length ||
      $('#noesia-swa-business-news').length ||
      $('#noesia-swa-health-news').length ||
      $('#noesia-swa-economy-news').length ||
      $('#noesia-swa-politics-news').length ||
      $('#noesia-swa-world-news').length
    );
    if (!hasAny) return false;

    state.fetching = true;
    state.refreshId += 1;
    var rid = state.refreshId;
    state.lastFetchAt = Date.now();

    var lang = getLang();
    var country = getCountry();
    var configs = panelConfigs();

    for (var i = 0; i < configs.length; i++) {
      if (configs[i].countryId && $('#' + configs[i].countryId).length) $('#' + configs[i].countryId).text(country);
    }

    for (var p = 0; p < configs.length; p++) {
      renderPanel(configs[p].listId, [], 'Loading headlines…', configs[p].key);
    }

    var chain = $.Deferred().resolve(true).promise();
    configs.forEach(function (c) {
      chain = chain.then(function () {
        if (rid !== state.refreshId) return $.Deferred().reject('cancelled').promise();
        return ajaxFetchRss(c).then(function (xmlText) {
          var items = parseRss(xmlText);
          state.panelCache[c.key] = items;
          renderPanel(c.listId, items, 'News unavailable right now.', c.key);
          return delay(90);
        }, function () {
          state.panelCache[c.key] = [];
          renderPanel(c.listId, [], 'News unavailable right now.', c.key);
          return delay(90);
        });
      });
    });

    chain.always(function () {
      state.fetching = false;
      renderCachedPanels();
      $(document).trigger('noesiaSwaNewsUpdated', [getMergedItems(8), getPanelCacheSnapshot()]);
    });

    return true;
  }

  function bindRefreshButtons() {
    $(document).off('click.noesiaSwaNews', '.noesia-swa-news-refresh');
    $(document).on('click.noesiaSwaNews', '.noesia-swa-news-refresh', function (e) {
      e.preventDefault();
      refreshAll();
    });
  }

  function bindViewButtons() {
    $(document).off('click.noesiaSwaNewsView', '[data-noesia-swa-news-view-btn]');
    $(document).on('click.noesiaSwaNewsView', '[data-noesia-swa-news-view-btn]', function (e) {
      e.preventDefault();
      applyViewMode($(this).attr('data-noesia-swa-news-view-btn'));
    });
  }

  function bindSettingsSync() {
    $(document).off('change.noesiaSwaNewsSettings', 'select[name="noesia_swa_options[news_language]"], input[name="noesia_swa_options[news_country]"], input[name="noesia_swa_options[weather_country]"]');
    $(document).on('change.noesiaSwaNewsSettings', 'select[name="noesia_swa_options[news_language]"], input[name="noesia_swa_options[news_country]"], input[name="noesia_swa_options[weather_country]"]', function () {
      clearNewsCache();
      window.setTimeout(function () {
        if ($('[data-noesia-swa-news-root="1"]').length || $('#noesia-swa-dashboard-news-slot').length || $('#noesia-swa-morning-briefing-slot').length) {
          refreshAll();
        }
      }, 80);
    });
  }

  function init() {
    if (state.initialized) return true;
    state.initialized = true;
    state.currentView = normalizeView(getStore(VIEW_KEY) || 'panels');

    bindRefreshButtons();
    bindViewButtons();
    bindSettingsSync();
    applyViewMode(state.currentView);

    if ($('#noesia-swa-dashboard-news-slot').length || $('#noesia-swa-morning-briefing-slot').length || $('[data-noesia-swa-news-root="1"]').length) {
      window.setTimeout(function () {
        renderCachedPanels();
        refreshAll();
      }, 150);
    }
    return true;
  }

  function onSectionOpen() {
    init();
    if (state.openTimer) window.clearTimeout(state.openTimer);
    state.openTimer = window.setTimeout(function () {
      applyViewMode(state.currentView);
      renderCachedPanels();
      var stale = !state.lastFetchAt || (Date.now() - state.lastFetchAt) > 120000;
      var empty = !state.panelCache || !state.panelCache.general;
      if (!state.fetching && (stale || empty)) refreshAll();
    }, 100);
    return true;
  }

  modules.news = $.extend({}, modules.news || {}, {
    init: init,
    onSectionOpen: onSectionOpen,
    refresh: refreshAll,
    renderCached: renderCachedPanels,
    stopTicker: stopTicker,
    clearCache: clearNewsCache,
    setViewMode: applyViewMode,
    getMergedItems: getMergedItems,
    getPanelCacheSnapshot: getPanelCacheSnapshot
  });

  window.noesiaSwaModules = window.noesiaSwaModules || {};
  window.noesiaSwaModules.news = modules.news;
  $(init);

})(window, document, window.jQuery);
