var SideBarToggle = (function() {
  var STORAGE_TOGGLE_KEY = "scinote-sidebar-toggled";
  var WRAPPER = '#wrapper'
  var SIDEBAR_CONTAINER = ".sidebar-container"

  function show() {
    $(SIDEBAR_CONTAINER).removeClass('collapsed');
    $(WRAPPER).css('paddingLeft', 'var(--wrapper-width)');
    $('.navbar-secondary').removeClass("navbar-without-sidebar");
    sessionStorage.setItem(STORAGE_TOGGLE_KEY, "un-toggled");
    $(WRAPPER).trigger('sideBar::show');
    $(WRAPPER).one("transitionend", function() {
      $(WRAPPER).trigger('sideBar::shown');
    })
  }

  function hide() {
    $(SIDEBAR_CONTAINER).addClass('collapsed');
    $(WRAPPER).css('paddingLeft', '0');
    $('.navbar-secondary').addClass("navbar-without-sidebar");
    sessionStorage.setItem(STORAGE_TOGGLE_KEY, "toggled");
    $(WRAPPER).trigger('sideBar::hide');
    $(WRAPPER).one("transitionend", function() {
      $(WRAPPER).trigger('sideBar::hidden');
    })
  }

  function isToggledStorage() {
    var val = sessionStorage.getItem(STORAGE_TOGGLE_KEY);
    if (val === null) {
      return null;
    }
    return val === "toggled";
  }

  function init() {
    $(document).on('click', `${SIDEBAR_CONTAINER} .close-sidebar`, function() {
      hide();
    }).on('click', `${SIDEBAR_CONTAINER} .show-sidebar`, function() {
      show();
    }).on('turbolinks:load', function() {
      if (isToggledStorage()) {
        hide();
      } else {
        show();
      }
      $(WRAPPER).show();
    })
  }

  return Object.freeze({
    init: init,
    show: show,
    hide: hide,
    isToggledStorage: isToggledStorage
  })
}());

SideBarToggle.init();
