<script setup>
import { Head, Link, router, usePage } from '@inertiajs/vue3';
import { ref, computed, watch } from 'vue';
import CoachLayout from '@/Layouts/CoachLayout.vue';
import ClientLayout from '@/Layouts/ClientLayout.vue';
import AdminLayout from '@/Layouts/AdminLayout.vue';
import SlideInCart from '@/Components/Store/SlideInCart.vue';

const props = defineProps({
    product: Object,
    relatedProducts: Array,
    reviews: Array,
    userReview: Object,
    shippingZones: Array,
    layout: String,
    routePrefix: String,
});

const LayoutComponent = computed(() => {
    if (props.layout === 'admin') return AdminLayout;
    if (props.layout === 'coach') return CoachLayout;
    return ClientLayout;
});

// Safe access to props
const safeProduct = computed(() => props.product || {});
const safeRelatedProducts = computed(() => props.relatedProducts || []);
const safeRoutePrefix = computed(() => props.routePrefix || 'client.store');

const quantity = ref(1);
const activeImage = ref(0);

// Selected variants (independent selection)
const selectedSize = ref(null);
const selectedFlavor = ref(null);

// Parse sizes - handle both old format (string[]) and new format ({name, price}[])
const parsedSizes = computed(() => {
    const sizes = safeProduct.value.sizes || [];
    if (!sizes.length) return [];
    // Check if new format
    if (typeof sizes[0] === 'object' && sizes[0].name) {
        return sizes;
    }
    // Old format - convert
    return sizes.map(s => ({ name: s, price: safeProduct.value.price }));
});

// Calculate current price based on selected size
const currentPrice = computed(() => {
    if (selectedSize.value) {
        const size = parsedSizes.value.find(s => s.name === selectedSize.value);
        if (size) return size.price;
    }
    return safeProduct.value.price;
});

const images = computed(() => {
    const imgs = [];
    if (safeProduct.value.image_url) {
        imgs.push(safeProduct.value.image_url);
    }
    if (safeProduct.value.gallery_urls) {
        imgs.push(...safeProduct.value.gallery_urls);
    }
    return imgs;
});

// Cart state
const cartOpen = ref(false);

// Use global cartItems from Inertia props
const page = usePage();
const cartItems = computed(() => page.props.cartItems || []);

const addToCart = () => {
    if (!safeProduct.value.id) return;

    router.post(route(safeRoutePrefix.value + '.cart.add'), {
        product_id: safeProduct.value.id,
        quantity: quantity.value,
        size: selectedSize.value,
        flavor: selectedFlavor.value,
    }, {
        preserveScroll: true,
        onSuccess: () => {
            // Open cart after adding
            refreshCart();
            cartOpen.value = true;
        },
    });
};

const refreshCart = () => {
    // Reload cart data to update global cartItems
    router.reload({ only: ['cartCount', 'cartItems'] });
};

import { formatCurrency } from '@/Utils/currency';

const isInStock = computed(() => {
    if (!safeProduct.value.track_stock) return true;
    return (safeProduct.value.stock || 0) > 0 || safeProduct.value.allow_backorder;
});

// Reviews
const safeReviews = computed(() => props.reviews || []);
const safeShippingZones = computed(() => props.shippingZones || []);
const averageRating = computed(() => safeProduct.value.average_rating || 0);
const reviewsCount = computed(() => safeProduct.value.reviews_count || 0);

const reviewRating = ref(props.userReview?.rating || 5);
const reviewTitle = ref(props.userReview?.title || '');
const reviewComment = ref(props.userReview?.comment || '');
const submittingReview = ref(false);

const setRating = (n) => { reviewRating.value = n; };

const submitReview = () => {
    submittingReview.value = true;
    router.post(route(safeRoutePrefix.value + '.reviews.store', safeProduct.value.id), {
        rating: reviewRating.value,
        title: reviewTitle.value,
        comment: reviewComment.value,
    }, {
        preserveScroll: true,
        onFinish: () => { submittingReview.value = false; },
    });
};

