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

{% block title %}{{ category_slug | replace('-', ' ') | title if category_slug else 'Category' }}{% endblock %}

{# Alpine.js component #}
{% block alpine_data %}shopCategory(){% 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 }}products" class="hover:text-primary">Products</a>
        <span>/</span>
        <span class="text-gray-900 dark:text-gray-200 font-medium" x-text="categoryName">{{ category_slug | replace('-', ' ') | title if category_slug else 'Category' }}</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" x-text="categoryName">
            {{ category_slug | replace('-', ' ') | title if category_slug else 'Category' }}
        </h1>
        <p class="text-gray-600 dark:text-gray-400" x-show="!loading && total > 0">
            <span x-text="total" class="font-semibold"></span> product<span x-show="total !== 1">s</span> in this category
        </p>
    </div>

    {# Sort Bar #}
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-sm p-4 mb-6">
        <div class="flex flex-wrap items-center justify-between gap-4">
            <div class="text-sm text-gray-600 dark:text-gray-400">
                Showing <span x-text="products.length" class="font-semibold"></span> of <span x-text="total" class="font-semibold"></span> products
            </div>
            <div class="flex items-center gap-2">
                <label class="text-sm text-gray-600 dark:text-gray-400">Sort by:</label>
                <select
                    x-model="sortBy"
                    @change="loadProducts()"
                    class="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 in This Category
            </h3>
            <p class="text-gray-600 dark:text-gray-400 mb-4">
                Check back later or browse other categories.
            </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 All Products
            </a>
        </div>

        {# Pagination #}
        <div x-show="!loading && totalPages > 1" class="mt-8 flex justify-center">
            <div class="flex gap-2">
                <button
                    @click="goToPage(currentPage - 1)"
                    :disabled="currentPage === 1"
                    class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    Previous
                </button>

                <template x-for="page in visiblePages" :key="page">
                    <button
                        @click="goToPage(page)"
                        :class="page === currentPage ? 'bg-primary text-white' : 'border border-gray-300 dark:border-gray-600 hover:bg-gray-100 dark:hover:bg-gray-700'"
                        class="px-4 py-2 rounded-lg"
                        :style="page === currentPage ? 'background-color: var(--color-primary)' : ''"
                        x-text="page"
                    ></button>
                </template>

                <button
                    @click="goToPage(currentPage + 1)"
                    :disabled="currentPage === totalPages"
                    class="px-4 py-2 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                    Next
                </button>
            </div>
        </div>
    </div>

</div>
{% endblock %}

{% block extra_scripts %}
<script>
// Pass category slug from template to JavaScript
window.CATEGORY_SLUG = '{{ category_slug | default("") }}';

document.addEventListener('alpine:init', () => {
    Alpine.data('shopCategory', () => ({
        ...storefrontLayoutData(),

        // Data
        categorySlug: window.CATEGORY_SLUG,
        categoryName: '',
        products: [],
        total: 0,
        loading: true,
        sortBy: 'newest',

        // Pagination
        currentPage: 1,
        perPage: 12,

        get totalPages() {
            return Math.ceil(this.total / this.perPage);
        },

        get visiblePages() {
            const pages = [];
            const total = this.totalPages;
            const current = this.currentPage;

            let start = Math.max(1, current - 2);
            let end = Math.min(total, current + 2);

            if (end - start < 4) {
                if (start === 1) {
                    end = Math.min(total, 5);
                } else {
                    start = Math.max(1, total - 4);
                }
            }

            for (let i = start; i <= end; i++) {
                pages.push(i);
            }
            return pages;
        },

        async init() {
            console.log('[STOREFRONT] Category page initializing...');
            console.log('[STOREFRONT] Category slug:', this.categorySlug);

            // Convert slug to display name
            this.categoryName = this.categorySlug
                .split('-')
                .map(word => word.charAt(0).toUpperCase() + word.slice(1))
                .join(' ');

            await this.loadProducts();
        },

        async loadProducts() {
            this.loading = true;

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

                if (this.sortBy) {
                    params.append('sort', this.sortBy);
                }

                console.log(`[STOREFRONT] Loading category 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.total = data.total;
            } catch (error) {
                console.error('[STOREFRONT] Failed to load category products:', error);
                this.showToast('Failed to load products', 'error');
            } finally {
                this.loading = false;
            }
        },

        async goToPage(page) {
            if (page < 1 || page > this.totalPages) return;
            this.currentPage = page;
            await this.loadProducts();
            window.scrollTo({ top: 0, behavior: 'smooth' });
        },

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