<template>
  <div class="datepicker" :class="{ disabled: disabled }" ref="datepickerRef">
    <div class="datepicker-trigger" :class="{ mobile: isMobile, disabled: disabled }" @click="!disabled && toggleCalendar()">
      <i data-lucide="calendar"></i>
      <span v-if="modelValue" class="date-text">{{ formatCompactDate(modelValue) }}</span>
      <span v-else class="placeholder">Выберите дату</span>
      <button v-if="modelValue && !disabled" class="clear-btn" @click.stop="clearDate">
        <i data-lucide="x"></i>
      </button>
    </div>
    
    <!-- Desktop: dropdown calendar -->
    <Transition v-if="!isMobile" name="dropdown">
      <div v-if="isOpen" class="calendar" :class="{ 'open-up': openUp }" ref="calendarRef">
        <div class="calendar-header">
          <button class="nav-btn" @click="prevMonth">
            <i data-lucide="chevron-left"></i>
          </button>
          <span class="current-month">{{ monthNames[currentMonth] }} {{ currentYear }}</span>
          <button class="nav-btn" @click="nextMonth">
            <i data-lucide="chevron-right"></i>
          </button>
        </div>
        
        <div class="calendar-weekdays">
          <span v-for="day in weekdays" :key="day">{{ day }}</span>
        </div>
        
        <div class="calendar-days">
          <button
            v-for="day in calendarDays"
            :key="day.key"
            class="day"
            :class="{
              'other-month': !day.currentMonth,
              'today': day.isToday,
              'selected': day.isSelected
            }"
            @click="selectDate(day)"
          >
            {{ day.day }}
          </button>
        </div>
      </div>
    </Transition>

    <!-- Mobile: fullscreen overlay -->
    <Teleport to="body">
      <Transition name="mobile-calendar">
        <div v-if="isMobile && isOpen" class="mobile-calendar-overlay">
          <div class="mobile-calendar-panel">
            <div class="mobile-calendar-body">
              <div class="calendar-nav">
                <button class="nav-btn" @click="prevMonth">
                  <i data-lucide="chevron-left"></i>
                </button>
                <span class="current-month">{{ monthNames[currentMonth] }} {{ currentYear }}</span>
                <button class="nav-btn" @click="nextMonth">
                  <i data-lucide="chevron-right"></i>
                </button>
              </div>
              
              <div class="calendar-weekdays">
                <span v-for="day in weekdays" :key="day">{{ day }}</span>
              </div>
              
              <div class="calendar-days">
                <button
                  v-for="day in calendarDays"
                  :key="day.key"
                  class="day"
                  :class="{
                    'other-month': !day.currentMonth,
                    'today': day.isToday,
                    'selected': day.isSelected
                  }"
                  @click="selectDate(day)"
                >
                  {{ day.day }}
                </button>
              </div>
            </div>
            
            <div class="mobile-calendar-footer">
              <button class="btn-today" @click="selectToday">Сегодня</button>
              <button v-if="modelValue" class="btn-clear" @click="clearDate">Очистить</button>
              <button class="btn-close-footer" @click="closeCalendar">
                <i data-lucide="x"></i>
              </button>
            </div>
          </div>
        </div>
      </Transition>
    </Teleport>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { useMobile } from '../composables/useMobile'

const { isMobile } = useMobile()

const props = defineProps({
  modelValue: String,
  disabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue'])

const datepickerRef = ref(null)
const calendarRef = ref(null)
const isOpen = ref(false)
const openUp = ref(false)
const currentMonth = ref(new Date().getMonth())
const currentYear = ref(new Date().getFullYear())

const weekdays = ['Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб', 'Вс']
const monthNames = [
  'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
  'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'
]

const monthNamesShort = [
  'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь',
  'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'
]

const formatCompactDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const day = date.getDate()
  const monthShort = ['янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек']
  return `${day} ${monthShort[date.getMonth()]} ${date.getFullYear()}`
}

const formatDisplayDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  const day = date.getDate()
  const month = monthNames[date.getMonth()]
  const year = date.getFullYear()
  return `${day} ${month} ${year}`
}

const closeCalendar = () => {
  isOpen.value = false
}

const calendarDays = computed(() => {
  const days = []
  const firstDay = new Date(currentYear.value, currentMonth.value, 1)
  const lastDay = new Date(currentYear.value, currentMonth.value + 1, 0)
  
  // День недели первого числа (0 = воскресенье, переводим в понедельник = 0)
  let startDay = firstDay.getDay() - 1
  if (startDay < 0) startDay = 6
  
  // Дни предыдущего месяца
  const prevMonthLastDay = new Date(currentYear.value, currentMonth.value, 0).getDate()
  for (let i = startDay - 1; i >= 0; i--) {
    const day = prevMonthLastDay - i
    days.push({
      key: `prev-${day}`,
      day,
      currentMonth: false,
      date: new Date(currentYear.value, currentMonth.value - 1, day),
      isToday: false,
      isSelected: false
    })
  }
  
  // Дни текущего месяца
  const today = new Date()
  const selectedDate = props.modelValue ? new Date(props.modelValue) : null
  
  for (let day = 1; day <= lastDay.getDate(); day++) {
    const date = new Date(currentYear.value, currentMonth.value, day)
    const isToday = date.toDateString() === today.toDateString()
    const isSelected = selectedDate && date.toDateString() === selectedDate.toDateString()
    
    days.push({
      key: `curr-${day}`,
      day,
      currentMonth: true,
      date,
      isToday,
      isSelected
    })
  }
  
  // Дни следующего месяца (заполняем до 42 ячеек = 6 недель)
  const remaining = 42 - days.length
  for (let day = 1; day <= remaining; day++) {
    days.push({
      key: `next-${day}`,
      day,
      currentMonth: false,
      date: new Date(currentYear.value, currentMonth.value + 1, day),
      isToday: false,
      isSelected: false
    })
  }
  
  return days
})

