<template>
  <div class="modal is-active" @click="doClick">
  <div class="modal-background" :style="`opacity:${count===0? 0.7 : 0.3} !important;'`"></div>
  <div class="modal-card" :id="docid" :style="`width:${vWidth};`">
      <header class="modal-card-head my-0 py-2" v-if="title">
        <div style="width: 100%;">
        <div class="field is-grouped">
          <div class="control is-expanded has-text-left">
            <p class="fsb-18 has-text-dark" v-html="title"></p>
          </div>
          <div class="control has-text-right">
            <button class="delete is-medium" @click="closeModal()"></button>
          </div>
        </div>
        </div>
      </header>
      <section class="modal-card-body px-4 py-4" :style="`min-height:${height? height : '700px'}`">        
        <component :is="getComponent()" v-bind="props.vbind" @modalevent="modalEvent" @close="closeModal" />
      </section>
    </div>
  </div>
</template>
<script setup>
  import { onMounted, defineAsyncComponent } from 'vue'
  import { useStore } from '~/stores/index'
  const emit = defineEmits(['close', 'remove'])
  const store = useStore()
  const { $id } = useNuxtApp()
  var props = defineProps({
    component: String,
    width: String,
    height: String,
    vbind:  Object,
    title: String
  })
  function getComponent() {
    let arr = props.component.split('/')
    if(arr.length===2) {
      return defineAsyncComponent(() => import(`@/components/${arr[0]}/${arr[1]}.vue`))
    } else {
      return defineAsyncComponent(() => import(`@/components/${arr[0]}.vue`))
    }
  }
  const docid = $id()
  const viewport = store.viewport
  var title = props.title
  var count = 0
  var lock = false
  var vWidth = viewport<=2? '100%'  : props.width || '60%'
  const closeModal = function() {
    if(!lock) emit('close')
  }
  const modalEvent = function(ev) {
    emit(ev.name, ev.data)
  }
  const doClick = function(e) {
    //e.stopPropagation()
    if(!e.srcElement.offsetParent) return
    if(document.getElementById(docid)) {
      if(!document.getElementById(docid).contains(e.target)) {
        closeModal()
      }
    }
  }
  onMounted(()=> {
    window.addEventListener('keydown', (e) => {if(e.key==='Escape') closeModal()})
    const collection = document.getElementsByClassName("modal-background")
    count = collection.length
  })
</script>