{# app/modules/catalog/templates/catalog/storefront/wishlist.html #}
{% extends "storefront/base.html" %}

{% block title %}My Wishlist{% endblock %}

{# Alpine.js component #}
{% block alpine_data %}shopWishlist(){% endblock %}

{% block content %}
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">

    {# Breadcrumbs #}
    <div class="breadcrumb mb-6">
        <a href="{{ base_url }}" class="hover:text-primary">Home</a>
        <span>/</span>
        <a href="{{ base_url }}account/dashboard" class="hover:text-primary">Account</a>
        <span>/</span>
        <span class="text-gray-900 dark:text-gray-200 font-medium">Wishlist</span>
    </div>

    {# Page Header #}
    <div class="mb-8">
        <h1 class="text-3xl md:text-4xl font-bold text-gray-800 dark:text-gray-200 mb-2">
            My Wishlist
        </h1>
        <p class="text-gray-600 dark:text-gray-400" x-show="!loading && items.length > 0">
            <span x-text="items.length" class="font-semibold"></span> saved item<span x-show="items.length !== 1">s</span>
        </p>
    </div>

    {# Wishlist Content #}
    <div>
        {# Loading State #}
        <div x-show="loading" class="flex justify-center items-center py-12">
            <div class="spinner"></div>
        </div>

        {# Not Logged In Message #}
        <div x-show="!loading && !isLoggedIn" class="text-center py-12 bg-white dark:bg-gray-800 rounded-lg border-2 border-dashed border-gray-300 dark:border-gray-600">
            <div class="text-6xl mb-4">
                <span x-html="$icon('user', 'w-16 h-16 mx-auto text-gray-400')"></span>
            </div>
            <h3 class="text-2xl font-semibold text-gray-700 dark:text-gray-200 mb-2">
                Please Log In
            </h3>
            <p class="text-gray-600 dark:text-gray-400 mb-6">
                Log in to your account to view and manage your wishlist.
            </p>
            <a href="{{ base_url }}account/login" class="inline-block px-6 py-3 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors" style="background-color: var(--color-primary)">
                Log In
            </a>
        </div>

        {# Wishlist Items Grid #}
        <div x-show="!loading && isLoggedIn && items.length > 0" class="product-grid">
            <template x-for="item in items" :key="item.id">
                <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm hover:shadow-md transition-shadow overflow-hidden relative">
                    {# Remove from Wishlist Button #}
                    <button
                        @click="removeFromWishlist(item)"
                        class="absolute top-2 right-2 z-10 p-2 bg-white dark:bg-gray-700 rounded-full shadow-md hover:bg-red-50 dark:hover:bg-red-900 transition-colors group"
                        title="Remove from wishlist"
                    >
                        <span x-html="$icon('heart', 'w-5 h-5 text-red-500 fill-current')"></span>
                    </button>

                    <a :href="`{{ base_url }}products/${item.product.id}`">
                        <img loading="lazy" :src="item.product.marketplace_product?.image_link || '/static/storefront/img/placeholder.svg'"
                             @error="$el.src = '/static/storefront/img/placeholder.svg'"
                             :alt="item.product.marketplace_product?.title"
                             class="w-full h-48 object-cover">
                    </a>
                    <div class="p-4">
                        <a :href="`{{ base_url }}products/${item.product.id}`" class="block">
                            <h3 class="text-lg font-semibold text-gray-800 dark:text-gray-200 mb-2 line-clamp-2" x-text="item.product.marketplace_product?.title"></h3>
                        </a>
                        <p class="text-sm text-gray-600 dark:text-gray-400 mb-3 line-clamp-2" x-text="item.product.marketplace_product?.description"></p>

                        {# Availability #}
                        <div class="mb-3">
                            <span
                                x-show="item.product.available_inventory > 0"
                                class="text-sm text-green-600 dark:text-green-400"
                            >
                                In Stock
                            </span>
                            <span
                                x-show="!item.product.available_inventory || item.product.available_inventory <= 0"
                                class="text-sm text-red-600 dark:text-red-400"
                            >
                                Out of Stock
                            </span>
                        </div>

                        <div class="flex items-center justify-between gap-2">
                            <div class="min-w-0">
                                <span class="text-xl sm:text-2xl font-bold text-primary" x-text="formatPrice(item.product.price)"></span>
                                <span x-show="item.product.sale_price" class="text-sm text-gray-500 line-through ml-2" x-text="formatPrice(item.product.sale_price)"></span>
                            </div>
                            <button @click.prevent="addToCart(item.product)"
                                    :disabled="!item.product.available_inventory || item.product.available_inventory <= 0"
                                    class="flex-shrink-0 p-2 sm:px-4 sm:py-2 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
                                    style="background-color: var(--color-primary)"
                                    :title="'Add to Cart'">
                                <span class="w-5 h-5" x-html="$icon('shopping-cart', 'w-5 h-5')"></span>
                                <span class="hidden sm:inline">Add to Cart</span>
                            </button>
                        </div>
                    </div>
                </div>
            </template>
        </div>

        {# Empty Wishlist Message #}
        <div x-show="!loading && isLoggedIn && items.length === 0" class="text-center py-12 bg-white dark:bg-gray-800 rounded-lg border-2 border-dashed border-gray-300 dark:border-gray-600">
            <div class="text-6xl mb-4">
                <span x-html="$icon('heart', 'w-16 h-16 mx-auto text-gray-400')"></span>
            </div>
            <h3 class="text-2xl font-semibold text-gray-700 dark:text-gray-200 mb-2">
                Your Wishlist is Empty
            </h3>
            <p class="text-gray-600 dark:text-gray-400 mb-6">
                Save items you like by clicking the heart icon on product pages.
            </p>
            <a href="{{ base_url }}products" class="inline-block px-6 py-3 bg-primary text-white rounded-lg hover:bg-primary-dark transition-colors" style="background-color: var(--color-primary)">
                Browse Products
            </a>
        </div>
    </div>

</div>
{% endblock %}

{% block extra_scripts %}
<script>
document.addEventListener('alpine:init', () => {
    Alpine.data('shopWishlist', () => ({
        ...storefrontLayoutData(),

        // Data
        items: [],
        loading: true,
        isLoggedIn: false,

        async init() {
            console.log('[STOREFRONT] Wishlist page initializing...');

            // Check if user is logged in
            this.isLoggedIn = await this.checkLoginStatus();

            if (this.isLoggedIn) {
                await this.loadWishlist();
            } else {
                this.loading = false;
            }
        },

        async checkLoginStatus() {
            try {
                const response = await fetch('/api/v1/storefront/customers/me');
                return response.ok;
            } catch (error) {
                return false;
            }
        },

        async loadWishlist() {
            this.loading = true;

            try {
                console.log('[STOREFRONT] Loading wishlist...');

                const response = await fetch('/api/v1/storefront/wishlist');

                if (!response.ok) {
                    if (response.status === 401) {
                        this.isLoggedIn = false;
                        return;
                    }
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }

                const data = await response.json();

                console.log(`[STOREFRONT] Loaded ${data.items?.length || 0} wishlist items`);

                this.items = data.items || [];
            } catch (error) {
                console.error('[STOREFRONT] Failed to load wishlist:', error);
                this.showToast('Failed to load wishlist', 'error');
            } finally {
                this.loading = false;
            }
        },

        async removeFromWishlist(item) {
            try {
                console.log('[STOREFRONT] Removing from wishlist:', item);

                const response = await fetch(`/api/v1/storefront/wishlist/${item.id}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    this.items = this.items.filter(i => i.id !== item.id);
                    this.showToast('Removed from wishlist', 'success');
                } else {
                    throw new Error('Failed to remove from wishlist');
                }
            } catch (error) {
                console.error('[STOREFRONT] Failed to remove from wishlist:', error);
                this.showToast('Failed to remove from wishlist', 'error');
            }
        },

        async addToCart(product) {
            console.log('[STOREFRONT] Adding to cart:', product);

            try {
                const url = `/api/v1/storefront/cart/${this.sessionId}/items`;
                const payload = {
                    product_id: product.id,
                    quantity: 1
                };

                const response = await fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(payload)
                });

                if (response.ok) {
                    const result = await response.json();
                    console.log('[STOREFRONT] Add to cart success:', result);
                    this.cartCount += 1;
                    this.showToast(`${product.marketplace_product?.title || 'Product'} added to cart`, 'success');
                } else {
                    const error = await response.json();
                    console.error('[STOREFRONT] Add to cart error:', error);
                    this.showToast(error.message || 'Failed to add to cart', 'error');
                }
            } catch (error) {
                console.error('[STOREFRONT] Add to cart exception:', error);
                this.showToast('Failed to add to cart', 'error');
            }
        }
    }));
});
</script>
{% endblock %}
