<?php $__env->startSection('title', $product->product_name . ' - NewTech'); ?>

<?php $__env->startSection('content'); ?>
<div class="bg-gray-50 min-h-screen py-4 sm:py-8" x-data="productPageData()">
    <div class="container mx-auto px-4">
        <!-- Breadcrumbs -->
        <nav class="mb-4 sm:mb-6" aria-label="Breadcrumb">
            <ol class="flex items-center space-x-2 text-xs sm:text-sm">
                <li>
                    <a href="<?php echo e(route('home')); ?>" class="text-gray-500 hover:text-blue-600 flex items-center transition-colors">
                        <i class="fas fa-home mr-1 sm:mr-2"></i> Home
                    </a>
                </li>
                <li><i class="fas fa-chevron-right text-gray-300 text-xs"></i></li>
                <li>
                    <a href="<?php echo e(route('products.index')); ?>" class="text-gray-500 hover:text-blue-600 transition-colors">Products</a>
                </li>
                <li><i class="fas fa-chevron-right text-gray-300 text-xs"></i></li>
                <li class="text-gray-800 font-medium truncate max-w-[150px] sm:max-w-xs"><?php echo e($product->product_name); ?></li>
            </ol>
        </nav>

        <div class="bg-white rounded-2xl shadow-lg overflow-hidden">
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 sm:gap-8 p-4 sm:p-6 md:p-8">
                <!-- Product Image Gallery -->
                <div class="space-y-4 sm:space-y-6">
                    <!-- Tabs for Image/3D -->
                    <div class="flex border-b mb-4">
                        <button
                            @click="activeTab = 'images'; setupThreeJS()"
                            :class="activeTab === 'images' ? 'text-blue-600 font-semibold border-b-2 border-blue-600' : 'text-gray-500 hover:text-gray-700'"
                            class="py-2 sm:py-3 px-4 sm:px-6 text-sm sm:text-base focus:outline-none transition-colors duration-300"
                        >
                            <i class="fas fa-images mr-1 sm:mr-2"></i> Images
                        </button>
                        <button
                            @click="activeTab = '3d'; setupThreeJS()"
                            :class="activeTab === '3d' ? 'text-blue-600 font-semibold border-b-2 border-blue-600' : 'text-gray-500 hover:text-gray-700'"
                            class="py-2 sm:py-3 px-4 sm:px-6 text-sm sm:text-base focus:outline-none transition-colors duration-300"
                        >
                            <i class="fas fa-cube mr-1 sm:mr-2"></i> 3D View
                        </button>
                    </div>

                    <!-- Image Gallery -->
                    <div x-show="activeTab === 'images'" x-transition.opacity.duration.500ms class="space-y-4">
                        <!-- Main Image with Zoom -->
                        <div
                            class="relative border border-gray-200 rounded-xl overflow-hidden bg-gray-50 h-[300px] sm:h-[400px] md:h-[500px] cursor-zoom-in"
                            @mousemove="handleZoom($event)"
                            @mouseleave="resetZoom()"
                            @click="toggleZoom()"
                        >
                            <img
                                :src="mainImage"
                                alt="<?php echo e($product->product_name); ?>"
                                class="w-full h-full object-contain p-2 sm:p-4 transition-transform duration-300 ease-out"
                                :style="zoomStyle"
                            >
                            <!-- Zoom Lens -->
                            <div
                                x-show="isZoomed"
                                class="absolute bg-gray-200 bg-opacity-30 border border-gray-400 rounded-full"
                                :style="lensStyle"
                            ></div>
                            <!-- Zoom Indicator -->
                            <div x-show="isZoomed" class="absolute top-2 sm:top-4 right-2 sm:right-4 bg-black bg-opacity-50 text-white px-2 sm:px-3 py-1 rounded-full text-xs sm:text-sm">
                                <i class="fas fa-search-plus mr-1"></i> Zoomed
                            </div>
                        </div>

                        <!-- Thumbnails -->
                        <div class="grid grid-cols-4 gap-2 sm:gap-3">
                            <template x-for="(thumb, index) in activeThumbnails" :key="index">
                                <button
                                    @click="changeMainImage(thumb.image)"
                                    :class="mainImage === thumb.image ? 'border-blue-500 ring-2 ring-blue-200' : 'border-gray-200 hover:border-blue-300'"
                                    class="border-2 rounded-lg p-1 transition-all duration-300 transform hover:scale-105"
                                >
                                    <img :src="thumb.image" :alt="`Thumbnail for ${thumb.color}`" class="w-full h-16 sm:h-20 object-contain rounded-md">
                                </button>
                            </template>
                        </div>
                    </div>

                    <!-- 3D Model Viewer -->
                    <div x-show="activeTab === '3d'" x-transition.opacity.duration.500ms>
                        <?php $model3dPath = 'models/phone.glb'; ?>
                        <?php if(true): ?>
                            <div class="border border-gray-200 rounded-xl bg-gray-50 h-[300px] sm:h-[400px] md:h-[500px] flex items-center justify-center">
                                <canvas id="threejs-canvas" class="w-full h-full"></canvas>
                            </div>
                        <?php else: ?>
                            <div class="h-[300px] sm:h-[400px] md:h-[500px] border border-gray-200 rounded-xl bg-gray-50 flex flex-col items-center justify-center text-center text-gray-500 p-4 sm:p-6">
                                <div class="w-12 sm:w-16 h-12 sm:h-16 bg-gray-100 rounded-full flex items-center justify-center mb-4">
                                    <i class="fas fa-cube text-xl sm:text-2xl text-gray-400"></i>
                                </div>
                                <p class="font-semibold text-base sm:text-lg mb-2">3D Model Not Available</p>
                                <p class="text-gray-500 text-sm sm:text-base max-w-md">An interactive 3D view of this product will be available soon.</p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Product Details -->
                <div class="sticky top-4 sm:top-8">
                    <div class="space-y-4 sm:space-y-6">
                        <div x-data="{ productName: '<?php echo e($product->product_name); ?>' }" x-init="$watch('selectedProduct', value => productName = value.product_name)">
                            <h1 class="text-2xl sm:text-3xl md:text-4xl font-bold text-gray-900 mb-2 sm:mb-3 leading-tight"><?php echo e($product->product_name); ?></h1>
                            <div class="flex items-center flex-wrap gap-2 sm:gap-3 mb-3 sm:mb-4">
                                <div class="flex text-yellow-400">
                                    <?php for($i = 1; $i <= 5; $i++): ?>
                                        <i class="fas fa-star text-xs sm:text-sm"></i>
                                    <?php endfor; ?>
                                </div>
                                <span class="text-gray-500 text-xs sm:text-sm">(15 Reviews)</span>
                                <span class="w-2 h-2 bg-gray-300 rounded-full hidden sm:block"></span>
                                <span class="text-green-600 font-semibold text-xs sm:text-sm flex items-center">
                                    <i class="fas fa-check-circle mr-1"></i> In Stock
                                </span>
                            </div>
                        </div>

                        <!-- Price -->
                        <div class="mb-2" x-data="{ price: <?php echo e($product->price ?? 0); ?>, discount_price: <?php echo e($product->discount_price ?? 0); ?> }" x-init="$watch('selectedProduct', value => { price = value.price; discount_price = value.discount_price; })">
                            <template x-if="discount_price > 0">
                                <div class="flex items-baseline gap-2 sm:gap-3">
                                    <span class="text-2xl sm:text-3xl md:text-4xl font-bold text-red-600" x-text="`৳${Number(discount_price).toLocaleString()}`"></span>
                                    <span class="text-lg sm:text-xl text-gray-400 line-through" x-text="`৳${Number(price).toLocaleString()}`"></span>
                                    <span class="bg-red-100 text-red-800 text-xs sm:text-sm font-medium px-2 sm:px-2.5 py-0.5 rounded-full">
                                        Save <span x-text="`৳${Number(price - discount_price).toLocaleString()}`"></span>
                                    </span>
                                </div>
                            </template>
                            <template x-if="!discount_price || discount_price <= 0">
                                <span class="text-2xl sm:text-3xl md:text-4xl font-bold text-gray-900" x-text="`৳${Number(price).toLocaleString()}`"></span>
                            </template>
                        </div>

                        <!-- Short Description -->
                        <p class="text-gray-600 leading-relaxed text-sm sm:text-base md:text-lg" x-text="selectedProduct.description || 'No description available for this product.'"></p>

                        <!-- Color Selection -->
                        <div class="mt-4 sm:mt-6">
                            <h3 class="text-base sm:text-lg font-medium text-gray-900 mb-2 sm:mb-3">Color</h3>
                            <div class="flex flex-wrap gap-2 sm:gap-3">
                                <template x-for="(item, index) in allGroupItems" :key="index">
                                    <button @click="selectProduct(item)"
                                        :class="selectedProduct.color === item.color ? 'ring-2 ring-blue-500 ring-offset-2 scale-110' : ''"
                                        class="w-8 h-8 sm:w-10 sm:h-10 rounded-full border-2 border-white shadow-md transition-all duration-300 hover:scale-110"
                                        :style="`background-color: ${item.colorHex}`"
                                        :title="item.color"
                                    >
                                        <span x-show="selectedProduct.color === item.color" class="flex items-center justify-center h-full text-white text-xs sm:text-sm">
                                            ✓
                                        </span>
                                    </button>
                                </template>
                            </div>
                            <div class="mt-2 text-xs sm:text-sm text-gray-600">
                                Selected: <span x-text="selectedProduct.color" class="font-medium"></span>
                            </div>
                        </div>

                        <!-- Add to Cart Section -->
                        <div class="bg-gray-50 rounded-xl p-4 sm:p-6 space-y-4 sm:space-y-5 mt-4 sm:mt-6 border border-gray-200 hover:border-blue-300 transition-all duration-300 hover:shadow-md">
                            <div class="flex items-center justify-between">
                                <span class="font-medium text-gray-700 text-sm sm:text-base">Quantity</span>
                                <div class="flex items-center border border-gray-300 rounded-lg overflow-hidden">
                                    <button @click="quantity > 1 ? quantity-- : 1" class="px-3 sm:px-4 py-1 sm:py-2 text-gray-600 hover:bg-gray-100 transition-colors quantity-decrease" :disabled="isAddingToCart">-</button>
                                    <input type="text" x-model="quantity" class="w-10 sm:w-12 text-center border-l border-r focus:outline-none py-1 sm:py-2 text-sm quantity-input">
                                    <button @click="quantity++" class="px-3 sm:px-4 py-1 sm:py-2 text-gray-600 hover:bg-gray-100 transition-colors quantity-increase" :disabled="isAddingToCart">+</button>
                                </div>
                            </div>

                            <div class="flex gap-2 sm:gap-3">
                                <button @click.prevent="addToCart(selectedProduct.id, selectedProduct.product_name)" :disabled="isAddingToCart" class="flex-1 bg-primary text-white font-bold py-3 sm:py-4 px-4 sm:px-6 rounded-xl hover:bg-opacity-90 transition-all duration-300 hover:shadow-lg transform hover:-translate-y-0.5 add-to-cart">
                                    <template x-if="!isAddingToCart">
                                        <span><i class="fas fa-shopping-cart mr-1 sm:mr-2"></i> Add to Cart</span>
                                    </template>
                                    <template x-if="isAddingToCart">
                                        <span><i class="fas fa-spinner fa-spin mr-1 sm:mr-2"></i> Adding...</span>
                                    </template>
                                </button>
                                <button @click.prevent="toggleWishlist(selectedProduct.id)" class="p-3 sm:p-4 border border-gray-300 rounded-xl hover:bg-gray-50 transition-colors hover:border-blue-300" :class="{ 'bg-red-50 border-red-200': inWishlist }">
                                    <i class="fa-heart text-lg sm:text-xl transition-colors" :class="inWishlist ? 'fas text-red-500' : 'far text-gray-600 hover:text-red-500'"></i>
                                </button>
                            </div>

                            <!-- Buy Now Button -->
                            <button class="w-full bg-secondary text-white font-bold py-3 sm:py-4 px-4 sm:px-6 rounded-xl hover:bg-opacity-90 transition-colors transform hover:-translate-y-0.5">
                                <i class="fas fa-bolt mr-1 sm:mr-2"></i> Buy Now
                            </button>
                        </div>

                        <!-- Features -->
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4 mt-4 sm:mt-6">
                            <div class="flex items-center gap-2 sm:gap-3 p-3 bg-blue-50 rounded-lg">
                                <div class="w-8 sm:w-10 h-8 sm:h-10 bg-blue-100 rounded-full flex items-center justify-center">
                                    <i class="fas fa-shipping-fast text-blue-600"></i>
                                </div>
                                <div>
                                    <p class="font-medium text-xs sm:text-sm">Free Shipping</p>
                                    <p class="text-xs text-gray-500">Over ৳5000</p>
                                </div>
                            </div>
                            <div class="flex items-center gap-2 sm:gap-3 p-3 bg-green-50 rounded-lg">
                                <div class="w-8 sm:w-10 h-8 sm:h-10 bg-green-100 rounded-full flex items-center justify-center">
                                    <i class="fas fa-shield-alt text-green-600"></i>
                                </div>
                                <div>
                                    <p class="font-medium text-xs sm:text-sm">2 Year Warranty</p>
                                    <p class="text-xs text-gray-500">Full coverage</p>
                                </div>
                            </div>
                        </div>

                        <!-- Meta Info -->
                        <div class="text-xs sm:text-sm text-gray-500 space-y-2 sm:space-y-3 pt-4 border-t border-gray-200">
                            <div class="flex justify-between">
                                <span class="font-medium text-gray-700">SKU:</span>
                                <span x-text="selectedProduct.serial_no"></span>
                            </div>
                            <div class="flex justify-between">
                                <span class="font-medium text-gray-700">Category:</span>
                                <a :href="`/products?category=${selectedProduct.category_slug}`" class="text-blue-600 hover:underline" x-text="selectedProduct.category_name"></a>
                            </div>
                            <div class="flex justify-between">
                                <span class="font-medium text-gray-700">Delivery:</span>
                                <span>2-4 business days</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Product Description / Specs -->
            <div class="border-t border-gray-200 mt-6 sm:mt-8">
                <div class="flex border-b overflow-x-auto">
                    <button class="tab-button py-3 sm:py-4 px-4 sm:px-6 font-medium text-gray-500 hover:text-gray-700 border-b-2 border-blue-600 text-blue-600 text-sm sm:text-base" data-tab="description">
                        Description
                    </button>
                    <button class="tab-button py-3 sm:py-4 px-4 sm:px-6 font-medium text-gray-500 hover:text-gray-700 text-sm sm:text-base" data-tab="specifications">
                        Specifications
                    </button>
                    <button class="tab-button py-3 sm:py-4 px-4 sm:px-6 font-medium text-gray-500 hover:text-gray-700 text-sm sm:text-base" data-tab="reviews">
                        Reviews (15)
                    </button>
                </div>

                <div class="p-4 sm:p-6 md:p-8">
                    <!-- Description Tab -->
                    <div id="description-tab" class="tab-content transition-opacity duration-500">
                        <div class="prose max-w-none text-gray-700 text-sm sm:text-base">
                            <p class="text-base sm:text-lg">Discover the amazing features of the <strong><?php echo e($product->product_name); ?></strong>. This device is designed to provide a seamless and powerful user experience, combining elegant design with top-tier performance.</p>

                            <h3 class="text-lg sm:text-xl font-semibold mt-4 sm:mt-6 mb-2 sm:mb-3">Key Features:</h3>
                            <ul class="list-disc pl-4 sm:pl-6 space-y-2">
                                <li><strong>Premium Build:</strong> Crafted with high-quality materials for durability and style</li>
                                <li><strong>Advanced Technology:</strong> Incorporating the latest innovations for optimal performance</li>
                                <li><strong>User-Friendly:</strong> Intuitive design that's easy to use right out of the box</li>
                                <li><strong>Eco-Conscious:</strong> Manufactured with sustainable practices and materials</li>
                            </ul>

                            <h3 class="text-lg sm:text-xl font-semibold mt-4 sm:mt-6 mb-2 sm:mb-3">What's in the box?</h3>
                            <p>The package includes the <?php echo e($product->product_name); ?>, a charging cable, a user manual, and a warranty card. Everything you need to get started right away.</p>
                        </div>
                    </div>

                    <!-- Specifications Tab -->
                    <div id="specifications-tab" class="tab-content hidden transition-opacity duration-500">
                        <div class="prose max-w-none text-sm sm:text-base">
                            <h3 class="text-lg sm:text-xl font-semibold mb-3 sm:mb-4">Technical Specifications</h3>
                            <div class="bg-gray-50 rounded-xl p-4 sm:p-6 mt-3 sm:mt-4">
                                <div class="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
                                    <div class="flex justify-between py-2 sm:py-3 border-b border-gray-200">
                                        <span class="font-medium text-gray-700">Model</span>
                                        <span class="text-gray-600"><?php echo e($product->product_name); ?></span>
                                    </div>
                                    <div class="flex justify-between py-2 sm:py-3 border-b border-gray-200">
                                        <span class="font-medium text-gray-700">SKU</span>
                                        <span class="text-gray-600"><?php echo e($product->serial_no); ?></span>
                                    </div>
                                    <div class="flex justify-between py-2 sm:py-3 border-b border-gray-200">
                                        <span class="font-medium text-gray-700">Warranty</span>
                                        <span class="text-gray-600"><?php echo e($product->warranty_period ?? '1 Year'); ?></span>
                                    </div>
                                    <div class="flex justify-between py-2 sm:py-3 border-b border-gray-200">
                                        <span class="font-medium text-gray-700">Color</span>
                                        <span class="text-gray-600"><?php echo e(is_array($product->color) ? implode(', ', $product->color) : $product->color); ?></span>
                                    </div>
                                    <div class="flex justify-between py-2 sm:py-3 border-b border-gray-200">
                                        <span class="font-medium text-gray-700">Condition</span>
                                        <span class="text-gray-600"><?php echo e($product->condition); ?></span>
                                    </div>
                                    <div class="flex justify-between py-2 sm:py-3 border-b border-gray-200">
                                        <span class="font-medium text-gray-700">Manufacture Date</span>
                                        <span class="text-gray-600"><?php echo e($product->manufacture_date ? \Carbon\Carbon::parse($product->manufacture_date)->format('F Y') : 'N/A'); ?></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Reviews Tab -->
                    <div id="reviews-tab" class="tab-content hidden transition-opacity duration-500">
                        <div class="prose max-w-none text-sm sm:text-base">
                            <h3 class="text-lg sm:text-xl font-semibold mb-3 sm:mb-4">Customer Reviews</h3>
                            <div class="flex flex-col sm:flex-row items-start gap-4 sm:gap-6 my-4 sm:my-6">
                                <div class="text-center bg-gray-50 rounded-xl p-4 sm:p-6 w-full sm:w-auto">
                                    <div class="text-4xl sm:text-5xl font-bold text-gray-800">4.8</div>
                                    <div class="flex text-yellow-400 justify-center my-2">
                                        <?php for($i = 1; $i <= 5; $i++): ?>
                                            <i class="fas fa-star text-sm sm:text-base"></i>
                                        <?php endfor; ?>
                                    </div>
                                    <div class="text-gray-500 text-xs sm:text-sm">Based on 15 reviews</div>
                                </div>
                                <div class="flex-1">
                                    <button @click="showReviewForm = !showReviewForm" class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors text-sm sm:text-base">
                                        Write a Review
                                    </button>
                                </div>
                            </div>

                            <!-- Review Form -->
                            <div x-show="showReviewForm" x-transition.opacity.duration.500ms class="mt-4 sm:mt-6 bg-gray-50 p-4 sm:p-6 rounded-xl">
                                <h4 class="text-base sm:text-lg font-semibold mb-3">Submit Your Review</h4>
                                <div class="space-y-4">
                                    <div>
                                        <label class="block text-xs sm:text-sm font-medium text-gray-700">Rating</label>
                                        <div class="flex text-yellow-400">
                                            <template x-for="i in 5" :key="i">
                                                <button @click="selectedRating = i" :class="selectedRating >= i ? 'text-yellow-400' : 'text-gray-300'" class="text-lg sm:text-xl">
                                                    <i class="fas fa-star"></i>
                                                </button>
                                            </template>
                                        </div>
                                    </div>
                                    <div>
                                        <label for="review-comment" class="block text-xs sm:text-sm font-medium text-gray-700">Comment</label>
                                        <textarea id="review-comment" rows="4" class="w-full border border-gray-300 rounded-lg p-2 sm:p-3 focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm sm:text-base"></textarea>
                                    </div>
                                    <button class="bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors text-sm sm:text-base">Submit Review</button>
                                </div>
                            </div>

                            <div class="space-y-4 sm:space-y-6 mt-6 sm:mt-8">
                                <!-- Sample Review -->
                                <div class="border-b border-gray-200 pb-4 sm:pb-6">
                                    <div class="flex justify-between mb-2">
                                        <div class="font-semibold text-sm sm:text-base">John D.</div>
                                        <div class="text-xs sm:text-sm text-gray-500">2 weeks ago</div>
                                    </div>
                                    <div class="flex text-yellow-400 mb-2 sm:mb-3">
                                        <?php for($i = 1; $i <= 5; $i++): ?>
                                            <i class="fas fa-star text-xs sm:text-sm"></i>
                                        <?php endfor; ?>
                                    </div>
                                    <p class="text-gray-600 text-sm sm:text-base">This product exceeded my expectations. The quality is outstanding and it arrived sooner than expected. Highly recommended!</p>
                                </div>

                                <!-- Another sample review -->
                                <div class="border-b border-gray-200 pb-4 sm:pb-6">
                                    <div class="flex justify-between mb-2">
                                        <div class="font-semibold text-sm sm:text-base">Sarah M.</div>
                                        <div class="text-xs sm:text-sm text-gray-500">1 month ago</div>
                                    </div>
                                    <div class="flex text-yellow-400 mb-2 sm:mb-3">
                                        <?php for($i = 1; $i <= 5; $i++): ?>
                                            <i class="fas fa-star text-xs sm:text-sm"></i>
                                        <?php endfor; ?>
                                    </div>
                                    <p class="text-gray-600 text-sm sm:text-base">Great value for money. The product works perfectly and looks even better in person. Will definitely purchase from this seller again.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Floating Action Buttons -->
