<script setup lang="ts">
import { nextTick, watch } from 'vue'
import Drawer from 'primevue/drawer'

const props=withDefaults(defineProps<{open:boolean;title:string;position?:'left'|'right';width?:string}>(),{position:'right',width:'560px'})
const emit=defineEmits<{ 'update:open':[boolean] }>()
let restoreTarget:HTMLElement|null=null

function captureRestoreTarget(){
  const active=document.activeElement
  restoreTarget=active instanceof HTMLElement&&active!==document.body?active:null
}
async function restoreFocus(){
  const target=restoreTarget
  restoreTarget=null
  if(!target||!target.isConnected||target.matches(':disabled,[aria-disabled="true"]'))return
  await nextTick()
  target.focus({preventScroll:true})
}
watch(()=>props.open,(open,previous)=>{if(open&&!previous)captureRestoreTarget()})
</script>

<template>
  <Drawer
    :visible="open"
    :header="title"
    :position="position"
    :style="{width}"
    data-kbx-component="drawer"
    @update:visible="emit('update:open',$event)"
    @hide="restoreFocus"
  >
    <slot/>
    <template #footer><slot name="footer"/></template>
  </Drawer>
</template>
