<script setup>
import { DateTimePicker } from 'tedir-calendar'

// tedir-calendar's DateTimePicker has no confirm/close button — its open state is
// internal and only the backdrop click closes it. The value is already committed
// live on every date/time click, so "OK" only needs to close the popup: we move
// our footer into the picker's .pickerContent (so it shows/hides with the
// dropdown) and close by triggering the picker's own backdrop click handler.
defineOptions({ inheritAttrs: false })

const props = defineProps({
  modelValue: { type: [String, Number, Date, Object], default: () => new Date() },
  confirmLabel: { type: String, default: 'OK' }
})
const emit = defineEmits(['update:modelValue', 'handler'])

const rootEl = ref(null)
const footerEl = ref(null)
const footerMoved = ref(false)

onMounted(() => {
  const content = rootEl.value?.querySelector('.pickerContent')
  if (content && footerEl.value) {
    content.appendChild(footerEl.value)
    footerMoved.value = true
  }
})

const closePicker = () => {
  rootEl.value?.querySelector('.pickerBackdrop')?.click()
}
</script>

<template>
  <div ref="rootEl" class="dtpConfirm">
    <DateTimePicker
      :model-value="props.modelValue"
      v-bind="$attrs"
      @update:model-value="(val) => emit('update:modelValue', val)"
      @handler="(val) => emit('handler', val)"
    />
    <div ref="footerEl" v-show="footerMoved" class="dtpConfirmFooter">
      <button type="button" class="button is-primary is-small" @click="closePicker">
        {{ props.confirmLabel }}
      </button>
    </div>
  </div>
</template>

<!-- Non-scoped on purpose: the footer is relocated into the picker's dropdown,
     outside this component's element tree (same gotcha as teleported elements). -->
<style>
.dtpConfirmFooter {
  padding: 0.4rem 0.5rem;
  border-top: 1px solid #d9d9d9;
  text-align: right;
}
.dark .dtpConfirmFooter,
[data-mode="dark"] .dtpConfirmFooter {
  border-top-color: #5f5f5f;
}
</style>
