(function () {
  'use strict';

  function toArray(collection) {
    return Array.prototype.slice.call(collection || []);
  }

  function isDisabled(control) {
    return control.getAttribute('aria-disabled') === 'true'
      || control.getAttribute('data-disabled') === '1'
      || control.classList.contains('is-disabled');
  }

  function setRovingFocus(controls, activeControl) {
    controls.forEach(function (control) {
      control.setAttribute('tabindex', control === activeControl && !isDisabled(control) ? '0' : '-1');
    });
  }

  function focusAdjacentControl(event, controls) {
    var enabled = controls.filter(function (control) {
      return !isDisabled(control) && control.offsetParent !== null;
    });
    if (!enabled.length) {
      return;
    }

    var currentIndex = enabled.indexOf(event.currentTarget);
    var targetIndex = currentIndex;
    if (event.key === 'ArrowRight' || event.key === 'ArrowDown') {
      targetIndex = (currentIndex + 1) % enabled.length;
    } else if (event.key === 'ArrowLeft' || event.key === 'ArrowUp') {
      targetIndex = (currentIndex - 1 + enabled.length) % enabled.length;
    } else if (event.key === 'Home') {
      targetIndex = 0;
    } else if (event.key === 'End') {
      targetIndex = enabled.length - 1;
    } else {
      return;
    }

    event.preventDefault();
    enabled[targetIndex].focus();
    enabled[targetIndex].click();
  }

  function enhanceSettingsNavigation() {
    var tabsRoot = document.getElementById('nexdirectory-settings-tabs');
    var subtabsRoot = document.getElementById('nexdirectory-settings-subtabs');
    var tabs = tabsRoot ? toArray(tabsRoot.querySelectorAll('[data-tab]')) : [];
    var subtabs = subtabsRoot
      ? toArray(subtabsRoot.querySelectorAll('[data-parent-tab][data-subtab]'))
      : [];
    var panels = toArray(document.querySelectorAll('.nexdirectory-settings-panel[data-tab][data-subtab]'));

    if (tabsRoot) {
      tabsRoot.setAttribute('role', 'tablist');
      tabsRoot.setAttribute('aria-label', 'Settings categories');
    }
    if (subtabsRoot) {
      subtabsRoot.setAttribute('role', 'tablist');
      subtabsRoot.setAttribute('aria-label', 'Settings sections');
    }

    tabs.forEach(function (tab, index) {
      if (!tab.id) {
        tab.id = 'nexdirectory-settings-category-' + (tab.getAttribute('data-tab') || index);
      }
      tab.setAttribute('role', 'tab');
      tab.addEventListener('keydown', function (event) {
        focusAdjacentControl(event, tabs);
      });
      if (isDisabled(tab)) {
        tab.addEventListener('click', function (event) {
          event.preventDefault();
        });
      }
    });

    subtabs.forEach(function (tab, index) {
      var parentKey = tab.getAttribute('data-parent-tab') || 'section';
      var childKey = tab.getAttribute('data-subtab') || String(index);
      var panelId = 'nexdirectory-tab-' + parentKey + '--' + childKey;
      if (!tab.id) {
        tab.id = 'nexdirectory-settings-section-' + parentKey + '-' + childKey;
      }
      tab.setAttribute('role', 'tab');
      tab.setAttribute('aria-controls', panelId);
      tab.addEventListener('keydown', function (event) {
        var visibleSubtabs = subtabs.filter(function (candidate) {
          return candidate.getAttribute('data-parent-tab') === parentKey;
        });
        focusAdjacentControl(event, visibleSubtabs);
      });
      if (isDisabled(tab)) {
        tab.addEventListener('click', function (event) {
          event.preventDefault();
        });
      }
    });

    panels.forEach(function (panel) {
      var parentKey = panel.getAttribute('data-tab') || '';
      var childKey = panel.getAttribute('data-subtab') || '';
      var label = document.querySelector(
        '#nexdirectory-settings-subtabs [data-parent-tab="' + parentKey + '"][data-subtab="' + childKey + '"]'
      );
      panel.setAttribute('role', 'tabpanel');
      if (label && label.id) {
        panel.setAttribute('aria-labelledby', label.id);
      }
    });

    function syncStates() {
      var activeTab = null;
      tabs.forEach(function (tab) {
        var active = tab.classList.contains('nav-tab-active');
        tab.setAttribute('aria-selected', active ? 'true' : 'false');
        if (active) {
          activeTab = tab;
        }
      });
      setRovingFocus(tabs, activeTab || tabs[0]);

      var groupedSubtabs = {};
      subtabs.forEach(function (tab) {
        var group = tab.getAttribute('data-parent-tab') || '';
        var active = tab.classList.contains('is-active');
        tab.setAttribute('aria-selected', active ? 'true' : 'false');
        groupedSubtabs[group] = groupedSubtabs[group] || { controls: [], active: null };
        groupedSubtabs[group].controls.push(tab);
        if (active) {
          groupedSubtabs[group].active = tab;
        }
      });
      Object.keys(groupedSubtabs).forEach(function (group) {
        var item = groupedSubtabs[group];
        setRovingFocus(item.controls, item.active || item.controls[0]);
      });

      panels.forEach(function (panel) {
        panel.setAttribute('aria-hidden', panel.classList.contains('is-active') ? 'false' : 'true');
      });
    }

    syncStates();
    var observer = new MutationObserver(syncStates);
    tabs.concat(subtabs).concat(panels).forEach(function (element) {
      observer.observe(element, { attributes: true, attributeFilter: ['class', 'hidden'] });
    });
  }

  function enhanceForms() {
    toArray(document.querySelectorAll('.nexdirectory-admin-premium form, .nexdirectory-settings-premium form')).forEach(function (form) {
      form.addEventListener('submit', function () {
        form.setAttribute('aria-busy', 'true');
        toArray(form.querySelectorAll('button[type="submit"], input[type="submit"]')).forEach(function (button) {
          button.classList.add('is-busy');
          button.setAttribute('aria-disabled', 'true');
        });
      });
    });
  }

  function enhanceDemoImportConfirmations() {
    toArray(document.querySelectorAll('[data-nexdirectory-demo-import-confirm-form]')).forEach(function (form) {
      if (form.getAttribute('data-confirmation-bound') === '1') {
        return;
      }
      form.setAttribute('data-confirmation-bound', '1');

      form.addEventListener('submit', function (event) {
        var confirmedInput;
        var message;

        if (form.getAttribute('data-confirmed-submit') === '1') {
          return;
        }

        event.preventDefault();
        confirmedInput = form.querySelector('[data-nexdirectory-demo-import-confirmed-input]');
        if (confirmedInput) {
          confirmedInput.value = '0';
        }

        message = form.getAttribute('data-confirm-message') || 'Import sample content into this site?';
        if (!window.confirm(message)) {
          return;
        }

        if (confirmedInput) {
          confirmedInput.value = '1';
        }
        form.setAttribute('data-confirmed-submit', '1');
        form.submit();
      });
    });
  }

  function enhanceExternalLinks() {
    toArray(document.querySelectorAll('.nexdirectory-admin-premium a[target="_blank"], .nexdirectory-settings-premium a[target="_blank"]')).forEach(function (link) {
      var values = (link.getAttribute('rel') || '').split(/\s+/).filter(Boolean);
      ['noopener', 'noreferrer'].forEach(function (value) {
        if (values.indexOf(value) === -1) {
          values.push(value);
        }
      });
      link.setAttribute('rel', values.join(' '));
    });
  }

  function boot() {
    document.body.classList.add('nexdirectory-admin-ui-ready');
    enhanceSettingsNavigation();
    enhanceForms();
    enhanceDemoImportConfirmations();
    enhanceExternalLinks();
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot, { once: true });
  } else {
    boot();
  }
}());
