<template>
  <dialog
    ref="modalRef"
    class="modal"
    aria-modal="true"
    :aria-labelledby="titleId"
    @cancel="$emit('close')"
    @close="onDialogClose"
  >
    <div class="modal-box transition-all duration-200" @click.stop>
      <h3 :id="titleId" class="font-bold text-lg">{{ title }}</h3>
      <div class="py-2">
        <label class="label py-0"><span>Name</span></label>
        <input
          ref="inputRef"
          v-model="localName"
          type="text"
          class="input input-bordered w-full"
          placeholder="Bookmark name"
          @keydown.enter.prevent="onSubmit"
        />
      </div>
      <div class="modal-action">
        <form method="dialog" @submit.prevent="onSubmit">
          <button type="submit" class="btn btn-primary">Save</button>
          <button type="button" class="btn" @click="$emit('close')">Cancel</button>
        </form>
      </div>
    </div>
    <div class="modal-backdrop cursor-pointer" aria-label="Close" @click="$emit('close')" />
  </dialog>
</template>

<script setup lang="ts">
const props = withDefaults(
  defineProps<{
    open: boolean
    defaultName: string
    title?: string
  }>(),
  { title: 'Add bookmark' }
)

const emit = defineEmits<{
  close: []
  submit: [name: string]
}>()

const titleId = computed(() => `bookmark-modal-title-${Math.random().toString(36).slice(2)}`)
const modalRef = ref<HTMLDialogElement | null>(null)
const inputRef = ref<HTMLInputElement | null>(null)
const localName = ref(props.defaultName)
let previousActiveElement: HTMLElement | null = null

watch(
  () => props.open,
  (open) => {
    if (open) {
      previousActiveElement = (import.meta.client ? document.activeElement : null) as HTMLElement | null
      localName.value = props.defaultName || ''
      nextTick(() => {
        modalRef.value?.showModal()
        inputRef.value?.focus()
      })
    } else {
      modalRef.value?.close()
    }
  },
  { immediate: true }
)

function onDialogClose() {
  if (import.meta.client && previousActiveElement && typeof previousActiveElement.focus === 'function' && document.contains(previousActiveElement)) {
    nextTick(() => previousActiveElement?.focus())
  }
}

watch(
  () => props.defaultName,
  (name) => {
    if (props.open) localName.value = name || ''
  }
)

function onSubmit() {
  const name = localName.value.trim() || props.defaultName || 'Bookmark'
  emit('submit', name)
  emit('close')
}
</script>
