<template>
  <div class="select-dropdown" ref="dropdownRef">
    <!-- Триггер -->
    <button class="dropdown-trigger" :class="{ mobile: isMobile }" @click="toggleDropdown" :disabled="disabled">
      <slot name="selected" :selected="selectedOption">
        <img 
          v-if="selectedOption?.avatar" 
          :src="selectedOption.avatar" 
          :alt="selectedOption.label" 
          class="option-avatar"
        >
        <span v-else-if="selectedOption?.label" class="avatar-placeholder">{{ selectedOption.label[0] }}</span>
        <span v-else-if="!selectedOption" class="no-selection-icon">—</span>
        <span class="selected-label">{{ selectedOption?.label || placeholder }}</span>
      </slot>
      <i data-lucide="chevron-down" class="dropdown-arrow"></i>
    </button>
    
    <!-- Desktop: выпадающий список -->
    <Transition v-if="!isMobile" name="dropdown">
      <div v-if="isOpen" class="dropdown-menu" :class="{ 'open-up': openUp }">
        <input 
          v-if="searchable"
          type="text" 
          v-model="searchQuery" 
          :placeholder="searchPlaceholder"
          class="dropdown-search"
          ref="searchInputRef"
          @click.stop
        >
        <div class="dropdown-list" ref="listRef">
          <!-- Опция "не выбрано" -->
          <button 
            v-if="allowEmpty"
            class="dropdown-item"
            :class="{ active: !modelValue }"
            @click="selectOption(null)"
          >
            <span class="no-selection-icon">—</span>
            <span>{{ emptyLabel }}</span>
          </button>
          
          <!-- Опции -->
          <button 
            v-for="option in filteredOptions" 
            :key="option.value"
            class="dropdown-item"
            :class="{ active: isActive(option.value) }"
            @click="selectOption(option.value)"
          >
            <slot name="option" :option="option">
              <img 
                v-if="option.avatar" 
                :src="option.avatar" 
                :alt="option.label" 
                class="option-avatar"
              >
              <span v-else class="avatar-placeholder">{{ (option.label || '?')[0] }}</span>
              <div class="option-content">
                <span class="option-label">{{ option.label }}</span>
                <a 
                  v-if="option.subtitle" 
                  class="option-subtitle" 
                  :href="'https://t.me/' + option.subtitle.replace('@', '')"
                  target="_blank"
                  @click.stop
                >
                  <i data-lucide="send"></i>
                  {{ option.subtitle.startsWith('@') ? option.subtitle : '@' + option.subtitle }}
                </a>
              </div>
            </slot>
          </button>
          
          <!-- Пустой результат поиска -->
          <div v-if="searchable && filteredOptions.length === 0" class="dropdown-empty">
            Ничего не найдено
          </div>
        </div>
      </div>
    </Transition>

    <!-- Mobile: fullscreen панель -->
    <Teleport to="body">
      <Transition name="mobile-select">
        <div v-if="isMobile && isOpen" class="mobile-select-overlay" @click.self="closeDropdown">
          <div 
            class="mobile-select-panel" 
            :class="{ dragging: isDragging }"
            :style="panelDragStyle"
            @click.stop
            ref="mobilePanelRef"
          >
            <div 
              class="mobile-select-handle"
              @touchstart="onDragStart"
              @touchmove="onDragMove"
              @touchend="onDragEnd"
            ></div>
            
            <div v-if="searchable" class="mobile-select-search" @click.stop>
              <i data-lucide="search"></i>
              <input 
                type="text" 
                v-model="searchQuery" 
                :placeholder="searchPlaceholder"
                ref="mobileSearchRef"
              >
            </div>
            
            <div class="mobile-select-list">
              <!-- Опция "не выбрано" -->
              <button 
                v-if="allowEmpty"
                class="mobile-select-item"
                :class="{ active: !modelValue }"
                @click="selectOption(null)"
              >
                <span class="no-selection-icon">—</span>
                <span class="item-label">{{ emptyLabel }}</span>
                <i v-if="!modelValue" data-lucide="check" class="check-icon"></i>
              </button>
              
              <!-- Опции -->
              <button 
                v-for="option in filteredOptions" 
                :key="option.value"
                class="mobile-select-item"
                :class="{ active: isActive(option.value) }"
                @click="selectOption(option.value)"
              >
              <img 
                v-if="option.avatar" 
                :src="option.avatar" 
                :alt="option.label" 
                class="option-avatar"
              >
              <span v-else class="avatar-placeholder">{{ (option.label || '?')[0] }}</span>
              <div class="option-content">
                  <span class="option-label">{{ option.label }}</span>
                  <a 
                    v-if="option.subtitle" 
                    class="option-subtitle" 
                    :href="'https://t.me/' + option.subtitle.replace('@', '')"
                    target="_blank"
                    @click.stop
                  >
                    <i data-lucide="send"></i>
                    {{ option.subtitle.startsWith('@') ? option.subtitle : '@' + option.subtitle }}
                  </a>
                </div>
                <i v-if="isActive(option.value)" data-lucide="check" class="check-icon"></i>
              </button>
              
              <!-- Пустой результат поиска -->
              <div v-if="searchable && filteredOptions.length === 0" class="mobile-select-empty">
                Ничего не найдено
              </div>
            </div>
          </div>
        </div>
      </Transition>
    </Teleport>
  </div>
