// marketplace.js
$(document).ready(function() {
    // State management
    let currentFilters = {
        search: '',
        category_id: '',
        min_price: '',
        max_price: '',
        location: '',
        type: [],
        seller_type: '',
        delivery_options: [],
        sort_by: 'created_at',
        sort_order: 'desc',
        limit: 12,
        offset: 0
    };

    let currentPage = 1;
    let hasMorePages = true;
    let isLoading = false;

    // Initialize page
    loadDashboardStats();
    loadProducts();
    loadRecommendedProducts();
    loadPopularSellers();

    // Search handler with debounce
    let searchTimeout;
    $('#searchInput').on('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            currentFilters.search = $(this).val();
            resetAndReload();
        }, 500);
    });

    // Location search handler
    $('#locationInput').on('input', function() {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            currentFilters.location = $(this).val();
            resetAndReload();
        }, 500);
    });

    // Category filter handler
    $('.category-filter').on('click', function() {
        $('.category-filter').removeClass('active');
        $(this).addClass('active');
        currentFilters.category_id = $(this).data('id') || '';
        resetAndReload();
    });

    // Price range slider
    const priceSlider = document.getElementById('priceRange');
    if (priceSlider) {
        noUiSlider.create(priceSlider, {
            start: [0, 1000],
            connect: true,
            range: {
                'min': 0,
                'max': 10000
            },
            format: {
                to: value => Math.round(value),
                from: value => Math.round(value)
            }
        });

        priceSlider.noUiSlider.on('change', function(values) {
            currentFilters.min_price = values[0];
            currentFilters.max_price = values[1];
            $('#minPrice').text(values[0]);
            $('#maxPrice').text(values[1]);
            resetAndReload();
        });
    }

    // Condition filter handlers
    $('input[name="type"]').on('change', function() {
        currentFilters.type = $('input[name="type"]:checked').map(function() {
            return $(this).val();
        }).get();
        resetAndReload();
    });

    // Seller type filter
    $('input[name="seller_type"]').on('change', function() {
        currentFilters.seller_type = $(this).val();
        resetAndReload();
    });

    // Delivery options filter
    $('input[name="delivery_options"]').on('change', function() {
        currentFilters.delivery_options = $('input[name="delivery_options"]:checked').map(function() {
            return $(this).val();
        }).get();
        resetAndReload();
    });

    // Sort handlers
    $('#sortBy, #sortOrder').on('change', function() {
        currentFilters.sort_by = $('#sortBy').val();
        currentFilters.sort_order = $('#sortOrder').val();
        resetAndReload();
    });

    // Reset filters
    $('#resetFilters').on('click', function() {
        // Reset all form elements
        $('input[type="checkbox"]').prop('checked', false);
        $('input[type="radio"]').prop('checked', false);
        $('#searchInput, #locationInput').val('');
        
        // Reset price slider if exists
        if (priceSlider && priceSlider.noUiSlider) {
            priceSlider.noUiSlider.reset();
        }
        
        // Reset category pills
        $('.category-filter').removeClass('active');
        $('.category-filter[data-id=""]').addClass('active');

        // Reset filter state
        currentFilters = {
            search: '',
            category_id: '',
            min_price: '',
            max_price: '',
            location: '',
            type: [],
            seller_type: '',
            delivery_options: [],
            sort_by: 'created_at',
            sort_order: 'desc',
            limit: 12,
            offset: 0
        };

        resetAndReload();
    });

    // Load more handler
    $('#loadMoreBtn').on('click', function() {
        if (!isLoading && hasMorePages) {
            currentPage++;
            loadProducts(true);
        }
    });

    // Save product handler
    $(document).on('click', '.save-product', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        if (!isAuthenticated) {
            showLoginPrompt();
            return;
        }

        const productId = $(this).data('id');
        const $button = $(this);

        axios.post(`${base_url}/webapi/marketplace/products/${productId}/toggle-save`)
            .then(response => {
                if (response.data.code === 200) {
                    $button.toggleClass('btn-outline-primary btn-primary');
                    $button.find('i').toggleClass('far fas');
                    showSuccess(response.data.message);
                }
            })
            .catch(error => {
                console.error('Error saving product:', error);
                showError('Error saving product. Please try again.');
            });
    });

    // Contact seller handler
    $(document).on('click', '.contact-seller', function(e) {
        e.preventDefault();
        
        if (!isAuthenticated) {
            showLoginPrompt();
            return;
        }

        const productId = $(this).data('id');
        $('#contactSellerModal').modal('show');
        $('#productId').val(productId);
    });

    // Submit contact form
    $('#contactSellerForm').on('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const productId = $('#productId').val();

        axios.post(`${base_url}/webapi/marketplace/products/${productId}/contact-seller`, formData)
            .then(response => {
                if (response.data.code === 200) {
                    $('#contactSellerModal').modal('hide');
                    showSuccess('Message sent successfully');
                    this.reset();
                }
            })
            .catch(error => {
                console.error('Error sending message:', error);
                showError('Error sending message. Please try again.');
            });
    });

    // Load dashboard stats
    function loadDashboardStats() {
        axios.get(`${base_url}/webapi/marketplace/dashboard-stats`)
            .then(response => {
                if (response.data.code === 200) {
                    updateStatistics(response.data.data);
                }
            })
            .catch(error => console.error('Error loading stats:', error));
    }

    // Load products
    function loadProducts(append = false) {
        if (isLoading) return;
        isLoading = true;

        if (!append) {
            showLoader('#productsGrid');
        }

        const params = {
            ...currentFilters,
            page: currentPage
        };

        axios.post(`${base_url}/webapi/marketplace/products`, params)
            .then(response => {
                if (response.data.code === 200) {
                    const { data, meta } = response.data;
                    
                    if (!append) {
                        $('#productsGrid').empty();
                    }

                    if (data.length === 0 && currentPage === 1) {
                        showEmptyState();
                        return;
                    }

                    renderProducts(data);
                    updateLoadMore(meta);
                }
            })
            .catch(error => {
                console.error('Error loading products:', error);
                showError('Error loading products. Please try again.');
            })
            .finally(() => {
                isLoading = false;
                hideLoader('#productsGrid');
            });
    }

    // Load recommended products
    function loadRecommendedProducts() {
        axios.get(`${base_url}/webapi/marketplace/recommended`)
            .then(response => {
                if (response.data.code === 200) {
                    renderRecommendedProducts(response.data.data);
                }
            })
            .catch(error => console.error('Error loading recommended products:', error));
    }

    // Load popular sellers
    function loadPopularSellers() {
        axios.get(`${base_url}/webapi/marketplace/popular-sellers`)
            .then(response => {
                if (response.data.code === 200) {
                    renderPopularSellers(response.data.data);
                }
            })
            .catch(error => console.error('Error loading popular sellers:', error));
    }

    // Update statistics
    function updateStatistics(stats) {
        // Animate counters
        animateCount('#totalProducts', stats.total_products);
        animateCount('#totalShops', stats.total_shops);
        animateCount('#totalOrders', stats.total_orders);
        animateCount('#savedItems', stats.saved_items);

        // Update category counts
        stats.category_counts.forEach(category => {
            $(`.category-filter[data-id="${category.id}"] .badge`)
                .text(category.products_count);
        });
    }

    // Continue with rendering functions and utilities...
    
