{# app/templates/admin/store-products.html #}
{% extends "admin/base.html" %}
{% from 'shared/macros/pagination.html' import pagination %}
{% from 'shared/macros/headers.html' import page_header_flex, refresh_button %}
{% from 'shared/macros/alerts.html' import loading_state, error_state %}
{% from 'shared/macros/tables.html' import table_wrapper %}
{% from 'shared/macros/modals.html' import modal_simple %}
{% from 'shared/macros/inputs.html' import entity_selector, entity_selected_badge %}

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

{% block alpine_data %}adminStoreProducts(){% endblock %}

{% block content %}
<!-- Page Header with Store Selector -->
{% call page_header_flex(title='Store Products', subtitle='Browse store-specific product catalogs with override capability') %}
    <div class="flex items-center gap-4">
        <!-- Store Autocomplete (Tom Select) -->
        {{ entity_selector(ref_name='storeSelect', id='store-select', placeholder='Filter by store...') }}
        {{ refresh_button(loading_var='loading', onclick='refresh()', variant='secondary') }}
        <a
            href="/admin/store-products/create"
            class="flex items-center px-4 py-2 text-sm font-medium leading-5 text-white transition-colors duration-150 bg-purple-600 border border-transparent rounded-lg hover:bg-purple-700 focus:outline-none focus:shadow-outline-purple"
        >
            <span x-html="$icon('plus', 'w-4 h-4 mr-2')"></span>
            Create Product
        </a>
    </div>
{% endcall %}

<!-- Selected Store Info -->
{{ entity_selected_badge(entity_var='selectedStore', clear_fn='clearStoreFilter()', code_field='store_code', color='purple') }}

{{ loading_state('Loading products...') }}

{{ error_state('Error loading products') }}

<!-- Stats Cards -->
<div x-show="!loading" class="grid gap-6 mb-8 md:grid-cols-2 xl:grid-cols-5">
    <!-- Card: Total Products -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-purple-500 bg-purple-100 rounded-full dark:text-purple-100 dark:bg-purple-500">
            <span x-html="$icon('cube', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                Total Products
            </p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.total || 0">
                0
            </p>
        </div>
    </div>

    <!-- Card: Active Products -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-green-500 bg-green-100 rounded-full dark:text-green-100 dark:bg-green-500">
            <span x-html="$icon('check-circle', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                Active
            </p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.active || 0">
                0
            </p>
        </div>
    </div>

    <!-- Card: Featured Products -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-yellow-500 bg-yellow-100 rounded-full dark:text-yellow-100 dark:bg-yellow-500">
            <span x-html="$icon('star', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                Featured
            </p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.featured || 0">
                0
            </p>
        </div>
    </div>

    <!-- Card: Digital Products -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-blue-500 bg-blue-100 rounded-full dark:text-blue-100 dark:bg-blue-500">
            <span x-html="$icon('code', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                Digital
            </p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.digital || 0">
                0
            </p>
        </div>
    </div>

    <!-- Card: Physical Products -->
    <div class="flex items-center p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
        <div class="p-3 mr-4 text-orange-500 bg-orange-100 rounded-full dark:text-orange-100 dark:bg-orange-500">
            <span x-html="$icon('truck', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                Physical
            </p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.physical || 0">
                0
            </p>
        </div>
    </div>
</div>

<!-- Search and Filters Bar -->
<div x-show="!loading" class="mb-6 p-4 bg-white rounded-lg shadow-xs dark:bg-gray-800">
    <div class="flex flex-col lg:flex-row lg:items-center lg:justify-between gap-4">
        <!-- Search Input -->
        <div class="flex-1 max-w-xl">
            <div class="relative">
                <span class="absolute inset-y-0 left-0 flex items-center pl-3">
                    <span x-html="$icon('search', 'w-5 h-5 text-gray-400')"></span>
                </span>
                <input
                    type="text"
                    x-model="filters.search"
                    @input="debouncedSearch()"
                    placeholder="Search by title or store SKU..."
                    class="w-full pl-10 pr-4 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none dark:bg-gray-700 dark:text-gray-300"
                >
            </div>
        </div>

        <!-- Filters -->
        <div class="flex flex-wrap gap-3">
            <!-- Status Filter -->
            <select
                x-model="filters.is_active"
                @change="pagination.page = 1; loadProducts()"
                class="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none"
            >
                <option value="">All Status</option>
                <option value="true">Active</option>
                <option value="false">Inactive</option>
            </select>

            <!-- Featured Filter -->
            <select
                x-model="filters.is_featured"
                @change="pagination.page = 1; loadProducts()"
                class="px-4 py-2 text-sm text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg focus:border-purple-400 focus:outline-none"
            >
                <option value="">All Products</option>
                <option value="true">Featured Only</option>
                <option value="false">Not Featured</option>
            </select>
        </div>
    </div>
</div>

<!-- Products Table with Pagination -->
<div x-show="!loading">
    {% call table_wrapper() %}
            <thead>
                <tr class="text-xs font-semibold tracking-wide text-left text-gray-500 uppercase border-b dark:border-gray-700 bg-gray-50 dark:text-gray-400 dark:bg-gray-800">
                    <th class="px-4 py-3">Product</th>
                    <th class="px-4 py-3">Store</th>
                    <th class="px-4 py-3">Source</th>
                    <th class="px-4 py-3">Price</th>
                    <th class="px-4 py-3">Status</th>
                    <th class="px-4 py-3">Actions</th>
                </tr>
            </thead>
            <tbody class="bg-white divide-y dark:divide-gray-700 dark:bg-gray-800">
                <!-- Empty State -->
                <template x-if="products.length === 0">
                    <tr>
                        <td colspan="6" class="px-4 py-8 text-center text-gray-600 dark:text-gray-400">
                            <div class="flex flex-col items-center">
                                <span x-html="$icon('cube', 'w-12 h-12 mb-2 text-gray-300')"></span>
                                <p class="font-medium">No store products found</p>
                                <p class="text-xs mt-1" x-text="filters.search || filters.store_id || filters.is_active ? 'Try adjusting your filters' : 'Copy products from the Marketplace Products page'"></p>
                            </div>
                        </td>
                    </tr>
                </template>

                <!-- Product Rows -->
                <template x-for="product in products" :key="product.id">
                    <tr class="text-gray-700 dark:text-gray-400">
                        <!-- Product Info -->
                        <td class="px-4 py-3">
                            <div class="flex items-center">
                                <!-- Product Image -->
                                <div class="w-12 h-12 mr-3 rounded-lg overflow-hidden bg-gray-100 dark:bg-gray-700 flex-shrink-0">
                                    <template x-if="product.image_url">
                                        <img :src="product.image_url" :alt="product.title" class="w-full h-full object-cover" loading="lazy" />
                                    </template>
                                    <template x-if="!product.image_url">
                                        <div class="w-full h-full flex items-center justify-center">
                                            <span x-html="$icon('photograph', 'w-6 h-6 text-gray-400')"></span>
                                        </div>
                                    </template>
                                </div>
                                <!-- Product Details -->
                                <div class="min-w-0">
                                    <p class="font-semibold text-sm truncate max-w-xs" x-text="product.title || 'Untitled'"></p>
                                    <p class="text-xs text-gray-500 dark:text-gray-400" x-text="product.brand || 'No brand'"></p>
                                    <template x-if="product.store_sku">
                                        <p class="text-xs text-gray-400 font-mono">SKU: <span x-text="product.store_sku"></span></p>
                                    </template>
                                    <template x-if="product.is_digital">
                                        <span class="inline-flex items-center px-2 py-0.5 mt-1 text-xs font-medium text-blue-700 bg-blue-100 dark:bg-blue-900/30 dark:text-blue-400 rounded">
                                            <span x-html="$icon('code', 'w-3 h-3 mr-1')"></span>
                                            Digital
                                        </span>
                                    </template>
                                </div>
                            </div>
                        </td>

                        <!-- Store Info -->
                        <td class="px-4 py-3 text-sm">
                            <p class="font-medium" x-text="product.store_name || 'Unknown'"></p>
                            <p class="text-xs text-gray-500 dark:text-gray-400 font-mono" x-text="product.store_code || ''"></p>
                        </td>

                        <!-- Source (Marketplace) -->
                        <td class="px-4 py-3 text-sm">
                            <p x-text="product.source_marketplace || 'Unknown'"></p>
                            <p class="text-xs text-gray-500 dark:text-gray-400 truncate max-w-[120px]" x-text="'from ' + (product.source_store || 'Unknown')"></p>
                        </td>

                        <!-- Price -->
                        <td class="px-4 py-3 text-sm">
                            <template x-if="product.effective_price">
                                <p class="font-medium" x-text="formatPrice(product.effective_price, product.effective_currency)"></p>
                            </template>
                            <template x-if="!product.effective_price">
                                <p class="text-gray-400">-</p>
                            </template>
                        </td>

                        <!-- Status -->
                        <td class="px-4 py-3 text-sm">
                            <div class="flex flex-col gap-1">
                                <span class="px-2 py-1 font-semibold leading-tight rounded-full text-xs w-fit"
                                      :class="product.is_active ? 'text-green-700 bg-green-100 dark:bg-green-700 dark:text-green-100' : 'text-red-700 bg-red-100 dark:bg-red-700 dark:text-red-100'"
                                      x-text="product.is_active ? 'Active' : 'Inactive'">
                                </span>
                                <template x-if="product.is_featured">
                                    <span class="px-2 py-1 font-semibold leading-tight rounded-full text-xs w-fit text-yellow-700 bg-yellow-100 dark:bg-yellow-700 dark:text-yellow-100">
                                        Featured
                                    </span>
                                </template>
                            </div>
                        </td>

                        <!-- Actions -->
                        <td class="px-4 py-3 text-sm">
                            <div class="flex items-center space-x-2">
                                <a
                                    :href="'/admin/store-products/' + product.id"
                                    class="flex items-center justify-center px-2 py-1 text-xs font-medium leading-5 text-purple-600 rounded-lg dark:text-purple-400 focus:outline-none hover:bg-gray-100 dark:hover:bg-gray-700"
                                    title="View"
                                >
                                    <span x-html="$icon('eye', 'w-4 h-4')"></span>
                                </a>
                                <a
                                    :href="'/admin/store-products/' + product.id + '/edit'"
                                    class="flex items-center justify-center px-2 py-1 text-xs font-medium leading-5 text-blue-600 rounded-lg dark:text-blue-400 focus:outline-none hover:bg-gray-100 dark:hover:bg-gray-700"
                                    title="Edit"
                                >
                                    <span x-html="$icon('pencil', 'w-4 h-4')"></span>
                                </a>
                                <button
                                    @click="confirmRemove(product)"
                                    class="flex items-center justify-center px-2 py-1 text-xs font-medium leading-5 text-red-600 rounded-lg dark:text-red-400 focus:outline-none hover:bg-gray-100 dark:hover:bg-gray-700"
                                    title="Delete"
                                >
                                    <span x-html="$icon('delete', 'w-4 h-4')"></span>
                                </button>
                            </div>
                        </td>
                    </tr>
                </template>
            </tbody>
    {% endcall %}

    {{ pagination(show_condition="!loading && pagination.total > 0") }}
</div>

<!-- Confirm Remove Modal -->
{% call modal_simple('confirmRemoveModal', 'Remove from Catalog', show_var='showRemoveModal', size='sm') %}
<div class="space-y-4">
    <p class="text-sm text-gray-600 dark:text-gray-400">
        Are you sure you want to remove this product from the store's catalog?
    </p>
    <p class="text-sm font-medium text-gray-700 dark:text-gray-300" x-text="productToRemove?.title || 'Untitled'"></p>
    <p class="text-xs text-gray-500 dark:text-gray-400">
        This will not delete the source product from the marketplace repository.
    </p>

    <div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
        <button
            @click="showRemoveModal = false"
            class="px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 transition-colors"
        >
            Cancel
        </button>
        <button
            @click="executeRemove()"
            :disabled="removing"
            class="px-4 py-2 text-sm font-medium text-white bg-red-600 rounded-lg hover:bg-red-700 transition-colors disabled:opacity-50"
        >
            <span x-text="removing ? 'Removing...' : 'Remove'"></span>
        </button>
    </div>
</div>
{% endcall %}
{% endblock %}

{% block extra_scripts %}
<!-- Tom Select JS with local fallback -->
<script>
(function() {
    var script = document.createElement('script');
    script.src = 'https://cdn.jsdelivr.net/npm/tom-select@2.4.1/dist/js/tom-select.complete.min.js';
    script.onerror = function() {
        console.warn('Tom Select CDN failed, loading local copy...');
        var fallbackScript = document.createElement('script');
        fallbackScript.src = '{{ url_for("static", path="shared/js/lib/tom-select.complete.min.js") }}';
        document.head.appendChild(fallbackScript);
    };
    document.head.appendChild(script);
})();
</script>
<script defer src="{{ url_for('catalog_static', path='admin/js/products.js') }}"></script>
{% endblock %}
