/**
 * EdGEL page layout.
 */
import { html } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { EdGELElement } from '../base.js'

import '../../edgel-locator.js'

export class EdGELPage extends EdGELElement {
  static properties = {
    // Link for the "Contact us" button in the locator
    contactLink: { type: String, attribute: 'contact-link' },
    hasMenu: { type: Boolean, attribute: false }
  }

  constructor() {
    super()

    this.hasMenu = false

    this.observer = new MutationObserver(this._checkMenu.bind(this))
  }

  _checkMenu() {
    const element = this.shadowRoot ? this.shadowRoot.host : this
    this.hasMenu = Boolean(element.querySelector('[slot="menu"]'))
  }

  connectedCallback() {
    super.connectedCallback()

    this._checkMenu()
    this.observer.observe(this.shadowRoot.host, { childList: true, subtree: true })
  }

  disconnectedCallback() {
    super.disconnectedCallback()

    this.observer.disconnect()
  }

  render() {
    const menu = this.hasMenu ?
      html`<div class="col-md-3"><slot name="menu"></slot></div>` :
      html``

    return html`
      <div id="skip-link">
        <a href="#uoe-main-content" class="skip-link">Skip to main content</a>
      </div>
      <slot name="top-nav"></slot>
      <slot name="masthead"><edgel-masthead></edgel-masthead></slot>

      <div class="container-content">
        <div class="row">
          ${menu}
          <div class="col">
            <edgel-locator contact-link=${ifDefined(this.contactLink)}></edgel-locator>
            <main id="uoe-main-content" class="main-content">
              <slot></slot>
            </main>
          </div>
        </div>
      </div>

      <slot name="footer"></slot>
    `
  }

  updated() {
    if (document.body.classList.contains('preloader')) {
      const renderEvent = new CustomEvent('loaded.edgel.preloader', {
        bubbles: true,
        cancelable: false
      })
      this.dispatchEvent(renderEvent)
    }
  }
}