// Render products grid
function renderProducts(products) {
    products.forEach(product => {
        const card = createProductCard(product);
        $('#productsGrid').append(card);
    });

    // Initialize tooltips
    $('[data-bs-toggle="tooltip"]').tooltip();
}

// Create product card
function createProductCard(product) {
    const isSaved = product.is_saved ? 'fas btn-primary' : 'far btn-outline-primary';
    const condition = product.type === 'new' ? 'bg-success' : 'bg-warning';
    const image = product.media.length > 0 ? product.media[0].image : '/assets/images/placeholder.jpg';

    return `
        <div class="col-md-4 col-lg-4 mb-4">
            <div class="card h-100">
                <div class="position-relative">
                    <img src="${image}" class="card-img-top" alt="${product.name}"
                         style="height: 200px; object-fit: cover;">
                    <div class="position-absolute top-0 start-0 m-2">
                        <span class="badge ${condition}">${capitalizeFirst(product.type)}</span>
                        ${product.is_featured ? '<span class="badge bg-primary ms-1">Featured</span>' : ''}
                    </div>
                    <button class="btn btn-icon btn-sm ${isSaved} rounded-circle position-absolute top-0 end-0 m-2 save-product"
                            data-id="${product.id}" data-bs-toggle="tooltip" data-bs-placement="top" title="Save Item">
                        <i class="${isSaved} fa-heart"></i>
                    </button>
                </div>
                <div class="card-body">
                    <h5 class="card-title mb-1">${product.name}</h5>
                    <p class="text-primary fw-bold mb-2">${formatPrice(product.price, product.currency)}</p>
                    <p class="small mb-2">
                        <i class="fas fa-tag me-2"></i>${product.category.name}
                    </p>
                    <p class="small mb-2">
                        <i class="fas fa-map-marker-alt me-2"></i>${product.location}
                    </p>
                    <p class="small mb-3">
                        <i class="fas fa-clock me-2"></i>Posted ${moment(product.created_at).fromNow()}
                    </p>
                    <div class="d-grid gap-2">
                        <a href="${base_url}/marketplace/products/${product.id}" 
                           class="btn btn-sm btn-primary">View Details</a>
                        <button class="btn btn-sm btn-outline-primary contact-seller" 
                                data-id="${product.id}">Contact Seller</button>
                    </div>
                </div>
            </div>
        </div>
    `;
}

