/**
 * EdGEL locator component.
 *
 * Style a breadcrumb optionally followed by a contact button.
 *
 * The menu object can optionally be passed as a JSON string as the innerText.  If not provided
 * window.EdGEL.menu will be used instead and this value will be set by an EdGEL menu custom
 * element on the page.
 */

import { html } from 'lit'
import { ifDefined } from 'lit/directives/if-defined.js'
import { EdGELMenu } from './menu.js'

export class EdGELLocator extends EdGELMenu {
  static properties = {
    contactLink: { type: String, attribute: 'contact-link' }
  }

  _validateMenu() {
    if (!this.menu || !this.menu.breadcrumb || !Array.isArray(this.menu.breadcrumb)) {
      this.menu = { breadcrumb: [] }
    }

    return true
  }

  connectedCallback() {
    super.connectedCallback()

    document.addEventListener('updated.edgel.menu', this._setMenuHtml)
  }

  disconnectedCallback() {
    super.disconnectedCallback()

    document.removeEventListener('updated.edgel.menu', this._setMenuHtml)
  }

  _processMenu() {
    this._breadcrumb = this.menu.breadcrumb.slice(0)
    if (this._breadcrumb.length) {
      this._breadcrumb.at(-1)._active = true
    }
  }

  _itemLink({ url, text, locked, _active }) {
    const classes = ['breadcrumb-item']

    if (_active) {
      classes.push('active')
    }

    const suffix = this._lockSuffix(locked)

    let item = html`${text} ${suffix}`

    if (!_active) {
      item = html`<a href=${url}>${item}</a>`
    }

    return html`
      <li class=${classes.join(' ')} aria-current=${ifDefined(_active ? 'page' : undefined)}>
        ${item}
      </li>
    `
  }

  _renderMenu() {
    // If there is no breadcrumb, there is nothing to render.
    if (!this._breadcrumb.length) {
      return null
    }

    const items = []
    for (const item of this._breadcrumb) {
      items.push(this._itemLink(item))
    }

    return html`<ol class="breadcrumb">${items}</ol>`
  }

  render() {
    this.collapseDisabled = true

    if (!this.menuHtml && !this.contactLink) {
      return
    }

    let breadcrumb = html`<div class="col"></div>`
    if (this.menuHtml) {
      breadcrumb = html`
        <div class="col">
          <nav aria-label="breadcrumb">
            ${this.menuHtml}
          </nav>
        </div>
      `
    }

    let contact = html``
    if (this.contactLink && this.contactLink.trim()) {
      contact = html`
        <div class="col-md-auto">
          <a href=${this.contactLink.trim()} class="btn btn-contact">
            Contact us
          </a>
        </div>
      `
    }

    return html`
      <div class="row">
        ${breadcrumb}
        ${contact}
      </div>
    `
  }
}
