@extends('frontend.layouts.app')

@section('title', 'Compare Products - NewTech')

@section('content')
<!-- Page Title -->
<div class="bg-gradient-to-r from-blue-50 to-indigo-100 py-12 px-4 border-b border-gray-200">
    <div class="container mx-auto max-w-7xl">
        <nav class="mb-4" aria-label="breadcrumb">
            <ol class="flex items-center space-x-2 text-sm text-gray-600">
                <li><a href="{{ route('home') }}" class="hover:text-blue-600 transition-colors duration-200">Home</a></li>
                <li><span class="mx-2">/</span></li>
                <li class="font-semibold text-gray-800" aria-current="page">Compare</li>
            </ol>
        </nav>
        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between">
            <div>
                <h1 class="text-4xl font-bold text-gray-900 mb-3">Compare Products</h1>
                <p class="text-gray-600 text-lg">Side-by-side comparison of your selected products.</p>
            </div>
            @if(!$products->isEmpty())
            <div class="mt-4 sm:mt-0 flex items-center space-x-3">
                <div class="bg-white rounded-lg px-4 py-2 shadow-soft">
                    <span class="text-sm text-gray-600">Products:</span>
                    <span class="font-bold text-primary-600 ml-1" id="product-count">{{ $products->count() }}</span>
                </div>
                <button id="clear-compare-list" class="v-btn v-btn-danger-outline group text-sm">
                    <i class="fas fa-times mr-2 transform group-hover:rotate-90 transition-transform"></i> Clear All
                </button>
            </div>
            @endif
        </div>
    </div>
</div>

