<script setup>
import { computed } from 'vue';
import { router } from '@inertiajs/vue3';

const props = defineProps({
    isOpen: Boolean,
    items: {
        type: Array,
        default: () => []
    },
    routePrefix: String,
});

const emit = defineEmits(['close', 'update']);

const safeItems = computed(() => props.items || []);

const subtotal = computed(() => {
    return safeItems.value.reduce((sum, item) => sum + (Number(item.subtotal) || 0), 0);
});

const itemCount = computed(() => {
    return safeItems.value.reduce((sum, item) => sum + (Number(item.quantity) || 0), 0);
});

const updateQuantity = (productId, newQuantity) => {
    router.post(route(props.routePrefix + '.cart.update'), {
        product_id: productId,
        quantity: newQuantity,
    }, {
        preserveScroll: true,
        onSuccess: () => emit('update'),
    });
};

const removeItem = (productId) => {
    router.post(route(props.routePrefix + '.cart.remove'), {
        product_id: productId,
    }, {
        preserveScroll: true,
        onSuccess: () => emit('update'),
    });
};

const goToCheckout = () => {
    emit('close');
    router.visit(route(props.routePrefix + '.checkout'));
};
</script>

<template>
    <Teleport to="body">
        <!-- Overlay -->
        <Transition
            enter-active-class="transition-opacity duration-300 ease-out"
            enter-from-class="opacity-0"
            enter-to-class="opacity-100"
            leave-active-class="transition-opacity duration-200 ease-in"
            leave-from-class="opacity-100"
            leave-to-class="opacity-0"
        >
            <div
                v-if="isOpen"
                class="fixed inset-0 bg-black/50 backdrop-blur-sm"
                style="z-index: 9998;"
                @click="$emit('close')"
            ></div>
        </Transition>

        <!-- Slide-in Panel -->
        <Transition
            enter-active-class="transition-transform duration-300 ease-out"
            enter-from-class="translate-x-full"
            enter-to-class="translate-x-0"
            leave-active-class="transition-transform duration-200 ease-in"
            leave-from-class="translate-x-0"
            leave-to-class="translate-x-full"
        >
            <div
                v-if="isOpen"
                class="fixed right-0 top-0 h-full w-full max-w-md bg-white dark:bg-gray-900 shadow-2xl flex flex-col"
                style="z-index: 9999;"
            >
                <!-- Header -->
                <div class="flex items-center justify-between px-6 py-5 border-b border-gray-200 dark:border-gray-800 flex-shrink-0">
                    <div class="flex items-center gap-3">
                        <svg class="w-6 h-6 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
                        </svg>
                        <div>
                            <h2 class="text-xl font-bold text-gray-900 dark:text-white">Carrito</h2>
                            <p class="text-sm text-gray-500 dark:text-gray-400">{{ itemCount }} {{ itemCount === 1 ? 'producto' : 'productos' }}</p>
                        </div>
                    </div>
                    <button
                        @click="$emit('close')"
                        class="p-2 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors"
                        aria-label="Cerrar carrito"
                    >
                        <svg class="w-6 h-6 text-gray-500" 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>
                </div>

                <!-- Items List -->
                <div class="flex-1 overflow-y-auto px-6 py-4" style="min-height: 0;">
                    <!-- Empty State -->
                    <div v-if="safeItems.length === 0" class="flex flex-col items-center justify-center h-full text-center py-12">
                        <svg class="w-20 h-20 text-gray-300 dark:text-gray-600 mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z" />
                        </svg>
                        <h3 class="text-lg font-semibold text-gray-900 dark:text-white mb-2">Tu carrito está vacío</h3>
                        <p class="text-gray-500 dark:text-gray-400 mb-6">Agrega productos para comenzar tu compra</p>
                        <button
                            @click="$emit('close')"
                            class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition font-medium"
                        >
                            Continuar Comprando
                        </button>
                    </div>

                    <!-- Items -->
                    <div v-else class="space-y-4">
                        <div
                            v-for="item in safeItems"
                            :key="item.product?.id || Math.random()"
                            class="flex gap-4 p-4 bg-gray-50 dark:bg-gray-800 rounded-xl"
                        >
                            <!-- Product Image -->
                            <div class="w-20 h-20 rounded-lg bg-gray-200 dark:bg-gray-700 overflow-hidden flex-shrink-0">
                                <img
                                    v-if="item.product?.image_url"
                                    :src="item.product.image_url"
                                    :alt="item.product?.name"
                                    class="w-full h-full object-cover"
                                />
                                <div v-else class="w-full h-full flex items-center justify-center">
                                    <svg class="w-8 h-8 text-gray-400" 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>

                            <!-- Product Info -->
                            <div class="flex-1 min-w-0">
                                <h3 class="font-semibold text-gray-900 dark:text-white truncate text-sm">{{ item.product?.name }}</h3>
                                <p class="text-sm text-gray-500 dark:text-gray-400 mt-0.5">RD${{ Number(item.product?.price || 0).toFixed(2) }} c/u</p>

                                <!-- Quantity Controls -->
                                <div class="flex items-center gap-2 mt-2">
                                    <button
                                        @click="updateQuantity(item.product?.id, item.quantity - 1)"
                                        :disabled="item.quantity <= 1"
                                        class="w-7 h-7 rounded-md border border-gray-300 dark:border-gray-600 flex items-center justify-center hover:bg-gray-100 dark:hover:bg-gray-700 transition disabled:opacity-40 disabled:cursor-not-allowed text-gray-600 dark:text-gray-300"
                                    >
                                        <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="M20 12H4" />
                                        </svg>
                                    </button>
                                    <span class="w-8 text-center font-medium text-sm text-gray-900 dark:text-white">{{ item.quantity }}</span>
                                    <button
                                        @click="updateQuantity(item.product?.id, item.quantity + 1)"
                                        :disabled="item.quantity >= 10"
                                        class="w-7 h-7 rounded-md border border-gray-300 dark:border-gray-600 flex items-center justify-center hover:bg-gray-100 dark:hover:bg-gray-700 transition disabled:opacity-40 disabled:cursor-not-allowed text-gray-600 dark:text-gray-300"
                                    >
                                        <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="M12 4v16m8-8H4" />
                                        </svg>
                                    </button>
                                </div>
                            </div>

                            <!-- Price & Remove -->
                            <div class="flex flex-col items-end justify-between flex-shrink-0">
                                <button
                                    @click="removeItem(item.product?.id)"
                                    class="p-1 text-red-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded transition"
                                    aria-label="Eliminar producto"
                                >
                                    <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                                    </svg>
                                </button>
                                <p class="font-bold text-gray-900 dark:text-white text-sm">RD${{ Number(item.subtotal || 0).toFixed(2) }}</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Footer -->
                <div v-if="safeItems.length > 0" class="border-t border-gray-200 dark:border-gray-800 p-6 space-y-4 flex-shrink-0 bg-white dark:bg-gray-900">
                    <!-- Subtotal -->
                    <div class="flex justify-between items-center">
                        <span class="font-medium text-gray-700 dark:text-gray-300">Subtotal:</span>
                        <span class="text-xl font-bold text-gray-900 dark:text-white">RD${{ subtotal.toFixed(2) }}</span>
                    </div>

                    <!-- Checkout Button -->
                    <button
                        @click="goToCheckout"
                        class="w-full py-3.5 bg-blue-600 text-white font-semibold rounded-xl hover:bg-blue-700 transition shadow-lg hover:shadow-xl flex items-center justify-center gap-2"
                    >
                        <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="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                        </svg>
                        Proceder al Checkout
                    </button>

                    <!-- Continue Shopping -->
                    <button
                        @click="$emit('close')"
                        class="w-full py-2.5 text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-white font-medium transition text-sm"
                    >
                        Continuar Comprando
                    </button>
                </div>
            </div>
        </Transition>
    </Teleport>
</template>