// Render recommended products
function renderRecommendedProducts(products) {
    const container = $('#recommendedProducts');
    container.empty();

    products.forEach(product => {
        container.append(`
            <div class="card border-0 shadow-sm mb-3">
                <div class="card-body">
                    <div class="row align-items-center">
                        <div class="col-auto">
                            <img src="${product.media[0]?.image || '/assets/images/placeholder.jpg'}" 
                                 class="rounded-3" style="width: 100px; height: 100px; object-fit: cover;"
                                 alt="${product.name}">
                        </div>
                        <div class="col">
                            <h5 class="mb-1">${product.name}</h5>
                            <p class="text-primary mb-1">${formatPrice(product.price, product.currency)}</p>
                            <div class="d-flex flex-wrap gap-2">
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-tag me-1"></i>${product.category.name}
                                </span>
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-map-marker-alt me-1"></i>${product.location}
                                </span>
                                <span class="badge bg-light text-dark">
                                    <i class="fas fa-clock me-1"></i>Posted ${moment(product.created_at).fromNow()}
                                </span>
                            </div>
                        </div>
                        <div class="col-auto">
                            <div class="d-flex gap-2">
                                <a href="${base_url}/marketplace/products/${product.id}" 
                                   class="btn btn-sm btn-primary">View Details</a>
                                <button class="btn btn-sm btn-outline-primary save-product" 
                                        data-id="${product.id}">
                                    <i class="${product.is_saved ? 'fas' : 'far'} fa-heart"></i>
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        `);
    });
}

