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

{% block title %}Products{% endblock %}

{# Alpine.js component #}
{% block alpine_data %}shopProducts(){% 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>
        <span class="text-gray-900 dark:text-gray-200 font-medium">Products</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">
            All Products
        </h1>
        <p class="text-gray-600 dark:text-gray-400">
            Discover our complete collection
        </p>
    </div>

    {# Filters & Search Bar #}
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4 mb-6">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-4">

            {# Search #}
            <div class="md:col-span-2">
                <input
                    type="text"
                    placeholder="Search products..."
                    class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent dark:bg-gray-700 dark:text-white"
                >
            </div>

            {# Category Filter #}
            <div>
                <select class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent dark:bg-gray-700 dark:text-white">
                    <option value="">All Categories</option>
                    <option value="home">Home & Living</option>
                    <option value="fashion">Fashion</option>
                    <option value="electronics">Electronics</option>
                    <option value="arts">Arts & Crafts</option>
                </select>
            </div>

            {# Sort #}
            <div>
                <select class="w-full px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-primary focus:border-transparent dark:bg-gray-700 dark:text-white">
                    <option value="newest">Newest First</option>
                    <option value="price-low">Price: Low to High</option>
                    <option value="price-high">Price: High to Low</option>
                    <option value="popular">Most Popular</option>
                </select>
            </div>
        </div>
    </div>

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

        {# Products Grid #}
        <div x-show="!loading && products.length > 0" class="product-grid">
            <template x-for="product in products" :key="product.id">
                <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm hover:shadow-md transition-shadow overflow-hidden">
                    <a :href="`{{ base_url }}products/${product.id}`">
                        <img loading="lazy" :src="product.marketplace_product?.image_link || '/static/storefront/img/placeholder.svg'"
                             @error="$el.src = '/static/storefront/img/placeholder.svg'"
                             :alt="product.marketplace_product?.title"
                             class="w-full h-48 object-cover">
                    </a>
                    <div class="p-4">
                        <a :href="`{{ base_url }}products/${product.id}`" class="block">
                            <h3 class="text-lg font-semibold text-gray-800 dark:text-gray-200 mb-2 line-clamp-2" x-text="product.marketplace_product?.title"></h3>
                        </a>
                        <p class="text-sm text-gray-600 dark:text-gray-400 mb-3 line-clamp-2" x-text="product.marketplace_product?.description"></p>
                        <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(product.price)"></span>
                                <span x-show="product.sale_price" class="text-sm text-gray-500 line-through ml-2" x-text="formatPrice(product.sale_price)"></span>
                            </div>
                            <button @click.prevent="addToCart(product)"
                                    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"
                                    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>

        {# No Products Message #}
        <div x-show="!loading && products.length === 0" class="col-span-full 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">📦</div>
            <h3 class="text-2xl font-semibold text-gray-700 dark:text-gray-200 mb-2">
                No Products Yet
            </h3>
            <p class="text-gray-600 dark:text-gray-400 mb-4">
                Products will appear here once they are added to the catalog.
            </p>
            <p class="text-sm text-gray-500 dark:text-gray-500">
                <strong>For Developers:</strong> Add products through the store dashboard or admin panel.
            </p>
        </div>

        {# Pagination (hidden for now) #}
        <div x-show="false" class="mt-8 flex justify-center">
            <div class="flex gap-2">
                <button class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
                    Previous
                </button>
                <button class="px-4 py-2 bg-primary text-white rounded-lg">
                    1
                </button>
                <button class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
                    2
                </button>
                <button class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
                    3
                </button>
                <button class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">
                    Next
                </button>
            </div>
        </div>
    </div>

</div>
{% endblock %}

{% block extra_scripts %}
<script>
document.addEventListener('alpine:init', () => {
    Alpine.data('shopProducts', () => ({
        ...storefrontLayoutData(),
        products: [],
        loading: true,
        filters: {
            search: '',
            category: '',
            sort: 'newest'
        },
        pagination: {
            page: 1,
            perPage: 12,
            total: 0
        },

        async init() {
            console.log('[STOREFRONT] Products page initializing...');
            await this.loadProducts();
        },

        async loadProducts() {
            this.loading = true;

            try {
                const params = new URLSearchParams({
                    skip: (this.pagination.page - 1) * this.pagination.perPage,
                    limit: this.pagination.perPage
                });

                // Add search filter if present
                if (this.filters.search) {
                    params.append('search', this.filters.search);
                }

                console.log(`[STOREFRONT] Loading products from /api/v1/storefront/products?${params}`);

                const response = await fetch(`/api/v1/storefront/products?${params}`);

                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }

                const data = await response.json();

                console.log(`[STOREFRONT] Loaded ${data.products.length} products (total: ${data.total})`);

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

        filterProducts() {
            this.loading = true;
            this.loadProducts();
        },

        // formatPrice is inherited from storefrontLayoutData() via spread operator

        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} 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 %}
