@extends('frontend.layouts.app')

@section('title', 'My Wishlist - 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">Wishlist</li>
            </ol>
        </nav>
        <h1 class="text-4xl font-bold text-gray-900 mb-3">My Wishlist</h1>
        <p class="text-gray-600 text-lg">Products you've saved for later</p>
    </div>
</div>

<!-- Main Content -->
<section class="py-12 px-4 bg-gray-50">
    <div class="container mx-auto max-w-7xl">
        @if($wishlistItems->isEmpty())
        <div class="bg-white rounded-2xl shadow-lg p-8 text-center border border-gray-100">
            <i class="far fa-heart text-blue-400 text-6xl mb-4"></i>
            <h2 class="text-2xl font-bold text-gray-800 mb-2">Your Wishlist is Empty!</h2>
            <p class="text-gray-600 mb-6">Looks like you haven't added anything to your wishlist yet. Start browsing and add your favorite products!</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>
        @else
        <div class="bg-white rounded-2xl shadow-lg overflow-hidden border border-gray-100">
            <div class="overflow-x-auto">
                <table class="min-w-full divide-y divide-gray-200">
                    <thead class="bg-gray-50">
                        <tr>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Product</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Price</th>
                            <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Stock Status</th>
                            <th scope="col" class="px-6 py-3 text-center text-xs font-medium text-gray-500 uppercase tracking-wider">Actions</th>
                        </tr>
                    </thead>
                    <tbody class="bg-white divide-y divide-gray-200">
                        @foreach($wishlistItems as $item)
                        <tr class="wishlist-item-row">
                            <td class="px-6 py-4 whitespace-nowrap">
                                <div class="flex items-center">
                                    <div class="flex-shrink-0 h-20 w-20">
                                        <img class="h-20 w-20 rounded-md object-cover" src="{{ $item->product->image ? asset('storage/' . $item->product->image) : 'https://via.placeholder.com/150' }}" alt="{{ $item->product->product_name }}">
                                    </div>
                                    <div class="ml-4">
                                        <div class="text-sm font-medium text-gray-900 hover:text-blue-600 transition">
                                            <a href="{{ route('products.show', $item->product->id) }}">{{ $item->product->product_name }}</a>
                                        </div>
                                    </div>
                                </div>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                @if($item->product->discount_price)
                                    <div class="flex flex-col">
                                        <span class="text-sm font-bold text-red-600">৳{{ number_format($item->product->discount_price) }}</span>
                                        <span class="text-xs text-gray-500 line-through">৳{{ number_format($item->product->price) }}</span>
                                    </div>
                                @else
                                    <div class="text-sm text-gray-900 font-bold">৳{{ number_format($item->product->price) }}</div>
                                @endif
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap">
                                <span @class([
                                    'px-3 py-1 inline-flex text-xs leading-5 font-semibold rounded-full',
                                    'bg-green-100 text-green-800' => $item->product->in_stock,
                                    'bg-red-100 text-red-800' => !$item->product->in_stock,
                                ])>
                                    {{ $item->product->in_stock ? 'In Stock' : 'Out of Stock' }}
                                </span>
                            </td>
                            <td class="px-6 py-4 whitespace-nowrap text-center text-sm font-medium">
                                <button class="v-btn bg-primary hover:bg-opacity-90 p-2 rounded text-white add-to-cart" data-product-id="{{ $item->product->id }}" data-product-name="{{ e($item->product->product_name) }}" data-quantity="1" @if(!$item->product->in_stock) disabled @endif>
                                    <span>Add to Cart</span>
                                </button>
                                <button class="text-gray-400 hover:text-red-600 transition ml-4 remove-from-wishlist" data-product-id="{{ $item->product->id }}" title="Remove from wishlist">
                                    <i class="fas fa-trash-alt fa-lg"></i>
                                </button>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
        @endif
    </div>
</section>
@include('frontend.pages.partials.quick-view-modal')
@endsection

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    // Wishlist remove functionality
    document.body.addEventListener('click', function(event) {
        const button = event.target.closest('.remove-from-wishlist');
        if (!button) return;

        event.preventDefault(); // Prevent any default action

        const productId = button.dataset.productId;
        const productRow = button.closest('.wishlist-item-row');

        // Optimistically update UI
        if (productRow) {
            productRow.style.transition = 'transform 0.4s ease, opacity 0.4s ease';
            productRow.style.transform = 'scale(0.95)';
            productRow.style.opacity = '0';
        }

        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 => response.json())
        .then(data => {
            if (data.success && data.status === 'removed') {
                showNotification(data.message, 'success');
                // Remove the card from the DOM after the animation
                setTimeout(() => {
                    if (productRow) {
                        productRow.remove();
                        // Check if wishlist is now empty
                        if (document.querySelectorAll('.remove-from-wishlist').length === 0) {
                            location.reload(); // Reload to show the "empty" message
                        }
                    }
                }, 400);
            } else {
                // If removal failed, revert the UI changes
                if (productRow) {
                    productRow.style.transform = 'scale(1)';
                    productRow.style.opacity = '1';
                }
                showNotification(data.message || 'Could not remove item.', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            if (productRow) {
                productRow.style.transform = 'scale(1)';
                productRow.style.opacity = '1';
            }
            showNotification('An error occurred. Please try again.', 'error');
        });
    });

    // Add to Cart functionality
    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 quantity = button.dataset.quantity || 1;

        // Show loading state
        const buttonSpan = button.querySelector('span');
        if (buttonSpan) buttonSpan.innerHTML = '<i class="fas fa-spinner fa-spin"></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: quantity })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showNotification(`Added '${productName}' to cart!`, 'success');
                // Update cart count in navbar
                const cartCountEl = document.getElementById('cart-count');
                if (cartCountEl) cartCountEl.textContent = data.cartCount;

                if (buttonSpan) buttonSpan.innerHTML = '<i class="fas fa-check"></i> Added';
                setTimeout(() => {
                    if (buttonSpan) buttonSpan.innerHTML = 'Add to Cart';
                    button.disabled = false;
                }, 2000); // Revert text and re-enable after 2 seconds

            } else {
                showNotification(data.message || 'Could not add to cart.', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showNotification('An error occurred.', 'error');
        })
        .finally(() => {
            if (!button.querySelector('.fa-check')) { // Only revert if not in "Added" state
                if (buttonSpan) buttonSpan.innerHTML = 'Add to Cart';
                button.disabled = false;
            }
        });
    });

    // Enhanced Notification function
    function showNotification(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 icons = { success: 'fa-check-circle', error: 'fa-exclamation-circle', info: 'fa-info-circle' };
        const borderColors = { success: 'border-green-500', error: 'border-red-500', info: 'border-blue-500' };
        const textColors = { success: 'text-green-500', error: 'text-red-500', info: 'text-blue-500' };

        notification.classList.add(borderColors[type] || borderColors.info);

        notification.innerHTML = `
            <div class="flex items-start gap-4">
                <i class="fas ${icons[type] || icons.info} ${textColors[type] || textColors.info} 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 ${borderColors[type] ? borderColors[type].replace('border', 'bg') : 'bg-blue-500'} 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>
@endpush
