/**
 * Products API Integration for БОМИ клима
 * Handles XML API from multiple distributors:
 * 1. bulclima.com - Brand-based API
 * 2. Bittel (dealers.bittel.bg) - Paginated product API
 * 
 * API Structures:
 * - Bulclima: Base URL returns brands list, each brand URL returns products
 * - Bittel: Paginated XML API with direct product list
 */

// ============================================
// DISTRIBUTOR 1: Bulclima API Configuration
// ============================================
const BULCLIMA_API_BASE_URL = 'https://www.bulclima.com/tools/api/items/';
const USE_BULCLIMA = true; // Set to false to disable this distributor

// ============================================
// DISTRIBUTOR 2: Bittel API Configuration
// ============================================
// Bittel API Key - provided by Bittel
const BITTEL_API_KEY = 'b6a9278e9e8796f985c820a2b7d22dbb';
const BITTEL_API_BASE_URL = `https://dealers.bittel.bg/bg/api/xml_v4/${BITTEL_API_KEY}`;
const USE_BITTEL = true; // Set to false to disable this distributor

// CORS Proxy - Use a proxy to bypass CORS restrictions
// Option 1: Use a public CORS proxy (for development/testing)
const USE_CORS_PROXY = true;
const CORS_PROXY_URL = 'https://corsproxy.io/?';

// Option 2: If you have your own backend, use this instead:
// const USE_CORS_PROXY = false;
// const BACKEND_API_URL = '/api/products'; // Your backend endpoint

// Legacy support - keep for backward compatibility
const API_BASE_URL = BULCLIMA_API_BASE_URL;

// Category mapping (maps your categories to API categories if needed)
const CATEGORY_MAP = {
    'wall': ['Стенни', 'стенен', 'стенни', 'wall'],
    'floor': ['Подови', 'подов', 'подови', 'floor'],
    'cassette': ['Касетъчни', 'касетъчен', 'касетъчни', 'касетен', 'cassette'],
    'duct': ['Канални', 'канален', 'канални', 'duct'],
    'ceiling': ['Таванни', 'таванен', 'таванни', 'ceiling'],
    'column': ['Колонни', 'колонен', 'колонни', 'column'],
    'mobile': ['Мобилни', 'мобилен', 'мобилни', 'mobile', 'portable'],
    'multisplit': ['мулти сплит система', 'мулти сплит', 'мултисплит'],
    'wifi': ['WiFi', 'wifi', 'аксесоари', 'accessories', 'accessory']
};

/**
 * Fetch brands from API
 */
async function fetchBrands() {
    try {
        // Build the URL - use proxy if enabled
        let fetchUrl = BULCLIMA_API_BASE_URL;
        if (USE_CORS_PROXY) {
            fetchUrl = CORS_PROXY_URL + encodeURIComponent(BULCLIMA_API_BASE_URL);
        }
        
        console.log(`Fetching brands from: ${fetchUrl}`);
        const response = await fetch(fetchUrl, {
            method: 'GET',
            headers: {
                'Accept': 'application/xml, text/xml, */*'
            }
        });
        
        console.log('Response status:', response.status, response.statusText);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const text = await response.text();
        console.log('Raw XML response length:', text.length);
        console.log('Raw XML response (first 500 chars):', text.substring(0, 500));
        
        if (!text || text.trim().length === 0) {
            throw new Error('Empty response from API');
        }
        
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(text, 'text/xml');
        
        // Check for parsing errors
        const parserError = xmlDoc.querySelector('parsererror');
        if (parserError) {
            console.error('XML Parse Error:', parserError.textContent);
            return null;
        }
        
        // Log the root element to understand structure
        console.log('Root element:', xmlDoc.documentElement.tagName);
        console.log('Root element children:', Array.from(xmlDoc.documentElement.children).map(c => c.tagName));
        
        // Parse brands - structure is <brands><brand><title>...</title><url>...</url></brand></brands>
        const brands = [];
        const brandElements = xmlDoc.querySelectorAll('brand');
        
        console.log(`Found ${brandElements.length} brand elements`);
        
        if (brandElements.length === 0) {
            console.warn('No brand elements found in XML. Full XML structure:', text);
        }
        
        brandElements.forEach((brand, index) => {
            const titleElement = brand.querySelector('title');
            const urlElement = brand.querySelector('url');
            
            const title = titleElement?.textContent?.trim() || '';
            const url = urlElement?.textContent?.trim() || '';
            
            // Extract ID from URL (e.g., "https://www.bulclima.com/tools/api/items/2" -> "2")
            const id = url.split('/').filter(Boolean).pop() || index.toString();
            
            if (title && url) {
                brands.push({
                    id: id,
                    title: title,
                    url: url
                });
                console.log(`Parsed brand ${index + 1}: ${title} (ID: ${id})`);
            } else {
                console.warn(`Brand ${index} missing title or url:`, { title, url, brandHTML: brand.outerHTML });
            }
        });
        
        console.log(`Successfully parsed ${brands.length} brands:`, brands);
        return brands;
    } catch (error) {
        console.error('Error fetching brands:', error);
        console.error('Error name:', error.name);
        console.error('Error message:', error.message);
        // If CORS error, show helpful message
        if (error.message.includes('CORS') || error.message.includes('fetch') || error.name === 'TypeError') {
            console.error('CORS or network error detected. This might be a CORS issue.');
            console.error('Possible solutions:');
            console.error('1. Use a CORS proxy');
            console.error('2. Contact the API provider to enable CORS');
            console.error('3. Use a backend server to fetch the data');
        }
        return null;
    }
}

/**
 * Fetch products for a specific brand
 */
