import Utils from "../../Utils/Utils";
class ProductCard {
    /**
     * Format price according to WooCommerce currency settings
     */
    static formatPrice(price) {
        const settings = window.FuseCommerceSearch?.currency_settings || {};
        const decimals = settings.decimals || 2;
        const decimalSeparator = settings.decimal_separator || '.';
        const thousandSeparator = settings.thousand_separator || ',';
        const symbol = settings.symbol || '$';
        const position = settings.position || 'left';

        // Format the number
        const parts = parseFloat(price).toFixed(decimals).split('.');
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandSeparator);
        const formattedPrice = parts.join(decimalSeparator);

        // Add currency symbol based on position
        switch (position) {
            case 'left':
                return `${symbol}${formattedPrice}`;
            case 'right':
                return `${formattedPrice}${symbol}`;
            case 'left_space':
                return `${symbol} ${formattedPrice}`;
            case 'right_space':
                return `${formattedPrice} ${symbol}`;
            default:
                return `${symbol}${formattedPrice}`;
        }
    }

    static render(product) {
        // Get labels with fallbacks

        if (window?.overrideRenderProductCard && Utils.isFunction(window?.overrideRenderProductCard)) {
            const result = window?.overrideRenderProductCard(product);
            if (result && Utils.isString(result) && result.length > 0) {
                return result;
            }
        }
        const labels = window.FuseCommerceSearch?.labels || {
            product_card_price: 'Price:',
            product_card_sku: 'SKU:',
            product_card_untitled: 'Untitled Product',
            product_card_view_product: 'View Product'
        };

        const categories = product.categories && Array.isArray(product.categories)
            ? product.categories.map(catId => {
                const categoryData = window.CategoryData?.getInstance();
                return categoryData?.getCategoryNameById?.(catId) || `Category ${catId}`;
            }).join(', ')
            : '';

        const linkTarget = "_self";

        // Use first image from images array
        const imageUrl = product.images && product.images.length > 0
            ? product.images[0]
            : '';
        const imageHtml = imageUrl
            ? `<a target="${linkTarget}" href="${product.permalink || '#'}" class="!no-underline !outline-none !focus:outline-none !hover:no-underline block relative mb-3 w-full h-[300px] rounded-lg overflow-hidden product-card-image">
                    <div id="skeleton"
                        class="absolute inset-0 bg-gray-200 overflow-hidden z-0">
                        <div class="absolute inset-0
                            bg-gradient-to-r from-gray-200 via-gray-100 to-gray-200
                            animate-[shimmer_1.5s_infinite]">
                        </div>
                    </div>
                    <img 
                    class="relative z-10 w-full h-full object-cover object-center" src="${imageUrl}" alt="${product.name || ''}" loading="lazy" />
                </a>`
            : `<a target="${linkTarget}" href="${product.permalink || '#'}" class="!no-underline !outline-none !focus:outline-none !hover:no-underline block relative mb-3 w-full h-[300px] rounded-lg overflow-hidden product-card-image">
                <div id="skeleton"
                    class="absolute inset-0 bg-gray-200 overflow-hidden z-0">
                    <div class="absolute inset-0
                        bg-gradient-to-r from-gray-200 via-gray-100 to-gray-200
                        animate-[shimmer_1.5s_infinite]">
                    </div>
                </div>
            </a>`;
            

        // Handle price display based on product type
        let priceHtml = '';
        if (product.type === 'variable' && product.price_range) {
            // Variable product - show price range
            const minPrice = this.formatPrice(product.price_range.min);
            const maxPrice = this.formatPrice(product.price_range.max);
            if (parseFloat(product.price_range.min) === parseFloat(product.price_range.max)) {
                priceHtml = `<div class="font-semibold product-card-price">${labels.product_card_price} ${minPrice}</div>`;
            } else {
                priceHtml = `<div class="font-semibold product-card-price product-card-price-range">${labels.product_card_price} ${minPrice} - ${maxPrice}</div>`;
            }
        } else if (product.price) {
            // Simple product - show single price
            priceHtml = `<div class="font-semibold product-card-price">${labels.product_card_price} ${this.formatPrice(product.price)}</div>`;
        }

        const skuHtml = product.sku
            ? `<div class="product-card-sku">${labels.product_card_sku} ${product.sku}</div>`
            : '';

        const categoryHtml = categories
            ? `<div class="product-card-categories">${categories}</div>`
            : '';

        const card = `
            <div class="product-card" data-product-id="${product.id || ''}" data-product-type="${product.type || 'simple'}">
                ${imageHtml}
                <div class="product-card-content">
                    <a target="${linkTarget}" href="${product.permalink || '#'}" class="!no-underline !outline-none !focus:outline-none !hover:no-underline text-lg font-semibold mb-2 product-card-title">${product.name || labels.product_card_untitled}</a>
                    <div class="flex items-center justify-center mb-4 product-card-actions">
                        <a target="${linkTarget}" href="${product.permalink || '#'}" class="!block !no-underline !outline-none !focus:outline-none !hover:no-underline
                        w-full bg-[#F2F2F2] hover:bg-[#F1F1F1] transition-colors duration-200 text-black font-medium text-center rounded-lg py-2 px-3 product-card-link">${labels.product_card_view_product}</a>
                    </div>
                    ${priceHtml}
                    ${categoryHtml}
                    ${skuHtml}
                </div>
            </div>
        `;

        return card;
    }
}

export default ProductCard;
