(() => {
  'use strict';

  /**
   * Page tab selection
   */
  const pageTriggers = document.querySelectorAll('.oroku-menu__link');
  const pageElements = document.querySelectorAll('.oroku-page');

  // console.log('Page elements: ', pageElements);

  if ((pageTriggers.length > 0) && (pageElements.length > 0)) {
    function selectElement(elements, selectedId, selector) {
      for (const element of elements) {
        const elementId = element.getAttribute('data-id');
        // console.log('Current element id: ', elementId);

        if (elementId === selectedId) {
          element.classList.add(selector);
        } else {
          element.classList.remove(selector);
        }
      }
    }

    function selectPage() {
      // console.log('Window hash: ', window.location.hash);

      let validIds = [];

      if (typeof orokublocksAdminConstants.submenuItems !== 'undefined') {
        validIds = Object.keys(orokublocksAdminConstants.submenuItems);
      }

      // console.log('Valid Ids: ', validIds);

      let selectedPageId = 'general';

      if (window.location.hash !== '') {
        const selectedPageIdRegex = /^#tab=(.*)$/igm;
        const selectedPageIdMatches = selectedPageIdRegex.exec(window.location.hash);

        // console.log('Selected page id matches: ', selectedPageIdMatches);

        if ((selectedPageIdMatches instanceof Array) && (selectedPageIdMatches.length > 1) && (validIds.includes(selectedPageIdMatches[1]))) {
          selectedPageId = selectedPageIdMatches[1];
        }
      }

      // console.log('Selected page id: ', selectedPageId);
      
      // activate trigger
      selectElement(pageTriggers, selectedPageId, 'oroku-menu__link--active');

      // display page
      selectElement(pageElements, selectedPageId, 'oroku-page--visible');
    }

    window.addEventListener('load', selectPage);
    window.addEventListener('popstate', selectPage);
  }
})();