<template>
  <div class="color-picker" ref="pickerRef">
    <!-- Триггер - текущий цвет -->
    <button 
      class="color-trigger"
      ref="triggerRef"
      :style="{ backgroundColor: modelValue }"
      @click="togglePicker"
      :title="'Выбрать цвет'"
    >
      <span class="color-check" v-if="modelValue">
        <i data-lucide="check"></i>
      </span>
    </button>
    
    <!-- Desktop: dropdown палитра (teleport чтобы не обрезалось) -->
    <Teleport to="body">
      <Transition v-if="!isMobile" name="dropdown">
        <div 
          v-if="isOpen" 
          class="color-dropdown" 
          ref="dropdownRef"
          :style="dropdownStyle"
        >
          <div class="color-grid">
            <button
              v-for="color in colors"
              :key="color"
              class="color-option"
              :class="{ selected: modelValue === color }"
              :style="{ backgroundColor: color }"
              @click="selectColor(color)"
            >
              <i v-if="modelValue === color" data-lucide="check"></i>
            </button>
          </div>
        </div>
      </Transition>
    </Teleport>

    <!-- Mobile: bottom sheet -->
    <Teleport to="body">
      <Transition name="mobile-picker">
        <div v-if="isMobile && isOpen" class="mobile-overlay" @click.self="closePicker">
          <div class="mobile-sheet">
            <div class="sheet-header">
              <span class="sheet-title">Выберите цвет</span>
              <button class="sheet-close" @click="closePicker">
                <i data-lucide="x"></i>
              </button>
            </div>
            
            <div class="sheet-body">
              <div class="color-grid mobile">
                <button
                  v-for="color in colors"
                  :key="color"
                  class="color-option"
                  :class="{ selected: modelValue === color }"
                  :style="{ backgroundColor: color }"
                  @click="selectColor(color)"
                >
                  <i v-if="modelValue === color" data-lucide="check"></i>
                </button>
              </div>
            </div>
          </div>
        </div>
      </Transition>
    </Teleport>
  </div>
</template>

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

const { isMobile } = useMobile()
const { refreshIcons } = useLucideIcons()

const props = defineProps({
  modelValue: {
    type: String,
    default: '#6366f1'
  }
})

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

// Предустановленные цвета
const colors = [
  // Основные
  '#ef4444', // red
  '#f97316', // orange
  '#f59e0b', // amber
  '#eab308', // yellow
  '#84cc16', // lime
  '#22c55e', // green
  '#10b981', // emerald
  '#14b8a6', // teal
  '#06b6d4', // cyan
  '#0ea5e9', // sky
  '#3b82f6', // blue
  '#6366f1', // indigo
  '#8b5cf6', // violet
  '#a855f7', // purple
  '#d946ef', // fuchsia
  '#ec4899', // pink
  '#f43f5e', // rose
  // Нейтральные
  '#64748b', // slate
  '#6b7280', // gray
  '#78716c', // stone
]

const pickerRef = ref(null)
const triggerRef = ref(null)
const dropdownRef = ref(null)
const isOpen = ref(false)
const dropdownPosition = ref({ top: 0, left: 0 })

// Вычисляем позицию dropdown относительно триггера
const updateDropdownPosition = () => {
  if (triggerRef.value) {
    const rect = triggerRef.value.getBoundingClientRect()
    const dropdownWidth = 220
    const dropdownHeight = 320
    
    // Левый край dropdown начинается от левого края триггера
    let top = rect.bottom + 8
    let left = rect.left
    
    // Проверяем не выходит ли за правый край
    if (left + dropdownWidth > window.innerWidth - 16) {
      left = window.innerWidth - dropdownWidth - 16
    }
    
    // Проверяем не выходит ли за нижний край — открываем вверх
    if (top + dropdownHeight > window.innerHeight - 16) {
      top = rect.top - dropdownHeight - 8
    }
    
    dropdownPosition.value = { top, left }
  }
}

const dropdownStyle = computed(() => ({
  position: 'fixed',
  top: `${dropdownPosition.value.top}px`,
  left: `${dropdownPosition.value.left}px`,
  zIndex: 2000
}))

