import { html, TemplateResult } from 'lit'
import { property, state } from 'lit/decorators.js'
import { classMap } from 'lit/directives/class-map.js'
import { UiElement } from '../../../md/UiElement.js'

export default class NavigationItem extends UiElement {
  static override shadowRootOptions: ShadowRootInit = {
    mode: 'open',
    delegatesFocus: true,
  }

  /**
   * When set, the button is a disabled state.
   * @attribute
   */
  @property({ reflect: true, type: Boolean }) accessor disabled = false

  /**
   * Whether the navigation item is selected.
   * @attribute
   */
  @property({ reflect: true, type: Boolean }) accessor selected = false

  /**
   * Determines when the element has an icon in the "icon" slot.
   */
  @state() protected accessor hasIcon = false

  /**
   * Sets the `_hasIcon` state property when the "icon" slot change event is dispatched.
   */
  protected handleIconSlotChange(e: Event): void {
    const slot = e.target as HTMLSlotElement
    this.hasIcon = !!slot.assignedNodes().length
  }

  protected override render(): TemplateResult {
    const { pressed = false } = this
    const containerClasses = classMap({
      button: true,
      icon: this.hasIcon,
      pressed,
    })
    return html`
      <button class="${containerClasses}" id="button">
        <md-focus-ring part="focus-ring" for="button"></md-focus-ring>
        <md-ripple></md-ripple>
        ${this.renderIcon()}
        <slot></slot>
      </button>
    `
  }

  protected renderIcon(): TemplateResult {
    return html`<span role="presentation" class="icon"
      ><slot name="icon" @slotchange="${this.handleIconSlotChange}"></slot
    ></span>`
  }
}