<div class="fixed bottom-4 sm:bottom-8 right-4 sm:right-8 z-50 flex flex-col gap-2 sm:gap-3">
    <button class="floating-action-btn bg-white text-gray-700 shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-110 group" x-data>
        <i class="fas fa-share-alt text-sm sm:text-base"></i>
        <span class="tooltip">Share Product</span>
    </button>
    <button @click.prevent="$dispatch('toggle-wishlist-float', { id: <?php echo e($product->id); ?> })" class="floating-action-btn bg-white text-gray-700 shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-110 group" x-data="{ inWishlist: <?php echo e(in_array($product->id, $wishlistProductIds ?? []) ? 'true' : 'false'); ?> }" @update-wishlist-float.window="inWishlist = $event.detail.inWishlist">
        <i class="fa-heart text-sm sm:text-base" :class="inWishlist ? 'fas text-red-500' : 'far'"></i>
        <span class="tooltip" x-text="inWishlist ? 'In Wishlist' : 'Add to Wishlist'"></span>
    </button>
    <button @click.prevent="$dispatch('add-to-cart-float', { id: <?php echo e($product->id); ?>, name: '<?php echo e(e($product->product_name)); ?>' })" class="floating-action-btn bg-primary text-white shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-110 animate-pulse group add-to-cart">
        <i class="fas fa-shopping-cart text-sm sm:text-base"></i>
        <span class="tooltip">Add to Cart</span>
    </button>