const togglePicker = () => {
  isOpen.value = !isOpen.value
  if (isOpen.value) {
    updateDropdownPosition()
    nextTick(refreshIcons)
  }
}

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

const selectColor = (color) => {
  emit('update:modelValue', color)
  // Закрываем dropdown после выбора цвета из палитры
  closePicker()
  nextTick(refreshIcons)
}

const handleClickOutside = (e) => {
  // Проверяем что клик не на триггере и не на dropdown
  const isClickOnTrigger = pickerRef.value && pickerRef.value.contains(e.target)
  const isClickOnDropdown = dropdownRef.value && dropdownRef.value.contains(e.target)
  
  if (!isClickOnTrigger && !isClickOnDropdown) {
    isOpen.value = false
  }
}

// Обновляем позицию при скролле/ресайзе
watch(isOpen, (val) => {
  if (val && !isMobile.value) {
    window.addEventListener('scroll', updateDropdownPosition, true)
    window.addEventListener('resize', updateDropdownPosition)
  } else {
    window.removeEventListener('scroll', updateDropdownPosition, true)
    window.removeEventListener('resize', updateDropdownPosition)
  }
})

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

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
  window.removeEventListener('scroll', updateDropdownPosition, true)
  window.removeEventListener('resize', updateDropdownPosition)
})
</script>

<style scoped>
.color-picker {
  position: relative;
}

.color-trigger {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.15s;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.1);
}

.color-trigger:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.color-check {
  display: none;
}

/* ========== DROPDOWN (Desktop) ========== */
.color-dropdown {
  background: #1e1e24;
  border: 1px solid rgba(255, 255, 255, 0.12);
  border-radius: 12px;
  padding: 12px;
  box-shadow: 0 12px 32px rgba(0, 0, 0, 0.5);
  min-width: 220px;
}

.color-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 8px;
}

.color-option {
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.15s;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.1);
}

.color-option:hover {
  transform: scale(1.15);
  z-index: 1;
}

.color-option.selected {
  box-shadow: 0 0 0 2px var(--bg-body), 0 0 0 4px currentColor;
}

.color-option i {
  width: 16px;
  height: 16px;
  color: #fff;
  filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.5));
}

/* Кастомный цвет */
.custom-color {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid rgba(255, 255, 255, 0.08);
}

.custom-label {
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  color: var(--text-secondary);
  font-size: 13px;
}

.native-picker {
  width: 32px;
  height: 32px;
  padding: 0;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  background: transparent;
}

.native-picker::-webkit-color-swatch-wrapper {
  padding: 2px;
}

.native-picker::-webkit-color-swatch {
  border-radius: 6px;
  border: none;
}

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

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

/* ========== MOBILE: Bottom Sheet ========== */
.mobile-overlay {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
  z-index: 2000;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.mobile-sheet {
  width: 100%;
  max-height: 70vh;
  background: var(--bg-body);
  border-radius: 20px 20px 0 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.sheet-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
}

.sheet-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.sheet-close {
  width: 32px;
  height: 32px;
  background: rgba(255, 255, 255, 0.06);
  border: none;
  border-radius: 8px;
  color: var(--text-muted);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.sheet-close i {
  width: 18px;
  height: 18px;
}

.sheet-body {
  padding: 20px;
  padding-bottom: calc(20px + env(safe-area-inset-bottom, 0px));
  overflow-y: auto;
}

.color-grid.mobile {
  display: grid;
  grid-template-columns: repeat(5, 48px);
  gap: 10px;
  justify-content: center;
}

.color-grid.mobile .color-option {
  width: 48px;
  height: 48px;
  border-radius: 10px;
}

.color-grid.mobile .color-option i {
  width: 20px;
  height: 20px;
}

.custom-color.mobile {
  margin-top: 20px;
  padding-top: 20px;
}

.custom-color.mobile .custom-label {
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.04);
  border-radius: 12px;
  font-size: 15px;
}

.custom-preview {
  width: 28px;
  height: 28px;
  border-radius: 8px;
  box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.1);
}

.custom-color.mobile .native-picker {
  width: 40px;
  height: 40px;
  margin-left: auto;
}

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

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

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

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