const toggleCalendar = async () => {
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    // Устанавливаем текущий месяц на выбранную дату или сегодня
    if (props.modelValue) {
      const date = new Date(props.modelValue)
      currentMonth.value = date.getMonth()
      currentYear.value = date.getFullYear()
    } else {
      currentMonth.value = new Date().getMonth()
      currentYear.value = new Date().getFullYear()
    }
    
    await nextTick()
    updatePosition()
    
    if (window.lucide) window.lucide.createIcons()
  }
}

const prevMonth = () => {
  if (currentMonth.value === 0) {
    currentMonth.value = 11
    currentYear.value--
  } else {
    currentMonth.value--
  }
}

const nextMonth = () => {
  if (currentMonth.value === 11) {
    currentMonth.value = 0
    currentYear.value++
  } else {
    currentMonth.value++
  }
}

const selectDate = (day) => {
  const date = day.date
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const dayNum = String(date.getDate()).padStart(2, '0')
  emit('update:modelValue', `${year}-${month}-${dayNum}`)
  isOpen.value = false
}

const selectToday = () => {
  const today = new Date()
  const year = today.getFullYear()
  const month = String(today.getMonth() + 1).padStart(2, '0')
  const day = String(today.getDate()).padStart(2, '0')
  emit('update:modelValue', `${year}-${month}-${day}`)
  isOpen.value = false
}

const clearDate = () => {
  emit('update:modelValue', '')
}

const handleClickOutside = (e) => {
  if (datepickerRef.value && !datepickerRef.value.contains(e.target)) {
    isOpen.value = false
  }
}

// Пересчёт позиции при изменении размера/скролле
const updatePosition = () => {
  if (isOpen.value && datepickerRef.value) {
    const rect = datepickerRef.value.getBoundingClientRect()
    const calendarHeight = 350
    const footerOffset = 80 // отступ для футера панели с кнопками
    
    // Ищем родительский контейнер со скроллом (SlidePanel)
    const scrollParent = datepickerRef.value.closest('.panel-body')
    let availableBottom = window.innerHeight - footerOffset
    
    if (scrollParent) {
      const parentRect = scrollParent.getBoundingClientRect()
      availableBottom = parentRect.bottom
    }
    
    const spaceBelow = availableBottom - rect.bottom
    openUp.value = spaceBelow < calendarHeight
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
  window.addEventListener('resize', updatePosition)
  window.addEventListener('scroll', updatePosition, true)
  if (window.lucide) window.lucide.createIcons()
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  window.removeEventListener('resize', updatePosition)
  window.removeEventListener('scroll', updatePosition, true)
})

watch(isOpen, () => {
  nextTick(() => {
    if (window.lucide) window.lucide.createIcons()
  })
})
</script>

<style scoped>
.datepicker {
  position: relative;
}

.datepicker-trigger {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  padding: 0 14px;
  height: 48px;
  background: var(--bg-input);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 10px;
  color: var(--text-primary);
  font-size: 14px;
  cursor: pointer;
  transition: all 0.15s;
}

.datepicker-trigger:hover {
  border-color: rgba(255, 255, 255, 0.15);
}

.datepicker-trigger.disabled {
  cursor: default;
  opacity: 0.7;
}

.datepicker-trigger.disabled:hover {
  border-color: rgba(255, 255, 255, 0.08);
}

.datepicker-trigger i {
  width: 18px;
  height: 18px;
  color: var(--text-muted);
  flex-shrink: 0;
}

.datepicker-trigger .placeholder {
  color: var(--text-muted);
}

.clear-btn {
  margin-left: auto;
  background: none;
  border: none;
  padding: 4px;
  cursor: pointer;
  color: var(--text-muted);
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.15s;
}

.clear-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: var(--text-primary);
}

.clear-btn i {
  width: 14px;
  height: 14px;
}

.calendar {
  position: absolute;
  top: calc(100% + 8px);
  left: 0;
  right: 0;
  background: #1e1e24;
  border: 1px solid rgba(255, 255, 255, 0.12);
  border-radius: 12px;
  padding: 16px;
  z-index: 1000;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.5);
}

.calendar.open-up {
  top: auto;
  bottom: calc(100% + 8px);
  box-shadow: 0 -12px 32px rgba(0, 0, 0, 0.5);
}

.calendar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.current-month {
  font-size: 15px;
  font-weight: 600;
  color: var(--text-primary);
}

