import { pivotize } from '../src/textProcessing/pivotize.js'
import { RSVPComponent } from './rsvp-component.js'

class RSVPWord extends RSVPComponent {
  constructor() {
    super()
    const style = document.createElement('style')
    const word = document.createElement('div')
    const prefix = document.createElement('span')
    const pivot = document.createElement('span')
    const suffix = document.createElement('span')

    word.setAttribute('class', 'word')
    prefix.setAttribute('class', 'prefix')
    pivot.setAttribute('class', 'pivot')
    suffix.setAttribute('class', 'suffix')

    style.textContent =
      '.word{display:flex; font-size: 2.4em;}.pivot{color:red}.prefix{flex:1}.suffix{flex:1}.prefix{text-align:right}'

    word.appendChild(prefix)
    word.appendChild(pivot)
    word.appendChild(suffix)
    this._root.appendChild(style)
    this._root.appendChild(word)

    this.wordParts = { prefix, pivot, suffix }
  }

  update({ chapter }) {
    const [prefix, pivot, suffix] = pivotize(chapter.currentSegment)
    this.wordParts.prefix.innerText = prefix
    this.wordParts.pivot.innerText = pivot
    this.wordParts.suffix.innerText = suffix
  }

  static get observedAttributes() {
    return ['word']
  }

  attributeChangedCallback() {
    this.updateDisplay()
  }

  updateDisplay() {
    const [prefix, pivot, suffix] = pivotize(this.getAttribute('word') || '')
    this.wordParts.prefix.innerText = prefix
    this.wordParts.pivot.innerText = pivot
    this.wordParts.suffix.innerText = suffix
  }
}

window.customElements.define('rsvp-word', RSVPWord)