<!-- Main Content -->
<section class="py-12 px-4 bg-gray-50">
    <div class="container mx-auto max-w-7xl">
        @if($products->isEmpty())
        <!-- Empty State -->
        <div id="empty-state" class="bg-white rounded-2xl shadow-lg p-8 text-center border border-gray-100 transform hover:shadow-xl transition-shadow duration-300">
            <div class="w-24 h-24 bg-gradient-to-br from-blue-100 to-indigo-100 rounded-full flex items-center justify-center mx-auto mb-6">
                <i class="fas fa-exchange-alt text-blue-500 text-4xl pulse-animation"></i>
            </div>
            <h2 class="text-2xl font-bold text-gray-800 mb-3">Your Compare List is Empty</h2>
            <p class="text-gray-600 mb-8 max-w-md mx-auto">You haven't added any products to compare yet. Browse our products and add them for a side-by-side view.</p>
            <a href="{{ route('products.index') }}" class="v-btn v-btn-primary">
                <i class="fas fa-shopping-bag mr-2"></i> Start Shopping
            </a>
        </div>
        <!-- Suggested Products -->
        <div class="mt-12">
            <h3 class="text-xl font-bold text-gray-800 mb-6 text-center">Popular Products You Might Like</h3>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
                @foreach($suggestedProducts as $suggested)
                <div class="compare-card product-card p-5 text-center">
                    <div class="w-32 h-32 mx-auto mb-4 bg-gray-100 rounded-lg flex items-center justify-center">
                        <img src="{{ $suggested->image ? asset('storage/' . $suggested->image) : 'https://via.placeholder.com/150' }}" alt="{{ $suggested->product_name }}" class="h-full w-full object-contain">
                    </div>
                    <h4 class="font-semibold text-gray-800 mb-2">{{ $suggested->product_name }}</h4>
                    <p class="text-gray-600 text-sm mb-3">{{ Str::limit($suggested->description, 50) }}</p>
                    <div class="text-primary-600 font-bold mb-4">
                        @if($suggested->discount_price)
                            ৳{{ number_format($suggested->discount_price) }}
                            <span class="text-xs text-gray-500 line-through">৳{{ number_format($suggested->price) }}</span>
                        @else
                            ৳{{ number_format($suggested->price) }}
                        @endif
                    </div>
                    <button class="v-btn v-btn-primary w-full add-to-compare" data-product-id="{{ $suggested->id }}">
                        <i class="fas fa-plus mr-2"></i> Add to Compare
                    </button>
                </div>
                @endforeach
            </div>
        </div>
        @else
        <!-- Comparison Table -->
        <div id="comparison-table" class="fade-in">
            <!-- Summary Cards -->
            @php
                $effectivePrices = $products->mapWithKeys(fn($p) => [$p->id => $p->discount_price ?? $p->price]);
                $minPrice = $effectivePrices->min();
                $bestBudgetId = $effectivePrices->search($minPrice);
                $bestBudget = $products->find($bestBudgetId);
                $maxPerformance = $products->sortByDesc(fn($p) => $p->performance_score ?? 0)->first(); // Assuming a performance_score field
                $bestValue = $products->sortBy(fn($p) => $p->value_score ?? 0)->first(); // Assuming a value_score field
            @endphp
            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
                <div class="compare-card p-5 text-center feature-highlight text-white">
                    <i class="fas fa-trophy text-3xl mb-3"></i>
                    <h3 class="font-bold text-lg mb-1">Best Value</h3>
                    <p class="text-blue-100">{{ $bestValue->product_name ?? 'N/A' }}</p>
                </div>
                <div class="compare-card p-5 text-center">
                    <i class="fas fa-bolt text-yellow-500 text-3xl mb-3"></i>
                    <h3 class="font-bold text-lg mb-1">Best Performance</h3>
                    <p class="text-gray-600">{{ $maxPerformance->product_name ?? 'N/A' }}</p>
                </div>
                <div class="compare-card p-5 text-center">
                    <i class="fas fa-dollar-sign text-green-500 text-3xl mb-3"></i>
                    <h3 class="font-bold text-lg mb-1">Best Budget</h3>
                    <p class="text-gray-600">{{ $bestBudget->product_name ?? 'N/A' }}</p>
                </div>
            </div>
            <!-- Comparison Table -->
            <div class="bg-white rounded-2xl shadow-lg overflow-hidden border border-gray-100 sticky-compare">
                @php
                    if (!function_exists('generateStarRating')) {
                        function generateStarRating($rating) {
                            if ($rating === null) {
                                $rating = 0;
                            }
                            $stars = '<span class="sr-only">Rating: ' . $rating . ' out of 5</span>';
                            $fullStars = floor($rating);
                            $hasHalfStar = ($rating - $fullStars) >= 0.5;
                            
                            for ($i = 0; $i < $fullStars; $i++) {
                                $stars .= '<i class="fas fa-star text-yellow-400 text-xs"></i>';
                            }
                    
                            if ($hasHalfStar) {
                                $stars .= '<i class="fas fa-star-half-alt text-yellow-400 text-xs"></i>';
                            }
                    
                            $emptyStars = 5 - ceil($rating);
                            for ($i = 0; $i < $emptyStars; $i++) {
                                $stars .= '<i class="far fa-star text-yellow-400 text-xs"></i>';
                            }
                            return $stars;
                        }
                    }
                @endphp
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200 border-collapse" id="compare-table" role="grid" aria-label="Product comparison table">
                        <thead class="bg-gray-50/75 backdrop-blur-sm z-10" id="compare-header">
                            <tr>
                                <th scope="col" class="px-6 py-4 text-left text-sm font-semibold text-gray-900 sticky left-0 bg-gray-50/75 backdrop-blur-sm z-20">
                                    <div class="flex items-center">
                                        <span>Feature</span>
                                        <i class="fas fa-info-circle ml-2 text-gray-400" title="Hover over rows for details"></i>
                                    </div>
                                </th>
                                @foreach($products as $product)
                                <th scope="col" class="px-6 py-4 text-center text-xs font-medium text-gray-500 uppercase tracking-wider relative group min-w-[200px]" data-product-column="{{ $product->id }}">
                                    <div class="flex flex-col items-center gap-2 w-full">
                                        <a href="{{ route('products.show', $product->id) }}" class="w-16 h-16 rounded-lg bg-gray-100 flex items-center justify-center mb-2 hover:scale-105 transition-transform">
                                            <img src="{{ $product->image ? asset('storage/' . $product->image) : 'https://via.placeholder.com/150' }}" alt="{{ $product->product_name }}" class="h-full w-full object-contain">
                                        </a>
                                        <a href="{{ route('products.show', $product->id) }}" class="font-semibold text-gray-700 hover:text-blue-600 transition-colors text-sm">{{ $product->product_name }}</a>
                                        <div class="flex items-center mt-1">
                                            {!! generateStarRating($product->rating) !!}
                                            <span class="text-xs text-gray-500 ml-1">{{ $product->rating }}</span>
                                        </div>
                                        <button class="absolute top-2 right-2 w-6 h-6 bg-gray-200 text-gray-500 rounded-full flex items-center justify-center hover:bg-red-500 hover:text-white transition-all duration-200 opacity-50 group-hover:opacity-100 remove-from-compare" data-product-id="{{ $product->id }}" title="Remove from compare" aria-label="Remove {{ $product->product_name }} from compare">
                                            <i class="fas fa-times text-xs"></i>
                                        </button>
                                    </div>
                                </th>
                                @endforeach
                            </tr>
                        </thead>
                        <tbody class="bg-white divide-y divide-gray-200" id="compare-body">
                            <!-- Image -->
                            <tr class="compare-row">
                                <th scope="row" class="px-6 py-4 text-left text-sm font-medium text-gray-900 sticky left-0 bg-white z-10 whitespace-nowrap">Image</th>
                                @foreach($products as $product)
                                <td class="px-6 py-4 text-center" data-product-column="{{ $product->id }}">
                                    <div class="flex justify-center">
                                        <img class="h-24 w-24 rounded-md object-contain p-1 border border-gray-200" src="{{ $product->image ? asset('storage/' . $product->image) : 'https://via.placeholder.com/150' }}" alt="{{ $product->product_name }}">
                                    </div>
                                </td>
                                @endforeach
                            </tr>
                            <!-- Price -->
                            <tr class="compare-row bg-gray-50">
                                <th scope="row" class="px-6 py-4 text-left text-sm font-medium text-gray-900 sticky left-0 bg-gray-50 z-10 whitespace-nowrap">Price</th>
                                @foreach($products as $product)
                                <td class="px-6 py-4 text-center" data-product-column="{{ $product->id }}">
                                    @if($product->discount_price)
                                    <div class="flex flex-col items-center">
                                        <span class="text-lg font-bold text-red-600">৳{{ number_format($product->discount_price) }}</span>
                                        <span class="text-sm text-gray-500 line-through">৳{{ number_format($product->price) }}</span>
                                        <span class="text-xs bg-red-100 text-red-800 px-2 py-1 rounded-full mt-1">Save ৳{{ number_format($product->price - $product->discount_price) }}</span>
                                    </div>
                                    @else
                                    <div class="text-lg text-gray-900 font-bold">৳{{ number_format($product->price) }}</div>
                                    @endif
                                </td>
                                @endforeach
                            </tr>
                            <!-- Availability -->
                            <tr class="compare-row">
                                <th scope="row" class="px-6 py-4 text-left text-sm font-medium text-gray-900 sticky left-0 bg-white z-10 whitespace-nowrap">Availability</th>
                                @foreach($products as $product)
                                <td class="px-6 py-4 text-center" data-product-column="{{ $product->id }}">
                                    <span @class([
                                        'px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full',
                                        'bg-green-100 text-green-800' => $product->in_stock,
                                        'bg-red-100 text-red-800' => !$product->in_stock,
                                    ])>
                                        {{ $product->in_stock ? 'In Stock' : 'Out of Stock' }}
                                    </span>
                                </td>
                                @endforeach
                            </tr>
                            <!-- Description -->
                            <tr class="compare-row bg-gray-50">
                                <th scope="row" class="px-6 py-4 text-left text-sm font-medium text-gray-900 sticky left-0 bg-gray-50 z-10 whitespace-nowrap">Description</th>
                                @foreach($products as $product)
                                <td class="px-6 py-4 text-sm text-gray-600 min-w-[200px] text-left" data-product-column="{{ $product->id }}">{{ Str::limit($product->description, 150) }}</td>
                                @endforeach
                            </tr>
                            <!-- Specs (Dynamic) -->
                            @php
                                $specsToShow = [
                                    'quality' => 'Quality',
                                    'distributor_name' => 'Distributor',
                                    'warranty_period' => 'Warranty'
                                ];
                            @endphp
                            @foreach($specsToShow as $specKey => $specName)
                                @php
                                    // Check if at least one product has this spec
                                    $hasSpec = $products->contains(fn($p) => !empty($p->$specKey));
                                @endphp
                                @if($hasSpec)
                                <tr class="compare-row">
                                    <th scope="row" class="px-6 py-4 text-left text-sm font-medium text-gray-900 sticky left-0 bg-white z-10 whitespace-nowrap">{{ $specName }}</th>
                                    @foreach($products as $product)
                                    <td class="px-6 py-4 text-center" data-product-column="{{ $product->id }}">{{ $product->$specKey ?? 'N/A' }}</td>
                                    @endforeach
                                </tr>
                                @endif
                            @endforeach
                            <!-- Actions -->
                            <tr class="compare-row">
                                <th scope="row" class="px-6 py-4 text-left text-sm font-medium text-gray-900 sticky left-0 bg-white z-10 whitespace-nowrap">Actions</th>
                                @foreach($products as $product)
                                <td class="px-6 py-4 text-center" data-product-column="{{ $product->id }}">
                                    <div class="flex flex-col items-center space-y-2">
                                        <button class="v-btn v-btn-primary add-to-cart {{ !$product->in_stock ? 'opacity-50 cursor-not-allowed' : '' }}"
                                                data-product-id="{{ $product->id }}"
                                                data-product-name="{{ e($product->product_name) }}"
                                                {{ !$product->in_stock ? 'disabled' : '' }}>
                                            <span><i class="fas fa-shopping-cart mr-2"></i> Add to Cart</span>
                                        </button>                                        <button class="v-btn v-btn-secondary text-sm add-to-wishlist"
                                                data-product-id="{{ $product->id }}">
                                            <i class="far fa-heart mr-2"></i> Add to Wishlist
                                        </button>
                                    </div>
                                </td>
                                @endforeach
                            </tr>
                        </tbody>
                    </table>
                </div>
                <!-- Scroll Indicator for Mobile -->
                <div class="md:hidden py-3 bg-gray-50 text-center text-sm text-gray-500">
                    <i class="fas fa-arrow-left scroll-indicator mr-2"></i>
                    Scroll horizontally to compare
                </div>
            </div>
            <!-- Quick Actions -->
            {{-- <div class="mt-8 flex flex-wrap gap-3 justify-center">
                <button class="v-btn v-btn-secondary">
                    <i class="fas fa-download mr-2"></i> Export Comparison
                </button>
                <button class="v-btn v-btn-secondary">
                    <i class="fas fa-share-alt mr-2"></i> Share Comparison
                </button>
                <button class="v-btn v-btn-secondary">
                    <i class="fas fa-print mr-2"></i> Print Comparison
                </button>
            </div> --}}
        </div>
        @endif
    </div>