.nav-btn {
  background: none;
  border: none;
  padding: 6px;
  cursor: pointer;
  color: var(--text-muted);
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.15s;
}

.nav-btn:hover {
  background: rgba(255, 255, 255, 0.08);
  color: var(--text-primary);
}

.nav-btn i {
  width: 18px;
  height: 18px;
}

.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
  margin-bottom: 8px;
}

.calendar-weekdays span {
  text-align: center;
  font-size: 11px;
  font-weight: 600;
  color: var(--text-muted);
  text-transform: uppercase;
  padding: 4px;
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
}

.day {
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: none;
  border: none;
  border-radius: 8px;
  font-size: 13px;
  color: var(--text-primary);
  cursor: pointer;
  transition: all 0.15s;
}

.day:hover {
  background: rgba(255, 255, 255, 0.08);
}

.day.other-month {
  color: var(--text-muted);
  opacity: 0.4;
}

.day.today {
  border: 1px solid var(--accent);
  color: var(--accent);
}

.day.selected {
  background: var(--accent);
  color: #000;
  font-weight: 600;
}

.day.selected:hover {
  background: #00e6b8;
}


/* Transition */
.dropdown-enter-active,
.dropdown-leave-active {
  transition: all 0.15s ease;
}

.dropdown-enter-from,
.dropdown-leave-to {
  opacity: 0;
  transform: translateY(-8px);
}

.calendar.open-up.dropdown-enter-from,
.calendar.open-up.dropdown-leave-to {
  transform: translateY(8px);
}

/* ========== MOBILE: Компактный триггер ========== */
.datepicker-trigger.mobile {
  padding: 0 12px;
  height: 48px;
  font-size: 13px;
}

.datepicker-trigger.mobile i:first-child {
  width: 16px;
  height: 16px;
}

.date-text {
  flex: 1;
}

/* ========== MOBILE: Fullscreen Calendar ========== */
.mobile-calendar-overlay {
  position: fixed;
  inset: 0;
  background: var(--bg-body);
  z-index: 2000;
  display: flex;
  flex-direction: column;
  touch-action: none;
}

.mobile-calendar-panel {
  width: 100%;
  height: 100%;
  background: var(--bg-body);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.mobile-calendar-body {
  flex: 1;
  padding: 20px 16px;
  /* Safe area для iPhone notch */
  padding-top: calc(20px + env(safe-area-inset-top, 0px));
  display: flex;
  flex-direction: column;
}

.calendar-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}

.calendar-nav .current-month {
  font-size: 18px;
  font-weight: 600;
}

.calendar-nav .nav-btn {
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.06);
  border-radius: 10px;
}

.calendar-nav .nav-btn i {
  width: 20px;
  height: 20px;
}

.mobile-calendar-body .calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 4px;
  margin-bottom: 8px;
}

.mobile-calendar-body .calendar-weekdays span {
  text-align: center;
  font-size: 12px;
  font-weight: 600;
  color: var(--text-muted);
  text-transform: uppercase;
  padding: 8px;
}

.mobile-calendar-body .calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 6px;
}

.mobile-calendar-body .day {
  aspect-ratio: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  background: none;
  border: none;
  border-radius: 10px;
  font-size: 15px;
  color: var(--text-primary);
  cursor: pointer;
  transition: all 0.15s;
}

.mobile-calendar-body .day:active {
  background: rgba(255, 255, 255, 0.1);
}

.mobile-calendar-body .day.other-month {
  color: var(--text-muted);
  opacity: 0.4;
}

.mobile-calendar-body .day.today {
  border: 2px solid var(--accent);
  color: var(--accent);
}

.mobile-calendar-body .day.selected {
  background: var(--accent);
  color: #000;
  font-weight: 600;
}

.mobile-calendar-footer {
  display: flex;
  gap: 12px;
  padding: 16px;
  padding-bottom: calc(16px + var(--safe-area-bottom, 0px));
  border-top: 1px solid rgba(255, 255, 255, 0.06);
  margin-top: auto;
}

.btn-today {
  flex: 1;
  padding: 14px;
  background: var(--accent);
  border: none;
  border-radius: 10px;
  color: #000;
  font-family: inherit;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.15s;
}

.btn-today:active {
  filter: brightness(0.9);
}

.btn-clear {
  padding: 14px 20px;
  background: rgba(255, 255, 255, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  color: var(--text-secondary);
  font-family: inherit;
  font-size: 15px;
  cursor: pointer;
  transition: all 0.15s;
}

.btn-clear:active {
  background: rgba(255, 255, 255, 0.1);
}

.btn-close-footer {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.06);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  color: var(--text-secondary);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.15s;
  flex-shrink: 0;
}

.btn-close-footer i {
  width: 20px;
  height: 20px;
}

.btn-close-footer:active {
  background: rgba(255, 255, 255, 0.1);
}

/* Mobile calendar transition */
.mobile-calendar-enter-active,
.mobile-calendar-leave-active {
  transition: opacity 0.2s ease;
}

.mobile-calendar-enter-from,
.mobile-calendar-leave-to {
  opacity: 0;
}
</style>