// Render popular sellers
function renderPopularSellers(sellers) {
    const container = $('#popularSellers');
    
    // Add the header row if we have sellers
    if (sellers.length > 0) {
        container.append(`
            <div class="col-12">
                <div class="d-flex justify-content-between align-items-center mb-4">
                    <h3 class="mb-0">Popular Shops</h3>
                    <a href="${base_url}/marketplace/shops" class="btn btn-link text-decoration-none">
                        View All
                    </a>
                </div>
            </div>
        `);
    }

    sellers.forEach(seller => {
        container.append(`
            <div class="col-md-4">
                <div class="card h-100 border-0 shadow-sm">
                    <div class="position-relative">
                        <img src="${seller.cover_image || '/assets/images/covers/default.jpg'}" 
                             class="card-img-top" alt="${seller.shop_name}"
                             style="height: 120px; object-fit: cover;">
                        <div class="position-absolute top-0 start-0 m-3">
                            ${seller.is_verified ? '<span class="badge bg-primary">Verified</span>' : ''}
                        </div>
                        <div class="position-absolute bottom-0 start-50 translate-middle-x mb-n4">
                            <img src="${seller.avatar || '/assets/images/avatars/default.jpg'}" 
                                 class="rounded-circle border-4 border-white" 
                                 style="width: 80px; height: 80px; object-fit: cover;"
                                 alt="${seller.name}">
                        </div>
                    </div>
                    <div class="card-body pt-5 text-center">
                        <h5 class="card-title mb-1">${seller.shop_name}</h5>
                        <p class="text-muted small mb-2">@${seller.username}</p>
                        <p class="small mb-2">
                            <i class="fas fa-star text-warning me-1"></i>${seller.rating} (${seller.reviews_count} reviews)
                        </p>
                        <p class="small mb-3">
                            <i class="fas fa-map-marker-alt me-2"></i>${seller.location}
                        </p>
                        <div class="d-flex justify-content-center gap-2 mb-3">
                            <span class="badge bg-light text-dark">
                                <i class="fas fa-box me-1"></i>${seller.products_count} Products
                            </span>
                            <span class="badge bg-light text-dark">
                                <i class="fas fa-shopping-bag me-1"></i>${seller.sales_count} Sales
                            </span>
                        </div>
                    </div>
                    <div class="card-footer bg-white p-2 border-0">
                        <div class="d-grid">
                            <a href="${base_url}/marketplace/shops/${seller.id}" 
                               class="btn btn-sm btn-primary">
                                <i class="fas fa-store me-2"></i>Visit Shop
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        `);
    });
}

// Show empty state
function showEmptyState() {
    $('#productsGrid').html(`
        <div class="col-12 text-center py-5">
            <img src="/assets/images/empty-state.svg" alt="No Products" 
                 style="width: 200px;" class="mb-4">
            <h4>No Products Found</h4>
            <p class="text-muted mb-4">Try adjusting your search or filter criteria</p>
            <button class="btn btn-primary" id="resetFilters">
                Reset Filters
            </button>
        </div>
    `);
    $('#loadMoreContainer').hide();
}

// Update load more button
function updateLoadMore(meta) {
    hasMorePages = meta.offset + meta.limit < meta.total;
    $('#loadMoreContainer').toggle(hasMorePages);
    $('#totalResults').text(meta.total);
}

// Show login prompt
function showLoginPrompt() {
    myAlert.fire({
        title: 'Login Required',
        text: 'Please login to perform this action',
        icon: 'info',
        showCancelButton: true,
        confirmButtonText: 'Login',
        cancelButtonText: 'Cancel'
    }).then((result) => {
        if (result.isConfirmed) {
            window.location.href = `${base_url}/login?redirect=${encodeURIComponent(window.location.href)}`;
        }
    });
}
});