</section>

<!-- Floating Action Button -->
<div class="fixed bottom-6 right-6 z-50">
    <button class="v-btn v-btn-primary rounded-full w-14 h-14 floating-action" id="add-product-btn" aria-label="Add new product to compare">
        <i class="fas fa-plus text-lg"></i>
    </button>
</div>

<!-- Add Product Modal -->
<div id="add-product-modal" class="fixed inset-0 bg-gray-600 bg-opacity-50 hidden flex items-center justify-center z-50">
    <div class="bg-white rounded-lg p-6 w-full max-w-md">
        <h2 class="text-xl font-bold mb-4">Add Product to Compare</h2>
        <select id="product-select" class="w-full p-2 border rounded mb-4">
            <option value="">Select a product</option>
            @foreach($allProducts as $product)
            <option value="{{ $product->id }}">{{ $product->product_name }}</option>
            @endforeach
        </select>
        <div class="flex justify-end gap-2">
            <button class="v-btn v-btn-secondary" id="cancel-modal">Cancel</button>
            <button class="v-btn v-btn-primary" id="add-product">Add</button>
        </div>
    </div>
</div>
@endsection

@push('styles')
<style>
    .v-btn {
        @apply px-4 py-2 rounded-lg font-medium transition-all duration-300 flex items-center justify-center;
    }

    .v-btn-secondary {
        background-color: rgb(var(--color-secondary)) !important;
        @apply text-white hover:bg-opacity-90 shadow-sm hover:shadow-md;
    }
    .v-btn-danger-outline {
        @apply border border-danger-500 text-danger-500 hover:bg-danger-500 hover:text-white;
    }
    .compare-card {
        @apply bg-white rounded-xl shadow-soft border border-gray-100 overflow-hidden transition-all duration-300 hover:shadow-medium;
    }
    .feature-highlight {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    }
    .sticky-compare {
        position: sticky;
        top: 80px;
        z-index: 10;
    }
    .floating-action {
        box-shadow: 0 10px 25px -5px rgba(59, 130, 246, 0.4);
    }
    .pulse-animation {
        animation: pulse 2s infinite;
    }
    @keyframes pulse {
        0% { transform: scale(1); }
        50% { transform: scale(1.05); }
        100% { transform: scale(1); }
    }
    .fade-in {
        animation: fadeIn 0.5s ease-in;
    }
    @keyframes fadeIn {
        from { opacity: 0; transform: translateY(10px); }
        to { opacity: 1; transform: translateY(0); }
    }
    .compare-row {
        transition: all 0.3s ease;
    }
    .compare-row:hover {
        @apply bg-blue-50;
    }
    .product-card {
        transition: all 0.3s ease;
    }
    .product-card:hover {
        transform: translateY(-5px);
    }
    .scroll-indicator {
        animation: bounce 2s infinite;
    }
    @keyframes bounce {
        0%, 20%, 50%, 80%, 100% {transform: translateX(0);}
        40% {transform: translateX(-10px);}
        60% {transform: translateX(-5px);}
    }
    .compare-row td, .compare-row th {
        transition: background-color 0.2s ease-in-out, opacity 0.4s ease, transform 0.4s ease, padding 0.4s ease;
    }
    .compare-row:hover td, .compare-row:hover th {
        background-color: #f0f5ff !important;
    }
    [data-product-column] {
        transition: opacity 0.4s ease, transform 0.4s ease;
    }
    #compare-table {
        transition: opacity 0.4s ease, transform 0.4s ease;
    }
    .v-btn.add-to-cart, .v-btn.add-to-wishlist {
        width: 150px; /* Set a fixed width for consistency */
        font-size: 0.875rem; /* text-sm */
        padding-top: 0.5rem; /* py-2 */
        padding-bottom: 0.5rem; /* py-2 */
    }
