(function () {
  var content = document.querySelector('[data-shieldx-dashboard-widget-content]');
  var requested = false;

  if (!content) {
    return;
  }

  function widgetIsOpen() {
    var postbox = content.closest('.postbox');

    return !postbox || !postbox.classList.contains('closed');
  }

  function initDashboardWidgetLayout() {
    var widget = document.getElementById('shieldx_security_trends');
    var dashboard = document.getElementById('dashboard-widgets');
    var container;
    var sortable;

    if (!widget || !dashboard) {
      return;
    }

    container = document.getElementById('shieldx-dashboard-widget-container');

    if (!container) {
      container = document.createElement('div');
      container.id = 'shieldx-dashboard-widget-container';
      container.className = 'postbox-container shieldx-dashboard-widget-container';

      sortable = document.createElement('div');
      sortable.id = 'shieldx-dashboard-widget-sortables';
      sortable.className = 'meta-box-sortables ui-sortable';
      container.appendChild(sortable);

      dashboard.insertBefore(container, dashboard.firstElementChild);
    }

    sortable = container.querySelector('.meta-box-sortables');
    if (!sortable) {
      return;
    }

    container.classList.add('shieldx-dashboard-widget-container');

    if (widget.parentElement !== sortable) {
      sortable.appendChild(widget);
    }
  }

  function isSameOriginUrl(url) {
    var parsed;

    if (!url || !window.URL) {
      return false;
    }

    try {
      parsed = new window.URL(url, window.location.href);
    } catch (error) {
      return false;
    }

    return parsed.origin === window.location.origin;
  }

  function loadAdminScript() {
    var url = content.getAttribute('data-shieldx-dashboard-widget-script') || '';
    var existing;
    var script;

    if (!isSameOriginUrl(url)) {
      return;
    }

    existing = document.getElementById('shieldx-dashboard-admin-script');
    if (existing) {
      return;
    }

    script = document.createElement('script');
    script.id = 'shieldx-dashboard-admin-script';
    script.src = url;
    script.async = false;
    document.head.appendChild(script);
  }

  function loadAdminAssets() {
    var url = content.getAttribute('data-shieldx-dashboard-widget-css') || '';
    var existing;
    var style;

    if (requested || !widgetIsOpen()) {
      return;
    }

    requested = true;
    existing = document.getElementById('shieldx-dashboard-admin-style');
    if (existing || !isSameOriginUrl(url)) {
      loadAdminScript();
      return;
    }

    style = document.createElement('link');
    style.id = 'shieldx-dashboard-admin-style';
    style.rel = 'stylesheet';
    style.href = url;
    document.head.appendChild(style);
    // Styling is not a script dependency. Start both downloads together so an
    // open Dashboard widget does not wait an extra network round trip before
    // requesting its aggregate data.
    loadAdminScript();
  }

  // The full admin bundle styles the widget, but the lightweight loader must
  // position it first. Waiting for intersection before moving it creates a
  // circular dependency when WordPress initially renders the widget below the
  // viewport.
  initDashboardWidgetLayout();

  if (window.IntersectionObserver) {
    (new window.IntersectionObserver(function (entries, observer) {
      entries.forEach(function (entry) {
        if (!entry.isIntersecting) {
          return;
        }

        observer.disconnect();
        loadAdminAssets();
      });
    })).observe(content);
  } else {
    window.setTimeout(loadAdminAssets, 0);
  }

  document.addEventListener('click', function (event) {
    var toggle = event.target.closest('.hndle, .handlediv');
    var postbox = content.closest('.postbox');

    if (!toggle || !postbox || !postbox.contains(toggle)) {
      return;
    }

    window.setTimeout(loadAdminAssets, 0);
  });
}());