</template>

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

const { isMobile } = useMobile()

const props = defineProps({
  modelValue: {
    type: [String, Number, null],
    default: null
  },
  options: {
    type: Array,
    default: () => []
    // Формат: [{ value: 1, label: 'Name', subtitle: '@telegram', avatar: 'url' }]
  },
  placeholder: {
    type: String,
    default: 'Выберите...'
  },
  searchable: {
    type: Boolean,
    default: false
  },
  searchPlaceholder: {
    type: String,
    default: 'Поиск...'
  },
  allowEmpty: {
    type: Boolean,
    default: true
  },
  emptyLabel: {
    type: String,
    default: 'Не выбрано'
  },
  disabled: {
    type: Boolean,
    default: false
  }
})

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

const dropdownRef = ref(null)
const searchInputRef = ref(null)
const mobileSearchRef = ref(null)
const mobilePanelRef = ref(null)
const listRef = ref(null)
const isOpen = ref(false)
const openUp = ref(false)
const searchQuery = ref('')

// Drag to dismiss
const isDragging = ref(false)
const dragStartY = ref(0)
const dragCurrentY = ref(0)
const panelHeight = ref(0)

const panelDragStyle = computed(() => {
  if (!isDragging.value) return {}
  const deltaY = dragCurrentY.value - dragStartY.value
  if (deltaY < 0) return {} // Не двигать вверх
  return {
    transform: `translateY(${deltaY}px)`,
    transition: 'none'
  }
})

const onDragStart = (e) => {
  isDragging.value = true
  dragStartY.value = e.touches[0].clientY
  dragCurrentY.value = e.touches[0].clientY
  if (mobilePanelRef.value) {
    panelHeight.value = mobilePanelRef.value.offsetHeight
  }
}

const onDragMove = (e) => {
  if (!isDragging.value) return
  dragCurrentY.value = e.touches[0].clientY
}

const onDragEnd = () => {
  if (!isDragging.value) return
  
  const deltaY = dragCurrentY.value - dragStartY.value
  const threshold = panelHeight.value * 0.3 // 30% от высоты панели
  
  if (deltaY > threshold) {
    // Закрыть панель
    closeDropdown()
  }
  
  isDragging.value = false
  dragStartY.value = 0
  dragCurrentY.value = 0
}

const closeDropdown = () => {
  isOpen.value = false
  searchQuery.value = ''
}

// Сравнение значений (приводим к числу для корректного сравнения)
const isActive = (optionValue) => {
  if (props.modelValue === null || props.modelValue === undefined) return false
  return Number(optionValue) === Number(props.modelValue)
}

// Выбранная опция
const selectedOption = computed(() => {
  if (props.modelValue === null || props.modelValue === undefined) return null
  return props.options.find(opt => isActive(opt.value))
})

