class NavBar extends HTMLElement {
  #dockingTimeout

  connectedCallback() {
    document.addEventListener("scroll", this.onScroll.bind(this))
    this.addEventListener('transitionend', this.onTransitionEnd.bind(this))
    this.addEventListener('click', this.onClick.bind(this))
    document.addEventListener('click', this.onDocumentClick.bind(this))
    this.onScroll()
  }

  onScroll() {
    const scrollThreshold = parseInt(this.getAttribute('dock-logo-scroll-threshold'))
    const style = getComputedStyle(document.body)

    if(window.scrollY > scrollThreshold && !this.classList.contains("nav-bar__docked")) {
      this.classList.add("nav-bar__docking")
      this.classList.add("nav-bar__docked")
    }
    else if(window.scrollY <= scrollThreshold){
      this.classList.remove("nav-bar__docked")
    }
  }

  onTransitionEnd(evt) {
    if(evt.target.classList.contains('nav-bar--logo') && evt.propertyName == 'top') {
      this.classList.remove("nav-bar__docking")
    }
  }

  onClick(evt) {
    if(evt.target.matches('a')) {
      this.classList.remove('nav-bar__open')
    }
  }

  onDocumentClick(evt) {
    if(!this.contains(evt.target)) {
      this.classList.remove('nav-bar__open')
    }
  }
}

class ToggleNavBarButton extends HTMLElement {
  connectedCallback() {
    this.addEventListener('click', this.onClick.bind(this))
    const windowsChangeEvent = ('onorientationchange' in window) ? 'orientationchange':'resize';
    window.addEventListener(windowsChangeEvent, this.close.bind(this))
  }

  get navbar() {
    const navbar = this.closest('nav-bar')
    console.assert(navbar !== undefined)
    return navbar
  }

  onClick(evt) {
    this.navbar.classList.toggle('nav-bar__open')
    evt.preventDefault()
  }

  close() {
    this.navbar.classList.remove('nav-bar__open')
  }
}

window.customElements.define('nav-bar', NavBar)
window.customElements.define('toggle-nav-bar-button', ToggleNavBarButton)