</div>
<?php $__env->stopSection(); ?>

<?php $__env->startPush('scripts'); ?>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js"></script> <!-- This script seems to be duplicated, I will remove one -->
<script>
    function productPageData() {
        // Helper to convert color names to hex codes for swatches
        const colorNameToHex = (colorName) => {
            const map = {
                'black': '#1e293b', 'white': '#ffffff', 'silver': '#94a3b8', 'gray': '#6b7280',
                'red': '#ef4444', 'blue': '#3b82f6', 'green': '#10b981', 'gold': '#facc15',
                'cyan': '#22d3ee', 'pink': '#f472b6', 'purple': '#8b5cf6', 'deep purple': '#6d28d9'
            };
            return map[colorName.toLowerCase()] || colorName.toLowerCase(); // Fallback to the color name itself
        };

        const productGroupData = <?php echo json_encode($productGroup ?? [], 15, 512) ?>;

        // Create a unique list of color variants from the product group
        const allItems = productGroupData.map(item => {
            return {
                id: item.id,
                product_name: item.product_name,
                color: item.color,
                colorHex: colorNameToHex(item.color),
                price: item.price,
                discount_price: item.discount_price,
                description: item.description,
                serial_no: item.serial_no,
                category_name: item.category_name,
                category_slug: item.category_slug,
                image: item.image || 'https://via.placeholder.com/500',
                gallery: (item.gallery || []).map(g => ({ ...g, image: g.image || 'https://via.placeholder.com/500' }))
            };
        }).filter((v, i, a) => a.findIndex(t => t.color === v.color) === i); // Ensure unique colors

        // Get the initial selected item from the controller.
        const initialColorItem = <?php echo json_encode($initialColorItem, 15, 512) ?>;

        // Find the specific item for the current product from the group, or build a fallback.
        let initialProduct = null;
        if (initialColorItem && initialColorItem.color) {
            // Ensure case-insensitive matching for Alpine.js as well
            const requestedColorLower = initialColorItem.color.toLowerCase();
            initialProduct = allItems.find(item => (item.color || '').toLowerCase() === requestedColorLower);
        }

        // If no specific color was requested or found, default to the first item in the group.
        if (!initialProduct && allItems.length > 0) {
            initialProduct = allItems[0];
        }

        if (!initialProduct) {
            const initialColor = <?php echo json_encode(is_array($product->color) ? ($product->color[0] ?? 'Default') : ($product->color ?? 'Default'), 15, 512) ?>;
            const mainImage = <?php echo json_encode($product->image ? Storage::url($product->image) : 'https://via.placeholder.com/500', 15, 512) ?>;

            initialProduct = {
                id: <?php echo json_encode($product->id, 15, 512) ?>,
                product_name: <?php echo json_encode($product->product_name, 15, 512) ?>,
                color: initialColor,
                colorHex: colorNameToHex(initialColor),
                price: <?php echo e($product->price ?? 0); ?>,
                discount_price: <?php echo e($product->discount_price ?? 0); ?>,
                description: <?php echo json_encode($product->description, 15, 512) ?>,
                serial_no: <?php echo json_encode($product->serial_no, 15, 512) ?>,
                category_name: <?php echo json_encode($product->category->name ?? 'Uncategorized', 15, 512) ?>,
                category_slug: <?php echo json_encode($product->category->slug ?? '', 15, 512) ?>,
                image: mainImage,
                gallery: allItems.length > 0 ? allItems[0].gallery : []
            };
        }

        return {
            // Zoom State
            isZoomed: false,
            zoomStyle: '',
            lensStyle: '',

            // State
            quantity: 1,
            isAddingToCart: false,
            inWishlist: <?php echo e(in_array($product->id, $wishlistProductIds ?? []) ? 'true' : 'false'); ?>,
            showReviewForm: false,
            selectedRating: 0,
            activeTab: 'images',
            mainImage: initialProduct.image,
            activeThumbnails: initialProduct.gallery,
            allGroupItems: allItems.length > 0 ? allItems : [initialProduct], // Ensure allGroupItems is never empty
            selectedProduct: initialProduct,

            init() {
                this.setupThreeJS();
            },

            selectProduct(item) {
                if (!item || this.selectedProduct.color === item.color) return;

                this.selectedProduct = item;
                this.mainImage = item.image || 'https://via.placeholder.com/500'; // Set the main image to the selected color's image
                this.activeThumbnails = item.gallery; // The thumbnails should be the full gallery
                this.resetZoom();
                this.animateSelection(this.$event.currentTarget);
            },

            changeMainImage(newImage) {
                this.mainImage = newImage;
                this.resetZoom();
            },

            toggleZoom() {
                this.isZoomed = !this.isZoomed;
                if (!this.isZoomed) {
                    this.zoomStyle = '';
                    this.lensStyle = '';
                }
            },

            // --- Zoom Logic ---

            handleZoom(event) {
                if (!this.isZoomed) return;

                const container = event.currentTarget;
                const img = container.querySelector('img');
                const rect = container.getBoundingClientRect();

                const x = event.clientX - rect.left;
                const y = event.clientY - rect.top;

                const xPercent = (x / rect.width) * 100;
                const yPercent = (y / rect.height) * 100;

                this.zoomStyle = `transform: scale(2); transform-origin: ${xPercent}% ${yPercent}%;`;

                const lensSize = 80;
                const lensX = x - lensSize / 2;
                const lensY = y - lensSize / 2;
                this.lensStyle = `
                    width: ${lensSize}px;
                    height: ${lensSize}px;
                    top: ${lensY}px;
                    left: ${lensX}px;
                `;
            },

            resetZoom() {
                if (this.isZoomed) {
                    this.zoomStyle = 'transform: scale(2); transform-origin: center center;';
                    this.lensStyle = '';
                }
            },

            // --- 3D Viewer Logic ---

            setupThreeJS() {
                if (this.activeTab !== '3d') return;

                const canvas = document.getElementById('threejs-canvas');
                if (!canvas) return;

                const scene = new THREE.Scene();
                const camera = new THREE.PerspectiveCamera(75, canvas.clientWidth / canvas.clientHeight, 0.1, 1000);
                const renderer = new THREE.WebGLRenderer({ canvas, alpha: true });
                renderer.setSize(canvas.clientWidth, canvas.clientHeight);

                // Add orbit controls
                const controls = new THREE.OrbitControls(camera, renderer.domElement);
                controls.enableDamping = true;
                controls.dampingFactor = 0.05;

                // Simple cube as a placeholder
                const geometry = new THREE.BoxGeometry(1, 1, 1);
                const material = new THREE.MeshStandardMaterial({ color: 0x3b82f6 });
                const cube = new THREE.Mesh(geometry, material);
                scene.add(cube);

                // Add lighting
                const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
                scene.add(ambientLight);
                const pointLight = new THREE.PointLight(0xffffff, 0.5);
                pointLight.position.set(5, 5, 5);
                scene.add(pointLight);

                camera.position.z = 2;

                const animate = () => {
                    requestAnimationFrame(animate);
                    controls.update();
                    renderer.render(scene, camera);
                };
                animate();
            },

            // --- UI Animations ---

            animateSelection(button) {
                button.animate([
                    { transform: 'scale(1)' },
                    { transform: 'scale(1.2)' },
                    { transform: 'scale(1)' }
                ], {
                    duration: 300,
                    easing: 'ease-in-out'
                });
            },

            // --- Product Actions ---

            toggleWishlist(productId) {
                // Optimistically update UI
                this.inWishlist = !this.inWishlist;
                window.dispatchEvent(new CustomEvent('update-wishlist-float', { detail: { inWishlist: this.inWishlist }}));

                fetch(`/wishlist/toggle/${productId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name=\'csrf-token\']').getAttribute('content'),
                        'Accept': 'application/json',
                    }
                })
                .then(response => {
                    if (response.status === 401) {
                        window.location.href = '<?php echo e(route('login')); ?>';
                        return Promise.reject('Unauthenticated');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        showNotification(data.message, 'success');
                        const wishlistCountEl = document.getElementById('wishlist-count');
                        if (wishlistCountEl) wishlistCountEl.textContent = data.wishlistCount;
                    } else {
                        // Revert on failure if the selected product hasn't changed
                        this.inWishlist = !this.inWishlist;
                        window.dispatchEvent(new CustomEvent('update-wishlist-float', { detail: { inWishlist: this.inWishlist }}));
                    }
                })
                .catch(error => {
                    if (error !== 'Unauthenticated') {
                        this.inWishlist = !this.inWishlist;
                        window.dispatchEvent(new CustomEvent('update-wishlist-float', { detail: { inWishlist: this.inWishlist }}));
                    }});
            },
            addToCart(productId, productName) {
                this.isAddingToCart = true;
                const quantity = this.quantity || 1;
                const variantId = `${productId}-${this.selectedProduct.color.replace(/\s+/g, '-')}`;

                fetch(`/cart/add/${productId}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': document.querySelector('meta[name=\'csrf-token\']').getAttribute('content'),
                        'Accept': 'application/json',
                    },
                    body: JSON.stringify({
                        id: productId, // Main product ID
                        quantity: quantity,
                        color: this.selectedProduct.color,
                        // Pass the relative path for the backend
                        image: this.mainImage.replace('<?php echo e(config('app.url')); ?>/storage/', '')
                    })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        showNotification(`Added '${productName}' to cart!`, 'success', this.selectedProduct.image);
                        const cartCountEl = document.getElementById('cart-count');
                        if (cartCountEl) {
                            cartCountEl.textContent = data.cartCount;
                            cartCountEl.animate([{ transform: 'scale(1)' }, { transform: 'scale(1.3)' }, { transform: 'scale(1)' }], { duration: 300 });
                        }
                    } else {
                        showNotification(data.message || 'Could not add to cart.', 'error');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showNotification('An error occurred.', 'error');
                })
                .finally(() => {
                    this.isAddingToCart = false;
                });
            }
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        // Tab functionality
        // This remains vanilla JS as it's simple and doesn't need reactive state.
        const tabButtons = document.querySelectorAll('[data-tab]');
        const tabContents = document.querySelectorAll('.tab-content');

        tabButtons.forEach(button => {
            button.addEventListener('click', () => {
                const tabId = button.getAttribute('data-tab');

                // Update active tab button
                tabButtons.forEach(btn => {
                    btn.classList.remove('border-blue-600', 'text-blue-600');
                    btn.classList.add('text-gray-500');
                });
                button.classList.add('border-blue-600', 'text-blue-600');
                button.classList.remove('text-gray-500');

                // Show active tab content with animation
                tabContents.forEach(content => {
                    content.classList.add('hidden', 'opacity-0');
                });
                const activeTab = document.getElementById(`${tabId}-tab`);
                activeTab.classList.remove('hidden');
                setTimeout(() => {
                    activeTab.classList.remove('opacity-0');
                }, 50);
            });
        });

        // Notification function
        window.showNotification = function(message, type = 'info') {
            // Remove any existing notifications
            document.querySelectorAll('.toast-notification').forEach(n => n.remove());

            const notification = document.createElement('div');
            notification.className = 'toast-notification fixed top-5 right-5 w-full max-w-sm bg-white shadow-2xl rounded-xl p-4 border-l-4 z-[1000]';

            const styles = {
                success: { border: 'border-green-500', icon: 'fa-check-circle', text: 'text-green-500' },
                error: { border: 'border-red-500', icon: 'fa-exclamation-circle', text: 'text-red-500' },
                info: { border: 'border-blue-500', icon: 'fa-info-circle', text: 'text-blue-500' }
            };

            const style = styles[type] || styles.info;

            notification.classList.add(style.border);
            notification.innerHTML = `
                <div class="flex items-start gap-4"
                    <i class="fas ${style.icon} ${style.text} text-2xl mt-1"></i>
                    <div class="flex-1">
                        <p class="font-bold text-gray-800">${type.charAt(0).toUpperCase() + type.slice(1)}</p>
                        <p class="text-sm text-gray-600">${message}</p>
                    </div>
                    <button class="v-alert-close text-gray-400 hover:text-gray-600">&times;</button>
                </div>
                <div class="absolute bottom-0 left-0 h-1 bg-gray-200 rounded-bl-lg">
                    <div class="h-1 ${style.border.replace('border', 'bg')} rounded-bl-lg" style="width: 100%; animation: progress 4s linear forwards;"></div>
                </div>
            `;

            document.body.appendChild(notification);
            notification.style.animation = 'toast-in 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards';

            const close = () => {
                notification.style.animation = 'toast-out 0.5s ease-in forwards';
                notification.addEventListener('animationend', () => notification.remove(), { once: true });
            };

            const timer = setTimeout(close, 4000);

            notification.querySelector('.v-alert-close').addEventListener('click', () => {
                clearTimeout(timer);
                close();
            });
        }
    });