// Отфильтрованные опции (исключаем disabled, они только для отображения выбранного)
const filteredOptions = computed(() => {
  let opts = props.options.filter(opt => !opt.disabled)
  if (!searchQuery.value.trim()) return opts
  const query = searchQuery.value.toLowerCase()
  return opts.filter(opt => 
    opt.label?.toLowerCase().includes(query) ||
    opt.subtitle?.toLowerCase().includes(query)
  )
})

// Прокрутка к активному элементу
const scrollToActive = () => {
  if (listRef.value && props.modelValue) {
    const activeItem = listRef.value.querySelector('.dropdown-item.active')
    if (activeItem) {
      activeItem.scrollIntoView({ block: 'center', behavior: 'instant' })
    }
  }
}

// Переключение dropdown
const toggleDropdown = async () => {
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    await nextTick()
    updatePosition()
    scrollToActive()
    searchInputRef.value?.focus()
    refreshIcons()
  }
}

// Выбор опции
const selectOption = (value) => {
  emit('update:modelValue', value)
  emit('change', value)
  isOpen.value = false
  searchQuery.value = ''
}

// Закрытие при клике вне (только для десктопа)
const handleClickOutside = (e) => {
  if (isMobile.value) return // На мобильных закрытие только по кнопке
  if (dropdownRef.value && !dropdownRef.value.contains(e.target)) {
    isOpen.value = false
    searchQuery.value = ''
  }
}

// Пересчёт позиции при изменении размера/скролле
const updatePosition = () => {
  if (isOpen.value && dropdownRef.value) {
    const rect = dropdownRef.value.getBoundingClientRect()
    const menuHeight = 300
    const footerOffset = 80 // отступ для футера панели с кнопками
    
    // Ищем родительский контейнер со скроллом (SlidePanel)
    const scrollParent = dropdownRef.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 < menuHeight
  }
}

// Обновление иконок
const refreshIcons = () => {
  if (window.lucide) {
    window.lucide.createIcons()
  }
}

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

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

onUpdated(refreshIcons)
</script>

<style scoped>
.select-dropdown {
  position: relative;
}

.dropdown-trigger {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  padding: 14px 16px;
  height: 48px;
  background: rgba(255, 255, 255, 0.04);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 8px;
  box-sizing: border-box;
  color: var(--text-primary);
  font-family: inherit;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.15s;
  text-align: left;
}

.dropdown-trigger:hover:not(:disabled) {
  border-color: rgba(255, 255, 255, 0.15);
  background: rgba(255, 255, 255, 0.06);
}

.dropdown-trigger:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.dropdown-arrow {
  width: 16px;
  height: 16px;
  margin-left: auto;
  color: var(--text-muted);
  flex-shrink: 0;
}

.dropdown-menu {
  position: absolute;
  top: calc(100% + 6px);
  left: 0;
  right: 0;
  background: #1f1f23;
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.4);
  z-index: 100;
  overflow: hidden;
}

.dropdown-menu.open-up {
  top: auto;
  bottom: calc(100% + 6px);
  box-shadow: 0 -10px 40px rgba(0, 0, 0, 0.4);
}

.dropdown-search {
  width: 100%;
  padding: 12px 14px;
  background: transparent;
  border: none;
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
  color: var(--text-primary);
  font-family: inherit;
  font-size: 14px;
  outline: none;
  box-sizing: border-box;
}

.dropdown-search::placeholder {
  color: var(--text-muted);
}

.dropdown-list {
  max-height: 240px;
  overflow-y: auto;
  padding: 6px;
}

.dropdown-list::-webkit-scrollbar {
  width: 6px;
}

.dropdown-list::-webkit-scrollbar-track {
  background: transparent;
}

.dropdown-list::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.15);
  border-radius: 3px;
}

.dropdown-item {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
  padding: 10px 12px;
  background: transparent;
  border: none;
  border-radius: 6px;
  color: var(--text-secondary);
  font-family: inherit;
  font-size: 13px;
  cursor: pointer;
  transition: all 0.1s;
  text-align: left;
}

.dropdown-item:hover {
  background: rgba(255, 255, 255, 0.06);
  color: var(--text-primary);
}

.dropdown-item.active {
  background: var(--accent);
  color: #000;
}

.option-avatar {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;
}

.avatar-placeholder {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
  color: var(--text-secondary);
  background: rgba(255, 255, 255, 0.1);
  text-transform: uppercase;
  flex-shrink: 0;
}

