<template>
    <div class="min-h-screen bg-black/95 flex items-center justify-center">
        <!-- Layout estilo Instagram Modal: Imagen izquierda + Sidebar derecha -->
        <div class="w-full h-screen max-w-7xl mx-auto flex flex-col lg:flex-row">
            <!-- Columna izquierda: Foto con slider -->
            <div class="flex-1 lg:max-w-[65%] bg-black flex items-center justify-center p-4 lg:p-8 relative">
                <!-- Slider si tiene ANTES y DESPUÉS -->
                <div v-if="photo.after_image_path" class="relative w-full h-full flex items-center justify-center">
                    <!-- Imagen ANTES -->
                    <div 
                        :class="['absolute inset-0 flex items-center justify-center transition-opacity duration-500', currentSlide === 1 ? 'opacity-0' : 'opacity-100']"
                    >
                        <img 
                            :src="photo.image_path" 
                            alt="Foto ANTES"
                            class="max-w-full max-h-[85vh] object-contain rounded-lg shadow-2xl"
                        />
                        <div class="absolute top-4 left-4 bg-gradient-to-r from-red-500 to-pink-500 text-white px-6 py-3 rounded-full font-bold text-sm shadow-2xl">
                            📉 ANTES
                        </div>
                    </div>
                    
                    <!-- Imagen DESPUÉS -->
                    <div 
                        :class="['absolute inset-0 flex items-center justify-center transition-opacity duration-500', currentSlide === 1 ? 'opacity-100' : 'opacity-0']"
                    >
                        <img 
                            :src="photo.after_image_path" 
                            alt="Foto DESPUÉS"
                            class="max-w-full max-h-[85vh] object-contain rounded-lg shadow-2xl"
                        />
                        <div class="absolute top-4 left-4 bg-gradient-to-r from-emerald-500 to-green-500 text-white px-6 py-3 rounded-full font-bold text-sm shadow-2xl">
                            📈 DESPUÉS
                        </div>
                    </div>
                    
                    <!-- Indicadores -->
                    <div class="absolute top-4 left-1/2 transform -translate-x-1/2 flex gap-2 z-10">
                        <button
                            v-for="i in 2"
                            :key="i"
                            @click="currentSlide = i - 1"
                            :class="[
                                'w-16 h-1.5 rounded-full transition-all',
                                currentSlide === (i - 1) ? 'bg-white' : 'bg-white/40'
                            ]"
                        ></button>
                    </div>
                    
                    <!-- Botones navegación -->
                    <button
                        @click="currentSlide = 0"
                        class="absolute left-4 top-1/2 -translate-y-1/2 bg-white/10 backdrop-blur-sm hover:bg-white/20 text-white p-3 rounded-full transition-all z-20"
                    >
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
                        </svg>
                    </button>
                    <button
                        @click="currentSlide = 1"
                        class="absolute right-4 top-1/2 -translate-y-1/2 bg-white/10 backdrop-blur-sm hover:bg-white/20 text-white p-3 rounded-full transition-all z-20"
                    >
                        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
                        </svg>
                    </button>
                    
                    <!-- Hover effect -->
                    <div 
                        @mouseenter="currentSlide = 1"
                        @mouseleave="currentSlide = 0"
                        class="absolute inset-0 cursor-pointer"
                    ></div>
                </div>

                <!-- Solo imagen ANTES -->
                <img 
                    v-else
                    :src="photo.image_path" 
                    alt="Foto de progreso"
                    class="max-w-full max-h-[85vh] object-contain rounded-lg shadow-2xl"
                />
            </div>

            <!-- Columna derecha: Info y acciones -->
            <div class="lg:w-[35%] lg:max-w-md bg-white dark:bg-gray-900 flex flex-col">
                <!-- Header -->
                <div class="p-4 border-b border-gray-200 dark:border-gray-800">
                    <div class="flex items-center gap-3">
                        <div v-if="photo.client_avatar" class="w-10 h-10 rounded-full overflow-hidden ring-2 ring-purple-500">
                            <img :src="photo.client_avatar" :alt="photo.client_name" class="w-full h-full object-cover" />
                        </div>
                        <div v-else class="w-10 h-10 rounded-full bg-gradient-to-br from-purple-500 to-pink-500 flex items-center justify-center text-white font-bold ring-2 ring-purple-500">
                            {{ photo.client_name.charAt(0).toUpperCase() }}
                        </div>
                        <div class="flex-1">
                            <p class="font-semibold text-gray-900 dark:text-white text-sm">{{ photo.client_name }}</p>
                            <p class="text-xs text-gray-500 dark:text-gray-400">{{ photo.shared_at }}</p>
                        </div>
                        <div class="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                            </svg>
                            {{ photo.views_count }}
                        </div>
                    </div>
                </div>

                <!-- Info foto -->
                <div class="p-4 border-b border-gray-200 dark:border-gray-800">
                    <div class="flex items-center gap-2 flex-wrap">
                        <span v-if="photo.weight" class="px-3 py-1 bg-blue-100 dark:bg-blue-900 text-blue-700 dark:text-blue-300 text-xs font-semibold rounded-full">
                            ⚖️ {{ photo.weight }} kg
                        </span>
                        <span v-if="photo.after_image_path" class="px-3 py-1 bg-gradient-to-r from-emerald-500 to-green-500 text-white text-xs font-bold rounded-full">
                            ✨ TRANSFORMACIÓN
                        </span>
                    </div>
                </div>

                <!-- Acciones y comentarios -->
                <div class="flex-1 overflow-y-auto">
                    <!-- Like -->
                    <div class="p-4 border-b border-gray-200 dark:border-gray-800">
                        <button 
                            @click="handleLike"
                            :disabled="isLiking"
                            class="flex items-center gap-3 text-sm font-medium transition-all disabled:opacity-50"
                        >
                            <svg 
                                :class="['w-7 h-7 transition-all', hasLiked ? 'fill-red-500 text-red-500 scale-110' : 'text-gray-700 dark:text-gray-300']" 
                                :fill="hasLiked ? 'currentColor' : 'none'"
                                stroke="currentColor" 
                                viewBox="0 0 24 24"
                            >
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
                            </svg>
                            <span class="text-gray-900 dark:text-white font-semibold">
                                {{ likesCount }} Me gusta
                            </span>
                        </button>
                    </div>

                    <!-- Compartir -->
                    <div class="p-4 border-b border-gray-200 dark:border-gray-800">
                        <button 
                            @click="shareProgress"
                            class="w-full flex items-center justify-center gap-2 px-4 py-2.5 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white rounded-lg text-sm font-semibold transition-all"
                        >
                            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.684 13.342C8.886 12.938 9 12.482 9 12c0-.482-.114-.938-.316-1.342m0 2.684a3 3 0 110-2.684m0 2.684l6.632 3.316m-6.632-6l6.632-3.316m0 0a3 3 0 105.367-2.684 3 3 0 00-5.367 2.684zm0 9.316a3 3 0 105.368 2.684 3 3 0 00-5.368-2.684z" />
                            </svg>
                            <span>Compartir Progreso</span>
                        </button>
                    </div>

                    <!-- Comentarios -->
                    <div class="p-4 space-y-4">
                        <p class="font-semibold text-gray-900 dark:text-white text-sm">Comentarios</p>
                        
                        <div class="space-y-3 max-h-64 overflow-y-auto">
                            <div 
                                v-for="comment in allComments" 
                                :key="comment.id"
                                class="flex items-start gap-2"
                            >
                                <div class="w-8 h-8 rounded-full bg-gradient-to-br from-blue-500 to-indigo-500 flex items-center justify-center text-white font-bold text-xs shrink-0">
                                    {{ comment.author_name.charAt(0).toUpperCase() }}
                                </div>
                                <div class="flex-1 min-w-0 bg-gray-50 dark:bg-gray-800 rounded-lg p-3">
                                    <p class="text-xs font-semibold text-gray-900 dark:text-white">{{ comment.author_name }}</p>
                                    <p class="text-sm text-gray-700 dark:text-gray-300 mt-1">{{ comment.comment }}</p>
                                    <p class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                                        {{ comment.created_at }}
                                    </p>
                                </div>
                            </div>
                            
                            <p v-if="allComments.length === 0" class="text-center text-sm text-gray-500 dark:text-gray-400 py-4">
                                Aún no hay comentarios. ¡Sé el primero!
                            </p>
                        </div>
                    </div>
                </div>

                <!-- Form comentario -->
                <div class="p-4 border-t border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-800">
                    <form @submit.prevent="submitComment" class="space-y-3">
                        <input
                            v-model="commentForm.author_name"
                            type="text"
                            placeholder="Tu nombre"
                            maxlength="100"
                            required
                            class="w-full px-4 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg text-sm focus:ring-2 focus:ring-purple-500"
                        />
                        <div class="flex gap-2">
                            <textarea
                                v-model="commentForm.comment"
                                placeholder="Escribe un comentario..."
                                rows="2"
                                maxlength="1000"
                                required
                                class="flex-1 px-4 py-2 bg-white dark:bg-gray-900 border border-gray-300 dark:border-gray-700 rounded-lg text-sm resize-none focus:ring-2 focus:ring-purple-500"
                            ></textarea>
                            <button
                                type="submit"
                                :disabled="isSubmitting || !commentForm.author_name || !commentForm.comment"
                                class="px-4 py-2 bg-gradient-to-r from-purple-600 to-pink-600 hover:from-purple-700 hover:to-pink-700 text-white rounded-lg text-sm font-semibold disabled:opacity-50 disabled:cursor-not-allowed transition-all"
                            >
                                {{ isSubmitting ? 'Enviando...' : 'Enviar' }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <!-- Toast -->
        <Transition
            enter-active-class="transition ease-out duration-300"
            enter-from-class="opacity-0 translate-y-2"
            enter-to-class="opacity-100 translate-y-0"
            leave-active-class="transition ease-in duration-200"
            leave-from-class="opacity-100 translate-y-0"
            leave-to-class="opacity-0 translate-y-2"
        >
            <div v-if="showSuccessToast" class="fixed bottom-8 left-1/2 transform -translate-x-1/2 bg-gray-900 text-white px-6 py-3 rounded-full shadow-xl flex items-center space-x-2 z-50">
                <svg class="w-5 h-5 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                </svg>
                <span>{{ successMessage }}</span>
            </div>
        </Transition>
    </div>
</template>

<script setup>
import { ref } from 'vue';

const props = defineProps({
    photo: Object,
    comments: Array,
});

const currentSlide = ref(0);
const hasLiked = ref(props.photo.has_liked);
const likesCount = ref(props.photo.likes_count);
const isLiking = ref(false);
const allComments = ref([...props.comments]);
const commentForm = ref({ author_name: '', comment: '' });
const isSubmitting = ref(false);
const showSuccessToast = ref(false);
const successMessage = ref('');

const handleLike = async () => {
    if (isLiking.value) return;
    isLiking.value = true;
    try {
        const token = window.location.pathname.split('/').pop();
        const response = await window.axios.post(`/share/photo/${token}/like`);
        hasLiked.value = response.data.has_liked;
        likesCount.value = response.data.likes_count;
        showToast(hasLiked.value ? '¡Me gusta!' : 'Like eliminado');
    } catch (error) {
        alert('Error al dar like. Por favor, intenta de nuevo.');
    } finally {
        isLiking.value = false;
    }
};

const submitComment = async () => {
    if (isSubmitting.value) return;
    isSubmitting.value = true;
    try {
        const token = window.location.pathname.split('/').pop();
        const response = await window.axios.post(`/share/photo/${token}/comment`, commentForm.value);
        allComments.value.unshift(response.data.comment);
        commentForm.value = { author_name: '', comment: '' };
        showToast('Comentario publicado');
    } catch (error) {
        const errorMsg = error.response?.data?.message || 'Error al publicar el comentario.';
        alert(errorMsg);
    } finally {
        isSubmitting.value = false;
    }
};

const shareProgress = async () => {
    const currentUrl = window.location.href;
    
    // Intentar usar la API de compartir nativa si está disponible
    if (navigator.share) {
        try {
            await navigator.share({
                title: `Progreso de ${props.photo.client_name}`,
                text: `¡Mira mi transformación! ${props.photo.after_image_path ? '✨ ANTES y DESPUÉS' : ''}`,
                url: currentUrl
            });
            showToast('¡Compartido exitosamente!');
        } catch (error) {
            // Si el usuario cancela, no hacer nada
            if (error.name !== 'AbortError') {
                copyToClipboard(currentUrl);
            }
        }
    } else {
        // Fallback: copiar al portapapeles
        copyToClipboard(currentUrl);
    }
};

const copyToClipboard = (text) => {
    if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
            showToast('¡Enlace copiado al portapapeles!');
        }).catch(err => {
            fallbackCopyToClipboard(text);
        });
    } else {
        fallbackCopyToClipboard(text);
    }
};

const fallbackCopyToClipboard = (text) => {
    const textArea = document.createElement('textarea');
    textArea.value = text;
    textArea.style.position = 'fixed';
    textArea.style.left = '-999999px';
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    try {
        document.execCommand('copy');
        showToast('¡Enlace copiado al portapapeles!');
    } catch (err) {
        alert('No se pudo copiar el enlace. Por favor, copia manualmente: ' + text);
    }
    document.body.removeChild(textArea);
};

const showToast = (message) => {
    successMessage.value = message;
    showSuccessToast.value = true;
    setTimeout(() => showSuccessToast.value = false, 3000);
};
</script>
