{# app/templates/admin/marketplace-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, table_header %}
{% from 'shared/macros/modals.html' import modal_simple %}
{% from 'shared/macros/inputs.html' import entity_selector, entity_selected_badge %}

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

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

{% block content %}
<!-- Page Header with Store Selector -->
{% call page_header_flex(title='Marketplace Products', subtitle='Master product repository - Browse all imported products from external sources') %}
    <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') }}
    </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: Inactive 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-red-500 bg-red-100 rounded-full dark:text-red-100 dark:bg-red-500">
            <span x-html="$icon('x-circle', 'w-5 h-5')"></span>
        </div>
        <div>
            <p class="mb-2 text-sm font-medium text-gray-600 dark:text-gray-400">
                Inactive
            </p>
            <p class="text-lg font-semibold text-gray-700 dark:text-gray-200" x-text="stats.inactive || 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, GTIN, SKU, or brand..."
                    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">
            <!-- Marketplace Filter -->
            <select
                x-model="filters.marketplace"
                @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 Marketplaces</option>
                <template x-for="mp in marketplaces" :key="mp">
                    <option :value="mp" x-text="mp"></option>
                </template>
            </select>

            <!-- Product Type Filter -->
            <select
                x-model="filters.is_digital"
                @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 Types</option>
                <option value="false">Physical</option>
                <option value="true">Digital</option>
            </select>

            <!-- 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>
        </div>
    </div>
</div>

<!-- Bulk Actions Bar (shown when items selected) -->
<div x-show="!loading && selectedProducts.length > 0"
     x-transition
     class="mb-4 p-4 bg-purple-50 dark:bg-purple-900/20 border border-purple-200 dark:border-purple-800 rounded-lg">
    <div class="flex items-center justify-between">
        <div class="flex items-center gap-3">
            <span class="text-sm font-medium text-purple-700 dark:text-purple-300">
                <span x-text="selectedProducts.length"></span> product(s) selected
            </span>
            <button
                @click="clearSelection()"
                class="text-sm text-purple-600 dark:text-purple-400 hover:underline"
            >
                Clear selection
            </button>
        </div>
        <div class="flex items-center gap-2">
            <button
                @click="openCopyToStoreModal()"
                class="flex items-center px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 transition-colors"
            >
                <span x-html="$icon('duplicate', 'w-4 h-4 mr-2')"></span>
                Copy to Store Catalog
            </button>
        </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 w-10">
                        <input
                            type="checkbox"
                            @change="toggleSelectAll($event)"
                            :checked="products.length > 0 && selectedProducts.length === products.length"
                            :indeterminate="selectedProducts.length > 0 && selectedProducts.length < products.length"
                            class="rounded border-gray-300 dark:border-gray-600 text-purple-600 focus:ring-purple-500"
                        />
                    </th>
                    <th class="px-4 py-3">Product</th>
                    <th class="px-4 py-3">Identifiers</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="7" 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('database', 'w-12 h-12 mb-2 text-gray-300')"></span>
                                <p class="font-medium">No marketplace products found</p>
                                <p class="text-xs mt-1" x-text="filters.search || filters.marketplace || filters.is_active || selectedStore ? 'Try adjusting your search or filters' : 'Import products from the Import 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" :class="isSelected(product.id) && 'bg-purple-50 dark:bg-purple-900/10'">
                        <!-- Checkbox -->
                        <td class="px-4 py-3">
                            <input
                                type="checkbox"
                                :checked="isSelected(product.id)"
                                @change="toggleSelection(product.id)"
                                class="rounded border-gray-300 dark:border-gray-600 text-purple-600 focus:ring-purple-500"
                            />
                        </td>

                        <!-- 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_link">
                                        <img :src="product.image_link" :alt="product.title" class="w-full h-full object-cover" loading="lazy" />
                                    </template>
                                    <template x-if="!product.image_link">
                                        <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">
                                    <a :href="'/admin/marketplace-products/' + product.id" class="font-semibold text-sm truncate max-w-xs hover:text-purple-600 dark:hover:text-purple-400" x-text="product.title || 'Untitled'"></a>
                                    <p class="text-xs text-gray-500 dark:text-gray-400" x-text="product.brand || 'No brand'"></p>
                                    <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>

                        <!-- Identifiers -->
                        <td class="px-4 py-3 text-sm">
                            <div class="space-y-1">
                                <template x-if="product.gtin">
                                    <p class="text-xs"><span class="text-gray-500">GTIN:</span> <span x-text="product.gtin" class="font-mono"></span></p>
                                </template>
                                <template x-if="product.sku">
                                    <p class="text-xs"><span class="text-gray-500">SKU:</span> <span x-text="product.sku" class="font-mono"></span></p>
                                </template>
                                <template x-if="!product.gtin && !product.sku">
                                    <p class="text-xs text-gray-400">No identifiers</p>
                                </template>
                            </div>
                        </td>

                        <!-- Source (Marketplace & Store) -->
                        <td class="px-4 py-3 text-sm">
                            <p class="font-medium" x-text="product.marketplace || 'Unknown'"></p>
                            <p class="text-xs text-gray-500 dark:text-gray-400 truncate max-w-[150px]" x-text="'from ' + (product.store_name || 'Unknown')"></p>
                        </td>

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

                        <!-- Status -->
                        <td class="px-4 py-3 text-sm">
                            <span class="px-2 py-1 font-semibold leading-tight rounded-full text-xs"
                                  :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.availability">
                                <p class="text-xs text-gray-500 mt-1" x-text="product.availability"></p>
                            </template>
                        </td>

                        <!-- Actions -->
                        <td class="px-4 py-3 text-sm">
                            <div class="flex items-center space-x-2">
                                <a
                                    :href="'/admin/marketplace-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 Details"
                                >
                                    <span x-html="$icon('eye', 'w-4 h-4')"></span>
                                </a>
                                <button
                                    @click="copySingleProduct(product.id)"
                                    class="flex items-center justify-center px-2 py-1 text-xs font-medium leading-5 text-green-600 rounded-lg dark:text-green-400 focus:outline-none hover:bg-gray-100 dark:hover:bg-gray-700"
                                    title="Copy to Store Catalog"
                                >
                                    <span x-html="$icon('duplicate', 'w-4 h-4')"></span>
                                </button>
                            </div>
                        </td>
                    </tr>
                </template>
            </tbody>
    {% endcall %}

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

<!-- Copy to Store Modal -->
{% call modal_simple('copyToStoreModal', 'Copy to Store Catalog', show_var='showCopyModal', size='md') %}
<div class="space-y-4">
    <p class="text-sm text-gray-600 dark:text-gray-400">
        Copy <span class="font-medium" x-text="selectedProducts.length"></span> selected product(s) to a store catalog.
    </p>

    <!-- Target Store Selection -->
    <div>
        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
            Target Store <span class="text-red-500">*</span>
        </label>
        <select
            x-model="copyForm.store_id"
            class="w-full 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="">Select a store...</option>
            <template x-for="store in targetStores" :key="store.id">
                <option :value="store.id" x-text="store.name + ' (' + store.store_code + ')'"></option>
            </template>
        </select>
        <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">
            Products will be copied to this store's catalog
        </p>
    </div>

    <!-- Options -->
    <div class="space-y-2">
        <label class="flex items-center">
            <input
                type="checkbox"
                x-model="copyForm.skip_existing"
                class="rounded border-gray-300 dark:border-gray-600 text-purple-600 focus:ring-purple-500"
            />
            <span class="ml-2 text-sm text-gray-700 dark:text-gray-300">Skip products that already exist in catalog</span>
        </label>
    </div>

    <!-- Actions -->
    <div class="flex items-center justify-end gap-3 pt-4 border-t border-gray-200 dark:border-gray-700">
        <button
            @click="showCopyModal = 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="executeCopyToStore()"
            :disabled="!copyForm.store_id || copying"
            class="flex items-center px-4 py-2 text-sm font-medium text-white bg-purple-600 rounded-lg hover:bg-purple-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
        >
            <span x-show="copying" x-html="$icon('spinner', 'w-4 h-4 mr-2')"></span>
            <span x-text="copying ? 'Copying...' : 'Copy Products'"></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('marketplace_static', path='admin/js/marketplace-products.js') }}"></script>
{% endblock %}
