/**
 * Kbd - Keyboard shortcut display component
 * @countermeasure/web-components/primitives/kbd
 */

import { resolveContainer } from '../utils'

export interface KbdConfig {
  container?: HTMLElement | string
  keys: string[]
  className?: string
}

export class Kbd {
  public readonly el: HTMLSpanElement

  constructor(config: KbdConfig) {
    // Create the wrapper element
    this.el = document.createElement('span')
    this.el.className = 'cmm-kbd'

    if (config.className) {
      this.el.classList.add(config.className)
    }

    // Build key elements
    this.buildKeys(config.keys)

    // Mount if container provided
    if (config.container !== undefined) {
      const parent = resolveContainer(config.container)
      parent.appendChild(this.el)
    }
  }

  /** Update displayed keys */
  setKeys(keys: string[]): void {
    this.el.innerHTML = ''
    this.buildKeys(keys)
  }

  /** Remove from the DOM */
  destroy(): void {
    this.el.remove()
  }

  private buildKeys(keys: string[]): void {
    keys.forEach((key, index) => {
      if (index > 0) {
        const separator = document.createElement('span')
        separator.className = 'cmm-kbd__separator'
        separator.textContent = '+'
        this.el.appendChild(separator)
      }

      const kbd = document.createElement('kbd')
      kbd.className = 'cmm-kbd__key'
      kbd.textContent = key
      this.el.appendChild(kbd)
    })
  }
}
