<template>
  <!-- Desktop: обычный dropdown -->
  <div v-if="!isMobile" class="project-select" v-show="store.currentProject" @click.stop>
    <button class="project-btn" @click="dropdownOpen = !dropdownOpen">
      <i data-lucide="folder" class="folder-icon"></i>
      {{ store.currentProject?.name || 'Выберите проект' }}
      <i data-lucide="chevron-down" class="chevron" :class="{ open: dropdownOpen }"></i>
    </button>
    <div class="project-dropdown" v-if="dropdownOpen">
      <div 
        v-for="(project, index) in store.projects" 
        :key="project.id"
        class="project-option-wrapper"
        :class="{ 
          'is-dragging': dragIndex === index,
          'drag-over-top': dragOverIndex === index && dragPosition === 'top',
          'drag-over-bottom': dragOverIndex === index && dragPosition === 'bottom'
        }"
        draggable="true"
        @dragstart="handleDragStart($event, index)"
        @dragend="handleDragEnd"
        @dragover.prevent="handleDragOver($event, index)"
        @dragleave="handleDragLeave"
        @drop.prevent="handleDrop(index)"
      >
        <div class="project-drag-handle">
          <i data-lucide="grip-vertical"></i>
        </div>
        <button 
          class="project-option"
          :class="{ active: store.currentProjectId === project.id }"
          @click="handleSelect(project.id)"
        >
          {{ project.name }}
        </button>
        <button 
          v-if="project.is_admin"
          class="project-edit-btn"
          title="Настройки проекта"
          @click.stop="handleEdit(project)"
        >
          <i data-lucide="settings"></i>
        </button>
      </div>
    </div>
  </div>

  <!-- Mobile: полноэкранный селект -->
  <MobileSelect
    v-else
    v-model="mobileProjectId"
    :options="projectOptions"
    title="Выберите проект"
    placeholder="Проект"
    variant="accent"
    @update:model-value="handleMobileSelect"
  />
</template>

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

const store = useProjectsStore()
const { isMobile } = useMobile()
const dropdownOpen = ref(false)

const emit = defineEmits(['change', 'edit'])

// ==================== DRAG AND DROP ====================
const dragIndex = ref(null)
const dragOverIndex = ref(null)
const dragPosition = ref(null) // 'top' | 'bottom'

const handleDragStart = (e, index) => {
  dragIndex.value = index
  e.dataTransfer.effectAllowed = 'move'
  e.dataTransfer.setData('text/plain', index.toString())
}

const handleDragEnd = () => {
  dragIndex.value = null
  dragOverIndex.value = null
  dragPosition.value = null
}

const handleDragOver = (e, index) => {
  if (dragIndex.value === null || dragIndex.value === index) return
  
  const rect = e.currentTarget.getBoundingClientRect()
  const midY = rect.top + rect.height / 2
  
  dragOverIndex.value = index
  dragPosition.value = e.clientY < midY ? 'top' : 'bottom'
}

const handleDragLeave = () => {
  // Don't clear immediately to avoid flickering
}

const handleDrop = async (targetIndex) => {
  if (dragIndex.value === null || dragIndex.value === targetIndex) {
    handleDragEnd()
    return
  }
  
  const sourceIndex = dragIndex.value
  let insertIndex = targetIndex
  
  // Adjust insert index based on drag position
  if (dragPosition.value === 'bottom') {
    insertIndex = targetIndex + 1
  }
  
  // If moving down, adjust for removal
  if (sourceIndex < insertIndex) {
    insertIndex--
  }
  
  // Build new order array
  const projects = [...store.projects]
  const [movedProject] = projects.splice(sourceIndex, 1)
  projects.splice(insertIndex, 0, movedProject)
  
  // Get IDs in new order
  const ids = projects.map(p => p.id)
  
  // Update store
  await store.reorderProjects(ids)
  
  handleDragEnd()
  nextTick(refreshIcons)
}

// ==================== DESKTOP ====================
const handleSelect = async (projectId) => {
  dropdownOpen.value = false
  await store.selectProject(projectId)
  emit('change', projectId)
}

