/**
 * 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.skipLinkId = 'uoe-main-content'
    this.hasMenu = false

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

  _checkContent() {
    const element = this.shadowRoot ? this.shadowRoot.host : this
    if (!document.querySelector(`#${this.skipLinkId}`)) {
      let jumpTo = element.querySelector(':scope > :not([slot])')
      if (!jumpTo) {
        jumpTo = document.createElement('span')
        jumpTo.id = this.skipLinkId
        jumpTo.classList = 'visually-hidden'
        jumpTo.textContent = 'No main content available'
        element.append(jumpTo)
      } else if (jumpTo.id) {
        this.skipLinkId = jumpTo.id
      } else {
        jumpTo.id = this.skipLinkId
      }
    }

    this.hasMenu = Boolean(element.querySelector('[slot="menu"]'))
  }

  connectedCallback() {
    super.connectedCallback()

    this._checkContent()
    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="#${this.skipLinkId}" 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 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)
    }
  }
}