.dropdown-item.active .avatar-placeholder {
  background: rgba(0, 0, 0, 0.15);
  color: #000;
}

.option-content {
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
}

.option-label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.selected-label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.option-subtitle {
  font-size: 11px;
  color: var(--text-muted);
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 3px;
  transition: color 0.15s;
}

.option-subtitle:hover {
  color: var(--accent);
}

.option-subtitle :deep(svg) {
  width: 10px !important;
  height: 10px !important;
}

.dropdown-item.active .option-subtitle {
  color: rgba(0, 0, 0, 0.5);
}

.dropdown-item.active .option-subtitle:hover {
  color: rgba(0, 0, 0, 0.8);
}

.no-selection-icon {
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  font-size: 14px;
  flex-shrink: 0;
}

.dropdown-item.active .no-selection-icon {
  background: rgba(0, 0, 0, 0.15);
}

.dropdown-empty {
  padding: 16px;
  text-align: center;
  color: var(--text-muted);
  font-size: 13px;
}

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

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

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

/* ========== MOBILE: Fullscreen Select ========== */
.dropdown-trigger.mobile {
  height: 48px;
  font-size: 13px;
}

.mobile-select-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 2000;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  touch-action: none;
}

.mobile-select-panel {
  width: 100%;
  max-height: 80vh;
  background: #18181b;
  border-top-left-radius: 16px;
  border-top-right-radius: 16px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.mobile-select-handle {
  width: 100%;
  padding: 12px 0;
  display: flex;
  justify-content: center;
  flex-shrink: 0;
  cursor: grab;
  touch-action: none;
}

.mobile-select-handle::after {
  content: '';
  width: 36px;
  height: 4px;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 2px;
}

.mobile-select-panel.dragging .mobile-select-handle {
  cursor: grabbing;
}

.mobile-select-search {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 16px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.06);
  flex-shrink: 0;
}

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

.mobile-select-search input {
  flex: 1;
  background: none;
  border: none;
  color: var(--text-primary);
  font-family: inherit;
  font-size: 16px;
  outline: none;
}

.mobile-select-search input::placeholder {
  color: var(--text-muted);
}

.mobile-select-list {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
  -webkit-overflow-scrolling: touch;
}

.mobile-select-item {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
  padding: 14px 16px;
  background: none;
  border: none;
  color: var(--text-secondary);
  font-family: inherit;
  font-size: 16px;
  text-align: left;
  cursor: pointer;
  transition: all 0.15s;
}

.mobile-select-item:active {
  background: rgba(255, 255, 255, 0.06);
}

.mobile-select-item.active {
  color: var(--accent);
}

.mobile-select-item .option-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.mobile-select-item .avatar-placeholder {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  font-size: 16px;
}

.mobile-select-item .option-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 2px;
  min-width: 0;
}

.mobile-select-item .option-label {
  font-weight: 500;
}

.mobile-select-item .option-subtitle {
  font-size: 13px;
  color: var(--text-muted);
  text-decoration: none;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.mobile-select-item .option-subtitle :deep(svg) {
  width: 12px !important;
  height: 12px !important;
}

.mobile-select-item.active .option-subtitle {
  color: var(--accent);
  opacity: 0.7;
}

.mobile-select-item .no-selection-icon {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.08);
  border-radius: 10px;
  font-size: 16px;
  flex-shrink: 0;
}

.mobile-select-item .item-label {
  flex: 1;
}

.mobile-select-item .check-icon {
  width: 20px;
  height: 20px;
  color: var(--accent);
  flex-shrink: 0;
}

.mobile-select-empty {
  padding: 40px 16px;
  text-align: center;
  color: var(--text-muted);
  font-size: 15px;
}

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

.mobile-select-enter-active .mobile-select-panel,
.mobile-select-leave-active .mobile-select-panel {
  transition: transform 0.25s ease;
}

.mobile-select-enter-from,
.mobile-select-leave-to {
  opacity: 0;
}

.mobile-select-enter-from .mobile-select-panel,
.mobile-select-leave-to .mobile-select-panel {
  transform: translateY(100%);
}
</style>