async function fetchBrandProducts(brandId) {
    try {
        // Build the URL
        let url = brandId.startsWith('http') ? brandId : `${BULCLIMA_API_BASE_URL}${brandId}`;
        
        // Use proxy if enabled
        if (USE_CORS_PROXY && !brandId.startsWith('http')) {
            url = CORS_PROXY_URL + encodeURIComponent(url);
        } else if (USE_CORS_PROXY && brandId.startsWith('http')) {
            url = CORS_PROXY_URL + encodeURIComponent(brandId);
        }
        
        console.log(`Fetching products from: ${url}`);
        const response = await fetch(url);
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const text = await response.text();
        console.log(`Raw XML for brand ${brandId} (first 500 chars):`, text.substring(0, 500));
        
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(text, 'text/xml');
        
        // Check for parsing errors
        const parserError = xmlDoc.querySelector('parsererror');
        if (parserError) {
            console.error('XML Parse Error:', parserError.textContent);
            return null;
        }
        
        // Log structure
        console.log(`Root element for brand ${brandId}:`, xmlDoc.documentElement.tagName);
        
        const products = [];
        
        // Actual structure: <products><product>...</product></products>
        const productElements = xmlDoc.querySelectorAll('product');
        
        console.log(`Found ${productElements.length} product elements for brand ${brandId}`);
        
        productElements.forEach((item) => {
            // Helper function to get text content
            const getText = (selector) => {
                const element = item.querySelector(selector);
                return element?.textContent?.trim() || '';
            };
            
            // Get all images from images collection
            const imageElements = item.querySelectorAll('images > image');
            const images = Array.from(imageElements).map(img => img.textContent?.trim()).filter(Boolean);
            const imageUrl = images.length > 0 ? images[0] : '';
            
            // Get brand name
            const brandElement = item.querySelector('brands > brand > name');
            const brandName = brandElement?.textContent?.trim() || getText('manufacturer') || '';
            
            // Get product code/model
            const productCode = getText('product_code') || '';
            
            // Calculate discount if old_price exists
            const price = parseFloat(getText('price')) || 0;
            const oldPrice = parseFloat(getText('old_price')) || 0;
            let discount = '';
            if (oldPrice > price && oldPrice > 0) {
                const discountPercent = Math.round(((oldPrice - price) / oldPrice) * 100);
                discount = discountPercent > 0 ? discountPercent.toString() : '';
            }
            
            // Extract BTU from title or description if available
            const title = getText('title') || '';
            const btuMatch = title.match(/(\d+)\s*000?\s*btu/i) || title.match(/(\d+)\s*btu/i);
            const btu = btuMatch ? `${btuMatch[1]}000 BTU` : '';
            
            // Try to extract specifications from XML if available
            const specs = {};
            
            // Look for common specification fields in XML
            const specFields = {
                type: ['type', 'product_type', 'installation_type', 'mounting_type'],
                technology: ['technology', 'tech', 'inverter', 'inverter_type'],
                coolingPower: ['cooling_power', 'cooling_capacity', 'cooling', 'power_cooling'],
                heatingPower: ['heating_power', 'heating_capacity', 'heating', 'power_heating'],
                energyClassCooling: ['energy_class_cooling', 'energy_cooling', 'efficiency_cooling', 'seer_class'],
                energyClassHeating: ['energy_class_heating', 'energy_heating', 'efficiency_heating', 'scop_class'],
                seer: ['seer', 'seer_value', 'cooling_seer', 'efficiency_seer'],
                scop: ['scop', 'scop_value', 'heating_scop', 'efficiency_scop'],
                noiseIndoor: ['noise_indoor', 'noise_level_indoor', 'sound_indoor', 'db_indoor'],
                noiseOutdoor: ['noise_outdoor', 'noise_level_outdoor', 'sound_outdoor', 'db_outdoor'],
                refrigerant: ['refrigerant', 'gas', 'freon', 'refrigerant_type'],
                dimensions: ['dimensions', 'size', 'dimensions_indoor', 'size_indoor'],
                weight: ['weight', 'weight_indoor'],
                area: ['area', 'coverage_area', 'room_size', 'm2'],
                warranty: ['warranty', 'warranty_months', 'warranty_years', 'guarantee']
            };
            
            // Try to find each spec field in XML
            Object.keys(specFields).forEach(specKey => {
                for (const fieldName of specFields[specKey]) {
                    const value = getText(fieldName);
                    if (value) {
                        specs[specKey] = value;
                        break;
                    }
                }
            });
            
            // Try to extract specs from description and title if available
            const fullDescription = getText('description') || getText('short_description') || '';
            const fullText = (title + ' ' + fullDescription).toLowerCase();
            
            // Extract cooling power from BTU or kW in text - improved patterns
            if (!specs.coolingPower) {
                // Try multiple BTU patterns - handle various formats
                const btuPatterns = [
                    /(\d+)\s*000\s*btu/i,           // "12 000 BTU"
                    /(\d+)\s*,\s*000\s*btu/i,        // "12,000 BTU"
                    /(\d+)\s*000\s*btu/i,            // "12000 BTU"
                    /(\d+)\s*btu/i,                  // "12000 BTU" or "12 BTU"
                    /мощност[:\s]*(\d+)\s*000?\s*btu/i,  // "мощност: 12 000 BTU"
                    /cooling[:\s]*(\d+)\s*000?\s*btu/i,   // "cooling: 12 000 BTU"
                    /(\d+)\s*000/i                   // "12 000" (implied BTU)
                ];
                
                for (const pattern of btuPatterns) {
                    const btuMatch = fullText.match(pattern);
                if (btuMatch) {
                        let btuValue = parseInt(btuMatch[1]);
                        // If pattern has "000" in it, multiply by 1000
                        if (pattern.source.includes('000')) {
                            btuValue = btuValue * 1000;
                        } else if (btuValue < 1000 && btuValue >= 9) {
                            // Single digit like "9" usually means 9000 BTU
                            btuValue = btuValue * 1000;
                        }
                    if (btuValue >= 1000) {
                        specs.coolingPower = `${btuValue} BTU`;
                            console.log(`[Bulclima] Extracted cooling power: ${specs.coolingPower}`);
                            break;
                        }
                    }
                }
                
                // Also try kW if BTU not found
                if (!specs.coolingPower) {
                    const kwPatterns = [
                        /(\d+\.?\d*)\s*kw/i,
                        /(\d+\.?\d*)\s*квт/i,
                        /мощност[:\s]*(\d+\.?\d*)\s*kw/i,
                        /cooling[:\s]*(\d+\.?\d*)\s*kw/i
                    ];
                    
                    for (const pattern of kwPatterns) {
                        const kwMatch = fullText.match(pattern);
                if (kwMatch) {
                    specs.coolingPower = `${kwMatch[1]} kW`;
                            console.log(`[Bulclima] Extracted cooling power: ${specs.coolingPower}`);
                            break;
                        }
                    }
                }
            }
            
            // Extract noise level
            if (!specs.noiseIndoor) {
                const noiseMatch = fullText.match(/(\d+)\s*[-–]\s*(\d+)\s*db/i) || fullText.match(/(\d+)\s*db/i);
                if (noiseMatch) {
                    specs.noiseIndoor = noiseMatch[0];
                }
            }
            
            // Extract energy class - improved patterns
            if (!specs.energyClassCooling) {
                // Try multiple patterns for energy class
                const energyPatterns = [
                    /a\+\+\+/i,                      // "A+++"
                    /a\+\+/i,                        // "A++"
                    /a\+/i,                          // "A+"
                    /\ba\b/i,                        // Just "A"
                    /клас[:\s]*([a-z]\+{0,3})/i,    // "клас: A++"
                    /енергиен\s*клас[:\s]*([a-z]\+{0,3})/i,  // "енергиен клас: A++"
                    /energy[:\s]*class[:\s]*([a-z]\+{0,3})/i, // "energy class: A++"
                    /клас\s*охлаждане[:\s]*([a-z]\+{0,3})/i  // "клас охлаждане: A++"
                ];
                
                for (const pattern of energyPatterns) {
                    const energyMatch = fullText.match(pattern);
                if (energyMatch) {
                        const energyClass = energyMatch[1] || energyMatch[0];
                        specs.energyClassCooling = energyClass.toUpperCase();
                        console.log(`[Bulclima] Extracted energy class: ${specs.energyClassCooling}`);
                        break;
                    }
                }
            }
            
            // Extract refrigerant type
            if (!specs.refrigerant) {
                const refMatch = fullText.match(/r32/i) || fullText.match(/r410a/i) || fullText.match(/r134a/i);
                if (refMatch) {
                    specs.refrigerant = refMatch[0].toUpperCase();
                }
            }
            
            // Extract area coverage
            if (!specs.area) {
                const areaMatch = fullText.match(/(\d+)\s*m[²2]/i) || fullText.match(/до\s*(\d+)\s*m/i);
                if (areaMatch) {
                    specs.area = `до ${areaMatch[1]} m²`;
                }
            }
            
            // Extract SEER value
            if (!specs.seer) {
                const seerMatch = fullText.match(/seer[:\s]*(\d+\.?\d*)/i) || fullDescription.match(/seer[:\s]*(\d+\.?\d*)/i);
                if (seerMatch) {
                    specs.seer = seerMatch[1];
                }
            }
            
            // Extract SCOP value
            if (!specs.scop) {
                const scopMatch = fullText.match(/scop[:\s]*(\d+\.?\d*)/i) || fullDescription.match(/scop[:\s]*(\d+\.?\d*)/i);
                if (scopMatch) {
                    specs.scop = scopMatch[1];
                }
            }
            
            // Extract type from description
            if (!specs.type) {
                if (fullText.includes('стенен') || fullText.includes('wall')) {
                    specs.type = 'стенен климатик';
                } else if (fullText.includes('подов') || fullText.includes('floor')) {
                    specs.type = 'подов климатик';
                } else if (fullText.includes('таванен') || fullText.includes('ceiling')) {
                    specs.type = 'таванен климатик';
                } else if (fullText.includes('касет') || fullText.includes('cassette')) {
                    specs.type = 'касетъчен климатик';
                }
            }
            
            // Extract technology from description
            if (!specs.technology) {
                if (fullText.includes('инвертер') || fullText.includes('inverter')) {
                    specs.technology = 'инвертерен климатик';
                } else if (fullText.includes('хиперинвертер') || fullText.includes('hyperinverter')) {
                    specs.technology = 'хиперинвертерен климатик';
                }
            }
            
            // Extract warranty from description - improved pattern matching
            if (!specs.warranty) {
                // Try multiple patterns for warranty - more comprehensive
                const warrantyPatterns = [
                    /(\d+)\s*(месеца|месец|мес\.|months?)/i,
                    /(\d+)\s*(години|година|год\.|years?)/i,
                    /гаранция[:\s]*(\d+)\s*(месеца|месец|мес\.|months?|години|година|год\.|years?)/i,
                    /warranty[:\s]*(\d+)\s*(months?|years?|месеца|месец|години|година)/i,
                    /(\d+)\s*(мес|год)/i
                ];
                
                for (const pattern of warrantyPatterns) {
                    const warrantyMatch = fullText.match(pattern);
                    if (warrantyMatch) {
                        const number = warrantyMatch[1];
                        const unit = (warrantyMatch[2] || warrantyMatch[3] || '').toLowerCase();
                        
                        console.log(`[Bulclima] Found warranty match: ${number} ${unit} (from text: "${fullText.substring(Math.max(0, fullText.indexOf(warrantyMatch[0]) - 20), Math.min(fullText.length, fullText.indexOf(warrantyMatch[0]) + warrantyMatch[0].length + 20))}")`);
                        
                        // Normalize to Bulgarian format and convert months to years if >= 12
                        if (unit.includes('month') || unit.includes('месец') || unit.includes('мес')) {
                            const months = parseInt(number);
                            if (months >= 12) {
                                // Convert months to years during extraction for consistency
                                const years = Math.floor(months / 12);
                                specs.warranty = `${years} години`;
                                console.log(`[Bulclima] Converted ${months} months to ${years} години during extraction`);
                            } else {
                                specs.warranty = `${number} месеца`;
                                console.log(`[Bulclima] Stored as ${number} месеца (less than 12 months)`);
                            }
                        } else if (unit.includes('year') || unit.includes('год')) {
                            specs.warranty = `${number} години`;
                            console.log(`[Bulclima] Stored as ${number} години`);
                        } else {
                            specs.warranty = `${number} ${unit}`;
                            console.log(`[Bulclima] Stored as ${number} ${unit} (unknown unit)`);
                        }
                        break;
                    }
                }
            }
            
            const product = {
                id: getText('id') || '',
                name: title || productCode || 'Климатик',
                brand: brandName,
                model: productCode,
                btu: btu,
                price: price > 0 ? price.toString() : '',
                oldPrice: oldPrice > 0 ? oldPrice.toString() : '',
                image: imageUrl,
                images: images.length > 0 ? images : (imageUrl ? [imageUrl] : []),
                description: getText('short_description') || getText('description') || '',
                category: getText('category') || '',
                subCategory: getText('sub_category') || '',
                sku: getText('sku') || productCode,
                discount: discount,
                features: [],
                specifications: specs
            };
            
            // Extract features from multiple sources
            const features = [];
            
            // Try to get features from dedicated XML field
            const featuresElement = item.querySelector('features');
            if (featuresElement) {
                const featureItems = featuresElement.querySelectorAll('feature, item');
                featureItems.forEach(feature => {
                    const text = feature.textContent?.trim();
                    if (text) features.push(text);
                });
            }
            
            // Try characteristics field
            const characteristicsElement = item.querySelector('characteristics');
            if (characteristicsElement) {
                const charItems = characteristicsElement.querySelectorAll('characteristic, item');
                charItems.forEach(char => {
                    const text = char.textContent?.trim();
                    if (text) features.push(text);
                });
            }
            
            // Extract features from short_description if it contains HTML list
            const shortDesc = getText('short_description');
            if (shortDesc && features.length === 0) {
                // Try to parse HTML list items
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = shortDesc;
                const listItems = tempDiv.querySelectorAll('li');
                if (listItems.length > 0) {
                    features.push(...Array.from(listItems).map(li => li.textContent?.trim()).filter(Boolean));
                } else {
                    // Try to split by multiple spaces or other separators
                    const splitFeatures = shortDesc.split(/\s{4,}|[;。\n]/).map(f => f.trim()).filter(f => f.length > 0);
                    if (splitFeatures.length > 1) {
                        features.push(...splitFeatures);
                    }
                }
            }
            
            // Extract features from description if no features found yet
            if (features.length === 0) {
                const fullDesc = getText('description');
                if (fullDesc) {
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = fullDesc;
                    const listItems = tempDiv.querySelectorAll('li');
                    if (listItems.length > 0) {
                        features.push(...Array.from(listItems).map(li => li.textContent?.trim()).filter(Boolean));
                }
            }
            }
            
            product.features = features;
            
            // Only add product if it has at least an ID and name
            if (product.id && product.name && product.name !== 'Климатик') {
                products.push(product);
            }
        });
        
        console.log(`Products parsed for brand ${brandId}:`, products.length, products);
        return products;
    } catch (error) {
        console.error(`Error fetching products for brand ${brandId}:`, error);
        if (error.message.includes('CORS') || error.message.includes('fetch')) {
            console.warn('CORS error detected. You may need to use a proxy or enable CORS on the API server.');
        }
        return null;
    }
}

// ============================================
// DISTRIBUTOR 2: Bittel API Functions
// ============================================

/**
 * Fetch products from Bittel API (with pagination support)
 * @param {number} page - Page number (default: 1)
 * @returns {Promise<Array>} Array of products from Bittel
 */
