<template>
  <div class="date-input-wrapper">
    <button type="button" class="date-display-btn" @click="openPicker">
      {{ displayLabel }}
    </button>
    <input
      ref="pickerRef"
      class="date-input-hidden"
      type="date"
      :value="modelValue"
      :min="min"
      @change="onChanged"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'

const props = defineProps<{
  modelValue: string
  min?: string
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void
}>()

const pickerRef = ref<HTMLInputElement | null>(null)

const displayLabel = computed(() => {
  if (!props.modelValue) return 'Select date'
  const [y, m, d] = props.modelValue.split('-').map(Number)
  const date = new Date(y, m - 1, d)
  if (isNaN(date.getTime())) return props.modelValue
  return date.toLocaleDateString('en-US', {
    weekday: 'short',
    month: 'short',
    day: 'numeric',
    year: 'numeric',
  })
})

function openPicker() {
  if (pickerRef.value) {
    if (typeof pickerRef.value.showPicker === 'function') {
      pickerRef.value.showPicker()
    } else {
      pickerRef.value.click()
    }
  }
}

function onChanged(event: Event) {
  emit('update:modelValue', (event.target as HTMLInputElement).value)
}
</script>

<style scoped>
.date-input-wrapper {
  position: relative;
  display: inline-flex;
}

.date-display-btn {
  padding: 0.4rem 0.6rem;
  border: 1.5px solid var(--kebab-menu-border, #bcc1c9);
  border-radius: 6px;
  background: var(--modal-bg, #fff);
  color: var(--secondary, #7257b3);
  font-size: 0.95rem;
  font-weight: 600;
  font-family: inherit;
  cursor: pointer;
  outline: none;
  transition: border-color 0.15s;
  white-space: nowrap;
}

.date-display-btn:hover,
.date-display-btn:focus {
  border-color: var(--btn-primary, #667eea);
}

.date-input-hidden {
  position: absolute;
  inset: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  pointer-events: none;
  cursor: pointer;
}
</style>
