<script setup>
import { Head, Link, router, usePage } from '@inertiajs/vue3';
import { ref, watch, computed } 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({
    products: Object,
    categories: Array,
    featuredProducts: Array,
    filters: Object,
    layout: String,
    routePrefix: String,
});

const page = usePage();

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

// Safe route prefix - MUST be defined before watchers use it
const safeRoutePrefix = computed(() => props.routePrefix || 'client.store');

// Use global cartCount from middleware
const cartCount = computed(() => page.props.cartCount || 0);

// Safe access to products and featuredProducts
const productsList = computed(() => props.products?.data || []);
const featuredList = computed(() => props.featuredProducts || []);
const paginationLinks = computed(() => props.products?.links || []);
const categoriesList = computed(() => props.categories || []);

// Safe access to filters with fallback
const filters = computed(() => props.filters || {});
const search = ref(filters.value.search || '');
const category = ref(filters.value.category || '');
const sort = ref(filters.value.sort || '');

// Watch for filter changes
let timeout = null;
watch([search, category, sort], () => {
    clearTimeout(timeout);
    timeout = setTimeout(() => {
        router.get(route(safeRoutePrefix.value + '.index'), {
            search: search.value,
            category: category.value,
            sort: sort.value,
        }, { preserveState: true, replace: true });
    }, 300);
});

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

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

