/**
 * EdGEL menu component.
 */

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

export class EdGELMenuFull extends EdGELMenu {
  _validateMenu() {
    if (!this.menu.tree) {
      throw new Error('No tree supplied in the menu object.')
    }

    if (!this.menu.tree.text || !this.menu.tree.url) {
      throw new Error('Invalid tree supplied in the menu object.')
    }

    return super._validateMenu()
  }

  _processMenu() {
    this._current = this.menu.breadcrumb.at(-1)
  }

  _renderMenu() {
    return this._nestedList([this.menu.tree])
  }

  _nestedList(items, depth = 0) {
    if (depth > 2) {
      throw new Error('Trees more than three levels deep (including root) are not currently supported in the design')
    }

    // Simplified test for whether items are styled as leaves in just a three-level deep menu
    const leaves = depth > 1
    const children = depth === 1
    let rendered = ''

    for (const item of items) {
      item._active = (item.url === this._current.url)
      item._joint = false

      // Process if there are no children to consider.
      item._renderedChildren = html``
      if (!item.children || !item.children.length) {
        item._collapsed = false
        item._expanded = false
      } else {
        item._collapsed = (!this.menu.breadcrumb.some(crumb => crumb.url === item.url))
        item._expanded = !item._collapsed
        if (item._expanded) {
          item._renderedChildren = this._nestedList(item.children, depth + 1)
        }

        // If there are children off the active item,
        // or one of the children is the active item and has no children,
        // this is a joint
        if (item._active) {
          item._joint = true
        } else if (item.children.some(c => c._active && (!c.children || !c.children.length))) {
          item._joint = true
        }
      }
    }

    for (const item of items) {
      item._classes = []
      if (depth === 0) {
        item._classes.push('uoe-nav-link-root')
      } else if (item._joint) {
        item._classes.push('uoe-nav-link-joint')
      } else if (leaves) {
        item._classes.push('uoe-nav-link-leaf')
      } else if (children) {
        item._classes.push('uoe-nav-link-child')
      }

      if (item._collapsed) {
        item._classes.push('uoe-nav-link-collapsed')
      } else if (item._expanded) {
        item._classes.push('uoe-nav-link-expanded')
      }

      rendered = html`
        ${rendered}
        <li>
          ${this._itemLink(item)}
          ${item._renderedChildren}
        </li>
      `
    }

    return html`<ul id=${ifDefined(depth ? undefined : this.controls)}>${rendered}</ul>`
  }
}
