/**
 * EdGEL page masthead with search box.
 */

import { css, html } from 'lit'
import Collapse from 'bootstrap/js/src/collapse.js'
import { EdGELElement } from '../base.js'
import { dataUrl } from '../../images/uoe-logo.js'
import Search from '#plugins/search.js'

import '../../edgel-icon.js'

export class EdGELMasthead extends EdGELElement {
  static properties = {
    // Override the target for the UoE logo
    logoLink: { type: String, attribute: 'logo-link' },
    // Override the alt text for the UoE logo if changing its destination
    logoAlt: { type: String, attribute: 'logo-alt' },
    // Display the masthead search block
    hasSearch: { type: Boolean, attribute: 'has-search' },
    // Display a title in the masthead instead or search block
    heading: { type: String, attribute: 'heading' }
  }
  static styles = css`::slotted(*) {margin-bottom: 0 !important;}`

  constructor() {
    super()

    this.expanded = false
    this.targetId = 'uoe-search'
    this.logoLink = 'https://www.ed.ac.uk/'
    this.logoAlt = 'The University of Edinburgh home'
    this.hasSearch = false
    this.heading = ''
  }

  // Determine if change is enabling or disabling display of search block
  // Returns true if enabling, false if disabling, null if no effect
  _changeTogglesSearch(changes) {
    const oldHeading = changes.has('heading') ? changes.get('heading') : this.heading
    const oldHasSearch = changes.has('hasSearch') ? changes.get('hasSearch') : this.hasSearch
    const oldWithSearch = !oldHeading && oldHasSearch
    const newWithSearch = !this.heading && this.hasSearch

    if (newWithSearch && !oldWithSearch) {
      return true
    }

    if (!newWithSearch && oldWithSearch) {
      return false
    }
  }

  willUpdate(changedProperties) {
    super.willUpdate(changedProperties)

    if (this._changeTogglesSearch(changedProperties) === false && this.bsElement) {
      this.bsElement.dispose()
      this.searchElement.dispose()
    }
  }

  updated(changedProperties) {
    super.updated(changedProperties)

    if (this._changeTogglesSearch(changedProperties) === true) {
      const collapsible = this.shadowRoot.querySelector(`#${this.targetId}`)
      this.bsElement = Collapse.getOrCreateInstance(collapsible, { toggle: false })

      const searchInput = this.shadowRoot.querySelector('input')
      this.searchElement = Search.getOrCreateInstance(searchInput)
    }
  }

  disconnectedCallback() {
    super.disconnectedCallback()

    if (this.bsElement) {
      this.bsElement.dispose()
      this.searchElement.dispose()
    }
  }

  _toggle(e) {
    e.stopPropagation()

    this.expanded = !this.expanded
    if (this.expanded) {
      this.bsElement.show()
    } else {
      this.bsElement.hide()
    }
  }

  render() {
    const searchAction = globalThis.EdGEL?.Search?.Default?.action || 'https://search.ed.ac.uk/'
    const headingHtml = html`
      <p class="masthead-heading">${this.heading}</p>
    `

    const imgHtml = html`<img class="masthead-logo" src="${dataUrl}" alt=${this.logoAlt}>`

    const logoHtml = this.logoLink.trim() ? html`<a href=${this.logoLink.trim()}>${imgHtml}</a>` : imgHtml

    const searchHtml = html`
      <div class="edgel-js">
        <button
          class="btn btn-masthead-search-toggler"
          aria-expanded="false"
          aria-controls=${this.targetId}
          @click=${this._toggle}
        >
            <span class="visually-hidden">
              Show/hide site search
            </span>
        </button>

        <div class="masthead-text">
          <slot name="search-links">
            <ul class="list-inline">
              <li class="list-inline-item">
                <a href="https://www.ed.ac.uk/schools-departments/">Schools &amp; departments</a>
              </li>
              <li class="list-inline-item">
                <a href="https://www.myed.ed.ac.uk/">MyEd</a>
              </li>
            </ul>
          </slot>
        </div>

        <div role="search" id=${this.targetId} class="masthead-search collapse">
          <slot name="search-form">
            <form action=${searchAction} method="get">
              <div class="input-group input-group-lg">
                <input type="search" aria-label="Input your search term" placeholder="Search"
                       class="form-control" data-bs-items="4" name="q"
                       autoComplete="off" spellCheck="true" dir="auto"/>
                <button class="btn btn-search" type="submit">
                  <span class="visually-hidden">Submit search</span>
                </button>
              </div>
            </form>
          </slot>
        </div>
      </div>
    `

    const bannerHtml = this.heading ?
      headingHtml :
      (this.hasSearch ? searchHtml : html`<div class="text-end"><slot name="banner"><slot></div>`)

    return html`
      <header role="banner" class="masthead">
        <div class="container-masthead">
          <div class="row">
            <div class="col-md-7 col-lg-8">
              ${logoHtml}
            </div>
            <div class="col-md-5 col-lg-4">
              ${bannerHtml}
            </div>
          </div>
        </div>
        <slot></slot>
      </header>
    `
  }
}