</style>
@endpush

@push('scripts')
<script>
// Helper function to generate star ratings
function generateStarRating(rating) {
    let stars = `<span class="sr-only">Rating: ${rating} out of 5</span>`;
    const fullStars = Math.floor(rating);
    const hasHalfStar = rating % 1 !== 0;
    for (let i = 0; i < fullStars; i++) {
        stars += '<i class="fas fa-star text-yellow-400 text-xs"></i>';
    }
    if (hasHalfStar) {
        stars += '<i class="fas fa-star-half-alt text-yellow-400 text-xs"></i>';
    }
    const emptyStars = 5 - Math.ceil(rating);
    for (let i = 0; i < emptyStars; i++) {
        stars += '<i class="far fa-star text-yellow-400 text-xs"></i>';
    }
    return stars;
}

document.addEventListener('DOMContentLoaded', function() {
    // Adjust sticky header top position based on main navigation
    const mainNav = document.getElementById('main-nav');
    const compareHeader = document.getElementById('compare-header');
    if (mainNav && compareHeader) {
        const observer = new ResizeObserver(entries => {
            const navHeight = entries[0].target.offsetHeight;
            compareHeader.style.top = `${navHeight}px`;
        });
        observer.observe(mainNav);
    }

    // Remove from compare
    document.body.addEventListener('click', function(event) {
        const removeButton = event.target.closest('.remove-from-compare');
        if (!removeButton) return;

        event.preventDefault();
        const productId = removeButton.dataset.productId;
        const columns = document.querySelectorAll(`[data-product-column="${productId}"]`);

        // Optimistic UI update: animate and hide
        columns.forEach(col => {
            col.style.opacity = '0';
            col.style.transform = 'translateY(-20px)';
        });

        let url = "{{ route('compare.remove', ['product' => 'PLACEHOLDER']) }}";
        url = url.replace('PLACEHOLDER', productId);
        fetch(url, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                'Accept': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification(data.message, 'success');
                const compareCountEl = document.getElementById('compare-count');
                if (compareCountEl) compareCountEl.textContent = data.compareCount;
                window.dispatchEvent(new CustomEvent('compare-updated', { detail: { productId: productId, status: 'removed' } }));

                setTimeout(() => {
                    const table = document.getElementById('compare-table');
                    columns.forEach(col => col.remove());
                    const productCount = document.getElementById('product-count');
                    if (productCount) productCount.textContent = parseInt(productCount.textContent) - 1;
                    if (table && table.querySelectorAll('th[data-product-column]').length === 0) {
                        window.location.reload();
                    }
                }, 400);
            } else {
                showNotification(data.message || 'Could not remove item.', 'error');
                columns.forEach(col => {
                    col.style.opacity = '1';
                    col.style.transform = 'translateY(0)';
                });
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('An error occurred. Please try again.', 'error');
            columns.forEach(col => {
                col.style.opacity = '1';
                col.style.transform = 'translateY(0)';
            });
        });
    });

    // Clear all compare items
    const clearCompareBtn = document.getElementById('clear-compare-list');
    if (clearCompareBtn) {
        clearCompareBtn.addEventListener('click', function() {
            if (!confirm('Are you sure you want to remove all products from the compare list?')) {
                return;
            }

            const table = document.getElementById('compare-table');
            if (table) {
                table.style.opacity = '0';
                table.style.transform = 'scale(0.95)';
            }

            fetch("{{ route('compare.clear') }}", {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Accept': 'application/json',
                },
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification(data.message, 'success');
                    setTimeout(() => {
                        window.location.reload();
                    }, 400);
                } else {
                    showNotification(data.message || 'Could not clear the list.', 'error');
                    if (table) {
                        table.style.opacity = '1';
                        table.style.transform = 'scale(1)';
                    }
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('An error occurred.', 'error');
                if (table) {
                    table.style.opacity = '1';
                    table.style.transform = 'scale(1)';
                }
            });
        });
    }

    // Add to cart
    document.body.addEventListener('click', function(event) {
        const button = event.target.closest('.add-to-cart');
        if (!button) return;

        const productId = button.dataset.productId;
        const productName = button.dataset.productName;
        const buttonSpan = button.querySelector('span') || button;

        buttonSpan.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i> Adding...';
        button.disabled = true;

        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({ quantity: 1 })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification(`Added "${productName}" to cart!`, 'success');
                const cartCountEl = document.getElementById('cart-count');
                if (cartCountEl) cartCountEl.textContent = data.cartCount;
                buttonSpan.innerHTML = '<i class="fas fa-check mr-2"></i> Added';
                setTimeout(() => { // Revert button text after 2 seconds
                    buttonSpan.innerHTML = '<i class="fas fa-shopping-cart mr-2"></i> Add to Cart';
                    button.disabled = false;
                }, 2000);
            } else {
                showNotification(data.message || 'Could not add to cart.', 'error');
                buttonSpan.innerHTML = '<i class="fas fa-shopping-cart mr-2"></i> Add to Cart';
                button.disabled = false;
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('An error occurred.', 'error');
            buttonSpan.innerHTML = '<i class="fas fa-shopping-cart mr-2"></i> Add to Cart';
            button.disabled = false;
        });
    });

    // Add to wishlist
    document.body.addEventListener('click', function(event) {
        const button = event.target.closest('.add-to-wishlist');
        if (!button) return;

        const productId = button.dataset.productId;
        const icon = button.querySelector('i');

        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 = '{{ 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;

                // Toggle icon state
                if (data.status === 'added') {
                    icon.classList.remove('far');
                    icon.classList.add('fas', 'text-red-500');
                } else {
                    icon.classList.remove('fas', 'text-red-500');
                    icon.classList.add('far');
                }
            } else {
                showNotification(data.message || 'Could not update wishlist.', 'error');
            }
        }).catch(error => {
            if (error !== 'Unauthenticated') showNotification('An error occurred.', 'error');
        });
    });

    // Add to compare from suggested products
    document.body.addEventListener('click', function(event) {
        const button = event.target.closest('.add-to-compare');
        if (!button) return;

        const productId = button.dataset.productId;
        let url = "{{ route('compare.add', ['product' => 'PLACEHOLDER']) }}";
        url = url.replace('PLACEHOLDER', productId);

        fetch(url, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                'Accept': 'application/json',
            },
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification(data.message, 'success');
                const compareCountEl = document.getElementById('compare-count');
                if (compareCountEl) compareCountEl.textContent = data.compareCount;
                window.dispatchEvent(new CustomEvent('compare-updated', { detail: { productId: productId, status: 'added' } }));
                window.location.reload(); // Reload to reflect updated compare list
            } else {
                showNotification(data.message || 'Could not add to compare.', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('An error occurred.', 'error');
        });
    });

    // Add product modal
    const modal = document.getElementById('add-product-modal');
    const addProductBtn = document.getElementById('add-product-btn');
    const cancelModal = document.getElementById('cancel-modal');
    const addProduct = document.getElementById('add-product');
    const productSelect = document.getElementById('product-select');

    if (addProductBtn) {
        addProductBtn.addEventListener('click', () => {
            modal.classList.remove('hidden');
        });
    }

    if (cancelModal) {
        cancelModal.addEventListener('click', () => {
            modal.classList.add('hidden');
        });
    }

    if (addProduct) {
        addProduct.addEventListener('click', () => {
            const productId = productSelect.value;
            if (!productId) {
                showNotification('Please select a product', 'error');
                return;
            }

            let url = "{{ route('compare.add', ['product' => 'PLACEHOLDER']) }}";
            url = url.replace('PLACEHOLDER', productId);

            fetch(url, {
                method: 'POST',
                headers: {
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                    'Accept': 'application/json',
                },
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showNotification(data.message, 'success');
                    const compareCountEl = document.getElementById('compare-count');
                    if (compareCountEl) compareCountEl.textContent = data.compareCount;
                    window.dispatchEvent(new CustomEvent('compare-updated', { detail: { productId: productId, status: 'added' } }));
                    modal.classList.add('hidden');
                    window.location.reload();
                } else {
                    showNotification(data.message || 'Could not add to compare.', 'error');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                showNotification('An error occurred.', 'error');
            });
        });
    }

    // Notification function
    function showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `fixed top-4 right-4 z-50 px-6 py-3 rounded-lg shadow-lg text-white font-medium transform transition-transform duration-300 ${
            type === 'success' ? 'bg-green-500' :
            type === 'error' ? 'bg-red-500' : 'bg-blue-500'
        }`;
        notification.textContent = message;
        document.body.appendChild(notification);
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
        }, 10);
        setTimeout(() => {
            notification.style.transform = 'translateX(100%)';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }
});
</script>
@endpush
