<script setup>
/**
 * BottomSheet - Panel inferior modal para móviles
 * Similar a Google Maps, Apple Music, etc.
 */
import { ref, watch, computed, onMounted, onUnmounted } from 'vue';

const props = defineProps({
    modelValue: {
        type: Boolean,
        default: false,
    },
    title: {
        type: String,
        default: '',
    },
    snapPoints: {
        type: Array,
        default: () => [0.3, 0.6, 0.9], // Porcentajes de altura
    },
    initialSnap: {
        type: Number,
        default: 0, // Índice del snap point inicial
    },
    closeOnOverlay: {
        type: Boolean,
        default: true,
    },
    draggable: {
        type: Boolean,
        default: true,
    },
});

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

const sheetRef = ref(null);
const currentSnapIndex = ref(props.initialSnap);
const isDragging = ref(false);
const startY = ref(0);
const currentHeight = ref(0);

const maxHeight = computed(() => window.innerHeight * 0.95);

const heightPercent = computed(() => {
    return props.snapPoints[currentSnapIndex.value] || 0.5;
});

const sheetHeight = computed(() => {
    if (isDragging.value) {
        return currentHeight.value;
    }
    return maxHeight.value * heightPercent.value;
});

const close = () => {
    emit('update:modelValue', false);
};

const snapTo = (index) => {
    if (index >= 0 && index < props.snapPoints.length) {
        currentSnapIndex.value = index;
        emit('snap-change', index);
    }
};

// Touch handlers
const handleTouchStart = (e) => {
    if (!props.draggable) return;
    isDragging.value = true;
    startY.value = e.touches[0].clientY;
    currentHeight.value = sheetHeight.value;
};

const handleTouchMove = (e) => {
    if (!isDragging.value) return;
    
    const diff = startY.value - e.touches[0].clientY;
    const newHeight = currentHeight.value + diff;
    
    // Limitar altura
    currentHeight.value = Math.max(100, Math.min(maxHeight.value, newHeight));
    startY.value = e.touches[0].clientY;
};

const handleTouchEnd = () => {
    if (!isDragging.value) return;
    isDragging.value = false;
    
    // Encontrar el snap point más cercano
    const currentPercent = currentHeight.value / maxHeight.value;
    
    // Si está muy abajo, cerrar
    if (currentPercent < 0.15) {
        close();
        return;
    }
    
    // Encontrar el snap más cercano
    let closestIndex = 0;
    let closestDiff = Math.abs(props.snapPoints[0] - currentPercent);
    
    props.snapPoints.forEach((snap, index) => {
        const diff = Math.abs(snap - currentPercent);
        if (diff < closestDiff) {
            closestDiff = diff;
            closestIndex = index;
        }
    });
    
    snapTo(closestIndex);
};

// Prevenir scroll del body
watch(() => props.modelValue, (isOpen) => {
    if (isOpen) {
        document.body.style.overflow = 'hidden';
        currentSnapIndex.value = props.initialSnap;
    } else {
        document.body.style.overflow = '';
    }
});

// Cerrar con Escape
const handleKeydown = (e) => {
    if (e.key === 'Escape' && props.modelValue) {
        close();
    }
};

onMounted(() => {
    document.addEventListener('keydown', handleKeydown);
});

onUnmounted(() => {
    document.removeEventListener('keydown', handleKeydown);
    document.body.style.overflow = '';
});
</script>

<template>
    <Teleport to="body">
        <!-- Overlay -->
        <Transition
            enter-active-class="transition-opacity duration-300"
            enter-from-class="opacity-0"
            enter-to-class="opacity-100"
            leave-active-class="transition-opacity duration-300"
            leave-from-class="opacity-100"
            leave-to-class="opacity-0"
        >
            <div 
                v-if="modelValue"
                class="fixed inset-0 bg-black/50 z-40"
                @click="closeOnOverlay && close()"
            />
        </Transition>
        
        <!-- Bottom Sheet -->
        <Transition
            enter-active-class="transition-transform duration-300 ease-out"
            enter-from-class="translate-y-full"
            enter-to-class="translate-y-0"
            leave-active-class="transition-transform duration-300 ease-in"
            leave-from-class="translate-y-0"
            leave-to-class="translate-y-full"
        >
            <div
                v-if="modelValue"
                ref="sheetRef"
                class="fixed bottom-0 left-0 right-0 bg-white dark:bg-gray-900 rounded-t-3xl shadow-xl z-50 flex flex-col safe-area-bottom"
                :class="{ 'transition-all duration-300 ease-out': !isDragging }"
                :style="{ height: `${sheetHeight}px`, maxHeight: `${maxHeight}px` }"
            >
                <!-- Handle -->
                <div 
                    class="flex-shrink-0 pt-3 pb-2 cursor-grab active:cursor-grabbing"
                    @touchstart="handleTouchStart"
                    @touchmove="handleTouchMove"
                    @touchend="handleTouchEnd"
                >
                    <div class="w-10 h-1 mx-auto bg-gray-300 dark:bg-gray-600 rounded-full" />
                </div>
                
                <!-- Header -->
                <div 
                    v-if="title || $slots.header"
                    class="flex-shrink-0 px-4 pb-3 border-b border-gray-200 dark:border-gray-700"
                >
                    <slot name="header">
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white text-center">
                            {{ title }}
                        </h3>
                    </slot>
                </div>
                
                <!-- Content -->
                <div class="flex-1 overflow-y-auto overscroll-contain px-4 py-4">
                    <slot />
                </div>
                
                <!-- Footer -->
                <div 
                    v-if="$slots.footer"
                    class="flex-shrink-0 px-4 py-3 border-t border-gray-200 dark:border-gray-700"
                >
                    <slot name="footer" />
                </div>
            </div>
        </Transition>
    </Teleport>
</template>