const starArray = [1, 2, 3, 4, 5];
</script>

<template>
    <Head :title="safeProduct.name || 'Producto'" />

    <component :is="LayoutComponent">
        <div class="py-6">
            <!-- Breadcrumb -->
            <nav class="mb-6 text-sm text-gray-500 dark:text-gray-400">
                <Link :href="route(safeRoutePrefix + '.index')" class="hover:text-blue-600">Tienda</Link>
                <span class="mx-2">/</span>
                <span v-if="safeProduct.category">
                    <Link :href="route(safeRoutePrefix + '.index', { category: safeProduct.category.id })" class="hover:text-blue-600">{{ safeProduct.category.name }}</Link>
                    <span class="mx-2">/</span>
                </span>
                <span class="text-gray-900 dark:text-white">{{ safeProduct.name }}</span>
            </nav>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-10">
                <!-- Images -->
                <div class="space-y-4">
                    <div class="aspect-square bg-gray-100 dark:bg-gray-800 rounded-2xl overflow-hidden">
                        <img v-if="images[activeImage]" :src="images[activeImage]" :alt="safeProduct.name" class="w-full h-full object-cover">
                        <div v-else class="w-full h-full flex items-center justify-center text-gray-400">
                            <svg class="w-24 h-24" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
                            </svg>
                        </div>
                    </div>
                    <div v-if="images.length > 1" class="flex gap-2 overflow-x-auto pb-2">
                        <button
                            v-for="(img, i) in images"
                            :key="i"
                            @click="activeImage = i"
                            :class="[
                                'w-20 h-20 rounded-lg overflow-hidden flex-shrink-0 border-2 transition',
                                activeImage === i ? 'border-blue-600' : 'border-transparent hover:border-gray-300'
                            ]"
                        >
                            <img :src="img" class="w-full h-full object-cover">
                        </button>
                    </div>
                </div>

                <!-- Product Info -->
                <div>
                    <div class="mb-4">
                        <span v-if="safeProduct.category" class="text-sm text-blue-600">{{ safeProduct.category.name }}</span>
                        <h1 class="text-3xl font-bold text-gray-900 dark:text-white">{{ safeProduct.name }}</h1>
                        <!-- Average Rating -->
                        <div v-if="reviewsCount > 0" class="flex items-center gap-2 mt-1">
                            <div class="flex">
                                <svg v-for="s in starArray" :key="s" class="w-4 h-4" :class="s <= Math.round(averageRating) ? 'text-yellow-400' : 'text-gray-300'" fill="currentColor" viewBox="0 0 20 20"><path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/></svg>
                            </div>
                            <span class="text-sm text-gray-500 dark:text-gray-400">{{ averageRating }} ({{ reviewsCount }} reseñas)</span>
                        </div>
                    </div>

                    <div class="mb-6 flex items-baseline gap-3">
                        <span class="text-4xl font-bold text-blue-600">{{ formatCurrency(currentPrice) }}</span>
                        <span v-if="safeProduct.is_on_sale && safeProduct.compare_price" class="text-xl text-gray-400 line-through">{{ formatCurrency(safeProduct.compare_price) }}</span>
                        <span v-if="safeProduct.is_on_sale" class="px-2 py-1 bg-red-100 text-red-600 text-sm font-bold rounded">
                            {{ Math.round((1 - currentPrice / safeProduct.compare_price) * 100) }}% OFF
                        </span>
                    </div>

                    <div v-if="safeProduct.short_description" class="mb-6 text-gray-600 dark:text-gray-300">
                        {{ safeProduct.short_description }}
                    </div>

                    <!-- Stock Status -->
                    <div class="mb-6">
                        <div v-if="!safeProduct.track_stock" class="text-green-600 font-medium">
                            ✓ Disponible
                        </div>
                        <div v-else-if="safeProduct.stock > 10" class="text-green-600 font-medium">
                            ✓ En stock ({{ safeProduct.stock }} disponibles)
                        </div>
                        <div v-else-if="safeProduct.stock > 0" class="text-yellow-600 font-medium">
                            ⚠ Pocas unidades ({{ safeProduct.stock }} restantes)
                        </div>
                        <div v-else-if="safeProduct.allow_backorder" class="text-blue-600 font-medium">
                            📦 Disponible bajo pedido
                        </div>
                        <div v-else class="text-red-600 font-medium">
                            ✕ Agotado
                        </div>
                    </div>

                    <!-- Variantes del Producto (Tamaños y Sabores) - Selección Independiente -->
                    <div v-if="parsedSizes.length || (safeProduct.flavors && safeProduct.flavors.length)" class="mb-6 space-y-5">
                        <!-- Tamaños con Precios -->
                        <div v-if="parsedSizes.length">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">📦 Tamaño</label>
                            <div class="flex flex-wrap gap-2">
                                <button
                                    v-for="size in parsedSizes"
                                    :key="size.name"
                                    type="button"
                                    @click="selectedSize = selectedSize === size.name ? null : size.name"
                                    :class="[
                                        'px-4 py-3 border-2 rounded-lg text-sm font-medium transition-all',
                                        selectedSize === size.name
                                            ? 'border-blue-600 bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 ring-2 ring-blue-200 dark:ring-blue-800'
                                            : 'border-gray-300 dark:border-gray-600 hover:border-blue-400 hover:bg-blue-50 dark:hover:bg-blue-900/20'
                                    ]"
                                >
                                    <span class="block font-semibold">{{ size.name }}</span>
                                    <span class="block text-xs mt-0.5" :class="selectedSize === size.name ? 'text-blue-600' : 'text-gray-500'">
                                        {{ formatCurrency(size.price) }}
                                    </span>
                                </button>
                            </div>
                        </div>

                        <!-- Sabores -->
                        <div v-if="safeProduct.flavors && safeProduct.flavors.length">
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3">🍫 Sabor</label>
                            <div class="flex flex-wrap gap-2">
                                <button
                                    v-for="flavor in safeProduct.flavors"
                                    :key="flavor"
                                    type="button"
                                    @click="selectedFlavor = selectedFlavor === flavor ? null : flavor"
                                    :class="[
                                        'px-4 py-2 border-2 rounded-lg text-sm font-medium transition-all',
                                        selectedFlavor === flavor
                                            ? 'border-purple-600 bg-purple-50 dark:bg-purple-900/30 text-purple-700 dark:text-purple-300 ring-2 ring-purple-200 dark:ring-purple-800'
                                            : 'border-gray-300 dark:border-gray-600 hover:border-purple-400 hover:bg-purple-50 dark:hover:bg-purple-900/20'
                                    ]"
                                >
                                    {{ flavor }}
                                </button>
                            </div>
                        </div>

                        <!-- Selection Summary -->
                        <div v-if="selectedSize || selectedFlavor" class="p-3 bg-gray-50 dark:bg-gray-700 rounded-lg">
                            <p class="text-sm text-gray-600 dark:text-gray-300">
                                <strong>Selección:</strong>
                                <span v-if="selectedSize" class="ml-2 px-2 py-0.5 bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300 rounded text-xs">{{ selectedSize }}</span>
                                <span v-if="selectedFlavor" class="ml-2 px-2 py-0.5 bg-purple-100 dark:bg-purple-900/50 text-purple-700 dark:text-purple-300 rounded text-xs">{{ selectedFlavor }}</span>
                            </p>
                        </div>
                    </div>

                    <!-- Quantity & Add to Cart -->
                    <div class="mb-6 flex items-center gap-4">
                        <div class="flex items-center border border-gray-300 dark:border-gray-600 rounded-lg">
                            <button
                                @click="quantity = Math.max(1, quantity - 1)"
                                class="px-4 py-2 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 transition"
                            >−</button>
                            <input
                                v-model.number="quantity"
                                type="number"
                                min="1"
                                max="10"
                                class="w-16 text-center border-0 focus:ring-0 dark:bg-gray-800 dark:text-white"
                            >
                            <button
                                @click="quantity = Math.min(10, quantity + 1)"
                                class="px-4 py-2 text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 transition"
                            >+</button>
                        </div>

                        <button
                            @click="addToCart"
                            :disabled="!isInStock"
                            :class="[
                                'flex-1 py-3 px-6 rounded-lg font-semibold transition flex items-center justify-center gap-2',
                                isInStock
                                    ? 'bg-blue-600 text-white hover:bg-blue-700'
                                    : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                            ]"
                        >
                            <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="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13L5.4 5M7 13l-2.293 2.293c-.63.63-.184 1.707.707 1.707H17m0 0a2 2 0 100 4 2 2 0 000-4zm-8 2a2 2 0 11-4 0 2 2 0 014 0z" />
                            </svg>
                            {{ isInStock ? 'Agregar al carrito' : 'Agotado' }}
                        </button>
                    </div>

                    <!-- Product Details -->
                    <div class="border-t dark:border-gray-700 pt-6">
                        <h3 class="font-semibold text-gray-900 dark:text-white mb-4">Detalles del producto</h3>
                        <dl class="grid grid-cols-2 gap-4 text-sm">
                            <div v-if="safeProduct.sku">
                                <dt class="text-gray-500">SKU</dt>
                                <dd class="font-mono text-gray-900 dark:text-white">{{ safeProduct.sku }}</dd>
                            </div>
                            <div v-if="safeProduct.weight">
                                <dt class="text-gray-500">Peso</dt>
                                <dd class="text-gray-900 dark:text-white">{{ safeProduct.weight }} kg</dd>
                            </div>
                            <div v-if="safeProduct.dimensions">
                                <dt class="text-gray-500">Dimensiones</dt>
                                <dd class="text-gray-900 dark:text-white">{{ safeProduct.dimensions }}</dd>
                            </div>
                        </dl>
                    </div>

                    <!-- Description -->
                    <div v-if="safeProduct.description" class="border-t dark:border-gray-700 pt-6 mt-6">
                        <h3 class="font-semibold text-gray-900 dark:text-white mb-4">Descripción</h3>
                        <div class="prose dark:prose-invert max-w-none text-gray-600 dark:text-gray-300" v-html="safeProduct.description"></div>
                    </div>
                </div>
            </div>

            <!-- Shipping Zones -->
            <div v-if="safeShippingZones.length" class="mt-10">
                <h2 class="text-xl font-bold text-gray-900 dark:text-white mb-4">🚚 Zonas de Envío</h2>
                <div class="grid grid-cols-2 md:grid-cols-4 gap-3">
                    <div v-for="zone in safeShippingZones" :key="zone.id" class="p-3 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 text-center">
                        <p class="font-semibold text-gray-900 dark:text-white text-sm">{{ zone.name }}</p>
                        <p class="text-lg font-bold text-green-600">RD${{ Number(zone.cost).toFixed(2) }}</p>
                        <p v-if="zone.delivery_time" class="text-xs text-gray-500">🕐 {{ zone.delivery_time }}</p>
                    </div>
                </div>
            </div>

            <!-- Reviews Section -->
            <div class="mt-12">
                <h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-6">Reseñas de Clientes</h2>

                <!-- Write Review Form -->
                <div v-if="$page.props.auth?.user" class="bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700 p-6 mb-8">
                    <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-4">
                        {{ userReview ? 'Editar tu Reseña' : 'Escribe una Reseña' }}
                    </h3>
                    <form @submit.prevent="submitReview" class="space-y-4">
                        <!-- Star Picker -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Tu Calificación</label>
                            <div class="flex gap-1">
                                <button v-for="s in starArray" :key="s" type="button" @click="setRating(s)" class="focus:outline-none">
                                    <svg class="w-8 h-8 transition-colors" :class="s <= reviewRating ? 'text-yellow-400' : 'text-gray-300 dark:text-gray-600 hover:text-yellow-300'" fill="currentColor" viewBox="0 0 20 20">
                                        <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
                                    </svg>
                                </button>
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Título (opcional)</label>
                            <input v-model="reviewTitle" type="text" maxlength="255" placeholder="Ej: Excelente producto" class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white">
                        </div>
                        <div>
                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1">Comentario (opcional)</label>
                            <textarea v-model="reviewComment" rows="3" maxlength="1000" placeholder="Cuéntanos tu experiencia con este producto..." class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white"></textarea>
                        </div>
                        <button type="submit" :disabled="submittingReview" class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 font-medium">
                            {{ submittingReview ? 'Enviando...' : (userReview ? 'Actualizar Reseña' : 'Enviar Reseña') }}
                        </button>
                    </form>
                </div>

                <!-- Reviews List -->
                <div v-if="safeReviews.length" class="space-y-4">
                    <div v-for="review in safeReviews" :key="review.id" class="flex gap-4 p-4 bg-white dark:bg-gray-800 rounded-xl border border-gray-200 dark:border-gray-700">
                        <div class="flex-shrink-0">
                            <img v-if="review.user_avatar" :src="review.user_avatar" class="w-10 h-10 rounded-full object-cover">
                            <div v-else class="w-10 h-10 rounded-full bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center text-blue-600 font-bold text-sm">
                                {{ review.user_name.charAt(0).toUpperCase() }}
                            </div>
                        </div>
                        <div class="flex-1 min-w-0">
                            <div class="flex items-center gap-2 mb-1">
                                <span class="font-semibold text-gray-900 dark:text-white">{{ review.user_name }}</span>
                                <span class="text-xs text-gray-500">{{ review.created_at }}</span>
                            </div>
                            <div class="flex gap-0.5 mb-2">
                                <svg v-for="s in starArray" :key="s" class="w-4 h-4" :class="s <= review.rating ? 'text-yellow-400' : 'text-gray-300'" fill="currentColor" viewBox="0 0 20 20"><path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/></svg>
                            </div>
                            <h4 v-if="review.title" class="font-medium text-gray-900 dark:text-white mb-1">{{ review.title }}</h4>
                            <p v-if="review.comment" class="text-gray-600 dark:text-gray-300 text-sm">{{ review.comment }}</p>
                        </div>
                    </div>
                </div>

                <!-- No Reviews -->
                <div v-else class="text-center py-8 text-gray-500 dark:text-gray-400">
                    <p class="text-lg font-medium">Aún no hay reseñas</p>
                    <p class="text-sm mt-1">Sé el primero en compartir tu opinión</p>
                </div>
            </div>

            <!-- Related Products -->
            <div v-if="safeRelatedProducts.length" class="mt-16">
                <h2 class="text-2xl font-bold text-gray-900 dark:text-white mb-6">Productos relacionados</h2>
                <div class="grid grid-cols-2 md:grid-cols-4 gap-6">
                    <Link
                        v-for="related in safeRelatedProducts"
                        :key="related.id"
                        :href="route(safeRoutePrefix + '.show', related.id)"
                        class="group bg-white dark:bg-gray-800 rounded-xl overflow-hidden shadow-sm border border-gray-200 dark:border-gray-700 hover:shadow-lg transition"
                    >
                        <div class="aspect-square bg-gray-100 dark:bg-gray-700 overflow-hidden">
                            <img v-if="related.image_url" :src="related.image_url" :alt="related.name" class="w-full h-full object-cover group-hover:scale-105 transition duration-300">
                        </div>
                        <div class="p-4">
                            <h3 class="font-medium text-gray-900 dark:text-white truncate">{{ related.name }}</h3>
                            <p class="text-blue-600 font-bold">{{ formatCurrency(related.price) }}</p>
                        </div>
                    </Link>
                </div>
            </div>
        </div>

        <!-- Slide-in Cart -->
        <SlideInCart
            :is-open="cartOpen"
            :items="cartItems"
            :route-prefix="safeRoutePrefix"
            @close="cartOpen = false"
            @update="refreshCart"
        />
    </component>
</template>