</script>

<style>
    .tooltip {
        position: absolute;
        right: 100%;
        top: 50%;
        transform: translateY(-50%);
        background: rgba(0, 0, 0, 0.8);
        color: white;
        padding: 0.4rem 0.6rem;
        border-radius: 0.375rem;
        font-size: 0.75rem;
        white-space: nowrap;
        margin-right: 0.5rem;
        opacity: 0;
        pointer-events: none;
        transition: opacity 0.3s ease;
    }

    .group:hover .tooltip {
        opacity: 1;
    }

    .floating-action-btn {
        width: 44px;
        height: 44px;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        position: relative;
        transition: all 0.3s ease;
    }

    @media (min-width: 640px) {
        .floating-action-btn {
            width: 56px;
            height: 56px;
        }
        .tooltip {
            padding: 0.5rem 0.75rem;
            font-size: 0.875rem;
        }
    }

    .tab-content {
        transition: opacity 0.5s ease;
    }

    .tab-content.hidden {
        opacity: 0;
    }

    /* Toast Animations */
    @keyframes toast-in {
        from { transform: translateX(110%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    @keyframes toast-out {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(110%); opacity: 0; }
    }
    @keyframes progress {
        from { width: 100%; }
        to { width: 0%; }
    }
</style>

<?php $__env->stopPush(); ?>

<?php echo $__env->make('frontend.layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\xampp\htdocs\E-Product-Verify-Auth-Application-5\resources\views\frontend\pages\show.blade.php ENDPATH**/ ?>