// marketplace-create.js
$(document).ready(function() {
    // Image upload handling
    let imageFiles = [];
    const maxImages = 5;

    // Initialize rich text editor if available
    if (typeof ClassicEditor !== 'undefined') {
        ClassicEditor
            .create(document.querySelector('#description'))
            .catch(error => {
                console.error(error);
            });
    }

    // Image upload preview
    $('#productImages').on('change', function(e) {
        const files = Array.from(e.target.files);
        const remainingSlots = maxImages - imageFiles.length;
        
        if (files.length > remainingSlots) {
            showError(`You can only upload a maximum of ${maxImages} images`);
            return;
        }

        files.forEach(file => {
            if (file.size > 2 * 1024 * 1024) {
                showError('Each image must be less than 2MB');
                return;
            }

            if (!['image/jpeg', 'image/png', 'image/gif'].includes(file.type)) {
                showError('Only JPG, PNG and GIF images are allowed');
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                const preview = createImagePreview(e.target.result, imageFiles.length);
                $('#imagePreviewContainer').append(preview);
                imageFiles.push(file);
            };
            reader.readAsDataURL(file);
        });

        // Update remaining count
        updateImageCount();
    });

    // Remove image preview
    $(document).on('click', '.remove-image', function() {
        const index = $(this).data('index');
        imageFiles.splice(index, 1);
        $(this).closest('.image-preview-container').remove();
        
        // Reindex remaining previews
        $('.image-preview-container').each(function(i) {
            $(this).find('.remove-image').data('index', i);
        });

        updateImageCount();
    });

    // Make images sortable
    if ($.fn.sortable) {
        $('#imagePreviewContainer').sortable({
            placeholder: 'image-preview-placeholder',
            update: function() {
                const newImageFiles = [];
                $('.image-preview-container').each(function() {
                    const index = $(this).find('.remove-image').data('index');
                    newImageFiles.push(imageFiles[index]);
                });
                imageFiles = newImageFiles;
            }
        });
    }

    // Form submission
    $('#createProductForm').on('submit', function(e) {
        e.preventDefault();

        if (!validateForm()) {
            return;
        }

        const formData = new FormData(this);
        
        // Append images
        imageFiles.forEach((file, index) => {
            formData.append(`images[${index}]`, file);
        });

        // Show loading state
        const submitBtn = $(this).find('button[type="submit"]');
        const originalText = submitBtn.html();
        submitBtn.html('<i class="fas fa-spinner fa-spin"></i> Creating...').prop('disabled', true);

        // Submit form
        axios.post(`${base_url}/webapi/marketplace/products/create`, formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        .then(response => {
            if (response.data.code === 201) {
                showSuccess('Product created successfully!');
                setTimeout(() => {
                    window.location.href = `${base_url}/marketplace/products/${response.data.data.id}`;
                }, 2000);
            } else {
                throw new Error(response.data.message);
            }
        })
        .catch(error => {
            console.error('Error creating product:', error);
            showError(error.response?.data?.message || 'Error creating product. Please try again.');
        })
        .finally(() => {
            submitBtn.html(originalText).prop('disabled', false);
        });
    });

    // Helper Functions
    function createImagePreview(src, index) {
        return `
            <div class="image-preview-container">
                <div class="position-relative">
                    <img src="${src}" class="img-thumbnail" alt="Preview">
                    <button type="button" class="btn btn-sm btn-danger position-absolute top-0 end-0 m-1 remove-image"
                            data-index="${index}">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                ${index === 0 ? '<small class="text-muted">Main Image</small>' : ''}
            </div>
        `;
    }

    function updateImageCount() {
        const remaining = maxImages - imageFiles.length;
        $('#remainingImages').text(remaining);
        $('#uploadImagesBtn').prop('disabled', remaining === 0);
    }

    function validateForm() {
        const requiredFields = {
            name: 'Product name',
            category_id: 'Category',
            price: 'Price',
            currency: 'Currency',
            location: 'Location',
            type: 'Condition'
        };

        for (const [field, label] of Object.entries(requiredFields)) {
            const value = $(`#${field}`).val();
            if (!value) {
                showError(`${label} is required`);
                return false;
            }
        }

        if (imageFiles.length === 0) {
            showError('At least one image is required');
            return false;
        }

        const price = parseFloat($('#price').val());
        if (isNaN(price) || price <= 0) {
            showError('Please enter a valid price');
            return false;
        }

        return true;
    }

    function showSuccess(message) {
        myAlert.fire({
            icon: 'success',
            title: 'Success',
            text: message
        });
    }

    function showError(message) {
        myAlert.fire({
            icon: 'error',
            title: 'Error',
            text: message
        });
    }
});