async function fetchBittelProducts(page = 1) {
    if (!USE_BITTEL) {
        console.log('Bittel distributor is disabled');
        return {
            products: [],
            hasMore: false,
            currentPage: page,
            totalPages: 1
        };
    }
    
    try {
        // Build URL with pagination
        let url = `${BITTEL_API_BASE_URL}?page=${page}`;
        const originalUrl = url; // Keep for logging
        
        // Use proxy if enabled
        if (USE_CORS_PROXY) {
            url = CORS_PROXY_URL + encodeURIComponent(url);
        }
        
        console.log(`[BITTEL] Fetching products from page ${page}`);
        console.log(`[BITTEL] Original URL: ${originalUrl}`);
        console.log(`[BITTEL] Fetch URL: ${url.substring(0, 100)}...`);
        const response = await fetch(url, {
            method: 'GET',
            headers: {
                'Accept': 'application/xml, text/xml, */*'
            }
        });
        
        if (!response.ok) {
            console.error(`[BITTEL] HTTP error! status: ${response.status} ${response.statusText}`);
            const errorText = await response.text().catch(() => '');
            console.error(`[BITTEL] Error response:`, errorText.substring(0, 500));
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const text = await response.text();
        console.log(`[BITTEL] Response received, length: ${text.length} characters`);
        console.log(`[BITTEL] XML response (page ${page}, first 1000 chars):`, text.substring(0, 1000));
        
        if (!text || text.trim().length === 0) {
            console.error('Bittel: Empty response');
            return {
                products: [],
                hasMore: false,
                currentPage: page,
                totalPages: 1
            };
        }
        
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(text, 'text/xml');
        
        // Check for parsing errors
        const parserError = xmlDoc.querySelector('parsererror');
        if (parserError) {
            console.error('Bittel XML Parse Error:', parserError.textContent);
            console.error('XML content:', text.substring(0, 500));
            return {
                products: [],
                hasMore: false,
                currentPage: page,
                totalPages: 1
            };
        }
        
        // Log XML structure for debugging
        console.log(`[BITTEL] XML root element: ${xmlDoc.documentElement.tagName}`);
        const rootChildren = Array.from(xmlDoc.documentElement.children).map(c => c.tagName);
        console.log(`[BITTEL] XML root children (${rootChildren.length}):`, rootChildren);
        
        // Parse info section first (contains pagination info)
        const infoElement = xmlDoc.querySelector('info');
        let pagesCount = 1;
        let currentPageNum = page;
        let productsCount = 0;
        
        if (infoElement) {
            const pagesCountText = infoElement.querySelector('pages_count')?.textContent || '1';
            const currentPageText = infoElement.querySelector('pages_current')?.textContent || page.toString();
            const productsCountText = infoElement.querySelector('products_count')?.textContent || '0';
            const productsPerPageText = infoElement.querySelector('products_per_page')?.textContent || '0';
            
            pagesCount = parseInt(pagesCountText) || 1;
            currentPageNum = parseInt(currentPageText) || page;
            productsCount = parseInt(productsCountText) || 0;
            
            console.log(`[BITTEL] Info section found:`);
            console.log(`[BITTEL]   - Total products: ${productsCount}`);
            console.log(`[BITTEL]   - Products per page: ${productsPerPageText}`);
            console.log(`[BITTEL]   - Total pages: ${pagesCount}`);
            console.log(`[BITTEL]   - Current page: ${currentPageNum}`);
        } else {
            console.warn(`[BITTEL] No <info> element found, using fallback pagination detection`);
        }
        
        // Parse products - Bittel uses <product> elements
        const products = [];
        let productElements = xmlDoc.querySelectorAll('product');
        
        console.log(`[BITTEL] Found ${productElements.length} <product> elements on page ${page}`);
        
        // If no products found, try alternative selectors (shouldn't be needed but just in case)
        if (productElements.length === 0) {
            productElements = xmlDoc.querySelectorAll('products > product');
            console.log(`[BITTEL] Trying alternative selector "products > product": ${productElements.length} elements`);
        }
        
        let normalizedCount = 0;
        let skippedCount = 0;
        
        productElements.forEach((item, index) => {
            const product = normalizeBittelProduct(item);
            if (product) {
                products.push(product);
                normalizedCount++;
                if (index < 3) {
                    console.log(`[BITTEL] Normalized product ${index + 1}:`, {
                        id: product.id,
                        name: product.name,
                        brand: product.brand,
                        price: product.price
                    });
                }
            } else {
                skippedCount++;
                if (index < 3) {
                    console.warn(`[BITTEL] Skipped product ${index + 1} (normalization failed)`);
                }
            }
        });
        
        console.log(`[BITTEL] Normalized: ${normalizedCount}, Skipped: ${skippedCount}`);
        
        // Determine if there are more pages
        // Use info from <info> element if available, otherwise calculate
        const hasMore = currentPageNum < pagesCount;
        
        console.log(`[BITTEL] Page ${currentPageNum} of ${pagesCount}, found ${products.length} products, hasMore: ${hasMore}`);
        
        if (products.length === 0 && page === 1) {
            console.warn(`[BITTEL] WARNING: No products found on first page!`);
            console.warn(`[BITTEL] This might indicate:`);
            console.warn(`[BITTEL] 1. Invalid API key`);
            console.warn(`[BITTEL] 2. Different XML structure than expected`);
            console.warn(`[BITTEL] 3. API endpoint issue`);
            console.warn(`[BITTEL] Check the XML structure above to see what's actually returned`);
        }
        
        return {
            products: products,
            hasMore: hasMore,
            currentPage: currentPageNum,
            totalPages: pagesCount
        };
    } catch (error) {
        console.error(`[BITTEL] ERROR fetching products (page ${page}):`, error);
        console.error(`[BITTEL] Error message:`, error.message);
        console.error(`[BITTEL] Error stack:`, error.stack);
        return {
            products: [],
            hasMore: false,
            currentPage: page,
            totalPages: 1
        };
    }
}

/**
 * Fetch all products from Bittel (all pages)
 * @returns {Promise<Array>} Array of all products from Bittel
 */
async function fetchAllBittelProducts() {
    if (!USE_BITTEL) {
        return [];
    }
    
    let allProducts = [];
    let currentPage = 1;
    let hasMore = true;
    
    console.log('[BITTEL] ========================================');
    console.log('[BITTEL] Starting to fetch all Bittel products...');
    console.log('[BITTEL] API Key:', BITTEL_API_KEY.substring(0, 10) + '...');
    console.log('[BITTEL] Base URL:', BITTEL_API_BASE_URL);
    console.log('[BITTEL] ========================================');
    
    while (hasMore) {
        try {
            const result = await fetchBittelProducts(currentPage);
            
            // Check if we got a valid result
            if (!result || typeof result !== 'object') {
                console.error(`Bittel: Invalid result format on page ${currentPage}`);
                break;
            }
            
            // Add products if any
            if (result.products && Array.isArray(result.products)) {
                allProducts.push(...result.products);
                console.log(`[BITTEL] Page ${currentPage}: Added ${result.products.length} products (total: ${allProducts.length})`);
            } else {
                console.warn(`[BITTEL] Page ${currentPage}: No products array in result`);
            }
            
            // Check if we should continue
            hasMore = result.hasMore === true && result.products && result.products.length > 0;
            
            // If we got 0 products and it's not the first page, we've probably reached the end
            if (currentPage > 1 && (!result.products || result.products.length === 0)) {
                console.log(`Bittel: No products on page ${currentPage}, stopping`);
                hasMore = false;
            }
            
            currentPage++;
            
            // Safety limit: don't fetch more than 50 pages
            if (currentPage > 50) {
                console.warn('Bittel: Reached safety limit of 50 pages');
                break;
            }
            
            // Small delay between requests to avoid overwhelming the server
            if (hasMore) {
                await new Promise(resolve => setTimeout(resolve, 200));
            }
        } catch (error) {
            console.error(`Error fetching Bittel page ${currentPage}:`, error);
            console.error('Error details:', error.message);
            // If it's the first page and it fails, stop completely
            if (currentPage === 1) {
                console.error('Bittel: Failed to fetch first page, stopping');
                break;
            }
            // Otherwise, try to continue (might be a temporary issue)
            hasMore = false;
        }
    }
    
    console.log(`[BITTEL] ========================================`);
    console.log(`[BITTEL] Finished fetching: ${allProducts.length} total products`);
    console.log(`[BITTEL] ========================================`);
    
    if (allProducts.length === 0) {
        console.error(`[BITTEL] ⚠️  WARNING: No products fetched from Bittel!`);
        console.error(`[BITTEL] Possible reasons:`);
        console.error(`[BITTEL] 1. Invalid API key - check BITTEL_API_KEY`);
        console.error(`[BITTEL] 2. CORS issues - check network tab`);
        console.error(`[BITTEL] 3. API endpoint changed`);
        console.error(`[BITTEL] 4. XML structure different than expected`);
    }
    
    return allProducts;
}

/**
 * Normalize Bittel product XML to unified product format
 * @param {Element} item - XML product element from Bittel
 * @returns {Object|null} Normalized product object or null if invalid
 */
function normalizeBittelProduct(item) {
    try {
        // Helper function to get text content
        const getText = (selector) => {
            const element = item.querySelector(selector);
            return element?.textContent?.trim() || '';
        };
        
        // Get product ID (required)
        const id = getText('id');
        if (!id) {
            console.warn('Bittel product missing ID, skipping');
            return null;
        }
        
        // Get basic info
        const title = getText('title') || '';
        const manufacturer = getText('manufacturer') || '';
        const type = getText('type') || '';
        const group = getText('group_description') || getText('group') || '';
        const subgroup = getText('subgroup_description') || getText('subgroup') || '';
        const description = getText('description') || '';
        const link = getText('link') || '';
        const barcode = getText('barcode') || '';
        const color = getText('color') || '';
        
        // Get prices
        const priceClient = parseFloat(getText('price_client')) || 0;
        const priceClientPromo = parseFloat(getText('price_client_promo')) || 0;
        const dealerPrice = parseFloat(getText('dealer_price')) || 0;
        const isPromo = getText('is_promo') === '1';
        
        // Determine final price and old price
        let price = priceClient;
        let oldPrice = 0;
        let discount = '';
        
        if (isPromo && priceClientPromo > 0) {
            // Promo price is the current price, regular price is old price
            price = priceClientPromo;
            oldPrice = priceClient;
        } else if (priceClient > 0) {
            price = priceClient;
        }
        
        // Calculate discount percentage
        if (oldPrice > price && oldPrice > 0) {
            const discountPercent = Math.round(((oldPrice - price) / oldPrice) * 100);
            discount = discountPercent > 0 ? discountPercent.toString() : '';
        }
        
        // Get images from gallery - Bittel structure: <gallery><file>URL</file></gallery>
        const imageElements = item.querySelectorAll('gallery > file');
        const images = Array.from(imageElements).map(img => {
            const url = img.textContent?.trim();
            return url;
        }).filter(Boolean);
        const imageUrl = images.length > 0 ? images[0] : '';
        
        if (images.length > 0) {
            console.log(`[BITTEL] Product ${id} has ${images.length} images`);
        }
        
        // Extract BTU from title or description
        const fullText = (title + ' ' + description).toLowerCase();
        const btuMatch = fullText.match(/(\d+)\s*000?\s*btu/i) || fullText.match(/(\d+)\s*btu/i);
        const btu = btuMatch ? `${btuMatch[1]}000 BTU` : '';
        
        // Extract features from features structure
        const features = [];
        const featureGroups = item.querySelectorAll('features > feature');
        featureGroups.forEach(group => {
            const groupName = group.querySelector('name')?.textContent?.trim() || '';
            const items = group.querySelectorAll('items > item');
            items.forEach(item => {
                const itemName = item.querySelector('name')?.textContent?.trim() || '';
                const itemValue = item.querySelector('value')?.textContent?.trim() || '';
                if (itemName && itemValue) {
                    features.push(`${itemName}: ${itemValue}`);
                } else if (itemName) {
                    features.push(itemName);
                }
            });
        });
        
        // Extract specifications from features
        const specs = {};
        featureGroups.forEach(group => {
            const groupName = group.querySelector('name')?.textContent?.trim() || '';
            const items = group.querySelectorAll('items > item');
            items.forEach(item => {
                const itemName = item.querySelector('name')?.textContent?.trim() || '';
                const itemValue = item.querySelector('value')?.textContent?.trim() || '';
                
                // Map common characteristics to spec fields
                const nameLower = itemName.toLowerCase();
                const valueLower = itemValue.toLowerCase();
                
                if (nameLower.includes('тип') || nameLower.includes('type')) {
                    specs.type = itemValue;
                } else if (nameLower.includes('технология') || nameLower.includes('technology') || nameLower.includes('инвертер')) {
                    specs.technology = itemValue;
                } else if (nameLower.includes('мощност охлаждане') || nameLower.includes('cooling power') || nameLower.includes('btu')) {
                    specs.coolingPower = itemValue;
                } else if (nameLower.includes('мощност отопление') || nameLower.includes('heating power')) {
                    specs.heatingPower = itemValue;
                } else if (nameLower.includes('seer')) {
                    specs.seer = itemValue;
                } else if (nameLower.includes('scop')) {
                    specs.scop = itemValue;
                } else if (nameLower.includes('енергиен клас') || nameLower.includes('energy class')) {
                    if (!specs.energyClassCooling) {
                        specs.energyClassCooling = itemValue;
                    } else {
                        specs.energyClassHeating = itemValue;
                    }
                } else if (nameLower.includes('шум') || nameLower.includes('noise')) {
                    if (nameLower.includes('вътрешно') || nameLower.includes('indoor')) {
                        specs.noiseIndoor = itemValue;
                    } else if (nameLower.includes('външно') || nameLower.includes('outdoor')) {
                        specs.noiseOutdoor = itemValue;
                    }
                } else if (nameLower.includes('хладилен') || nameLower.includes('refrigerant')) {
                    specs.refrigerant = itemValue;
                } else if (nameLower.includes('размер') || nameLower.includes('dimension')) {
                    specs.dimensions = itemValue;
                } else if (nameLower.includes('гаранция') || nameLower.includes('warranty')) {
                    specs.warranty = itemValue;
                }
            });
        });
        
        // Extract type from group/subgroup if not in specs
        if (!specs.type && (group || subgroup || type)) {
            const typeText = (group + ' ' + subgroup + ' ' + type).toLowerCase();
            if (typeText.includes('стенен') || typeText.includes('wall')) {
                specs.type = 'стенен климатик';
            } else if (typeText.includes('подов') || typeText.includes('floor')) {
                specs.type = 'подов климатик';
            } else if (typeText.includes('таванен') || typeText.includes('ceiling')) {
                specs.type = 'таванен климатик';
            } else if (typeText.includes('касет') || typeText.includes('cassette')) {
                specs.type = 'касетъчен климатик';
            } else if (typeText.includes('канален') || typeText.includes('duct')) {
                specs.type = 'канален климатик';
            } else if (typeText.includes('колонен') || typeText.includes('column')) {
                specs.type = 'колонен климатик';
            } else if (typeText.includes('мобилен') || typeText.includes('mobile')) {
                specs.type = 'мобилен климатик';
            }
        }
        
        // Get availability - Bittel provides: "Наличен", "Ограничена наличност", "Неналичен"
        const availability = getText('availability') || '';
        const isAsk = getText('is_ask') === '1' || getText('is_ask') === 'true';
        const stockSize = getText('stock_size') || '';
        
        // Log if product has special availability status
        if (availability && availability !== 'Наличен') {
            console.log(`[BITTEL] Product ${id} availability: ${availability}${stockSize ? ` (${stockSize} left)` : ''}`);
        }
        
        // Build normalized product object
        const product = {
            id: `bittel_${id}`, // Prefix to avoid ID conflicts
            name: title || 'Климатик',
            brand: manufacturer,
            model: id, // Use ID as model if no separate model field
            btu: btu,
            price: price > 0 ? price.toString() : '',
            oldPrice: oldPrice > 0 ? oldPrice.toString() : '',
            dealerPrice: dealerPrice > 0 ? dealerPrice.toString() : '',
            image: imageUrl,
            images: images.length > 0 ? images : (imageUrl ? [imageUrl] : []),
            description: description,
            category: group,
            subCategory: subgroup,
            sku: barcode || id,
            discount: discount,
            features: features,
            specifications: specs,
            distributor: 'bittel', // Mark source
            availability: availability,
            isAsk: isAsk,
            stockSize: stockSize,
            link: link,
            color: color
        };
        
        return product;
    } catch (error) {
        console.error('Error normalizing Bittel product:', error);
        return null;
    }
}

// ============================================
// UNIFIED PRODUCT FETCHING
// ============================================

/**
 * Fetch all products from all enabled distributors and merge them
 * @returns {Promise<Array>} Array of all products from all distributors
 */
async function getAllProducts() {
    console.log('Fetching products from all distributors...');
    const allProducts = [];
    
    // Fetch from Bulclima
    if (USE_BULCLIMA) {
        try {
            console.log('Fetching from Bulclima...');
            const brands = await fetchBrands();
            if (brands && brands.length > 0) {
                console.log(`Found ${brands.length} brands from Bulclima`);
                for (const brand of brands) {
                    try {
                        const products = await fetchBrandProducts(brand.id);
                        if (products && products.length > 0) {
                            // Mark products with distributor source
                            products.forEach(p => {
                                p.distributor = 'bulclima';
                            });
                            allProducts.push(...products);
                            console.log(`Added ${products.length} products from brand: ${brand.title}`);
                        }
                    } catch (error) {
                        console.warn(`Failed to fetch products for Bulclima brand ${brand.id} (${brand.title}):`, error);
                    }
                }
            } else {
                console.warn('No brands found from Bulclima');
            }
            console.log(`Fetched ${allProducts.length} products from Bulclima`);
        } catch (error) {
            console.error('Error fetching from Bulclima:', error);
            console.error('Error details:', error.message, error.stack);
        }
    } else {
        console.log('Bulclima distributor is disabled');
    }
    
    // Fetch from Bittel
    if (USE_BITTEL) {
        try {
            console.log('Fetching from Bittel...');
            const bittelProducts = await fetchAllBittelProducts();
            if (bittelProducts && Array.isArray(bittelProducts) && bittelProducts.length > 0) {
                allProducts.push(...bittelProducts);
                console.log(`✓ Successfully fetched ${bittelProducts.length} products from Bittel`);
            } else {
                console.warn('⚠ No products fetched from Bittel (check API key and network connection)');
            }
        } catch (error) {
            console.error('✗ Error fetching from Bittel:', error);
            console.error('Error details:', error.message);
            if (error.stack) {
                console.error('Stack:', error.stack);
            }
            console.warn('⚠ Continuing with products from other distributors...');
        }
    } else {
        console.log('Bittel distributor is disabled (set USE_BITTEL = true and add API key to enable)');
    }
    
    // Count products by distributor
    const bulclimaCount = allProducts.filter(p => p.distributor === 'bulclima').length;
    const bittelCount = allProducts.filter(p => p.distributor === 'bittel').length;
    const unknownCount = allProducts.filter(p => !p.distributor).length;
    
    console.log('========================================');
    console.log('PRODUCT FETCHING SUMMARY:');
    console.log(`Total products: ${allProducts.length}`);
    console.log(`  - Bulclima: ${bulclimaCount}`);
    console.log(`  - Bittel: ${bittelCount}`);
    if (unknownCount > 0) {
        console.log(`  - Unknown source: ${unknownCount}`);
    }
    console.log('========================================');
    
    if (allProducts.length === 0) {
        console.error('⚠️  WARNING: No products fetched from any distributor!');
        console.error('Check:');
        console.error('1. USE_BULCLIMA is set to true');
        console.error('2. USE_BITTEL is set to true (if using Bittel)');
        console.error('3. Bittel API key is correct (if using Bittel)');
        console.error('4. Network/CORS issues');
    } else if (bittelCount === 0 && USE_BITTEL) {
        console.warn('⚠️  WARNING: Bittel is enabled but returned 0 products!');
        console.warn('Check the [BITTEL] logs above for details.');
    }
    
    return allProducts;
}

/**
 * Determine which category a product belongs to
 * Returns the category key (e.g., 'wall', 'floor') or null if no match
 */
function getProductCategory(product) {
    const catLower = (product.category || '').toLowerCase();
    const subCatLower = (product.subCategory || '').toLowerCase();
    const nameLower = (product.name || '').toLowerCase();
    
    // Check each category in CATEGORY_MAP
    for (const [categoryKey, keywords] of Object.entries(CATEGORY_MAP)) {
        for (const keyword of keywords) {
            const keywordLower = keyword.toLowerCase();
            if (catLower.includes(keywordLower) || 
                subCatLower.includes(keywordLower) || 
                nameLower.includes(keywordLower)) {
                return categoryKey;
            }
        }
    }
    
    return null; // Product doesn't match any known category
}

/**
 * Filter products by category
 */
function filterProductsByCategory(products, category) {
    if (!category || category === 'all') {
        return products;
    }
    
    const categoryKeywords = CATEGORY_MAP[category] || [category];
    console.log(`Filtering by category: ${category}`, categoryKeywords);
    console.log(`Total products before filter: ${products.length}`);
    
    // Special handling for multisplit - require exact phrase "мулти сплит система" in product name only
    if (category === 'multisplit') {
        const filtered = products.filter(product => {
            // Only check the product name field - ignore category/subcategory as they may be incorrect
            const nameLower = (product.name || '').toLowerCase();
            
            // Must contain the exact phrase "мулти сплит система" or "мулти сплит" in the product name
            // This ensures we only match products that explicitly have this in their name
            if (nameLower.includes('мулти сплит система') || 
                nameLower.includes('мулти сплит') || 
                nameLower.includes('мултисплит')) {
                return true;
            }
            
            return false;
        });
        
        console.log(`Products after filter: ${filtered.length}`);
        return filtered;
    }
    
    // Standard filtering for other categories
    const filtered = products.filter(product => {
        const catLower = (product.category || '').toLowerCase();
        const subCatLower = (product.subCategory || '').toLowerCase();
        const nameLower = (product.name || '').toLowerCase();
        
        // Check if any of the category keywords match
        for (const keyword of categoryKeywords) {
            const keywordLower = keyword.toLowerCase();
            if (catLower.includes(keywordLower) || 
                subCatLower.includes(keywordLower) || 
                nameLower.includes(keywordLower)) {
                return true;
            }
        }
        return false;
    });
    
    console.log(`Products after filter: ${filtered.length}`);
    return filtered;
}

/**
 * Filter products by brand
 */
function filterProductsByBrand(products, brandName) {
    if (!brandName || brandName === 'all') {
        return products;
    }
    
    return products.filter(product => 
        product.brand && 
        product.brand.toLowerCase().includes(brandName.toLowerCase())
    );
}

/**
 * Filter products by price range
 */
function filterProductsByPrice(products, minPrice, maxPrice) {
    return products.filter(product => {
        const price = parseFloat(product.price) || 0;
        if (minPrice && price < minPrice) return false;
        if (maxPrice && price > maxPrice) return false;
        return true;
    });
}

/**
 * Filter products by room size (based on BTU and area coverage)
 * BTU to m² mapping:
 * - 7000-9000 BTU ≈ до 15 m²
 * - 9000-12000 BTU ≈ 15-20 m²
 * - 12000-15000 BTU ≈ 20-25 m²
 * - 15000-18000 BTU ≈ 25-30 m²
 * - 18000-24000 BTU ≈ 30-40 m²
 * - 24000-30000 BTU ≈ 40-50 m²
 * - 30000-36000 BTU ≈ 50-65 m²
 * - 36000+ BTU ≈ над 65 m²
 */
function filterProductsByRoomSize(products, roomSizeRange) {
    if (!roomSizeRange || roomSizeRange === 'all') {
        return products;
    }
    
    const btuRanges = {
        '0-15': { min: 0, max: 9000 },
        '15-20': { min: 9000, max: 12000 },
        '20-25': { min: 12000, max: 15000 },
        '25-30': { min: 15000, max: 18000 },
        '30-40': { min: 18000, max: 24000 },
        '40-50': { min: 24000, max: 30000 },
        '50-65': { min: 30000, max: 36000 },
        '65+': { min: 36000, max: Infinity }
    };
    
    const range = btuRanges[roomSizeRange];
    if (!range) return products;
    
    return products.filter(product => {
        // Try to get BTU from product
        const btu = product.btu ? parseInt(product.btu) : null;
        
        // If we have BTU, use it
        if (btu) {
            if (roomSizeRange === '65+') {
                return btu >= range.min;
            }
            return btu >= range.min && btu < range.max;
        }
        
        // Otherwise, try to extract from area specification
        const area = product.specifications?.area;
        if (area) {
            const areaMatch = area.match(/(\d+)/);
            if (areaMatch) {
                const areaValue = parseInt(areaMatch[1]);
                switch (roomSizeRange) {
                    case '0-15': return areaValue <= 15;
                    case '15-20': return areaValue > 15 && areaValue <= 20;
                    case '20-25': return areaValue > 20 && areaValue <= 25;
                    case '25-30': return areaValue > 25 && areaValue <= 30;
                    case '30-40': return areaValue > 30 && areaValue <= 40;
                    case '40-50': return areaValue > 40 && areaValue <= 50;
                    case '50-65': return areaValue > 50 && areaValue <= 65;
                    case '65+': return areaValue > 65;
                }
            }
        }
        
        // If no data available, include the product (don't filter out)
        return true;
    });
}

/**
 * Filter products by promotional offers
 */
function filterProductsByPromo(products, promoPrice, promoInstallation) {
    if (!promoPrice && !promoInstallation) {
        return products;
    }
    
    return products.filter(product => {
        if (promoPrice && product.discount && product.discount > 0) {
            return true;
        }
        if (promoInstallation) {
            // Check if product has promotional installation (could be in description or features)
            const desc = (product.description || '').toLowerCase();
            const hasPromoInstall = desc.includes('промоционален монтаж') || 
                                   desc.includes('безплатен монтаж') ||
                                   desc.includes('монтаж включен');
            if (hasPromoInstall) return true;
        }
        return false;
    });
}

/**
 * Render product card HTML
 */
function renderProductCard(product) {
    // Handle image URL
    let imageUrl = product.image || '';
    if (!imageUrl || !imageUrl.startsWith('http')) {
        imageUrl = 'pictures/placeholder-ac.svg';
    }
    
    // Format price
    let price = 'По запитване';
    let priceHtml = '';
    
    // EUR to BGN conversion rate
    const EUR_TO_BGN_RATE = 1.95583;
    
    // Check if price exists and is valid
    const priceNum = product.price ? parseFloat(product.price) : 0;
    const oldPriceNum = product.oldPrice ? parseFloat(product.oldPrice) : 0;
    
    if (!isNaN(priceNum) && priceNum > 0) {
        const priceEuro = priceNum / EUR_TO_BGN_RATE;
        const oldPriceEuro = oldPriceNum > 0 ? oldPriceNum / EUR_TO_BGN_RATE : 0;
        
        if (oldPriceNum > priceNum && oldPriceNum > 0) {
            priceHtml = `
                <div class="product-price-wrapper">
                    <div class="product-price-old-wrapper">
                    <span class="product-price-old">${oldPriceNum.toFixed(2)} лв</span>
                        <span class="product-price-separator">/</span>
                        <span class="product-price-old-euro">${oldPriceEuro.toFixed(2)} €</span>
                    </div>
                    <div class="product-price-current-wrapper">
                        <span class="product-price">${priceNum.toFixed(2)} лв</span>
                        <span class="product-price-separator">/</span>
                        <span class="product-price-euro">${priceEuro.toFixed(2)} €</span>
                    </div>
                </div>
            `;
        } else {
            priceHtml = `
                <div class="product-price-wrapper">
                    <div class="product-price-current-wrapper">
                        <span class="product-price">${priceNum.toFixed(2)} лв</span>
                        <span class="product-price-separator">/</span>
                        <span class="product-price-euro">${priceEuro.toFixed(2)} €</span>
                    </div>
                </div>
            `;
        }
    } else {
        priceHtml = `
            <div class="product-price-wrapper">
                <span class="product-price">${price}</span>
            </div>
        `;
    }
    
    // Format BTU
    const btu = product.btu || '';
    
    // Get product name
    const productName = product.name || 'Климатик';
    const brandName = product.brand || '';
    
    // Build features list - limit to 2 for compact display
    let featuresHtml = '';
    if (product.features && product.features.length > 0) {
        featuresHtml = `<ul class="product-features">
            ${product.features.slice(0, 2).map(f => {
                const truncated = f.length > 50 ? f.substring(0, 50) + '...' : f;
                return `<li><i class="bi bi-check-circle-fill"></i> ${truncated}</li>`;
            }).join('')}
        </ul>`;
    } else if (btu) {
        featuresHtml = `<p class="product-spec">${btu}</p>`;
    }
    
    // Get price for sorting
    const priceForSort = priceNum > 0 ? priceNum : 999999; // Put "По запитване" at the end
    
    return `
        <div class="product-card" data-product-id="${product.id}" data-price="${priceForSort}">
            <div class="product-image-wrapper">
                <img src="${imageUrl}" alt="${productName}" class="product-image" loading="lazy" onerror="this.src='pictures/placeholder-ac.svg'">
                ${product.discount ? `<span class="discount-badge">-${product.discount}%</span>` : ''}
            </div>
            <div class="product-info">
                ${brandName ? `<div class="product-brand-name">${brandName}</div>` : ''}
                <h3 class="product-model">${productName}</h3>
                ${featuresHtml}
                ${priceHtml}
                <a href="product-detail.html?id=${encodeURIComponent(product.id)}&name=${encodeURIComponent(productName)}" class="btn btn-primary btn-small">Научи Повече</a>
            </div>
        </div>
    `;
}

/**
 * Initialize home page promotional products
 */
async function initHomePagePromoProducts() {
    const promoGrid = document.getElementById('promoProductsGrid');
    if (!promoGrid) {
        console.log('Promo products grid not found');
        return;
    }
    
    console.log('Loading promotional products for home page...');
    
    // Show loading state
    promoGrid.innerHTML = '<div class="loading-message" style="grid-column: 1 / -1; text-align: center; padding: var(--spacing-3xl);">Зареждане на промоционални продукти...</div>';
    
    try {
        // Fetch products from all distributors
        const allProducts = await getAllProducts();
        
        if (!allProducts || allProducts.length === 0) {
            promoGrid.innerHTML = '<p class="no-products" style="grid-column: 1 / -1; text-align: center; padding: var(--spacing-3xl);">Няма налични продукти в момента.</p>';
            return;
        }
        
        // Filter ONLY products with discounts (promotional products)
        const promoProductsWithDiscount = allProducts
            .filter(product => product.discount && product.discount > 0)
            .sort((a, b) => (b.discount || 0) - (a.discount || 0)); // Sort all by discount descending
        
        // Group promotional products by category and get the best discount from each category
        const categoryBestProducts = {};
        const categoryProducts = {}; // Store all products per category for fallback
        
        promoProductsWithDiscount.forEach(product => {
            const category = getProductCategory(product);
            if (category) {
                // Initialize category arrays if needed
                if (!categoryProducts[category]) {
                    categoryProducts[category] = [];
                }
                categoryProducts[category].push(product);
                
                // If we don't have a product for this category yet, or this product has a better discount
                if (!categoryBestProducts[category] || 
                    (product.discount || 0) > (categoryBestProducts[category].discount || 0)) {
                    categoryBestProducts[category] = product;
                }
            }
        });
        
        // Start with best product from each category
        let promoProducts = Object.values(categoryBestProducts)
            .sort((a, b) => (b.discount || 0) - (a.discount || 0));
        
        // If we have less than 4 products, fill remaining slots with next best products
        // Prioritize products from categories we haven't used yet, but allow duplicates if needed
        if (promoProducts.length < 4) {
            const usedProductIds = new Set(promoProducts.map(p => p.id));
            const remainingSlots = 4 - promoProducts.length;
            
            // Get all remaining promotional products (excluding already selected ones)
            const remainingProducts = promoProductsWithDiscount.filter(
                product => !usedProductIds.has(product.id)
            );
            
            // Add the next best products to fill remaining slots
            promoProducts = [...promoProducts, ...remainingProducts.slice(0, remainingSlots)];
        } else {
            // If we have 4 or more, just take top 4
            promoProducts = promoProducts.slice(0, 4);
        }
        
        // Final sort by discount to ensure best discounts are shown first
        promoProducts.sort((a, b) => (b.discount || 0) - (a.discount || 0));
        
        // Only show promotional products - don't fill with regular products
        // This ensures users only see actual promotional offers
        // Shows best discount from different categories when possible, fills with additional products if needed
        
        // Render products
        if (promoProducts.length > 0) {
            promoGrid.innerHTML = promoProducts.map(renderHomePageProductCard).join('');
            
            // Trigger animations
            setTimeout(() => {
                const cards = promoGrid.querySelectorAll('.product-card');
                cards.forEach((card, index) => {
                    setTimeout(() => {
                        card.classList.add('animate-in');
                    }, index * 100);
                });
            }, 100);
        } else {
            promoGrid.innerHTML = '<p class="no-products" style="grid-column: 1 / -1; text-align: center; padding: var(--spacing-3xl);">Няма налични промоционални продукти в момента.</p>';
        }
    } catch (error) {
        console.error('Error loading promotional products:', error);
        promoGrid.innerHTML = '<p class="no-products" style="grid-column: 1 / -1; text-align: center; padding: var(--spacing-3xl);">Грешка при зареждане на продукти.</p>';
    }
}

/**
 * Render product card for home page (with price label format)
 */
function renderHomePageProductCard(product) {
    // Handle image URL
    let imageUrl = product.image || '';
    if (!imageUrl || !imageUrl.startsWith('http')) {
        imageUrl = 'pictures/placeholder-ac.svg';
    }
    
    // Format price with old price if available
    let priceHtml = '';
    const priceNum = product.price ? parseFloat(product.price) : 0;
    const oldPriceNum = product.oldPrice ? parseFloat(product.oldPrice) : 0;
    
    // EUR to BGN conversion rate
    const EUR_TO_BGN_RATE = 1.95583;
    
    if (!isNaN(priceNum) && priceNum > 0) {
        const priceEuro = priceNum / EUR_TO_BGN_RATE;
        const oldPriceEuro = oldPriceNum > 0 ? oldPriceNum / EUR_TO_BGN_RATE : 0;
        
        if (oldPriceNum > priceNum && oldPriceNum > 0) {
            priceHtml = `
                <div class="product-price-wrapper">
                    <span class="price-label">Цена:</span>
                    <div class="product-price">
                        <div class="original-price-wrapper">
                        <span class="original-price">${oldPriceNum.toFixed(2).replace('.', ',')} лв</span>
                            <span class="price-separator-small">/</span>
                            <span class="original-price-euro">${oldPriceEuro.toFixed(2).replace('.', ',')} €</span>
                        </div>
                        <div class="current-price-wrapper">
                            <span class="current-price">${priceNum.toFixed(2).replace('.', ',')} лв</span>
                            <span class="price-separator-small">/</span>
                            <span class="current-price-euro">${priceEuro.toFixed(2).replace('.', ',')} €</span>
                        </div>
                    </div>
                </div>
            `;
        } else {
            priceHtml = `
                <div class="product-price-wrapper">
                    <span class="price-label">Цена:</span>
                    <div class="product-price">
                        <div class="current-price-wrapper">
                        <span class="current-price">${priceNum.toFixed(2).replace('.', ',')} лв</span>
                            <span class="price-separator-small">/</span>
                            <span class="current-price-euro">${priceEuro.toFixed(2).replace('.', ',')} €</span>
                        </div>
                    </div>
                </div>
            `;
        }
    } else {
        priceHtml = `
            <div class="product-price-wrapper">
                <span class="price-label">Цена:</span>
                <div class="product-price">
                    <span class="current-price">По запитване</span>
                </div>
            </div>
        `;
    }
    
    // Format BTU
    const btu = product.btu || '';
    const btuText = btu ? `Мощност: <strong>${btu}</strong>` : '';
    
    // Get product name
    const productName = product.name || 'Климатик';
    const brandName = product.brand || '';
    
    // Format discount badge
    const discountBadge = product.discount && product.discount > 0 
        ? `<span class="discount-badge">${product.discount}% OFF</span>` 
        : '';
    
    return `
        <div class="product-card" data-product-id="${product.id}">
            <div class="product-image-wrapper">
                <img src="${imageUrl}" alt="${productName}" class="product-image" loading="lazy" onerror="this.src='pictures/placeholder-ac.svg'">
                ${discountBadge}
            </div>
            <div class="product-info">
                ${brandName ? `<div class="product-brand-name">${brandName}</div>` : ''}
                <h3 class="product-model">${productName}</h3>
                ${btuText ? `<p class="product-spec">${btuText}</p>` : ''}
                ${priceHtml}
                <a href="product-detail.html?id=${encodeURIComponent(product.id)}&name=${encodeURIComponent(productName)}" class="btn btn-primary btn-small">Изпрати запитване</a>
            </div>
        </div>
    `;
}

/**
 * Initialize products page
 */
async function initProductsPage() {
    // Products page now just shows categories - no need to load products here
    // Categories are already displayed in the HTML
    console.log('Products page initialized - showing categories');
}

/**
 * Initialize category page
 */
async function initCategoryPage() {
    const urlParams = new URLSearchParams(window.location.search);
    const category = urlParams.get('category') || 'all';
    const promoOnly = urlParams.get('promo') === 'true';
    
    const productsGrid = document.getElementById('productsGrid');
    const resultsCount = document.getElementById('resultsCount');
    const categoryTitle = document.getElementById('categoryTitle');
    const categoryDescription = document.getElementById('categoryDescription');
    
    if (!productsGrid) return;
    
    // Update page title and description based on category or promo filter
    if (promoOnly) {
        if (categoryTitle) {
            categoryTitle.textContent = 'ПРОМОЦИОНАЛНИ ПРОДУКТИ';
        }
        if (categoryDescription) {
            categoryDescription.textContent = 'Избрани климатици от водещи световни марки с отлично съотношение цена-качество';
        }
    } else {
        const categoryNames = {
            'wall': 'СТЕННИ КЛИМАТИЦИ',
            'floor': 'ПОДОВИ КЛИМАТИЦИ',
            'ceiling': 'ТАВАННИ КЛИМАТИЦИ',
            'cassette': 'КАСЕТЪЧНИ КЛИМАТИЦИ',
            'duct': 'КАНАЛНИ КЛИМАТИЦИ',
            'column': 'КОЛОННИ КЛИМАТИЦИ',
            'mobile': 'МОБИЛНИ КЛИМАТИЦИ',
            'multisplit': 'МУЛТИСПЛИТ СИСТЕМИ',
            'wifi': 'WIFI И АКСЕСОАРИ',
            'all': 'ВСИЧКИ ПРОДУКТИ'
        };
        
        const categoryDescriptions = {
            'wall': 'Стенни климатици - идеално решение за всеки дом и офис',
            'floor': 'Подови климатици - комфорт и елегантност',
            'ceiling': 'Таванни климатици - незабележимо охлаждане',
            'cassette': 'Касетъчни климатици - професионално решение',
            'duct': 'Канални климатици - скрито охлаждане',
            'column': 'Колонни климатици - мощност и стил',
            'mobile': 'Мобилни климатици - гъвкавост и мобилност',
            'multisplit': 'Мултисплит системи - едно външно тяло, множество вътрешни',
            'wifi': 'WiFi и аксесоари - интелигентно управление',
            'all': 'Разгледайте целия ни асортимент от климатици'
        };
        
        if (categoryTitle) {
            categoryTitle.textContent = categoryNames[category] || categoryNames['all'];
        }
        
        if (categoryDescription) {
            categoryDescription.textContent = categoryDescriptions[category] || categoryDescriptions['all'];
        }
    }
    
    // Highlight active category in horizontal navigation
    const categoryNavItems = document.querySelectorAll('.category-nav-item');
    const allProductsNav = document.getElementById('allProductsNav');
    const categoryNavBar = document.querySelector('.category-nav-bar');
    
    // If showing promotional products, hide or modify category navigation
    if (promoOnly && categoryNavBar) {
        // Optionally hide category nav when viewing only promotional products
        // categoryNavBar.style.display = 'none';
    }
    
    categoryNavItems.forEach(item => {
        const href = item.getAttribute('href');
        if (promoOnly) {
            // When viewing promotional products, don't highlight any category
            item.classList.remove('active');
        } else if (category === 'all') {
            // If showing all products, highlight "All Products" link
            if (item === allProductsNav || (href && href === 'products-category.html')) {
                item.classList.add('active');
            } else {
                item.classList.remove('active');
            }
        } else {
            // If showing specific category, highlight that category
            if (item === allProductsNav || (href && href === 'products-category.html')) {
                item.classList.remove('active');
            } else if (href && href.includes(`category=${category}`)) {
                item.classList.add('active');
            } else {
                item.classList.remove('active');
            }
        }
    });
    
    // Show loading state
    productsGrid.innerHTML = '<div class="loading-message">Зареждане на продукти...</div>';
    if (resultsCount) {
        resultsCount.textContent = 'Зареждане...';
    }
    
    // Update breadcrumb
    const categoryName = document.getElementById('categoryName');
    if (categoryName) {
        if (promoOnly) {
            categoryName.textContent = 'Промоционални Продукти';
        } else {
            const categoryNames = {
                'wall': 'Стенни Климатици',
                'floor': 'Подови Климатици',
                'ceiling': 'Таванни Климатици',
                'cassette': 'Касетъчни Климатици',
                'duct': 'Канални Климатици',
                'column': 'Колонни Климатици',
                'mobile': 'Мобилни Климатици',
                'multisplit': 'Мултисплит Системи',
                'wifi': 'WiFi и Аксесоари',
                'all': 'Всички Продукти'
            };
            categoryName.textContent = categoryNames[category] || 'Всички Продукти';
        }
    }
    
    try {
        // Fetch products from all distributors
        const allProducts = await getAllProducts();
        
        if (!allProducts || allProducts.length === 0) {
            productsGrid.innerHTML = '<p class="no-products">Няма налични продукти в момента.</p>';
            if (resultsCount) {
                resultsCount.textContent = 'Няма продукти';
            }
            return;
        }
        
        // Filter by category (if category is 'all', show all products)
        let filteredProducts = category === 'all' 
            ? allProducts 
            : filterProductsByCategory(allProducts, category);
        
        // If promo filter is active, only show products with discounts
        if (promoOnly) {
            filteredProducts = filteredProducts.filter(product => product.discount && product.discount > 0);
            // Sort by discount (highest first)
            filteredProducts.sort((a, b) => (b.discount || 0) - (a.discount || 0));
        }
        
        // Render products
        if (filteredProducts.length > 0) {
            productsGrid.innerHTML = filteredProducts.map(renderProductCard).join('');
            
            // Trigger animations
            setTimeout(() => {
                const cards = productsGrid.querySelectorAll('.product-card');
                cards.forEach((card, index) => {
                    setTimeout(() => {
                        card.classList.add('animate-in');
                    }, index * 50);
                });
            }, 100);
        } else {
            productsGrid.innerHTML = '<p class="no-products">Няма налични продукти в тази категория.</p>';
        }
        
        // Update results count
        if (resultsCount) {
            resultsCount.textContent = `Показани ${filteredProducts.length} от ${allProducts.length} продукта`;
        }
        
        // Update category title if needed
        const categoryTitle = document.getElementById('categoryTitle');
        const categoryName = document.getElementById('categoryName');
        if (category && category !== 'all') {
            const categoryMap = {
                'wall': 'СТЕННИ КЛИМАТИЦИ',
                'floor': 'ПОДОВИ КЛИМАТИЦИ',
                'cassette': 'КАСЕТЪЧНИ КЛИМАТИЦИ',
                'duct': 'КАНАЛНИ КЛИМАТИЦИ',
                'ceiling': 'ТАВАННИ КЛИМАТИЦИ',
                'column': 'КОЛОННИ КЛИМАТИЦИ',
                'multisplit': 'МУЛТИСПЛИТ СИСТЕМИ'
            };
            const title = categoryMap[category] || category.toUpperCase();
            if (categoryTitle) categoryTitle.textContent = title;
            if (categoryName) categoryName.textContent = title.replace(' КЛИМАТИЦИ', '').replace(' СИСТЕМИ', '');
        }
        
        // Set active tab
        const activeTab = document.querySelector(`[data-category="${category}"]`);
        if (activeTab) {
            document.querySelectorAll('.category-tab').forEach(tab => tab.classList.remove('active'));
            activeTab.classList.add('active');
        }
        
        // Store products globally for filtering
        window.allProducts = allProducts;
        window.filteredProducts = filteredProducts;
        
        // Setup filter event listeners - pass filtered products to only show brands with products in this category
        setupFilters(allProducts, category, filteredProducts);
        
    } catch (error) {
        console.error('Error initializing category page:', error);
        productsGrid.innerHTML = '<p class="no-products">Грешка при зареждане на продукти. Моля, опитайте отново по-късно.</p>';
        if (resultsCount) {
            resultsCount.textContent = 'Грешка';
        }
    }
}

/**
 * Setup filter event listeners
 */
function setupFilters(allProducts, category, filteredProducts) {
    // Populate brand filters with only brands that have products in the current category
    populateBrandFilters(filteredProducts || allProducts);
    
    // Search input
    const searchInput = document.getElementById('productSearchInput');
    const searchClearBtn = document.getElementById('searchClearBtn');
    
    if (searchInput) {
        let searchTimeout;
        searchInput.addEventListener('input', (e) => {
            clearTimeout(searchTimeout);
            const query = e.target.value.trim();
            
            // Show/hide clear button
            if (searchClearBtn) {
                searchClearBtn.style.display = query ? 'flex' : 'none';
            }
            
            // Debounce search
            searchTimeout = setTimeout(() => {
                applyFilters(allProducts, category);
            }, 300);
        });
        
        // Clear search
        if (searchClearBtn) {
            searchClearBtn.addEventListener('click', () => {
                searchInput.value = '';
                searchClearBtn.style.display = 'none';
                applyFilters(allProducts, category);
            });
        }
    }
    
    // Brand filter
    const brandRadios = document.querySelectorAll('input[name="brand"]');
    brandRadios.forEach(radio => {
        radio.addEventListener('change', () => {
            applyFilters(allProducts, category);
        });
    });
    
    // Room size filter
    const roomSizeRadios = document.querySelectorAll('input[name="roomSize"]');
    roomSizeRadios.forEach(radio => {
        radio.addEventListener('change', () => {
            applyFilters(allProducts, category);
        });
    });
    
    // Promotional filters (checkboxes)
    const promoPriceCheckbox = document.getElementById('promoPrice');
    const promoInstallationCheckbox = document.getElementById('promoInstallation');
    
    if (promoPriceCheckbox) {
        promoPriceCheckbox.addEventListener('change', () => {
            applyFilters(allProducts, category);
        });
    }
    
    if (promoInstallationCheckbox) {
        promoInstallationCheckbox.addEventListener('change', () => {
            applyFilters(allProducts, category);
        });
    }
}

/**
 * Populate brand filter options
 */
function populateBrandFilters(products) {
    const brandFiltersContainer = document.getElementById('brandFilters');
    if (!brandFiltersContainer) return;
    
    // Get unique brands
    const brands = [...new Set(products.map(p => p.brand).filter(Boolean))].sort();
    
    // Add brand options (keep "Всички" option)
    const allOption = brandFiltersContainer.querySelector('label');
    brandFiltersContainer.innerHTML = '';
    if (allOption) {
        brandFiltersContainer.appendChild(allOption);
    }
    
    brands.forEach(brand => {
        const label = document.createElement('label');
        label.className = 'filter-option';
        label.innerHTML = `
            <input type="radio" name="brand" value="${brand}">
            <span>${brand}</span>
        `;
        brandFiltersContainer.appendChild(label);
        
        // Add event listener
        label.querySelector('input').addEventListener('change', () => {
            applyFilters(window.allProducts || products, new URLSearchParams(window.location.search).get('category'));
        });
    });
}

/**
 * Filter products by search query
 */
function filterProductsBySearch(products, searchQuery) {
    if (!searchQuery || searchQuery.trim() === '') {
        return products;
    }
    
    const query = searchQuery.toLowerCase().trim();
    
    return products.filter(product => {
        const name = (product.name || '').toLowerCase();
        const brand = (product.brand || '').toLowerCase();
        const model = (product.model || '').toLowerCase();
        const sku = (product.sku || '').toLowerCase();
        const description = (product.description || '').toLowerCase();
        const category = (product.category || '').toLowerCase();
        
        return name.includes(query) ||
               brand.includes(query) ||
               model.includes(query) ||
               sku.includes(query) ||
               description.includes(query) ||
               category.includes(query);
    });
}

/**
 * Apply all filters and update display
 */
function applyFilters(allProducts, category) {
    const productsGrid = document.getElementById('productsGrid');
    const resultsCount = document.getElementById('resultsCount');
    
    if (!productsGrid) return;
    
    // Get selected filters
    const selectedBrand = document.querySelector('input[name="brand"]:checked')?.value || 'all';
    const selectedRoomSize = document.querySelector('input[name="roomSize"]:checked')?.value || 'all';
    const promoPrice = document.getElementById('promoPrice')?.checked || false;
    const promoInstallation = document.getElementById('promoInstallation')?.checked || false;
    const searchQuery = document.getElementById('productSearchInput')?.value || '';
    
    let filtered;
    
    // If there's a search query, search in ALL products from both distributors (ignore category)
    if (searchQuery.trim()) {
        // Search in all products, regardless of category
        filtered = filterProductsBySearch(allProducts, searchQuery);
    } else {
        // No search query - apply category filter as normal
        filtered = filterProductsByCategory(allProducts, category);
    }
    
    // Apply brand filter
    if (selectedBrand !== 'all') {
        filtered = filterProductsByBrand(filtered, selectedBrand);
    }
    
    // Apply room size filter
    if (selectedRoomSize !== 'all') {
        filtered = filterProductsByRoomSize(filtered, selectedRoomSize);
    }
    
    // Apply promotional filters
    if (promoPrice || promoInstallation) {
        filtered = filterProductsByPromo(filtered, promoPrice, promoInstallation);
    }
    
    // Update display
    if (filtered.length > 0) {
        productsGrid.innerHTML = filtered.map(renderProductCard).join('');
        
        // Trigger animations
        setTimeout(() => {
            const cards = productsGrid.querySelectorAll('.product-card');
            cards.forEach((card, index) => {
                setTimeout(() => {
                    card.classList.add('animate-in');
                }, index * 50);
            });
        }, 100);
    } else {
        productsGrid.innerHTML = '<p class="no-products">Няма продукти, отговарящи на избраните филтри.</p>';
    }
    
    // Update results count
    if (resultsCount) {
        resultsCount.textContent = `Показани ${filtered.length} от ${allProducts.length} продукта`;
    }
    
    window.filteredProducts = filtered;
    
    // Update brand filters to only show brands that have products in current filtered results
    // But only if no brand filter is selected (to avoid removing the selected brand)
    if (selectedBrand === 'all') {
        populateBrandFilters(filtered);
    }
}

/**
 * Find product by ID across all distributors
 */
async function findProductById(productId) {
    console.log(`Searching for product ID: ${productId}`);
    
    try {
        // Fetch all products from all distributors
        const allProducts = await getAllProducts();
        
        if (!allProducts || allProducts.length === 0) {
            console.error('No products found');
            return null;
        }
        
        // Search for product by ID (handle both prefixed and non-prefixed IDs)
        const product = allProducts.find(p => 
            p.id === productId || 
            p.id.toString() === productId.toString() ||
            p.id === `bittel_${productId}` ||
            p.id === `bulclima_${productId}`
        );
        
                    if (product) {
            console.log(`Found product:`, product);
                        return product;
        }
        
        console.warn(`Product with ID ${productId} not found`);
        return null;
    } catch (error) {
        console.error('Error finding product:', error);
        return null;
    }
}

/**
 * Initialize product detail page
 */
async function initProductDetailPage() {
    const urlParams = new URLSearchParams(window.location.search);
    const productId = urlParams.get('id');
    const productName = urlParams.get('name');
    
    if (!productId) {
        console.error('No product ID provided');
        showError('Продуктът не е намерен.');
        return;
    }
    
    console.log('Loading product detail for ID:', productId);
    
    // Show loading state
    const productImage = document.getElementById('productImage');
    const productTitle = document.getElementById('productTitle');
    if (productImage) productImage.src = 'pictures/placeholder-ac.svg';
    if (productTitle) productTitle.textContent = 'Зареждане...';
    
    try {
        // Find the product
        const product = await findProductById(productId);
        
        if (!product) {
            showError('Продуктът не е намерен.');
            return;
        }
        
        // Populate product details
        populateProductDetail(product);
        
        // Load similar products
        loadSimilarProducts(product);
        
    } catch (error) {
        console.error('Error loading product detail:', error);
        showError('Грешка при зареждане на продукта.');
    }
}

/**
 * Populate product detail page with product data
 */
function populateProductDetail(product) {
    console.log('Populating product detail:', product);
    
    // Image - handle multiple images if available
    const imageWrapper = document.getElementById('productImageWrapper');
    const thumbnailsContainer = document.getElementById('productThumbnails');
    
    if (imageWrapper) {
        const mainImageContainer = imageWrapper.querySelector('.product-image-main');
        const productImage = document.getElementById('productImage');
        
        if (productImage) {
            const imageUrl = product.image || (product.images && product.images.length > 0 ? product.images[0] : 'pictures/placeholder-ac.svg');
            productImage.src = imageUrl;
            productImage.alt = product.name || 'Климатик';
            productImage.onerror = function() {
                this.src = 'pictures/placeholder-ac.svg';
            };
        }
        
        // Populate thumbnails if multiple images available
        if (thumbnailsContainer && product.images && product.images.length > 1) {
            thumbnailsContainer.innerHTML = product.images.slice(0, 4).map((img, idx) => `
                <img src="${img}" alt="${product.name || 'Климатик'} - Изображение ${idx + 1}" 
                     class="product-thumbnail ${idx === 0 ? 'active' : ''}" 
                     onclick="changeProductImage('${img}', this)"
                     onerror="this.style.display='none'">
            `).join('');
        } else if (thumbnailsContainer) {
            thumbnailsContainer.innerHTML = '';
        }
    }
    
    // Brand
    const productBrand = document.getElementById('productBrand');
    if (productBrand) {
        productBrand.textContent = product.brand || '';
    }
    
    // Title
    const productTitle = document.getElementById('productTitle');
    if (productTitle) {
        productTitle.textContent = product.name || 'Климатик';
    }
    
    // Breadcrumb
    const productBreadcrumb = document.getElementById('productBreadcrumb');
    if (productBreadcrumb) {
        productBreadcrumb.textContent = product.name || 'Детайли за продукт';
    }
    
    // Description - populate both locations
    let desc = product.description || '';
    if (desc) {
        const tempDiv = document.createElement('div');
        tempDiv.innerHTML = desc;
        desc = tempDiv.textContent || tempDiv.innerText || '';
    }
    const defaultDesc = 'Професионален климатик с отлични характеристики.';
    const finalDesc = desc || defaultDesc;
    
    // Description in tabs section - format as list with checkmarks
    const productDescriptionText = document.getElementById('productDescriptionText');
    if (productDescriptionText) {
        // Clear existing content
        productDescriptionText.innerHTML = '';
        
        // First, try to use features/characteristics if available
        let itemsToDisplay = [];
        
        if (product.features && product.features.length > 0) {
            // Use features array if available
            itemsToDisplay = product.features;
        } else if (finalDesc) {
            // Otherwise, parse description text
            // Split by multiple spaces (4+ spaces), semicolons, periods, or newlines
            // This handles cases where text is separated by multiple spaces like in the XML
            itemsToDisplay = finalDesc
                .split(/\s{4,}|[;。\n]/)
                .map(item => item.trim())
                .filter(item => item.length > 0);
        }
        
        if (itemsToDisplay.length > 0) {
            itemsToDisplay.forEach(item => {
                const li = document.createElement('li');
                li.textContent = item;
                productDescriptionText.appendChild(li);
            });
        } else if (finalDesc) {
            // If no separators found, use the whole text as one item
            const li = document.createElement('li');
            li.textContent = finalDesc;
            productDescriptionText.appendChild(li);
        }
    }
    
    // Auto-populate 4 Key Feature Cards
    // 1. BTU/Power - Auto-populate from product data (with fallback extraction for Bulclima)
    const productBTU = document.getElementById('productBTU');
    if (productBTU) {
        let power = product.specifications?.coolingPower || product.btu || '';
        
        // If still empty and it's a Bulclima product, try to extract from description
        if (!power && product.distributor === 'bulclima' && (product.description || product.name)) {
            const searchText = ((product.name || '') + ' ' + (product.description || '')).toLowerCase();
            
            // Try BTU patterns
            const btuPatterns = [
                /(\d+)\s*000\s*btu/i,
                /(\d+)\s*,\s*000\s*btu/i,
                /(\d+)\s*000\s*btu/i,
                /(\d+)\s*btu/i,
                /мощност[:\s]*(\d+)\s*000?\s*btu/i,
                /(\d+)\s*000/i
            ];
            
            for (const pattern of btuPatterns) {
                const btuMatch = searchText.match(pattern);
                if (btuMatch) {
                    let btuValue = parseInt(btuMatch[1]);
                    if (pattern.source.includes('000')) {
                        btuValue = btuValue * 1000;
                    } else if (btuValue < 1000 && btuValue >= 9) {
                        btuValue = btuValue * 1000;
                    }
                    if (btuValue >= 1000) {
                        power = `${btuValue} BTU`;
                        break;
                    }
                }
            }
            
            // Try kW if BTU not found
            if (!power) {
                const kwMatch = searchText.match(/(\d+\.?\d*)\s*kw/i) || searchText.match(/(\d+\.?\d*)\s*квт/i);
                if (kwMatch) {
                    power = `${kwMatch[1]} kW`;
                }
            }
        }
        
        if (power) {
            productBTU.textContent = power;
        } else {
            productBTU.textContent = 'По запитване';
        }
        console.log(`[Product Detail] Power/BTU card: "${productBTU.textContent}" (distributor: ${product.distributor || 'unknown'})`);
    }
    
    // 2. Energy Class - Auto-populate from product data (with fallback extraction for Bulclima)
    const productEnergyClass = document.getElementById('productEnergyClass');
    if (productEnergyClass) {
        let energyClass = product.specifications?.energyClassCooling || 
                         product.specifications?.energyClassHeating || 
                         '';
        
        // If still empty and it's a Bulclima product, try to extract from description
        if (!energyClass && product.distributor === 'bulclima' && (product.description || product.name)) {
            const searchText = ((product.name || '') + ' ' + (product.description || '')).toLowerCase();
            
            const energyPatterns = [
                /a\+\+\+/i,
                /a\+\+/i,
                /a\+/i,
                /\ba\b/i,
                /клас[:\s]*([a-z]\+{0,3})/i,
                /енергиен\s*клас[:\s]*([a-z]\+{0,3})/i,
                /energy[:\s]*class[:\s]*([a-z]\+{0,3})/i
            ];
            
            for (const pattern of energyPatterns) {
                const match = searchText.match(pattern);
                if (match) {
                    energyClass = (match[1] || match[0]).toUpperCase();
                    break;
                }
            }
        }
        
        if (energyClass) {
            productEnergyClass.textContent = energyClass;
        } else {
            productEnergyClass.textContent = 'По запитване';
        }
        console.log(`[Product Detail] Energy Class card: "${productEnergyClass.textContent}" (distributor: ${product.distributor || 'unknown'})`);
    }
    
    // 3. Delivery - Default value (always the same)
    const productDelivery = document.getElementById('productDelivery');
    if (productDelivery) {
        // Default delivery time, can be customized per product if needed
        productDelivery.textContent = '2-3 работни дни';
        console.log(`[Product Detail] Delivery card: "${productDelivery.textContent}"`);
    }
    
    // 4. Warranty - Auto-populate from product data
    // For Bulclima products, show "От производителя" since warranty info is in description
    const productWarranty = document.getElementById('productWarranty');
    if (productWarranty) {
        // For Bulclima products, always show "От производителя"
        if (product.distributor === 'bulclima') {
            productWarranty.textContent = 'От производителя';
            console.log(`[Product Detail] Warranty card: "От производителя" (Bulclima product)`);
        } else {
            // For other distributors (Bittel), try to get warranty from specifications
            let warranty = product.specifications?.warranty || '';
            
            if (warranty) {
                // Format warranty nicely
                const warrantyMatch = warranty.match(/(\d+)\s*(години|година|год\.|месеца|месец|мес\.|months?|years?)/i);
                if (warrantyMatch) {
                    const number = warrantyMatch[1];
                    const unit = warrantyMatch[2].toLowerCase();
                    if (unit.includes('месец') || unit.includes('month')) {
                        const months = parseInt(number);
                        if (months >= 12) {
                            productWarranty.textContent = `${Math.floor(months / 12)} години`;
                        } else {
                            productWarranty.textContent = `${number} месеца`;
                        }
                    } else {
                        productWarranty.textContent = `${number} години`;
                    }
                } else {
                    productWarranty.textContent = warranty; // Use as-is if pattern doesn't match
                }
            } else {
                productWarranty.textContent = '5 години'; // Default
            }
            console.log(`[Product Detail] Warranty card: "${productWarranty.textContent}" (distributor: ${product.distributor || 'unknown'})`);
        }
    }
    
    // Auto-populate Service Guarantee Cards
    // Delivery card
    const guaranteeDeliveryTitle = document.getElementById('guaranteeDeliveryTitle');
    const guaranteeDeliveryText = document.getElementById('guaranteeDeliveryText');
    if (guaranteeDeliveryTitle && guaranteeDeliveryText) {
        // Delivery is always free, but text can be customized
        guaranteeDeliveryTitle.textContent = 'Безплатна доставка';
        guaranteeDeliveryText.textContent = 'За цяла България';
    }
    
    // Warranty card - populate from product data (works for both Bulclima and Bittel)
    const guaranteeWarrantyTitle = document.getElementById('guaranteeWarrantyTitle');
    const guaranteeWarrantyText = document.getElementById('guaranteeWarrantyText');
    if (guaranteeWarrantyTitle && guaranteeWarrantyText) {
        // For Bulclima products, show "От производителя" in subtitle, keep warranty title format
        if (product.distributor === 'bulclima') {
            guaranteeWarrantyTitle.textContent = 'Гаранция';
            guaranteeWarrantyText.textContent = 'От производителя';
            console.log(`[Product Detail] Service guarantee card: "Гаранция" / "От производителя" (Bulclima product)`);
        } else {
            // For other distributors (Bittel), try to get warranty from specifications
            const warranty = product.specifications?.warranty || '';
            
            console.log(`[Product Detail] Auto-populating warranty card. Warranty: "${warranty}", Distributor: ${product.distributor || 'unknown'}`);
            
            if (warranty) {
            console.log(`[Product Detail] Processing warranty: "${warranty}"`);
            
            // Extract number and unit from warranty (e.g., "5 години", "36 months", "3 год.", "36 месеца", "36 мес.")
            // Try months first, then years
            const warrantyPatterns = [
                /(\d+)\s*(месеца|месец|мес\.|months?)/i,
                /(\d+)\s*(години|година|год\.|years?)/i,
                /(\d+)\s*(мес|год)/i
            ];
            
            let warrantyFormatted = '';
            for (const pattern of warrantyPatterns) {
                const warrantyMatch = warranty.match(pattern);
                if (warrantyMatch) {
                    const number = warrantyMatch[1];
                    const unit = (warrantyMatch[2] || '').toLowerCase();
                    
                    console.log(`[Product Detail] Matched pattern: number="${number}", unit="${unit}"`);
                    
                    // Format in Bulgarian
                    if (unit.includes('месец') || unit.includes('month') || unit.includes('мес')) {
                        // Convert months to years if >= 12
                        const months = parseInt(number);
                        if (months >= 12) {
                            const years = Math.floor(months / 12);
                            warrantyFormatted = `${years} год. гаранция`;
                            console.log(`[Product Detail] Converted ${months} months to ${years} год. гаранция`);
                        } else {
                            warrantyFormatted = `${number} мес. гаранция`;
                        }
                        break;
                    } else if (unit.includes('год') || unit.includes('year') || unit === 'г') {
                        warrantyFormatted = `${number} год. гаранция`;
                        break;
                    }
                }
            }
            
            if (warrantyFormatted) {
                guaranteeWarrantyTitle.textContent = warrantyFormatted;
                console.log(`[Product Detail] Warranty formatted: "${warrantyFormatted}"`);
            } else {
                // If pattern didn't match, try to extract just the number
                const numberMatch = warranty.match(/(\d+)/);
                if (numberMatch) {
                    const num = parseInt(numberMatch[1]);
                    console.log(`[Product Detail] Extracted number only: ${num}`);
                    
                    // Check if warranty string contains month indicators
                    const hasMonthIndicator = warranty.toLowerCase().includes('мес') || 
                                             warranty.toLowerCase().includes('month') ||
                                             warranty.toLowerCase().includes('месец');
                    
                    if (hasMonthIndicator && num >= 12) {
                        // It's months, convert to years
                        const years = Math.floor(num / 12);
                        guaranteeWarrantyTitle.textContent = `${years} год. гаранция`;
                        console.log(`[Product Detail] Detected months, converted ${num} to ${years} год. гаранция`);
                    } else if (hasMonthIndicator && num < 12) {
                        guaranteeWarrantyTitle.textContent = `${num} мес. гаранция`;
                    } else if (num >= 12 && !hasMonthIndicator) {
                        // If >= 12 and no month indicator, assume it's months (common case: "36" means 36 months)
                        const years = Math.floor(num / 12);
                        guaranteeWarrantyTitle.textContent = `${years} год. гаранция`;
                        console.log(`[Product Detail] Assumed ${num} is months (>=12), converted to ${years} год. гаранция`);
                    } else {
                        // Assume years
                        guaranteeWarrantyTitle.textContent = `${num} год. гаранция`;
                    }
                    console.log(`[Product Detail] Final warranty: "${guaranteeWarrantyTitle.textContent}"`);
                } else {
                    guaranteeWarrantyTitle.textContent = '5 год. гаранция'; // Default
                    console.log(`[Product Detail] Using default warranty - no number found`);
                }
            }
            } else {
                // No warranty found in specifications - use default
                guaranteeWarrantyTitle.textContent = '5 год. гаранция'; // Default
                console.log(`[Product Detail] No warranty found in specifications, using default. Distributor: ${product.distributor || 'unknown'}`);
                console.log(`[Product Detail] Product specifications:`, product.specifications);
            }
            guaranteeWarrantyText.textContent = 'От производителя';
        }
    }
    
    // Price - handle old price if available, add VAT text, and convert to Euro
    const productPrice = document.getElementById('productPrice');
    const productPriceEuro = document.getElementById('productPriceEuro');
    const priceMain = productPrice?.closest('.product-price-main');
    
    // BGN to EUR exchange rate (fixed rate: 1 EUR = 1.95583 BGN)
    const EUR_TO_BGN_RATE = 1.95583;
    
    if (productPrice && priceMain) {
        const priceNum = product.price ? parseFloat(product.price) : 0;
        const oldPriceNum = product.oldPrice ? parseFloat(product.oldPrice) : 0;
        
        if (priceNum > 0) {
            // Calculate Euro price
            const priceEuro = priceNum / EUR_TO_BGN_RATE;
            const oldPriceEuro = oldPriceNum > 0 ? oldPriceNum / EUR_TO_BGN_RATE : 0;
            
            if (oldPriceNum > priceNum && oldPriceNum > 0) {
                // Show old price with strikethrough
                priceMain.innerHTML = `
                    <div class="price-amount-wrapper">
                        <div style="display: flex; flex-direction: column; gap: 2px;">
                            <div style="display: flex; align-items: baseline; gap: var(--spacing-xs);">
                        <span class="price-amount-old" style="font-size: var(--font-size-lg); color: var(--color-text-light); text-decoration: line-through;">${oldPriceNum.toFixed(2)} лв.</span>
                                <span class="price-separator" style="color: var(--color-text-light);">/</span>
                                <span class="price-amount-old" style="font-size: var(--font-size-base); color: var(--color-text-light); text-decoration: line-through;">${oldPriceEuro.toFixed(2)} €</span>
                            </div>
                            <div style="display: flex; align-items: baseline; gap: var(--spacing-xs);">
                        <span class="price-amount" id="productPrice">${priceNum.toFixed(2)} лв.</span>
                                <span class="price-separator">/</span>
                                <span class="price-amount-euro-value" id="productPriceEuro">${priceEuro.toFixed(2)} €</span>
                    </div>
                        </div>
                    </div>
                `;
            } else {
                // Update price with Euro on same line
                const priceWrapper = productPrice.closest('.price-amount-wrapper');
                const separator = priceWrapper?.querySelector('.price-separator');
                const euroElement = document.getElementById('productPriceEuro');
                
                if (priceWrapper && separator && euroElement) {
                productPrice.textContent = `${priceNum.toFixed(2)} лв.`;
                    euroElement.textContent = `${priceEuro.toFixed(2)} €`;
                } else {
                    // If wrapper doesn't exist, create it
                    priceMain.innerHTML = `
                        <div class="price-amount-wrapper">
                            <span class="price-amount" id="productPrice">${priceNum.toFixed(2)} лв.</span>
                            <span class="price-separator">/</span>
                            <span class="price-amount-euro-value" id="productPriceEuro">${priceEuro.toFixed(2)} €</span>
                        </div>
                    `;
                }
            }
        } else {
            productPrice.textContent = 'По запитване';
            if (productPriceEuro) {
                productPriceEuro.textContent = '';
            }
        }
    }
    
    // Product Code/SKU
    const productCode = document.getElementById('productCode');
    if (productCode) {
        const code = product.product_code || product.sku || '';
        productCode.textContent = code ? `Код: ${code}` : '';
    }
    
    // Populate Specifications Grid
    const specsGrid = document.getElementById('specificationsGrid');
    const specsTable = document.getElementById('specificationsTable');
    
    // Icon mapping for specifications
    const getSpecIcon = (label) => {
        const labelLower = label.toLowerCase();
        if (labelLower.includes('мощност') || labelLower.includes('power')) {
            return 'bi-lightning-charge-fill';
        } else if (labelLower.includes('енергиен') || labelLower.includes('energy')) {
            return 'bi-leaf-fill';
        } else if (labelLower.includes('шум') || labelLower.includes('noise')) {
            return 'bi-volume-up-fill';
        } else if (labelLower.includes('хладилен') || labelLower.includes('refrigerant')) {
            return 'bi-droplet-fill';
        } else if (labelLower.includes('размер') || labelLower.includes('dimension')) {
            return 'bi-rulers';
        } else {
            return 'bi-info-circle-fill';
        }
    };
    
    if (specsGrid && product.specifications) {
        const specs = product.specifications;
        const specsItems = [];
        
        // Type
        if (specs.type) {
            specsItems.push({
                label: 'Тип',
                value: specs.type,
                icon: 'bi-box-seam'
            });
        }
        
        // Technology
        if (specs.technology) {
            specsItems.push({
                label: 'Технология',
                value: specs.technology,
                icon: 'bi-cpu'
            });
        }
        
        // Cooling Power
        if (specs.coolingPower || product.btu) {
            specsItems.push({
                label: 'Мощност охлаждане',
                value: specs.coolingPower || product.btu || 'По запитване',
                icon: 'bi-thermometer-half'
            });
        }
        
        // Heating Power
        if (specs.heatingPower) {
            specsItems.push({
                label: 'Мощност отопление',
                value: specs.heatingPower,
                icon: 'bi-thermometer-half'
            });
        }
        
        // SEER
        if (specs.seer) {
            specsItems.push({
                label: 'Охлаждане SEER',
                value: specs.seer,
                icon: 'bi-leaf-fill'
            });
        }
        
        // SCOP
        if (specs.scop) {
            specsItems.push({
                label: 'Отопление SCOP',
                value: specs.scop,
                icon: 'bi-leaf-fill'
            });
        }
        
        // Energy Class Cooling
        if (specs.energyClassCooling) {
            specsItems.push({
                label: 'Енергиен клас охлаждане',
                value: specs.energyClassCooling,
                icon: 'bi-leaf-fill'
            });
        }
        
        // Energy Class Heating
        if (specs.energyClassHeating) {
            specsItems.push({
                label: 'Енергиен клас отопление',
                value: specs.energyClassHeating,
                icon: 'bi-leaf-fill'
            });
        }
        
        // Noise Indoor
        if (specs.noiseIndoor) {
            specsItems.push({
                label: 'Ниво на шум (вътрешно тяло)',
                value: specs.noiseIndoor,
                icon: 'bi-volume-up-fill'
            });
        }
        
        // Noise Outdoor
        if (specs.noiseOutdoor) {
            specsItems.push({
                label: 'Ниво на шум (външно тяло)',
                value: specs.noiseOutdoor,
                icon: 'bi-volume-up-fill'
            });
        }
        
        // Refrigerant
        if (specs.refrigerant) {
            specsItems.push({
                label: 'Хладилен агент',
                value: specs.refrigerant,
                icon: 'bi-droplet-fill'
            });
        }
        
        // Dimensions
        if (specs.dimensions) {
            specsItems.push({
                label: 'Размери вътрешно тяло',
                value: specs.dimensions,
                icon: 'bi-rulers'
            });
        }
        
        // Capacity/BTU
        if (product.btu && !specs.coolingPower) {
            specsItems.push({
                label: 'Капацитет',
                value: product.btu,
                icon: 'bi-lightning-charge-fill'
            });
        }
        
        // Warranty
        if (specs.warranty) {
            specsItems.push({
                label: 'Гаранция',
                value: specs.warranty,
                icon: 'bi-shield-check-fill'
            });
        }
        
        if (specsItems.length > 0) {
            specsGrid.innerHTML = specsItems.map(item => `
                <div class="spec-item">
                    <i class="bi ${item.icon}"></i>
                    <span class="spec-label">${item.label}</span>
                    <span class="spec-value">${item.value}</span>
                </div>
            `).join('');
        } else {
            specsGrid.innerHTML = `
                <div style="grid-column: 1 / -1; text-align: center; padding: var(--spacing-xl); color: var(--color-text-light);">
                    Техническите спецификации са налични по запитване
                </div>
            `;
        }
    } else if (specsTable && product.specifications) {
        // Fallback to table if grid doesn't exist
        const specs = product.specifications;
        const specsRows = [];
        
        if (specs.coolingPower || product.btu) {
            specsRows.push(['Охлаждаща мощност', specs.coolingPower || product.btu || 'По запитване']);
        }
        if (specs.heatingPower) {
            specsRows.push(['Отоплителна мощност', specs.heatingPower]);
        }
        if (specs.energyClassCooling) {
            specsRows.push(['Енергиен клас (охлаждане)', specs.energyClassCooling]);
        }
        if (specs.energyClassHeating) {
            specsRows.push(['Енергиен клас (отопление)', specs.energyClassHeating]);
        }
        if (specs.noiseIndoor) {
            specsRows.push(['Шум (вътрешно тяло)', specs.noiseIndoor]);
        }
        if (specs.noiseOutdoor) {
            specsRows.push(['Шум (външно тяло)', specs.noiseOutdoor]);
        }
        if (specs.refrigerant) {
            specsRows.push(['Хладилен агент', specs.refrigerant]);
        }
        if (specs.dimensions) {
            specsRows.push(['Размери', specs.dimensions]);
        }
        
        if (specsRows.length > 0) {
            specsTable.innerHTML = specsRows.map(row => `
                <tr>
                    <td class="spec-label-cell">${row[0]}</td>
                    <td class="spec-value-cell">${row[1]}</td>
                </tr>
            `).join('');
        } else {
            specsTable.innerHTML = `
                <tr>
                    <td colspan="2" style="text-align: center; padding: var(--spacing-xl); color: var(--color-text-light);">
                        Техническите спецификации са налични по запитване
                    </td>
                </tr>
            `;
        }
    }
    
    // Populate Features List
    const featuresList = document.getElementById('featuresList');
    if (featuresList) {
        // Clear existing content
        featuresList.innerHTML = '';
        
        let featuresToDisplay = [];
        
        // Use product.features if available
        if (product.features && product.features.length > 0) {
            featuresToDisplay = product.features;
        } else {
            // Try to extract features from description
            const desc = product.description || '';
            if (desc) {
                // Split by multiple spaces (4+), semicolons, periods, or newlines
                const items = desc
                    .split(/\s{4,}|[;。\n]/)
                    .map(item => item.trim())
                    .filter(item => item.length > 0 && item.length > 10); // Filter out very short items
                
                if (items.length > 1) {
                    featuresToDisplay = items;
                }
            }
        }
        
        if (featuresToDisplay.length > 0) {
            featuresToDisplay.forEach(feature => {
                const div = document.createElement('div');
                div.className = 'characteristic-item';
                div.textContent = feature; // Use textContent to avoid HTML injection
                featuresList.appendChild(div);
            });
        } else {
            featuresList.innerHTML = `
                <div class="no-features" style="grid-column: 1 / -1; text-align: center; padding: var(--spacing-xl); color: var(--color-text-light);">
                    <p>Предимствата на продукта са включени в описанието.</p>
                </div>
            `;
        }
    }
    
    // Update inquiry button
    const inquiryBtn = document.getElementById('inquiryBtn');
    if (inquiryBtn) {
        inquiryBtn.onclick = function() {
            // Pass product information via URL parameters
            const params = new URLSearchParams({
                productId: product.id || '',
                productName: product.name || '',
                productPrice: product.price || '',
                productBrand: product.brand || '',
                productCode: product.product_code || product.sku || ''
            });
            window.location.href = `contact.html?${params.toString()}`;
        };
    }
    
    // Update page title and meta
    document.title = `${product.name} | БОМИ клима`;
    const metaDescription = document.querySelector('meta[name="description"]');
    if (metaDescription) {
        metaDescription.content = `${product.name} - ${product.brand || ''}. ${product.description ? product.description.substring(0, 150) : ''}`;
    }
}

/**
 * Load similar products
 */
async function loadSimilarProducts(currentProduct) {
    const similarGrid = document.getElementById('similarProductsGrid');
    if (!similarGrid) return;
    
    try {
        // Get all products from all distributors
        const allProducts = await getAllProducts();
        
        if (!allProducts || allProducts.length === 0) {
            return;
        }
        
        // Filter similar products (same brand or category, exclude current)
        const similar = allProducts
            .filter(p => p.id !== currentProduct.id && 
                    (p.brand === currentProduct.brand || 
                     p.category === currentProduct.category ||
                     p.subCategory === currentProduct.subCategory))
            .slice(0, 4);
        
        if (similar.length > 0) {
            similarGrid.innerHTML = similar.map(renderProductCard).join('');
            
            // Trigger animations
            setTimeout(() => {
                const cards = similarGrid.querySelectorAll('.product-card');
                cards.forEach((card, index) => {
                    setTimeout(() => {
                        card.classList.add('animate-in');
                    }, index * 100);
                });
            }, 100);
        } else {
            similarGrid.innerHTML = '<p class="no-products">Няма подобни продукти.</p>';
        }
    } catch (error) {
        console.warn('Error loading similar products:', error);
        similarGrid.innerHTML = '<p class="no-products">Неуспешно зареждане на подобни продукти.</p>';
    }
}

/**
 * Show error message on product detail page
 */
function showError(message) {
    const productTitle = document.getElementById('productTitle');
    if (productTitle) {
        productTitle.textContent = message;
    }
    
    const productDescription = document.getElementById('productDescription');
    if (productDescription) {
        productDescription.textContent = 'Моля, опитайте отново или се свържете с нас.';
    }
}

// Add loading message styles
const style = document.createElement('style');
style.textContent = `
    .loading-message {
        text-align: center;
        padding: var(--spacing-3xl);
        color: var(--color-text-light);
        font-size: var(--font-size-lg);
    }
    .no-products {
        text-align: center;
        padding: var(--spacing-3xl);
        color: var(--color-text-light);
        font-size: var(--font-size-lg);
    }
`;
document.head.appendChild(style);

// Auto-initialize based on page
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeProducts);
} else {
    // DOM already loaded
    initializeProducts();
}

function initializeProducts() {
    console.log('Products API script loaded');
    console.log('Window location:', window.location.href);
    console.log('Pathname:', window.location.pathname);
    
    const currentPage = window.location.pathname.split('/').pop() || window.location.pathname;
    console.log('Current page:', currentPage);
    
    // Check if we're on a products page
    if (currentPage === 'products.html' || currentPage.endsWith('products.html')) {
        console.log('Initializing products page...');
        initProductsPage();
    } else if (currentPage === 'products-category.html' || currentPage.includes('products-category')) {
        console.log('Initializing category page...');
        initCategoryPage();
    } else if (currentPage === 'product-detail.html' || currentPage.includes('product-detail')) {
        console.log('Initializing product detail page...');
        initProductDetailPage();
    } else if (currentPage === 'index.html' || currentPage === '' || currentPage === '/') {
        console.log('Initializing home page promo products...');
        initHomePagePromoProducts();
    } else {
        console.log('Not a products page, skipping initialization');
        console.log('Available elements:', {
            promoGrid: !!document.getElementById('promoProductsGrid'),
            productsGrid: !!document.getElementById('productsGrid')
        });
    }
}