const handleEdit = (project) => {
  dropdownOpen.value = false
  emit('edit', project)
}

// Закрытие дропдауна при клике вне
const closeDropdown = (e) => {
  if (!e.target.closest('.project-select')) {
    dropdownOpen.value = false
  }
}

// ==================== MOBILE ====================
const mobileProjectId = ref(store.currentProjectId)

const projectOptions = computed(() =>
  store.projects.map(p => ({ id: p.id, label: p.name }))
)

// Синхронизируем с текущим проектом
watch(() => store.currentProjectId, (id) => {
  mobileProjectId.value = id
}, { immediate: true })

const handleMobileSelect = async (projectId) => {
  await store.selectProject(projectId)
  emit('change', projectId)
}

// ==================== LIFECYCLE ====================
const refreshIcons = () => {
  if (window.lucide) window.lucide.createIcons()
}

onMounted(() => {
  document.addEventListener('click', closeDropdown)
  refreshIcons()
})

onUnmounted(() => {
  document.removeEventListener('click', closeDropdown)
})

// Refresh icons when dropdown opens
watch(dropdownOpen, (open) => {
  if (open) nextTick(refreshIcons)
})
</script>

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

.project-btn {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 5px 11px;
  background: var(--accent-soft);
  border: 1px solid var(--accent);
  border-radius: 6px;
  color: var(--accent);
  font-family: inherit;
  font-size: 12px;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.3px;
  cursor: pointer;
  transition: all 0.15s;
}

.project-btn:hover {
  background: var(--accent);
  color: #000;
}

.project-btn .folder-icon {
  width: 12px;
  height: 12px;
  margin-right: 2px;
}

.project-btn .chevron {
  width: 10px;
  height: 10px;
  margin-left: 4px;
  opacity: 0.7;
  transition: transform 0.2s;
}

.project-btn .chevron.open {
  transform: rotate(180deg);
}

.project-dropdown {
  position: absolute;
  top: calc(100% + 6px);
  left: 0;
  min-width: 200px;
  background: var(--bg-secondary);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 10px;
  padding: 6px;
  z-index: 100;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.4);
}

.project-option {
  display: block;
  width: 100%;
  padding: 10px 12px;
  background: transparent;
  border: none;
  border-radius: 6px;
  color: var(--text-secondary);
  font-family: inherit;
  font-size: 13px;
  text-align: left;
  cursor: pointer;
  transition: all 0.15s;
}

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

.project-option.active {
  background: var(--accent-soft);
  color: var(--accent);
}

/* ==================== DRAG AND DROP ==================== */

.project-option-wrapper {
  display: flex;
  align-items: center;
  gap: 4px;
  border-radius: 6px;
  transition: all 0.15s;
}

.project-option-wrapper:hover {
  background: rgba(255, 255, 255, 0.03);
}

.project-option-wrapper.is-dragging {
  opacity: 0.5;
}

.project-option-wrapper.drag-over-top {
  border-top: 2px solid var(--accent);
}

.project-option-wrapper.drag-over-bottom {
  border-bottom: 2px solid var(--accent);
}

.project-drag-handle {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  color: var(--text-muted);
  cursor: grab;
  flex-shrink: 0;
  margin-left: 2px;
  opacity: 0.5;
  transition: opacity 0.15s;
}

.project-drag-handle:hover {
  opacity: 1;
}

.project-drag-handle:active {
  cursor: grabbing;
}

.project-drag-handle i {
  width: 12px;
  height: 12px;
}

.project-option-wrapper .project-option {
  flex: 1;
  min-width: 0;
  text-align: left;
}

.project-edit-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 26px;
  height: 26px;
  background: none;
  border: none;
  border-radius: 6px;
  color: var(--text-muted);
  cursor: pointer;
  transition: all 0.15s;
  flex-shrink: 0;
  margin-right: 2px;
  opacity: 0.5;
}

.project-edit-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: var(--text-primary);
  opacity: 1;
}

.project-edit-btn i {
  width: 13px;
  height: 13px;
}

</style>
