function toggleFullscreen() {
  const flags = rootFlags(true);
  const id = location.href.match(/\?id=(.*)/i);
  if (flags.includes('isolated'))
    location.hash = location.hash.replace('#!/', '#/');
  else {
    let hash = `${location.hash}`;
    if (id) {
      const path = document.querySelector(`#${id[1]}`).textContent;
      hash = hash.replace(/(\?id=.*)/, `/${path}`);
      console.log(hash);
    }
    location.hash = hash.replace('#/', '#!/');
  }
}

function getParents(e) {
  const result = [];
  for (let p = e && e.parentElement; p; p = p.parentElement) {
    result.push(p);
  }
  return result;
}

function rootFlags(RETURN_FLAGS = false) {
  const $root = document.querySelector('html');
  const { hash, hostname } = window.location;
  const flags = [];

  if (hash === '#!/') flags.push('home');
  if (hostname === 'localhost') flags.push('local');
  if (hash.indexOf('#!') === 0) flags.push('isolated');

  if (RETURN_FLAGS) return flags;
  $root.setAttribute('flags', flags.join(' '))
}
rootFlags();

window.onload = function() {
  const $root = document.querySelector('html');
  const $nav = document.querySelector('[data-testid=sidebar] nav');

  const navScanner = function() {
    const $nav = document.querySelector('[data-testid=sidebar] nav');
    if (!$nav) return;
    
    const $priors = $nav.querySelectorAll('ul[open]');
    Array.from($priors).map(ul => {
      if (!ul.querySelectorAll('[class*=rsg--isSelected]').length) ul.removeAttribute('open');
      return true;
    });

    const $current = Array.from($nav.querySelectorAll('li[class*=rsg--isSelected]')).reverse()[0];
    if ($current) {
      const $parents = getParents($current).filter(e => e.nodeName === 'UL');
      const $subnav = $current.querySelector('ul');
      [...$parents, $subnav].map(nav => nav && nav.setAttribute('open', ''));
    }
  };

  const managePropsTab = function() {
    const $root = document.querySelector('html');
    const FLAGS = $root.getAttribute('flags').split(' ');
    if (FLAGS.includes('local') && FLAGS.includes('isolated')) {
      var $btn = $root.querySelectorAll('button[name=rsg-usage][class*=rsg--isActive-]');
      $btn.length && $btn.forEach($btn => $btn.click());
    }
  }

  managePropsTab();
  navScanner();

  document.addEventListener(
    'keypress',
    ({ key, code, altKey }) => (key === 'ƒ' || code === 'KeyF') && altKey && toggleFullscreen(),
    false
  );
 
  window.onhashchange = function () {
    rootFlags();
    navScanner();
    managePropsTab();
  }

  // sidebar links: right-click -> open isolated
  document.addEventListener('contextmenu', function (event) {
    const {target, altKey} = event;
    const match = 'a[href*="/#/"][class*="rsg--"]';
    const hrefs = [ 'Components', 'Compositions', 'Marketing', 'Quick%20Composer', 'Design%20System'];
    const bangx = altKey ? '#' : '#!';
  
    if (hrefs.map(h => target.matches(`${match}[href*="/${h}"]`)).includes(true)) {
      event.preventDefault();
      const isolated = [bangx, target.hash.split(/(?:#\/|\?)/)[1], target.text].join('/');
      window.location = isolated;
    }
  }, false);
  
  // props toggle: alt+click -> toggle all
  document.addEventListener('click', function (event) {
    const {target, altKey} = event;
    
    if (target.matches('button[name=rsg-usage]') && altKey) {
      let buttons;
      if (target.matches('[class*=rsg--isActive-]')) {
        console.log('is active');
        buttons = document.querySelectorAll('button[name=rsg-usage]:not([class*=rsg--isActive-])');
      }
      else {
        console.log('no active');
        buttons = document.querySelectorAll('button[name=rsg-usage][class*=rsg--isActive-]');
      }
      console.log(buttons);
      buttons.forEach(btn => btn.click());
    }
  }, false);

  if ($nav) {
    Array.from($nav.querySelectorAll('ul ul')).map(e => {
      e.classList.add('rsg--subnav');
      e.previousElementSibling.classList.add('rsg--subnav-link');
      return true;
    });
  
    const obsv = new MutationObserver(navScanner);
    obsv.observe($nav, {
      attributeFilter: ['class'],
      attributes: true,
      subtree: true,
    });
  }
  if (!rootFlags(true).includes('local'))
    document.querySelectorAll('[env="local"]').forEach(el => el.remove())
};
