document.head.insertAdjacentHTML('beforeend','<style type="text/tailwindcss" component="ModalWindow">'+stylFns['app/shared/ModalWindow/index.styl']+'</style>')

module.exports =
  name: 'ModalWindow'
  render: (new Function '_ctx', '_cache', renderFns['app/shared/ModalWindow/index.pug'])()
  props:
    isVisible:
      type: Boolean
      default: false
    title:
      type: String
      default: ''
    content:
      type: String
      default: ''
    closeOnOverlay:
      type: Boolean
      default: true
    closeOnEsc:
      type: Boolean
      default: true
    showFooter:
      type: Boolean
      default: true
    contentClass:
      type: String
      default: ''

  data: ->
    titleId: "modal-title-#{Math.random().toString(36).substr(2, 9)}"

  watch:
    isVisible: (newVal) ->
      if newVal
        @showModal()
      else
        @hideModal()

  mounted: ->
    @setupEventListeners()

  beforeUnmount: ->
    @removeEventListeners()

  methods:
    showModal: ->
      document.body.style.overflow = 'hidden'
      document.addEventListener 'keydown', @handleKeydown

    hideModal: ->
      document.body.style.overflow = ''
      document.removeEventListener 'keydown', @handleKeydown

    setupEventListeners: ->
      @$watch 'isVisible', (newVal) ->
        if newVal then @showModal() else @hideModal()

    removeEventListeners: ->
      document.removeEventListener 'keydown', @handleKeydown

    closeModal: ->
      @$emit 'update:isVisible', false
      @$emit 'modal-closed'

    handleConfirm: ->
      @$emit 'modal-confirmed'
      @closeModal()

    handleKeydown: (event) ->
      if event.key == 'Escape' and @closeOnEsc
        @closeModal()
      if event.key == 'Tab'
        @trapFocus(event)

    trapFocus: (event) ->
      modal = @$el.querySelector('.modal-content')
      focusableElements = modal.querySelectorAll(
        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
      )
      firstElement = focusableElements[0]
      lastElement = focusableElements[focusableElements.length - 1]

      if event.shiftKey
        if document.activeElement == firstElement
          event.preventDefault()
          lastElement.focus()
      else
        if document.activeElement == lastElement
          event.preventDefault()
          firstElement.focus()

  emits: ['update:isVisible', 'modal-closed', 'modal-confirmed']