const addToCart = (productId) => {
    router.post(route(safeRoutePrefix.value + '.cart.add'), {
        product_id: productId,
        quantity: 1,
    }, {
        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 formatCurrency = (value) => {
    return new Intl.NumberFormat('es-DO', { style: 'currency', currency: 'USD' }).format(value);
};
*/
</script>

<template>
    <Head title="Tienda" />

    <component :is="LayoutComponent">
        <div class="py-3 sm:py-6">
            <!-- Hero Header - Compact on mobile -->
            <div class="mb-4 sm:mb-8 bg-gradient-to-r from-blue-600 to-indigo-600 rounded-xl sm:rounded-2xl p-4 sm:p-6 md:p-8 text-white relative overflow-hidden mx-0">
                <div class="absolute inset-0 bg-black/10"></div>
                <div class="absolute -right-10 -top-10 w-40 h-40 bg-white/10 rounded-full blur-2xl"></div>
                <div class="absolute -left-10 -bottom-10 w-32 h-32 bg-white/10 rounded-full blur-2xl"></div>
                <div class="relative flex items-center justify-between gap-3">
                    <div>
                        <h1 class="text-xl sm:text-3xl md:text-4xl font-bold mb-0.5 sm:mb-2">Tienda</h1>
                        <p class="text-blue-100 text-xs sm:text-base">Los mejores productos para tu rendimiento 💪</p>
                    </div>
                    <button
                        @click="cartOpen = true"
                        class="relative flex-shrink-0 w-11 h-11 sm:w-auto sm:h-auto sm:inline-flex items-center sm:px-5 sm:py-3 bg-white text-blue-600 rounded-full sm:rounded-xl hover:bg-blue-50 transition font-semibold shadow-lg flex justify-center"
                    >
                        <svg class="w-5 h-5 sm:mr-2" 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>
                        <span class="hidden sm:inline">Mi Carrito</span>
                        <span v-if="cartCount > 0" class="absolute -top-1 -right-1 sm:-top-2 sm:-right-2 w-5 h-5 sm:w-6 sm:h-6 bg-red-500 text-white text-[10px] sm:text-xs rounded-full flex items-center justify-center font-bold animate-pulse">
                            {{ cartCount }}
                        </span>
                    </button>
                </div>
            </div>

            <!-- Main Layout with Sidebar -->
            <div class="flex flex-col lg:flex-row gap-4 sm:gap-6">
                <!-- Sidebar Categories (Shopify style) - Desktop -->
                <aside v-if="categoriesList.length" class="lg:w-64 flex-shrink-0 hidden lg:block">
                    <div class="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-4 lg:sticky lg:top-6">
                        <h3 class="font-semibold text-gray-900 dark:text-white mb-4 flex items-center gap-2">
                            <svg class="w-5 h-5 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h7" />
                            </svg>
                            Categorías
                        </h3>
                        <nav class="space-y-1">
                            <button
                                @click="category = ''"
                                :class="[
                                    'w-full text-left px-3 py-2 rounded-lg text-sm font-medium transition flex items-center justify-between',
                                    !category
                                        ? 'bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 border-l-4 border-blue-600'
                                        : 'text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                                ]"
                            >
                                <span>Todos los productos</span>
                                <span v-if="!category" class="text-xs bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300 px-2 py-0.5 rounded-full">
                                    {{ props.products?.total || productsList.length }}
                                </span>
                            </button>
                            <button
                                v-for="cat in categoriesList"
                                :key="cat.id"
                                @click="category = cat.id"
                                :class="[
                                    'w-full text-left px-3 py-2 rounded-lg text-sm font-medium transition flex items-center justify-between',
                                    category == cat.id
                                        ? 'bg-blue-50 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 border-l-4 border-blue-600'
                                        : 'text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700'
                                ]"
                            >
                                <span>{{ cat.name }}</span>
                                <span v-if="cat.products_count" class="text-xs bg-gray-100 dark:bg-gray-700 text-gray-500 dark:text-gray-400 px-2 py-0.5 rounded-full">
                                    {{ cat.products_count }}
                                </span>
                            </button>
                        </nav>

                        <div class="mt-6 pt-4 border-t dark:border-gray-700">
                            <h4 class="font-medium text-sm text-gray-700 dark:text-gray-300 mb-3">Ordenar por</h4>
                            <select v-model="sort" class="w-full text-sm px-3 py-2 rounded-lg border-gray-200 dark:border-gray-700 dark:bg-gray-700 dark:text-white focus:ring-2 focus:ring-blue-500">
                                <option value="">Relevancia</option>
                                <option value="newest">Más recientes</option>
                                <option value="popular">Más populares</option>
                                <option value="price_asc">Precio: menor a mayor</option>
                                <option value="price_desc">Precio: mayor a menor</option>
                            </select>
                        </div>
                    </div>
                </aside>

                <!-- Main Content -->
                <div class="flex-1 min-w-0">
                    <!-- Mobile Categories (horizontal scroll) -->
                    <div v-if="categoriesList.length" class="lg:hidden mb-4 -mx-1 px-1 overflow-x-auto scrollbar-hide">
                        <div class="flex gap-2 pb-1">
                            <button
                                @click="category = ''"
                                :class="[
                                    'px-3.5 py-1.5 rounded-full text-sm font-medium whitespace-nowrap transition-all',
                                    !category
                                        ? 'bg-blue-600 text-white shadow-md shadow-blue-500/20'
                                        : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300'
                                ]"
                            >
                                Todos
                            </button>
                            <button
                                v-for="cat in categoriesList"
                                :key="'mobile-' + cat.id"
                                @click="category = cat.id"
                                :class="[
                                    'px-3.5 py-1.5 rounded-full text-sm font-medium whitespace-nowrap transition-all',
                                    category == cat.id
                                        ? 'bg-blue-600 text-white shadow-md shadow-blue-500/20'
                                        : 'bg-gray-100 dark:bg-gray-800 text-gray-700 dark:text-gray-300'
                                ]"
                            >
                                {{ cat.name }}
                            </button>
                        </div>
                    </div>

                    <!-- Search + Sort row -->
                    <div class="mb-4 sm:mb-6 flex gap-2 sm:gap-3">
                        <div class="relative flex-1">
                            <svg class="absolute left-3 sm:left-4 top-1/2 -translate-y-1/2 w-4 h-4 sm:w-5 sm:h-5 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                            </svg>
                            <input
                                v-model="search"
                                type="text"
                                placeholder="Buscar..."
                                class="w-full pl-9 sm:pl-12 pr-3 sm:pr-4 py-2.5 sm:py-3 rounded-xl text-sm border-gray-200 dark:border-gray-700 dark:bg-gray-800 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                            >
                        </div>
                        <select v-model="sort" class="lg:hidden px-3 py-2.5 rounded-xl text-sm border-gray-200 dark:border-gray-700 dark:bg-gray-800 dark:text-white focus:ring-2 focus:ring-blue-500 w-auto max-w-[140px]">
                            <option value="">Ordenar</option>
                            <option value="newest">Recientes</option>
                            <option value="popular">Populares</option>
                            <option value="price_asc">Precio ↑</option>
                            <option value="price_desc">Precio ↓</option>
                        </select>
                    </div>

                    <!-- Active Filter Badge -->
                    <div v-if="category" class="mb-3 sm:mb-4 flex items-center gap-2">
                        <span class="text-xs sm:text-sm text-gray-500 dark:text-gray-400">Filtrando:</span>
                        <span class="inline-flex items-center gap-1 px-2.5 py-1 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-400 text-xs sm:text-sm rounded-full">
                            {{ categoriesList.find(c => c.id == category)?.name || 'Categoría' }}
                            <button @click="category = ''" class="ml-0.5 hover:text-blue-900 dark:hover:text-blue-200">
                                <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </span>
                    </div>

                    <!-- Featured Products -->
                    <div v-if="featuredList.length && !search && !category" class="mb-6 sm:mb-10">
                        <h2 class="text-base sm:text-xl font-bold text-gray-900 dark:text-white mb-3 sm:mb-4 flex items-center gap-2">
                            <span class="text-lg sm:text-2xl">⭐</span> Destacados
                        </h2>
                        <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-2.5 sm:gap-4">
                            <Link
                                v-for="product in featuredList"
                                :key="product.id"
                                :href="route(safeRoutePrefix + '.show', product.id)"
                                class="group bg-white dark:bg-gray-800 rounded-xl sm:rounded-2xl overflow-hidden shadow-sm border border-gray-100 dark:border-gray-700 hover:shadow-xl hover:-translate-y-1 transition-all duration-300 active:scale-[0.98]"
                            >
                                <div class="aspect-square bg-gray-100 dark:bg-gray-700 relative overflow-hidden">
                                    <img v-if="product.image_url" :src="product.image_url" :alt="product.name" class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500">
                                    <div v-else class="w-full h-full flex items-center justify-center text-gray-400">
                                        <svg class="w-10 h-10 sm:w-12 sm:h-12" 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 class="p-2.5 sm:p-3">
                                    <h3 class="font-medium text-xs sm:text-sm text-gray-900 dark:text-white truncate">{{ product.name }}</h3>
                                    <p class="text-blue-600 font-bold text-sm sm:text-base">{{ formatCurrency(product.price) }}</p>
                                </div>
                            </Link>
                        </div>
                    </div>

                    <!-- Products Grid -->
                    <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-2.5 sm:gap-4 md:gap-6">
                        <div
                            v-for="product in productsList"
                            :key="product.id"
                            class="group bg-white dark:bg-gray-800 rounded-xl sm:rounded-2xl overflow-hidden shadow-sm border border-gray-100 dark:border-gray-700 hover:shadow-xl hover:-translate-y-1 transition-all duration-300"
                        >
                            <Link :href="route(safeRoutePrefix + '.show', product.id)" class="block">
                                <div class="aspect-square bg-gray-100 dark:bg-gray-700 relative overflow-hidden">
                                    <img v-if="product.image_url" :src="product.image_url" :alt="product.name" class="w-full h-full object-cover group-hover:scale-110 transition-transform duration-500">
                                    <div v-else class="w-full h-full flex items-center justify-center text-gray-400">
                                        <svg class="w-12 h-12 sm:w-16 sm:h-16" 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>
                                    <!-- Badges -->
                                    <div class="absolute top-1.5 left-1.5 sm:top-2 sm:left-2 flex flex-col gap-1">
                                        <span v-if="product.is_featured" class="bg-gradient-to-r from-yellow-400 to-orange-400 text-white text-[10px] sm:text-xs font-bold px-1.5 sm:px-2 py-0.5 sm:py-1 rounded-full shadow">
                                            ⭐
                                        </span>
                                        <span v-if="product.is_on_sale" class="bg-gradient-to-r from-red-500 to-pink-500 text-white text-[10px] sm:text-xs font-bold px-1.5 sm:px-2 py-0.5 sm:py-1 rounded-full shadow">
                                            🔥
                                        </span>
                                    </div>
                                    <!-- Quick add button - always visible on mobile -->
                                    <button
                                        @click.prevent="addToCart(product.id)"
                                        :disabled="product.track_stock && product.stock <= 0"
                                        class="absolute bottom-1.5 right-1.5 sm:bottom-2 sm:right-2 w-9 h-9 sm:w-10 sm:h-10 bg-blue-600 text-white rounded-full shadow-lg sm:opacity-0 sm:group-hover:opacity-100 transition-all duration-300 flex items-center justify-center hover:bg-blue-700 active:scale-90 disabled:bg-gray-400 disabled:cursor-not-allowed"
                                    >
                                        <svg class="w-4 h-4 sm:w-5 sm:h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                                        </svg>
                                    </button>
                                </div>
                            </Link>

                            <div class="p-2.5 sm:p-4">
                                <Link :href="route(safeRoutePrefix + '.show', product.id)">
                                    <p class="text-[10px] sm:text-xs text-blue-600 dark:text-blue-400 font-medium uppercase tracking-wide">{{ product.category?.name || 'General' }}</p>
                                    <h3 class="mt-0.5 sm:mt-1 font-semibold text-sm sm:text-base text-gray-900 dark:text-white group-hover:text-blue-600 transition line-clamp-2 leading-tight">{{ product.name }}</h3>
                                </Link>

                                <div class="mt-1.5 sm:mt-3 flex items-baseline gap-1.5 sm:gap-2">
                                    <span class="text-base sm:text-xl font-bold text-gray-900 dark:text-white">{{ formatCurrency(product.price) }}</span>
                                    <span v-if="product.is_on_sale && product.compare_price" class="text-[10px] sm:text-sm text-gray-400 line-through">{{ formatCurrency(product.compare_price) }}</span>
                                </div>

                                <!-- Stock indicator -->
                                <div class="mt-1 sm:mt-2">
                                    <span v-if="!product.track_stock || product.stock > 10" class="text-[10px] sm:text-xs text-green-600 dark:text-green-400 font-medium">✓ Disponible</span>
                                    <span v-else-if="product.stock > 0" class="text-[10px] sm:text-xs text-yellow-600 dark:text-yellow-400 font-medium">⚡ ¡Últimas {{ product.stock }}!</span>
                                    <span v-else class="text-[10px] sm:text-xs text-red-500 font-medium">Agotado</span>
                                </div>

                                <!-- Add to cart - full width button -->
                                <button
                                    @click.prevent="addToCart(product.id)"
                                    :disabled="product.track_stock && product.stock <= 0"
                                    :class="[
                                        'mt-2 sm:mt-3 w-full py-2 sm:py-2.5 rounded-lg sm:rounded-xl text-xs sm:text-sm font-semibold transition-all duration-300 flex items-center justify-center gap-1.5 sm:gap-2 active:scale-[0.97]',
                                        product.track_stock && product.stock <= 0
                                            ? 'bg-gray-100 dark:bg-gray-700 text-gray-400 cursor-not-allowed'
                                            : 'bg-gradient-to-r from-blue-600 to-indigo-600 text-white hover:shadow-lg hover:shadow-blue-500/30'
                                    ]"
                                >
                                    <svg v-if="!(product.track_stock && product.stock <= 0)" class="w-3.5 h-3.5 sm:w-4 sm:h-4" 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>
                                    {{ product.track_stock && product.stock <= 0 ? 'Agotado' : 'Agregar' }}
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Empty State -->
                    <div v-if="!productsList.length" class="text-center py-12 sm:py-16 bg-white dark:bg-gray-800 rounded-xl sm:rounded-2xl border border-gray-100 dark:border-gray-700">
                        <div class="w-16 h-16 sm:w-20 sm:h-20 mx-auto bg-gray-100 dark:bg-gray-700 rounded-full flex items-center justify-center mb-3 sm:mb-4">
                            <svg class="h-8 w-8 sm:h-10 sm:w-10 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
                            </svg>
                        </div>
                        <h3 class="text-base sm:text-lg font-semibold text-gray-900 dark:text-white mb-1 sm:mb-2">No hay productos disponibles</h3>
                        <p class="text-sm text-gray-500 dark:text-gray-400">Intenta con otra búsqueda o categoría</p>
                    </div>

                    <!-- Pagination -->
                    <div v-if="productsList.length && paginationLinks.length > 3" class="mt-6 sm:mt-8 flex items-center justify-center gap-1.5 sm:gap-2 flex-wrap">
                        <Link
                            v-for="link in paginationLinks"
                            :key="link.label"
                            :href="link.url"
                            :class="[
                                'px-3 sm:px-4 py-1.5 sm:py-2 rounded-lg sm:rounded-xl text-xs sm:text-sm font-medium transition-all duration-300',
                                link.active
                                    ? 'bg-blue-600 text-white shadow-lg shadow-blue-500/30'
                                    : 'bg-white dark:bg-gray-800 text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-700 border border-gray-200 dark:border-gray-700',
                                !link.url && 'opacity-50 cursor-not-allowed pointer-events-none'
                            ]"
                            v-html="link.label"
                        />
                    </div>
                </div>
            </div>
        </div>

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