/**
 * Products API Integration for ЕР КЛИМА СОЛЮШЪНС ЕООД (ER CLIMA SOLUTIONS Ltd)
 * Handles API from multiple distributors:
 * - Bulclima: XML API - Brand-based API
 * - Bittel: JSON/XML API - Direct product API
 * 
 * API Structures:
 * - Bulclima: Base URL returns brands list, each brand URL returns products
 * - Bittel: Direct product list (JSON or XML format)
 *
 * ---------------------------------------------------------------------------
 * НОВИ линкове от дистрибутори (Bittel „Експорт…“, Bulclima продукти за качване):
 * 1) Най-лесно: редактирайте DEFAULT_DISTRIBUTOR_CONFIG по-долу (ключ, base URL, при нужда версии json_v3/xml_v4).
 * 2) Алтернатива: преди зареждане на този файл задайте:
 *    window.__DISTRIBUTOR_CONFIG__ = {
 *      bittelApiKey: '...',                    // от имейл Bittel
 *      bittelJsonUrl: 'https://...',           // пълен линк, ако е различен от шаблона
 *      bittelXmlUrl: 'https://...',
 *      bulclimaBaseUrl: 'https://.../fullInfo/',  // каталог по марки (fullInfo) или legacy .../items/
 *      bittelFormat: 'json' | 'xml',
 *      bittelUseAllExport: true   // опционално: ?all вместо ?page=
 *    };
 * ---------------------------------------------------------------------------
 */

// ============================================
// Distributor defaults (обновете от PDF/имейл на дистрибутора)
// ============================================
const DEFAULT_DISTRIBUTOR_CONFIG = {
    // Bulclima: пълен каталог по марки (fullInfo). Подавате домейна на магазина на доставчика за достъп; при нужда CORS ползвайте прокси.
    bulclimaBaseUrl: 'https://www.bulclima.com/tools/api/fullInfo/',
    // Bittel: API ключ от имейл с линкове json_v3 / xml_v4 (актуализация ~2 ч, странициране ?page= или ?all).
    bittelApiKey: '69761b00a3d6c3ca55117a2dc645762c',
    bittelBaseUrl: 'https://dealers.bittel.bg/bg/api',
    bittelJsonVersion: 'json_v3',
    bittelXmlVersion: 'xml_v4',
    bittelFormat: 'json',
    bittelJsonUrl: '',
    bittelXmlUrl: '',
    // true = една заявка с ?all (всички продукти); false = ?page=1,2… (препоръчано при много голям каталог)
    bittelUseAllExport: false
};

function getDistributorConfig() {
    const win = typeof window !== 'undefined' ? window : null;
    const override = win && win.__DISTRIBUTOR_CONFIG__ && typeof win.__DISTRIBUTOR_CONFIG__ === 'object'
        ? win.__DISTRIBUTOR_CONFIG__
        : {};
    return { ...DEFAULT_DISTRIBUTOR_CONFIG, ...override };
}

const _DIST = getDistributorConfig();

// ============================================
// Bulclima API Configuration
// ============================================
const BULCLIMA_API_BASE_URL = _DIST.bulclimaBaseUrl.endsWith('/')
    ? _DIST.bulclimaBaseUrl
    : `${_DIST.bulclimaBaseUrl}/`;
const USE_BULCLIMA = true; // Set to false to disable this distributor

// ============================================
// Bittel API Configuration
// ============================================
const BITTEL_API_KEY = _DIST.bittelApiKey;
const BITTEL_API_JSON_URL = (_DIST.bittelJsonUrl && String(_DIST.bittelJsonUrl).trim())
    ? String(_DIST.bittelJsonUrl).trim()
    : `${_DIST.bittelBaseUrl.replace(/\/$/, '')}/${_DIST.bittelJsonVersion}/${BITTEL_API_KEY}`;
const BITTEL_API_XML_URL = (_DIST.bittelXmlUrl && String(_DIST.bittelXmlUrl).trim())
    ? String(_DIST.bittelXmlUrl).trim()
    : `${_DIST.bittelBaseUrl.replace(/\/$/, '')}/${_DIST.bittelXmlVersion}/${BITTEL_API_KEY}`;
const BITTEL_API_FORMAT = _DIST.bittelFormat === 'xml' ? 'xml' : 'json';
const BITTEL_USE_ALL_EXPORT = _DIST.bittelUseAllExport === true;
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)
// Try direct access first - only use proxy if needed
const USE_CORS_PROXY = false; // Keep global proxy off by default
const USE_CORS_PROXY_BULCLIMA = true; // Bulclima requires proxy (no CORS headers)
const USE_CORS_PROXY_BITTEL = false; // Try Bittel direct access
const CORS_PROXY_URL = 'https://cors.eu.org/';

// Alternative CORS proxies (if needed):
// const CORS_PROXY_URL = 'https://api.allorigins.win/raw?url=';
// const CORS_PROXY_URL = 'https://cors-anywhere.herokuapp.com/';

// 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']
};

function escapeHtml(str) {
    if (str == null || str === '') return '';
    const d = document.createElement('div');
    d.textContent = String(str);
    return d.innerHTML;
}

/**
 * Извлича таблици от HTML описание (Bulclima fullInfo / евентуално Bittel).
 * @returns {{ caption: string, rows: { label: string, value: string }[] }[]}
 */
function parseHtmlSpecTables(html) {
    if (!html || typeof html !== 'string' || !html.includes('<')) return [];
    const host = document.createElement('div');
    host.innerHTML = html;
    const tables = Array.from(host.querySelectorAll('table'));
    return tables.map((table) => {
        const caption = table.querySelector('caption')?.textContent?.replace(/\s+/g, ' ').trim() || '';
        const rows = [];
        table.querySelectorAll('tr').forEach((tr) => {
            const cells = Array.from(tr.querySelectorAll('th, td'))
                .map((c) => c.textContent.replace(/\s+/g, ' ').trim())
                .filter(Boolean);
            if (cells.length >= 2) {
                rows.push({ label: cells[0], value: cells.slice(1).join(' ') });
            } else if (cells.length === 1 && cells[0].length > 2) {
                rows.push({ label: '', value: cells[0] });
            }
        });
        return { caption, rows: rows.filter((r) => r.label || r.value) };
    }).filter((t) => t.rows.length > 0);
}

function mergeTableRowsIntoSpecifications(specs, specTables) {
    if (!specs || !specTables || !specTables.length) return;
    const rows = specTables.flatMap((t) => t.rows);
    for (const row of rows) {
        const label = (row.label || '').toLowerCase();
        const value = row.value || '';
        if (!value) continue;
        const lv = `${label} ${value}`.toLowerCase();
        if (!specs.coolingPower && (/охлажд|cooling|btu|квт|\bkw\b|мощност/i.test(lv))) {
            specs.coolingPower = value;
        }
        if (!specs.heatingPower && (/отопл|heating/i.test(lv))) {
            specs.heatingPower = value;
        }
        if (!specs.seer && /seer/i.test(lv)) {
            specs.seer = value;
        }
        if (!specs.scop && /scop/i.test(lv)) {
            specs.scop = value;
        }
        const valueCompact = (value || '').replace(/\s/g, '');
        const looksEnergyLabel = /енергиен|energy|клас|seer|scop|ефективност|efficiency/i.test(label);
        const looksEnergyValue =
            /^[a-z]\+{0,3}$/i.test(valueCompact) ||
            /\b[a-z]\+{1,3}\b/i.test(value) ||
            /клас\s*[a-z]\+{0,3}/i.test(value);
        if (
            !specs.energyClassCooling &&
            value &&
            (looksEnergyLabel || looksEnergyValue)
        ) {
            specs.energyClassCooling = value;
        }
        if (!specs.noiseIndoor && (/шум|noise|дб|db/i.test(lv))) {
            specs.noiseIndoor = value;
        }
        if (!specs.refrigerant && (/r32|r410|r134|хладилен|refrigerant/i.test(lv))) {
            specs.refrigerant = value;
        }
        if (!specs.dimensions && (/размер|dimension|mm|\bсм\b|х\s*\d/i.test(lv))) {
            specs.dimensions = value;
        }
        if (!specs.warranty && (/гаранц|warranty/i.test(lv))) {
            specs.warranty = value;
        }
    }
}

/**
 * Единично име/стойност от Bittel JSON/XML → specs (широки БГ/EN шаблони).
 */
function ingestBittelKeyValue(specs, rawLabel, rawValue) {
    if (!specs) return;
    const value =
        rawValue != null ? String(rawValue).replace(/\s+/g, ' ').trim() : '';
    const label =
        rawLabel != null ? String(rawLabel).replace(/\s+/g, ' ').trim() : '';
    if (!value && !label) return;
    const lv = `${label} ${value}`.toLowerCase();
    const labelL = label.toLowerCase();

    if (!specs.coolingPower && value) {
        const byLabel =
            /охлажд|cooling|студено|охладител|хладилн|cold\s*capacity|cooling\s*capacity/i.test(
                labelL
            ) ||
            (/мощност|power|capacity|капацитет|номинал/i.test(labelL) &&
                /btu|квт|\bkw\b|\d{4,6}\b/i.test(value));
        const byCombined =
            /охлажд|cooling|студено|хладилн/i.test(lv) &&
            /btu|квт|\bkw\b|\d{3,}/i.test(value);
        if (byLabel || byCombined) {
            specs.coolingPower = value;
        }
    }

    if (!specs.heatingPower && value && /отопл|heating|топло/i.test(lv)) {
        if (/btu|квт|\bkw\b|\d/.test(value)) specs.heatingPower = value;
    }

    if (value) {
        const compactVal = value.replace(/\s/g, '');
        const looksLikeLetterClass =
            /^[a-z]\+{0,3}$/i.test(compactVal) ||
            /\b[a-z]\+{1,3}\b/i.test(value) ||
            /клас\s*[a-z]\+{0,3}/i.test(value);
        const energyCtx =
            /енергиен|енергий|energy|ефективност|efficiency|\bseer\b|\bscop\b|иклас/i.test(
                lv
            ) || /клас|class|rating/i.test(labelL);
        if (/отопл|heating/i.test(lv) && looksLikeLetterClass) {
            if (!specs.energyClassHeating) specs.energyClassHeating = value;
        } else if (!specs.energyClassCooling) {
            if (energyCtx && looksLikeLetterClass) {
                specs.energyClassCooling = value;
            } else if (/клас/i.test(labelL) && looksLikeLetterClass) {
                specs.energyClassCooling = value;
            }
        }
    }

    if (!specs.seer && /\bseer\b/i.test(lv) && /\d/.test(value)) specs.seer = value;
    if (!specs.scop && /\bscop\b/i.test(lv) && /\d/.test(value)) specs.scop = value;
    if (!specs.warranty && /гаранц|warranty/i.test(lv) && value) specs.warranty = value;
    if (!specs.type && value && (/^тип$/i.test(labelL) || /^type$/i.test(labelL))) {
        specs.type = value;
    }
}

function normalizeBittelFeatureRow(raw) {
    if (raw == null) return { name: '', value: '' };
    if (typeof raw === 'string') return { name: '', value: raw.trim() };
    const name = String(
        raw.name ??
            raw.param ??
            raw.parameter ??
            raw.title ??
            raw.label ??
            raw.key ??
            ''
    ).trim();
    let val = raw.value ?? raw.val ?? raw.text ?? raw.content ?? '';
    if (val != null && typeof val === 'object') {
        try {
            val = JSON.stringify(val);
        } catch {
            val = String(val);
        }
    }
    const value = val != null ? String(val).trim() : '';
    return { name, value };
}

function flattenBittelSpecificationsObject(obj, prefix = '') {
    const rows = [];
    if (obj == null || typeof obj !== 'object') return rows;
    if (Array.isArray(obj)) {
        obj.forEach((el) => {
            const { name, value } = normalizeBittelFeatureRow(el);
            if (name && value) rows.push({ name, value });
            else if (value) rows.push({ name: prefix || '', value });
            else if (name) rows.push({ name, value: '' });
        });
        return rows;
    }
    for (const [k, v] of Object.entries(obj)) {
        const key = prefix ? `${prefix} / ${k}` : k;
        if (v != null && typeof v === 'object' && !Array.isArray(v)) {
            rows.push(...flattenBittelSpecificationsObject(v, key));
        } else if (Array.isArray(v)) {
            v.forEach((el) => {
                const { name, value } = normalizeBittelFeatureRow(el);
                rows.push({
                    name: name || key,
                    value: value || (typeof el === 'string' ? el : '')
                });
            });
        } else if (v != null && v !== '') {
            rows.push({ name: key, value: String(v) });
        }
    }
    return rows;
}

function extractDocumentsFromBulclimaXml(item) {
    const docs = [];
    const push = (title, url) => {
        const u = (url || '').trim();
        if (!u || !/^https?:\/\//i.test(u)) return;
        docs.push({ title: (title || 'Документ').trim() || 'Документ', url: u });
    };
    item.querySelectorAll('documents > document').forEach((el) => {
        push(
            el.querySelector('title, name')?.textContent?.trim(),
            el.querySelector('url, link, href')?.textContent?.trim()
        );
    });
    item.querySelectorAll('downloads > item, brochures > brochure, manuals > manual').forEach((el) => {
        push(
            el.getAttribute('title') || el.querySelector('title, name')?.textContent?.trim(),
            el.getAttribute('url') || el.querySelector('url, link')?.textContent?.trim() || el.textContent?.trim()
        );
    });
    item.querySelectorAll('files > file').forEach((el) => {
        push(
            el.querySelector('title, name')?.textContent?.trim(),
            el.querySelector('url, link')?.textContent?.trim() || el.getAttribute('href')
        );
    });
    return docs;
}

function extractFeaturesRichFromBulclima(item) {
    const out = [];
    item.querySelectorAll('extras > extra, features > feature').forEach((node) => {
        const textEl = node.querySelector('name, title, text, label');
        const text = textEl?.textContent?.trim() || node.textContent?.replace(/\s+/g, ' ').trim();
        const iconEl = node.querySelector('icon, image, image_url, img_url, picture');
        let iconUrl = iconEl?.textContent?.trim() || iconEl?.getAttribute('src') || '';
        if (iconUrl && !iconUrl.startsWith('http')) iconUrl = '';
        if (text && text.length > 1) {
            out.push({ text, iconUrl });
        }
    });
    return out;
}

/**
 * Извлича числена стойност BTU от произволен текст (име, coolingPower, описание).
 * @param {{ allowBareLargeNumber?: boolean }} opts — ако true, приема и голямо число без думата „btu“ (само за полета като мощност).
 */
function parseBtuNumberFromString(str, opts) {
    if (str == null || str === '') return null;
    const s = String(str).replace(/\u00a0/g, ' ').trim();
    if (!s) return null;
    const low = s.toLowerCase();
    const allowBare = opts && opts.allowBareLargeNumber === true;

    const kw = low.match(/(\d+[.,]\d+|\d+)\s*(?:kw|квт)\b/);
    if (kw) {
        const val = parseFloat(kw[1].replace(',', '.'));
        if (val > 0.05 && val < 80) return Math.round(val * 3412);
    }

    let m = low.match(/(\d{1,2})\s*[,\s]?\s*000\s*btu/);
    if (m) return parseInt(m[1], 10) * 1000;
    m = low.match(/(\d{1,2})\s*000\s*btu/);
    if (m) {
        const n = parseInt(m[1], 10);
        if (n < 100) return n * 1000;
    }
    m = low.match(/(\d{4,6})\s*btu/);
    if (m) return parseInt(m[1], 10);
    m = low.match(/(\d+)\s*btu/);
    if (m) {
        const n = parseInt(m[1], 10);
        if (n >= 1000 && n <= 200000) return n;
        if (n >= 5 && n <= 48) return n * 1000;
    }
    m = low.match(/\b(\d{1,2})\s*k\b(?![a-zа-я])/i);
    if (m) {
        const k = parseInt(m[1], 10);
        if (k >= 5 && k <= 48) return k * 1000;
    }
    if (allowBare) {
        m = s.match(/\b(\d{4,6})\b/);
        if (m) {
            const n = parseInt(m[1], 10);
            if (n >= 4000 && n <= 120000) return n;
        }
    }
    return null;
}

/**
 * Fetch brands from API
 */
async function fetchBrands() {
    try {
        // Build the URL - use proxy if enabled
        let fetchUrl = BULCLIMA_API_BASE_URL;
        const useProxy = USE_CORS_PROXY || USE_CORS_PROXY_BULCLIMA;
        if (useProxy) {
            fetchUrl = CORS_PROXY_URL + encodeURIComponent(BULCLIMA_API_BASE_URL);
            console.log(`[BULCLIMA] Using CORS proxy`);
        } else {
            console.log(`[BULCLIMA] Attempting direct access (no proxy)`);
        }
        
        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
        // Bulclima-specific setting takes precedence over global setting
        const useProxy = USE_CORS_PROXY_BULCLIMA !== undefined ? USE_CORS_PROXY_BULCLIMA : USE_CORS_PROXY;
        if (useProxy && !brandId.startsWith('http')) {
            url = CORS_PROXY_URL + encodeURIComponent(url);
            console.log(`[BULCLIMA] Using CORS proxy for brand products`);
        } else if (useProxy && brandId.startsWith('http')) {
            url = CORS_PROXY_URL + encodeURIComponent(brandId);
            console.log(`[BULCLIMA] Using CORS proxy for brand products`);
        } else {
            console.log(`[BULCLIMA] Attempting direct access for brand products (no proxy)`);
        }
        
        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() : '';
            }
            
            const title = getText('title') || '';
            
            // 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;
                    }
                }
            });
            
            // Пълно HTML описание (fullInfo): таблици, вградени снимки и т.н.
            const getHtml = (selector) => {
                const element = item.querySelector(selector);
                return element?.innerHTML?.trim() || '';
            };
            const descHtmlSelectors = [
                'long_description',
                'full_description',
                'detailed_description',
                'opisaniee',
                'opisanie',
                'description'
            ];
            let descriptionHtml = '';
            for (let di = 0; di < descHtmlSelectors.length; di++) {
                const h = getHtml(descHtmlSelectors[di]);
                if (h && h.length > 12) {
                    descriptionHtml = h;
                    break;
                }
            }
            const plainFromDescriptionHtml = () => {
                if (!descriptionHtml) return '';
                const d = document.createElement('div');
                d.innerHTML = descriptionHtml;
                return d.textContent?.replace(/\s+/g, ' ').trim() || '';
            };
            const specTables = parseHtmlSpecTables(descriptionHtml);
            const shortPlain = getText('short_description');
            const opisaniePlain = getText('opisaniee') || getText('opisanie') || '';
            const fullDescription =
                shortPlain ||
                opisaniePlain ||
                plainFromDescriptionHtml() ||
                getText('description') ||
                '';
            const fullText = (title + ' ' + fullDescription + ' ' + plainFromDescriptionHtml()).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;
                    }
                }
            }
            
            mergeTableRowsIntoSpecifications(specs, specTables);
            
            const bulclimaDocs = extractDocumentsFromBulclimaXml(item);
            const featuresRich = extractFeaturesRichFromBulclima(item);
            
            let btuNumeric = parseBtuNumberFromString(title);
            if (btuNumeric == null) btuNumeric = parseBtuNumberFromString(specs.coolingPower, { allowBareLargeNumber: true });
            if (btuNumeric == null) btuNumeric = parseBtuNumberFromString(String(fullDescription).slice(0, 1500));
            const btu = btuNumeric != null ? `${btuNumeric} BTU` : '';
            
            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: fullDescription,
                descriptionHtml: descriptionHtml || '',
                specTables: specTables,
                documents: bulclimaDocs,
                featuresRich: featuresRich,
                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 HTML if no features found yet
            if (features.length === 0) {
                const fullDescHtml = descriptionHtml || getText('description');
                if (fullDescHtml) {
                    const tempDiv = document.createElement('div');
                    tempDiv.innerHTML = fullDescHtml.includes('<') ? fullDescHtml : `<p>${escapeHtml(fullDescHtml)}</p>`;
                    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;
    }
}

// ============================================
// Bittel API Functions
// ============================================

/**
 * Fetch products from Bittel API (supports both JSON and XML)
 * @param {number} page - Page number (default: 1, only for XML format)
 * @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,
            totalProducts: 0
        };
    }
    
    try {
        let url;
        let useJson = BITTEL_API_FORMAT === 'json';
        
        // Pagination (?page=) or full export (?all) — виж документация Bittel
        const cacheBuster = new Date().getTime();
        if (BITTEL_USE_ALL_EXPORT) {
            if (useJson) {
                const jSep = BITTEL_API_JSON_URL.includes('?') ? '&' : '?';
                url = `${BITTEL_API_JSON_URL}${jSep}all&t=${cacheBuster}`;
            } else {
                const xSep = BITTEL_API_XML_URL.includes('?') ? '&' : '?';
                url = `${BITTEL_API_XML_URL}${xSep}all&t=${cacheBuster}`;
            }
        } else if (useJson) {
            url = `${BITTEL_API_JSON_URL}?page=${page}&t=${cacheBuster}`;
        } else {
            url = `${BITTEL_API_XML_URL}?page=${page}&t=${cacheBuster}`;
        }
        
        // Use proxy if enabled
        // Bittel-specific setting takes precedence over global setting
        const originalUrl = url;
        let fetchUrl = url;
        const useProxy = USE_CORS_PROXY_BITTEL !== undefined ? USE_CORS_PROXY_BITTEL : USE_CORS_PROXY;
        if (useProxy) {
            fetchUrl = CORS_PROXY_URL + encodeURIComponent(url);
            console.log(`[BITTEL] Using CORS proxy for page ${page}`);
        } else {
            console.log(`[BITTEL] Attempting direct access (no proxy) for page ${page}`);
        }
        
        console.log(`[BITTEL] Fetching products (${useJson ? 'JSON' : 'XML'}) from page ${page}`);
        console.log(`[BITTEL] Original URL: ${originalUrl}`);
        console.log(`[BITTEL] Fetch URL: ${fetchUrl.substring(0, 150)}...`);
        
        let response;
        try {
            response = await fetch(fetchUrl, {
                method: 'GET',
                headers: {
                    'Accept': useJson ? 'application/json' : 'application/xml, text/xml, */*'
                }
            });
        } catch (fetchError) {
            console.error(`[BITTEL] Fetch error:`, fetchError);
            if (fetchError.message.includes('CORS') || fetchError.message.includes('Failed to fetch')) {
                console.warn('[BITTEL] ⚠️ CORS error detected. The API might not allow direct access.');
                console.warn('[BITTEL] Try enabling USE_CORS_PROXY or use a different proxy service.');
            }
            throw fetchError;
        }
        
        if (!response.ok) {
            console.error(`[BITTEL] HTTP error! status: ${response.status} ${response.statusText}`);
            console.error(`[BITTEL] Response URL: ${response.url}`);
            
            // If 403 and using proxy, suggest trying without proxy or different proxy
            if (response.status === 403 && USE_CORS_PROXY) {
                console.error('[BITTEL] ⚠️ 403 Forbidden from CORS proxy');
                console.error('[BITTEL] The proxy might be blocking the request.');
                console.error('[BITTEL] Try setting USE_CORS_PROXY = false to test direct access');
            }
            
            // Try to get error response body
            try {
                const errorText = await response.text();
                console.error(`[BITTEL] Error response body:`, errorText.substring(0, 500));
            } catch (e) {
                // Ignore if we can't read error body
            }
            
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        if (useJson) {
            // Handle JSON response - but check if it's actually XML
            const contentType = response.headers.get('content-type') || '';
            const text = await response.text();
            
            console.log(`[BITTEL] Response Content-Type: ${contentType}`);
            console.log(`[BITTEL] Response length: ${text.length} characters`);
            console.log(`[BITTEL] Response preview (first 500 chars):`, text.substring(0, 500));
            
            // Check if response is actually XML (sometimes JSON endpoint returns XML)
            const trimmedText = text.trim();
            const isXML = trimmedText.toLowerCase().startsWith('<?xml') || 
                         trimmedText.toLowerCase().startsWith('<info>') ||
                         trimmedText.toLowerCase().startsWith('<products>');
            
            if (isXML || contentType.includes('xml')) {
                console.warn('[BITTEL] ⚠️ JSON endpoint returned XML! Switching to XML parsing...');
                // Parse as XML instead
                const parser = new DOMParser();
                const xmlDoc = parser.parseFromString(text, 'text/xml');
                
                const parserError = xmlDoc.querySelector('parsererror');
                if (parserError) {
                    console.error('[BITTEL] XML Parse Error:', parserError.textContent);
                    return {
                        products: [],
                        hasMore: false,
                        currentPage: page,
                        totalPages: 1,
                        totalProducts: 0
                    };
                }
                
                // Parse pagination info from <info> element
                let totalPages = 1;
                let totalProducts = 0;
                let currentPageNum = page;
                
                const infoElement = xmlDoc.querySelector('info');
                if (infoElement) {
                    totalPages = parseInt(infoElement.querySelector('pages_count')?.textContent || 1);
                    totalProducts = parseInt(infoElement.querySelector('products_count')?.textContent || 0);
                    currentPageNum = parseInt(infoElement.querySelector('pages_current')?.textContent || page);
                    console.log(`[BITTEL] Pagination info (from XML):`, {
                        totalPages,
                        totalProducts,
                        currentPage: currentPageNum
                    });
                }
                
                // Parse XML products
                const productElements = xmlDoc.querySelectorAll('product');
                console.log(`[BITTEL] Found ${productElements.length} <product> elements`);
                
                const normalizedProducts = Array.from(productElements)
                    .map(item => normalizeBittelProduct(item, 'xml'))
                    .filter(Boolean);
                
                console.log(`[BITTEL] Normalized ${normalizedProducts.length} products`);
                
                const hasMore = BITTEL_USE_ALL_EXPORT ? false : (currentPageNum < totalPages);
                
                return {
                    products: normalizedProducts,
                    hasMore: hasMore,
                    currentPage: currentPageNum,
                    totalPages: totalPages,
                    totalProducts: totalProducts
                };
            }
            
            // Try to parse as JSON
            let data;
            try {
                data = JSON.parse(text);
            } catch (jsonError) {
                console.error('[BITTEL] ⚠️ Failed to parse as JSON:', jsonError);
                console.error('[BITTEL] Response text:', text.substring(0, 500));
                return {
                    products: [],
                    hasMore: false,
                    currentPage: page,
                    totalPages: 1,
                    totalProducts: 0
                };
            }
            
            console.log(`[BITTEL] JSON response received`);
            console.log(`[BITTEL] JSON structure keys:`, Object.keys(data));
            console.log(`[BITTEL] JSON response sample (first 1000 chars):`, JSON.stringify(data).substring(0, 1000));
            
            // Parse pagination info
            let totalPages = 1;
            let totalProducts = 0;
            let currentPageNum = page;
            let productsPerPage = 0;
            
            if (data.info) {
                totalPages = parseInt(data.info.pages_count || data.info.pagesCount || 1);
                totalProducts = parseInt(data.info.products_count || data.info.productsCount || 0);
                currentPageNum = parseInt(data.info.pages_current || data.info.pagesCurrent || page);
                productsPerPage = parseInt(data.info.products_per_page || data.info.productsPerPage || 0);
                console.log(`[BITTEL] Pagination info:`, {
                    totalPages,
                    totalProducts,
                    currentPage: currentPageNum,
                    productsPerPage
                });
            }
            
            // Parse JSON structure - try multiple possible structures
            let products = [];
            if (Array.isArray(data)) {
                products = data;
                console.log(`[BITTEL] Found array with ${products.length} items`);
            } else if (data.products && Array.isArray(data.products)) {
                products = data.products;
                console.log(`[BITTEL] Found data.products array with ${products.length} items`);
            } else if (data.data && Array.isArray(data.data)) {
                products = data.data;
                console.log(`[BITTEL] Found data.data array with ${products.length} items`);
            } else if (data.items && Array.isArray(data.items)) {
                products = data.items;
                console.log(`[BITTEL] Found data.items array with ${products.length} items`);
            } else if (data.result && Array.isArray(data.result)) {
                products = data.result;
                console.log(`[BITTEL] Found data.result array with ${products.length} items`);
            } else if (data.product && Array.isArray(data.product)) {
                products = data.product;
                console.log(`[BITTEL] Found data.product array with ${products.length} items`);
            } else {
                // Try to find any array property (excluding info)
                for (const key in data) {
                    if (key !== 'info' && Array.isArray(data[key])) {
                        products = data[key];
                        console.log(`[BITTEL] Found array in data.${key} with ${products.length} items`);
                        break;
                    }
                }
                
                if (products.length === 0) {
                    console.warn('[BITTEL] ⚠️ Unexpected JSON structure - no array found');
                    console.warn('[BITTEL] Available keys:', Object.keys(data));
                    console.warn('[BITTEL] Full response structure:', data);
                }
            }
            
            console.log(`[BITTEL] Found ${products.length} products in JSON response`);
            
            // Normalize products
            const normalizedProducts = products.map((item, index) => {
                try {
                    const normalized = normalizeBittelProduct(item, 'json');
                    if (!normalized && index < 3) {
                        console.warn(`[BITTEL] Failed to normalize product ${index}:`, item);
                    }
                    return normalized;
                } catch (error) {
                    console.error(`[BITTEL] Error normalizing product ${index}:`, error);
                    return null;
                }
            }).filter(Boolean);
            
            console.log(`[BITTEL] Normalized ${normalizedProducts.length} products (from ${products.length} raw products)`);
            
            if (normalizedProducts.length === 0 && products.length > 0) {
                console.error('[BITTEL] ⚠️ CRITICAL: All products failed normalization!');
                console.error('[BITTEL] Check normalizeBittelProduct function and product structure');
                console.error('[BITTEL] Sample raw product:', products[0]);
            }
            
            const hasMore = BITTEL_USE_ALL_EXPORT ? false : (currentPageNum < totalPages);
            
            return {
                products: normalizedProducts,
                hasMore: hasMore,
                currentPage: currentPageNum,
                totalPages: totalPages,
                totalProducts: totalProducts
            };
        } else {
            // Handle XML response
            const text = await response.text();
            console.log(`[BITTEL] XML response received, length: ${text.length} characters`);
            
            if (!text || text.trim().length === 0) {
                console.error('[BITTEL] Empty XML response');
                return {
                    products: [],
                    hasMore: false,
                    currentPage: page,
                    totalPages: 1,
                    totalProducts: 0
                };
            }
            
            // Check if response is HTML instead of XML
            const trimmedText = text.trim();
            const isHTML = trimmedText.toLowerCase().startsWith('<!doctype html') || 
                          trimmedText.toLowerCase().startsWith('<html');
            
            if (isHTML) {
                console.error('[BITTEL] ⚠️  ERROR: API returned HTML instead of XML!');
                console.error('[BITTEL] Response preview:', text.substring(0, 500));
                return {
                    products: [],
                    hasMore: false,
                    currentPage: page,
                    totalPages: 1,
                    totalProducts: 0
                };
            }
            
            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);
                return {
                    products: [],
                    hasMore: false,
                    currentPage: page,
                    totalPages: 1,
                    totalProducts: 0
                };
            }
            
            // Parse pagination info from <info> element
            let totalPages = 1;
            let totalProducts = 0;
            let currentPageNum = page;
            let productsPerPage = 0;
            
            const infoElement = xmlDoc.querySelector('info');
            if (infoElement) {
                totalPages = parseInt(infoElement.querySelector('pages_count')?.textContent || 1);
                totalProducts = parseInt(infoElement.querySelector('products_count')?.textContent || 0);
                currentPageNum = parseInt(infoElement.querySelector('pages_current')?.textContent || page);
                productsPerPage = parseInt(infoElement.querySelector('products_per_page')?.textContent || 0);
                console.log(`[BITTEL] Pagination info:`, {
                    totalPages,
                    totalProducts,
                    currentPage: currentPageNum,
                    productsPerPage
                });
            }
            
            // Parse XML products
            const productElements = xmlDoc.querySelectorAll('product');
            console.log(`[BITTEL] Found ${productElements.length} <product> elements`);
            
            const normalizedProducts = Array.from(productElements)
                .map(item => normalizeBittelProduct(item, 'xml'))
                .filter(Boolean);
            
            console.log(`[BITTEL] Normalized ${normalizedProducts.length} products`);
            
            const hasMore = BITTEL_USE_ALL_EXPORT ? false : (currentPageNum < totalPages);
            
            return {
                products: normalizedProducts,
                hasMore: hasMore,
                currentPage: currentPageNum,
                totalPages: totalPages,
                totalProducts: totalProducts
            };
        }
    } catch (error) {
        console.error(`[BITTEL] ERROR fetching products:`, error);
        console.error(`[BITTEL] Error message:`, error.message);
        return {
            products: [],
            hasMore: false,
            currentPage: page,
            totalPages: 1,
            totalProducts: 0
        };
    }
}

/**
 * Normalize Bittel product data to unified format
 * @param {Object|Element} item - Product data (JSON object or XML element)
 * @param {string} format - 'json' or 'xml'
 * @returns {Object|null} Normalized product object or null if invalid
 */
function normalizeBittelProduct(item, format = 'json') {
    try {
        let productData = {};
        
        if (format === 'json') {
            // Handle JSON format - use item directly
            productData = item;
            
            // Log first product structure for debugging
            if (!window._bittelProductLogged) {
                console.log('[BITTEL] Sample JSON product structure:', productData);
                window._bittelProductLogged = true;
            }
        } else {
            // Handle XML format
            const getText = (selector) => {
                const element = item.querySelector(selector);
                return element?.textContent?.trim() || '';
            };
            
            productData = {
                id: getText('id'),
                title: getText('title'),
                manufacturer: getText('manufacturer'),
                type: getText('type'),
                group_description: getText('group_description') || getText('group'),
                subgroup_description: getText('subgroup_description') || getText('subgroup'),
                description: getText('description') || getText('opisaniee') || getText('opisanie'),
                link: getText('link'),
                barcode: getText('barcode'),
                color: getText('color'),
                price_client: getText('price_client'),
                price_client_promo: getText('price_client_promo'),
                dealer_price: getText('dealer_price'),
                is_promo: getText('is_promo'),
                availability: getText('availability'),
                is_ask: getText('is_ask'),
                stock_size: getText('stock_size'),
                gallery: Array.from(item.querySelectorAll('gallery > file')).map(f => f.textContent?.trim()).filter(Boolean),
                features: Array.from(item.querySelectorAll('features > feature')).map(feature => {
                    const name = feature.querySelector('name')?.textContent?.trim() || '';
                    const items = Array.from(feature.querySelectorAll('items > item')).map(item => {
                        const itemName = item.querySelector('name')?.textContent?.trim() || '';
                        const itemValue = item.querySelector('value')?.textContent?.trim() || '';
                        return { name: itemName, value: itemValue };
                    });
                    return { name, items };
                })
            };
        }
        
        // Get product ID (required)
        const id = productData.id || productData.ID || '';
        if (!id) {
            console.warn('[BITTEL] Product missing ID, skipping');
            return null;
        }
        
        // Get basic info
        const title = productData.title || productData.name || '';
        const manufacturer = productData.manufacturer || productData.brand || '';
        const descriptionRaw =
            productData.description ||
            productData.opisaniee ||
            productData.opisanie ||
            '';
        let descriptionPlain = typeof descriptionRaw === 'string' ? descriptionRaw : '';
        let descriptionHtml = '';
        if (typeof descriptionRaw === 'string' && /<[a-z]/i.test(descriptionRaw)) {
            descriptionHtml = descriptionRaw;
            const tmpDesc = document.createElement('div');
            tmpDesc.innerHTML = descriptionRaw;
            descriptionPlain = tmpDesc.textContent?.replace(/\s+/g, ' ').trim() || '';
        }
        const description = descriptionPlain;
        let group = productData.group_description || productData.group || productData.category || '';
        let subgroup = productData.subgroup_description || productData.subgroup || productData.subcategory || '';
        
        // If group/subgroup not found, try to extract from product name
        if (!group && !subgroup && title) {
            const nameLower = title.toLowerCase();
            if (nameLower.includes('стенен') || nameLower.includes('wall')) {
                group = 'Стенни климатици';
            } else if (nameLower.includes('подов') || nameLower.includes('floor')) {
                group = 'Подови климатици';
            } else if (nameLower.includes('таванен') || nameLower.includes('ceiling')) {
                group = 'Таванни климатици';
            } else if (nameLower.includes('касет') || nameLower.includes('cassette')) {
                group = 'Касетъчни климатици';
            } else if (nameLower.includes('канален') || nameLower.includes('duct')) {
                group = 'Канални климатици';
            } else if (nameLower.includes('колонен') || nameLower.includes('column')) {
                group = 'Колонни климатици';
            } else if (nameLower.includes('мобилен') || nameLower.includes('mobile') || nameLower.includes('portable')) {
                group = 'Мобилни климатици';
            } else if (nameLower.includes('мулти сплит') || nameLower.includes('multisplit')) {
                group = 'Мултисплит системи';
            }
        }
        
        // Get prices
        const priceClient = parseFloat(productData.price_client || productData.price || 0);
        const priceClientPromo = parseFloat(productData.price_client_promo || productData.promo_price || 0);
        const isPromo = productData.is_promo === '1' || productData.is_promo === true || productData.isPromo === true;
        
        // Determine final price and old price
        let price = priceClient;
        let oldPrice = 0;
        let discount = '';
        
        if (isPromo && priceClientPromo > 0) {
            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 (JSON: gallery може да е масив от URL или обекти с file; XML: gallery/file)
        let images = [];
        if (format === 'json') {
            const g = productData.gallery;
            if (Array.isArray(g)) {
                images = g.map((entry) => {
                    if (typeof entry === 'string') return entry;
                    if (entry && typeof entry === 'object') {
                        const f = entry.file;
                        if (Array.isArray(f)) return f.filter(Boolean);
                        if (typeof f === 'string') return f;
                        return entry.url || entry.href || '';
                    }
                    return '';
                }).flat().filter(Boolean);
            } else if (g && typeof g === 'object') {
                const f = g.file;
                if (Array.isArray(f)) images = f.filter(Boolean);
                else if (typeof f === 'string') images = f.split(/[,\s]+/).map((s) => s.trim()).filter(Boolean);
            } else if (productData.image) {
                images = [productData.image];
            } else if (productData.images && Array.isArray(productData.images)) {
                images = productData.images;
            }
        } else {
            images = productData.gallery || [];
        }
        const imageUrl = images.length > 0 ? images[0] : '';
        
        // Extract features and specifications
        const features = [];
        const specs = {};
        
        let featureGroups = [];
        if (format === 'json') {
            if (Array.isArray(productData.features)) {
                featureGroups.push(...productData.features);
            }
            const specRoot =
                productData.specifications ||
                productData.specification ||
                productData.specs;
            if (specRoot && typeof specRoot === 'object') {
                if (Array.isArray(specRoot)) {
                    featureGroups.push({
                        name: '',
                        items: specRoot.map((x) => normalizeBittelFeatureRow(x))
                    });
                } else {
                    featureGroups.push({
                        name: 'specifications',
                        items: flattenBittelSpecificationsObject(specRoot)
                    });
                }
            }
            for (const ak of ['attributes', 'attrs', 'parameters', 'params', 'tech', 'technical']) {
                const arr = productData[ak];
                if (Array.isArray(arr) && arr.length > 0) {
                    featureGroups.push({
                        name: ak,
                        items: arr.map((x) => normalizeBittelFeatureRow(x))
                    });
                }
            }
        } else {
            featureGroups = productData.features || [];
        }
        
        featureGroups.forEach((group) => {
            const groupName = group.name || '';
            const items = group.items || group.item || [];
            const itemList = Array.isArray(items) ? items : [items];
            itemList.forEach((specItem) => {
                const { name: itemName, value: itemValue } = normalizeBittelFeatureRow(specItem);
                if (itemName && itemValue) {
                    features.push(`${itemName}: ${itemValue}`);
                    ingestBittelKeyValue(specs, itemName, itemValue);
                } else if (itemName && !itemValue) {
                    const colon = itemName.match(/^(.{1,120}?)[:：]\s*(.+)$/);
                    if (colon) {
                        const l = colon[1].trim();
                        const v = colon[2].trim();
                        features.push(`${l}: ${v}`);
                        ingestBittelKeyValue(specs, l, v);
                    } else {
                        features.push(itemName);
                        ingestBittelKeyValue(specs, groupName, itemName);
                    }
                } else if (itemValue) {
                    features.push(itemValue);
                    ingestBittelKeyValue(specs, groupName, itemValue);
                }
            });
        });

        if (format === 'json') {
            for (const k of Object.keys(productData)) {
                const v = productData[k];
                if (v == null || typeof v === 'object') continue;
                const vs = String(v).trim();
                if (!vs) continue;
                const kl = k.toLowerCase();
                if (
                    /cool|охлажд|btu|nominal_(cold|cool)|capacity_cold|power_cold|cold_power|хладилн/i.test(
                        kl
                    )
                ) {
                    ingestBittelKeyValue(specs, k, vs);
                }
                if (
                    /energy_class|efficiency|seer_class|scop_class|енерги|иклас|eef/i.test(kl)
                ) {
                    ingestBittelKeyValue(specs, k, vs);
                }
            }
        }
        
        const bittelSpecTables = parseHtmlSpecTables(descriptionHtml);
        mergeTableRowsIntoSpecifications(specs, bittelSpecTables);
        
        let btuNumeric = parseBtuNumberFromString(`${title} ${description}`);
        if (btuNumeric == null) btuNumeric = parseBtuNumberFromString(specs.coolingPower, { allowBareLargeNumber: true });
        if (btuNumeric == null) btuNumeric = parseBtuNumberFromString(features.join('\n').slice(0, 2500));
        const btu = btuNumeric != null ? `${btuNumeric} BTU` : '';
        
        const rawStock = productData.stock_size;
        const stockSizeStr = (rawStock == null || rawStock === '' || String(rawStock).toLowerCase() === 'null')
            ? ''
            : String(rawStock).trim();
        const dealerPriceNum = parseFloat(productData.dealer_price || 0);
        
        // Build normalized product object
        const product = {
            id: `bittel_${id}`,
            name: title || 'Климатик',
            brand: manufacturer,
            model: id,
            btu: btu,
            price: price > 0 ? price.toString() : '',
            oldPrice: oldPrice > 0 ? oldPrice.toString() : '',
            dealerPrice: dealerPriceNum > 0 ? dealerPriceNum.toString() : '',
            image: imageUrl,
            images: images.length > 0 ? images : (imageUrl ? [imageUrl] : []),
            description: description,
            descriptionHtml: descriptionHtml || '',
            specTables: bittelSpecTables,
            category: group,
            subCategory: subgroup,
            sku: productData.barcode || productData.sku || id,
            discount: discount,
            features: features,
            specifications: specs,
            distributor: 'bittel',
            availability: productData.availability || '',
            stockSize: stockSizeStr,
            isAsk: productData.is_ask === '1' || productData.is_ask === true || productData.is_ask === 1,
            link: productData.link || ''
        };
        
        return product;
    } catch (error) {
        console.error('[BITTEL] Error normalizing product:', error);
        return null;
    }
}

/**
 * Fetch all products from Bittel
 * @returns {Promise<Array>} Array of all products from Bittel
 */
async function fetchAllBittelProducts() {
    if (!USE_BITTEL) {
        return [];
    }
    
    console.log('[BITTEL] ========================================');
    console.log('[BITTEL] Starting to fetch all Bittel products...');
    console.log('[BITTEL] Format:', BITTEL_API_FORMAT);
    console.log('[BITTEL] JSON URL:', BITTEL_API_JSON_URL);
    console.log('[BITTEL] XML URL:', BITTEL_API_XML_URL);
    console.log('[BITTEL] Using CORS Proxy:', USE_CORS_PROXY_BITTEL);
    console.log('[BITTEL] Use ?all export:', BITTEL_USE_ALL_EXPORT);
    console.log('[BITTEL] ========================================');
    
    try {
        let allProducts = [];
        let currentPage = 1;
        let hasMore = true;
        let totalPages = 1;
        const maxPages = 50; // Safety limit
        
        // Fetch first page to get pagination info
        const firstPageResult = await fetchBittelProducts(1);
        
        if (!firstPageResult || !firstPageResult.products) {
            console.error('[BITTEL] Failed to fetch first page');
            console.error('[BITTEL] Result:', firstPageResult);
            return [];
        }
        
        allProducts.push(...firstPageResult.products);
        totalPages = firstPageResult.totalPages || 1;
        hasMore = firstPageResult.hasMore || false;
        
        console.log(`[BITTEL] Page 1: Added ${firstPageResult.products.length} products (total: ${allProducts.length})`);
        console.log(`[BITTEL] Total pages: ${totalPages}, Total products expected: ${firstPageResult.totalProducts || 0}`);
        
        // Fetch remaining pages
        currentPage = 2;
        while (hasMore && currentPage <= totalPages && currentPage <= maxPages) {
            const pageResult = await fetchBittelProducts(currentPage);
            
            if (pageResult && pageResult.products && pageResult.products.length > 0) {
                allProducts.push(...pageResult.products);
                console.log(`[BITTEL] Page ${currentPage}: Added ${pageResult.products.length} products (running total: ${allProducts.length})`);
                hasMore = pageResult.hasMore || false;
                currentPage++;
                
                // Small delay between requests to avoid overwhelming the server
                await new Promise(resolve => setTimeout(resolve, 200));
            } else {
                console.warn(`[BITTEL] Page ${currentPage}: No products returned`);
                hasMore = false;
            }
        }
        
        console.log(`[BITTEL] ========================================`);
        console.log(`[BITTEL] Finished fetching: ${allProducts.length} total products`);
        console.log(`[BITTEL] Expected: ${firstPageResult.totalProducts || 'unknown'}`);
        console.log(`[BITTEL] Pages fetched: ${currentPage - 1} of ${totalPages}`);
        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. API structure different than expected`);
            console.error(`[BITTEL] 5. Format setting (${BITTEL_API_FORMAT}) not matching API response`);
        }
        
        return allProducts;
    } catch (error) {
        console.error(`[BITTEL] ERROR fetching all products:`, error);
        console.error(`[BITTEL] Stack trace:`, error.stack);
        return [];
    }
}

// ============================================
// 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
    let bulclimaSuccess = false;
    let bulclimaError = null;
    if (USE_BULCLIMA) {
        try {
            console.log('========================================');
            console.log('[BULCLIMA] Starting fetch...');
            console.log('[BULCLIMA] API URL:', BULCLIMA_API_BASE_URL);
            const bulclimaUseProxy = USE_CORS_PROXY || USE_CORS_PROXY_BULCLIMA;
            console.log('[BULCLIMA] CORS Proxy:', bulclimaUseProxy ? 'Enabled' : 'Disabled');
            const brands = await fetchBrands();
            if (brands && brands.length > 0) {
                console.log(`[BULCLIMA] Found ${brands.length} brands`);
                let bulclimaProductCount = 0;
                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);
                            bulclimaProductCount += products.length;
                            console.log(`[BULCLIMA] Added ${products.length} products from brand: ${brand.title}`);
                        }
                    } catch (error) {
                        console.warn(`[BULCLIMA] Failed to fetch products for brand ${brand.id} (${brand.title}):`, error.message);
                    }
                }
                console.log(`[BULCLIMA] ✓ Successfully fetched ${bulclimaProductCount} total products`);
                bulclimaSuccess = bulclimaProductCount > 0;
            } else {
                console.warn('[BULCLIMA] ⚠ No brands found from Bulclima API');
                bulclimaError = 'No brands returned from API';
            }
        } catch (error) {
            console.error('[BULCLIMA] ✗ ERROR fetching from Bulclima:', error);
            console.error('[BULCLIMA] Error message:', error.message);
            if (error.stack) {
                console.error('[BULCLIMA] Stack trace:', error.stack);
            }
            bulclimaError = error.message;
        }
        console.log('[BULCLIMA] ========================================');
    } else {
        console.log('[BULCLIMA] Distributor is disabled (USE_BULCLIMA = false)');
    }
    
    // Fetch from Bittel
    let bittelSuccess = false;
    let bittelError = null;
    if (USE_BITTEL) {
        try {
            console.log('========================================');
            console.log('[BITTEL] Starting fetch...');
            console.log('[BITTEL] Format:', BITTEL_API_FORMAT);
            console.log('[BITTEL] JSON URL:', BITTEL_API_JSON_URL);
            console.log('[BITTEL] XML URL:', BITTEL_API_XML_URL);
            console.log('[BITTEL] CORS Proxy:', USE_CORS_PROXY ? 'Enabled' : 'Disabled');
            const bittelProducts = await fetchAllBittelProducts();
            if (bittelProducts && Array.isArray(bittelProducts) && bittelProducts.length > 0) {
                // Verify products have distributor marker
                bittelProducts.forEach(p => {
                    if (!p.distributor) {
                        p.distributor = 'bittel';
                    }
                });
                allProducts.push(...bittelProducts);
                console.log(`[BITTEL] ✓ Successfully fetched ${bittelProducts.length} products`);
                console.log(`[BITTEL] Sample product IDs:`, bittelProducts.slice(0, 3).map(p => p.id));
                bittelSuccess = true;
            } else {
                console.warn('[BITTEL] ⚠ No products fetched from Bittel');
                console.warn('[BITTEL] Possible reasons:');
                console.warn('[BITTEL] 1. API endpoint changed');
                console.warn('[BITTEL] 2. Network/CORS connection issues');
                console.warn('[BITTEL] 3. API structure changed');
                console.warn('[BITTEL] 4. Check Network tab in browser DevTools for failed requests');
                bittelError = 'No products returned';
            }
        } catch (error) {
            console.error('[BITTEL] ✗ ERROR fetching from Bittel:', error);
            console.error('[BITTEL] Error message:', error.message);
            if (error.stack) {
                console.error('[BITTEL] Stack trace:', error.stack);
            }
            bittelError = error.message;
            console.warn('[BITTEL] ⚠ Continuing with products from other distributors...');
        }
        console.log('[BITTEL] ========================================');
    } else {
        console.log('[BITTEL] Distributor is disabled (USE_BITTEL = false)');
    }
    
    // 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('========================================');
    console.log(`Total products combined: ${allProducts.length}`);
    console.log(`  - Bulclima: ${bulclimaCount} ${bulclimaSuccess ? '✓' : bulclimaError ? '✗' : '⚠'}`);
    if (bulclimaCount > 0) {
        console.log(`    Sample Bulclima products:`, allProducts.filter(p => p.distributor === 'bulclima').slice(0, 2).map(p => ({
            id: p.id,
            name: p.name,
            category: p.category,
            brand: p.brand
        })));
    }
    if (USE_BULCLIMA && !bulclimaSuccess) {
        console.log(`    Error: ${bulclimaError || 'No products fetched'}`);
    }
    console.log(`  - Bittel: ${bittelCount} ${bittelSuccess ? '✓' : bittelError ? '✗' : '⚠'}`);
    if (bittelCount > 0) {
        console.log(`    Sample Bittel products:`, allProducts.filter(p => p.distributor === 'bittel').slice(0, 2).map(p => ({
            id: p.id,
            name: p.name,
            category: p.category,
            brand: p.brand
        })));
    }
    if (USE_BITTEL && !bittelSuccess) {
        console.log(`    Error: ${bittelError || 'No products fetched'}`);
    }
    if (unknownCount > 0) {
        console.log(`  - Unknown source: ${unknownCount}`);
    }
    console.log('========================================');
    
    // Detailed warnings
    if (allProducts.length === 0) {
        console.error('⚠️  CRITICAL: No products fetched from any distributor!');
        console.error('Possible issues:');
        if (USE_BULCLIMA && !bulclimaSuccess) {
            console.error('  [BULCLIMA] Failed - Check:');
            console.error('    - API endpoint is accessible');
            console.error('    - XML structure hasn\'t changed');
            console.error('    - CORS proxy is working');
            console.error(`    - Error: ${bulclimaError || 'Unknown'}`);
        }
        if (USE_BITTEL && !bittelSuccess) {
            console.error('  [BITTEL] Failed - Check:');
            console.error('    - API endpoint is accessible');
            console.error('    - API structure hasn\'t changed');
            console.error('    - CORS proxy is working');
            console.error(`    - Error: ${bittelError || 'Unknown'}`);
        }
    } else {
        // Check if one distributor is missing
        if (USE_BULCLIMA && bulclimaCount === 0 && USE_BITTEL && bittelCount > 0) {
            console.warn('⚠️  WARNING: Bulclima is enabled but returned 0 products!');
            console.warn('  Bittel products are still showing, but Bulclima products are missing.');
            console.warn(`  Bulclima error: ${bulclimaError || 'No products returned'}`);
        } else if (USE_BITTEL && bittelCount === 0 && USE_BULCLIMA && bulclimaCount > 0) {
            console.warn('⚠️  WARNING: Bittel is enabled but returned 0 products!');
            console.warn('  Bulclima products are still showing, but Bittel products are missing.');
            console.warn(`  Bittel error: ${bittelError || 'No products returned'}`);
        }
    }
    
    return allProducts;
}

/**
 * Diagnostic function to test each distributor separately
 * Call this from browser console: testDistributors()
 * @returns {Promise<Object>} Diagnostic results for each distributor
 */
async function testDistributors() {
    console.log('🔍 Starting distributor diagnostics...');
    console.log('========================================');
    
    const results = {
        bulclima: { enabled: USE_BULCLIMA, success: false, products: 0, error: null },
        bittel: { enabled: USE_BITTEL, success: false, products: 0, error: null }
    };
    
    // Test Bulclima
    if (USE_BULCLIMA) {
        console.log('\n[BULCLIMA] Testing...');
        try {
            const brands = await fetchBrands();
            if (brands && brands.length > 0) {
                console.log(`[BULCLIMA] ✓ Found ${brands.length} brands`);
                let totalProducts = 0;
                for (let i = 0; i < Math.min(2, brands.length); i++) {
                    const brand = brands[i];
                    try {
                        const products = await fetchBrandProducts(brand.id);
                        if (products && products.length > 0) {
                            totalProducts += products.length;
                            console.log(`[BULCLIMA] ✓ Brand "${brand.title}": ${products.length} products`);
                        }
                    } catch (error) {
                        console.error(`[BULCLIMA] ✗ Brand "${brand.title}" failed:`, error.message);
                    }
                }
                results.bulclima.success = totalProducts > 0;
                results.bulclima.products = totalProducts;
            } else {
                results.bulclima.error = 'No brands returned';
                console.error('[BULCLIMA] ✗ No brands found');
            }
        } catch (error) {
            results.bulclima.error = error.message;
            console.error('[BULCLIMA] ✗ Error:', error.message);
        }
    } else {
        console.log('[BULCLIMA] Disabled');
    }
    
    // Test Bittel
    if (USE_BITTEL) {
        console.log('\n[BITTEL] Testing...');
        try {
            const bittelProducts = await fetchBittelProducts(1);
            if (bittelProducts && Array.isArray(bittelProducts) && bittelProducts.length > 0) {
                results.bittel.success = true;
                results.bittel.products = bittelProducts.length;
                console.log(`[BITTEL] ✓ Found ${bittelProducts.length} products`);
                console.log(`[BITTEL] Format: ${BITTEL_API_FORMAT}`);
                if (bittelProducts.length > 0) {
                    console.log(`[BITTEL] Sample product:`, {
                        id: bittelProducts[0].id,
                        name: bittelProducts[0].name,
                        brand: bittelProducts[0].brand
                    });
                }
            } else {
                results.bittel.error = 'No products returned';
                console.error('[BITTEL] ✗ No products found');
            }
        } catch (error) {
            results.bittel.error = error.message;
            console.error('[BITTEL] ✗ Error:', error.message);
        }
    } else {
        console.log('[BITTEL] Disabled');
    }
    
    console.log('\n========================================');
    console.log('📊 DIAGNOSTIC RESULTS:');
    console.log('========================================');
    console.log('Bulclima:', results.bulclima);
    console.log('Bittel:', results.bittel);
    console.log('========================================');
    console.log('\n💡 To test in detail, check browser console for [BULCLIMA] and [BITTEL] logs');
    console.log('💡 Check Network tab for failed API requests');
    
    return results;
}

// Make diagnostic function available globally
if (typeof window !== 'undefined') {
    window.testDistributors = testDistributors;
    console.log('💡 Diagnostic function available: Call testDistributors() in console to test each distributor');
}

/**
 * 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;
            }
        }
        
        // Debug warning for products without category that might be filtered out
        if (!catLower && !subCatLower && !nameLower) {
            console.warn(`Product missing both category and name:`, product.id);
        }
        
        return false;
    });
    
    console.log(`Products after filter: ${filtered.length}`);
    
    // Additional diagnostics if no products found
    if (filtered.length === 0) {
        console.warn(`⚠️  No products found for category "${category}"`);
        console.warn(`Looking for keywords: ${categoryKeywords.join(', ')}`);
        console.log(`Sample products and their categories:`, products.slice(0, 3).map(p => ({
            id: p.id,
            name: p.name,
            category: p.category,
            subCategory: p.subCategory,
            distributor: p.distributor
        })));
    }
    
    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;
    });
}

/**
 * Числена стойност на BTU за филтър (съвпада с parseBtuNumberFromString навсякъде).
 */
function extractProductBtuNumeric(product) {
    if (!product) return null;
    let n = parseBtuNumberFromString(product.btu);
    if (n != null) return n;
    n = parseBtuNumberFromString(product.specifications?.coolingPower, { allowBareLargeNumber: true });
    if (n != null) return n;
    const pname = product.name || '';
    n = parseBtuNumberFromString(pname);
    if (n == null && /btu|квт|\bkw\b|\d\s*000|мощност/i.test(pname)) {
        n = parseBtuNumberFromString(pname, { allowBareLargeNumber: true });
    }
    if (n != null) return n;
    const feat = (product.features || []).join('\n').slice(0, 2000);
    n = parseBtuNumberFromString(feat);
    if (n != null) return n;
    n = parseBtuNumberFromString(String(product.description || '').slice(0, 1200));
    if (n != null) return n;
    const model = product.model || product.sku || '';
    if (model && /\d{4,6}/.test(String(model))) {
        n = parseBtuNumberFromString(String(model), { allowBareLargeNumber: true });
    }
    return n;
}

/**
 * Площ (кв.м) за филтър — предимно от specifications.area, после от описание.
 */
function extractAreaSqmNumeric(product) {
    const parseChunk = (raw) => {
        if (!raw) return null;
        const s = String(raw).toLowerCase();
        const upto = s.match(/до\s*(\d+)\s*(?:m|м²|м2|кв|кв\.?\s*м)/);
        if (upto) return parseInt(upto[1], 10);
        const range = s.match(/(\d+)\s*[-–]\s*(\d+)\s*(?:m|м²|кв)/);
        if (range) return Math.max(parseInt(range[1], 10), parseInt(range[2], 10));
        const nums = s.match(/\d+/g);
        if (!nums || !nums.length) return null;
        const vals = nums.map((x) => parseInt(x, 10)).filter((v) => v > 0 && v <= 500);
        if (!vals.length) return null;
        return Math.max(...vals);
    };
    let v = parseChunk(product.specifications?.area);
    if (v != null) return v;
    v = parseChunk(String(product.description || '').slice(0, 1000));
    return v;
}

/**
 * Филтър по помещение: до ~20 m², 20–40 m², над 40 m².
 * BTU: ≤12k → до 20; 12k–24k → средна; >24k → големи.
 * Без открита мощност/площ — остават видими (за да не изчезне целият каталог).
 */
function filterProductsByRoomSize(products, roomSizeRange) {
    if (!roomSizeRange || roomSizeRange === 'all') {
        return products;
    }
    
    const known = new Set(['to-20', 'to-40', 'above-40']);
    if (!known.has(roomSizeRange)) {
        return products;
    }
    
    return products.filter((product) => {
        const btu = extractProductBtuNumeric(product);
        if (btu != null && btu > 0) {
            switch (roomSizeRange) {
                case 'to-20':
                    return btu <= 12000;
                case 'to-40':
                    return btu > 12000 && btu <= 24000;
                case 'above-40':
                    return btu > 24000;
                default:
                    return true;
            }
        }
        
        const areaSqm = extractAreaSqmNumeric(product);
        if (areaSqm != null && areaSqm > 0) {
            switch (roomSizeRange) {
                case 'to-20':
                    return areaSqm <= 20;
                case 'to-40':
                    return areaSqm > 20 && areaSqm <= 40;
                case 'above-40':
                    return areaSqm > 40;
                default:
                    return true;
            }
        }
        
        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 priceValue = product.price ? parseFloat(product.price) : 0;
    const oldPriceValue = product.oldPrice ? parseFloat(product.oldPrice) : 0;
    
    // Currency handling: Bulclima prices are in EUR, Bittel prices are in BGN
    const isBittel = product.distributor === 'bittel';
    const isBulclima = product.distributor === 'bulclima' || !product.distributor;
    
    if (!isNaN(priceValue) && priceValue > 0) {
        let priceEuro, priceBgn, oldPriceEuro, oldPriceBgn;
        
        if (isBittel) {
            // Bittel prices are already in BGN, convert to EUR for display
            priceBgn = priceValue;
            priceEuro = priceBgn / EUR_TO_BGN_RATE;
            oldPriceBgn = oldPriceValue > 0 ? oldPriceValue : 0;
            oldPriceEuro = oldPriceBgn > 0 ? oldPriceBgn / EUR_TO_BGN_RATE : 0;
        } else {
            // Bulclima prices are in EUR, convert to BGN
            priceEuro = priceValue;
            priceBgn = priceEuro * EUR_TO_BGN_RATE;
            oldPriceEuro = oldPriceValue > 0 ? oldPriceValue : 0;
            oldPriceBgn = oldPriceEuro > 0 ? oldPriceEuro * EUR_TO_BGN_RATE : 0;
        }
        
        if ((isBittel && oldPriceBgn > priceBgn && oldPriceBgn > 0) || 
            (isBulclima && oldPriceEuro > priceEuro && oldPriceEuro > 0)) {
            priceHtml = `
                <div class="product-price-wrapper">
                    <div class="product-price-old-wrapper">
                    <span class="product-price-old">${oldPriceEuro.toFixed(2)} €</span>
                        <span class="product-price-separator">/</span>
                        <span class="product-price-old-euro">${oldPriceBgn.toFixed(2)} лв</span>
                    </div>
                    <div class="product-price-current-wrapper">
                        <span class="product-price">${priceEuro.toFixed(2)} €</span>
                        <span class="product-price-separator">/</span>
                        <span class="product-price-euro">${priceBgn.toFixed(2)} лв</span>
                    </div>
                </div>
            `;
        } else {
            priceHtml = `
                <div class="product-price-wrapper">
                    <div class="product-price-current-wrapper">
                        <span class="product-price">${priceEuro.toFixed(2)} €</span>
                        <span class="product-price-separator">/</span>
                        <span class="product-price-euro">${priceBgn.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 (use BGN price for sorting)
    const priceForSort = (() => {
        if (!product.price) return 999999; // Put "По запитване" at the end
        const priceVal = parseFloat(product.price);
        if (isBittel) {
            // Bittel prices are already in BGN
            return priceVal;
        } else {
            // Bulclima prices are in EUR, convert to BGN
            return priceVal * EUR_TO_BGN_RATE;
        }
    })();
    
    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 = '';
    
    // EUR to BGN conversion rate
    const EUR_TO_BGN_RATE = 1.95583;
    
    // Currency handling: Bulclima prices are in EUR, Bittel prices are in BGN
    const isBittel = product.distributor === 'bittel';
    const isBulclima = product.distributor === 'bulclima' || !product.distributor;
    
    const priceValue = product.price ? parseFloat(product.price) : 0;
    const oldPriceValue = product.oldPrice ? parseFloat(product.oldPrice) : 0;
    
    if (!isNaN(priceValue) && priceValue > 0) {
        let priceEuro, priceBgn, oldPriceEuro, oldPriceBgn;
        
        if (isBittel) {
            // Bittel prices are already in BGN, convert to EUR for display
            priceBgn = priceValue;
            priceEuro = priceBgn / EUR_TO_BGN_RATE;
            oldPriceBgn = oldPriceValue > 0 ? oldPriceValue : 0;
            oldPriceEuro = oldPriceBgn > 0 ? oldPriceBgn / EUR_TO_BGN_RATE : 0;
        } else {
            // Bulclima prices are in EUR, convert to BGN
            priceEuro = priceValue;
            priceBgn = priceEuro * EUR_TO_BGN_RATE;
            oldPriceEuro = oldPriceValue > 0 ? oldPriceValue : 0;
            oldPriceBgn = oldPriceEuro > 0 ? oldPriceEuro * EUR_TO_BGN_RATE : 0;
        }
        
        if ((isBittel && oldPriceBgn > priceBgn && oldPriceBgn > 0) || 
            (isBulclima && oldPriceEuro > priceEuro && oldPriceEuro > 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">${oldPriceEuro.toFixed(2).replace('.', ',')} €</span>
                            <span class="price-separator-small">/</span>
                            <span class="original-price-euro">${oldPriceBgn.toFixed(2).replace('.', ',')} лв</span>
                        </div>
                        <div class="current-price-wrapper">
                            <span class="current-price">${priceEuro.toFixed(2).replace('.', ',')} €</span>
                            <span class="price-separator-small">/</span>
                            <span class="current-price-euro">${priceBgn.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">${priceEuro.toFixed(2).replace('.', ',')} €</span>
                            <span class="price-separator-small">/</span>
                            <span class="current-price-euro">${priceBgn.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 === `bulclima_${productId}` ||
            p.id === `bittel_${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(${JSON.stringify(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 || '';
    }
    
    const productStatus = document.getElementById('productStatus');
    if (productStatus) {
        productStatus.classList.remove('product-status--limited', 'product-status--out');
        if (product.distributor === 'bittel' && product.availability) {
            const a = String(product.availability);
            let label = a;
            if (/неналичен/i.test(a)) {
                productStatus.classList.add('product-status--out');
            } else if (/ограничена/i.test(a)) {
                productStatus.classList.add('product-status--limited');
                if (product.stockSize) label = `${a} (${product.stockSize} бр.)`;
            } else if (/наличен/i.test(a)) {
                label = `✓ ${a}`;
            }
            productStatus.textContent = label;
        } else {
            productStatus.textContent = '✓ По запитване';
        }
    }
    
    // Title
    const productTitle = document.getElementById('productTitle');
    if (productTitle) {
        productTitle.textContent = product.name || 'Климатик';
    }
    
    // Breadcrumb
    const productBreadcrumb = document.getElementById('productBreadcrumb');
    if (productBreadcrumb) {
        productBreadcrumb.textContent = product.name || 'Детайли за продукт';
    }

    const distBadge = document.getElementById('productDistributorBadge');
    if (distBadge) {
        const d =
            product.distributor === 'bittel'
                ? 'Bittel'
                : product.distributor === 'bulclima'
                  ? 'Bulclima'
                  : 'Каталог';
        distBadge.textContent = d;
        distBadge.title = `Каталожни данни от ${d}`;
    }

    const catMeta = document.getElementById('productCategoryMeta');
    if (catMeta) {
        const parts = [product.category, product.subCategory].filter(Boolean);
        catMeta.textContent = parts.length ? parts.join(' · ') : '';
    }

    const promoBadge = document.getElementById('productPromoBadge');
    if (promoBadge) {
        const pv = product.price ? parseFloat(product.price) : 0;
        const ov = product.oldPrice ? parseFloat(product.oldPrice) : 0;
        promoBadge.hidden = !(ov > pv && pv > 0);
    }
    
    // Описание: пълно HTML от дистрибутора (таблици, снимки) или списък от текст
    let desc = product.description || '';
    if (desc && typeof desc === 'string' && desc.includes('<')) {
        const stripDiv = document.createElement('div');
        stripDiv.innerHTML = desc;
        desc = stripDiv.textContent || stripDiv.innerText || '';
    }
    const defaultDesc = 'Професионален климатик с отлични характеристики.';
    const finalDesc = (desc || '').trim() || defaultDesc;
    
    const descRichEl = document.getElementById('productDescriptionRich');
    const listWrap = document.getElementById('productDescriptionListWrap');
    const productDescriptionText = document.getElementById('productDescriptionText');
    const richHtml = product.descriptionHtml && String(product.descriptionHtml).trim();
    const useRich = richHtml && richHtml.length > 20 && /<[a-z][\s\S]*/i.test(richHtml);
    
    if (descRichEl) {
        if (useRich) {
            descRichEl.innerHTML = richHtml;
            descRichEl.removeAttribute('hidden');
            if (listWrap) listWrap.setAttribute('hidden', '');
        } else {
            descRichEl.innerHTML = '';
            descRichEl.setAttribute('hidden', '');
            if (listWrap) listWrap.removeAttribute('hidden');
        }
    }
    
    // „Описание“: само narrative (plain / rich HTML), без product.features — те са в „Предимства“
    if (productDescriptionText && !useRich) {
        productDescriptionText.innerHTML = '';
        let itemsToDisplay = [];
        if (finalDesc) {
            itemsToDisplay = finalDesc
                .split(/\s{4,}|[;。\n]/)
                .map((item) => item.trim())
                .filter((item) => item.length > 0);
        }
        if (itemsToDisplay.length > 1) {
            itemsToDisplay.forEach((item) => {
                const li = document.createElement('li');
                li.textContent = item;
                productDescriptionText.appendChild(li);
            });
        } else if (finalDesc) {
            const li = document.createElement('li');
            li.textContent = finalDesc;
            productDescriptionText.appendChild(li);
        }
    } else if (productDescriptionText && useRich) {
        productDescriptionText.innerHTML = '';
    }
    
    // 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 || '';
        
        // Ако липсва в specs — търси в име, описание и редовете от features (Bittel/Bulclima)
        if (
            !power &&
            (product.description || product.name || (product.features && product.features.length))
        ) {
            const featChunk = (product.features || []).join(' ').slice(0, 2500);
            const searchText = `${product.name || ''} ${product.description || ''} ${featChunk}`.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) {
                const n = parseBtuNumberFromString(
                    `${product.name || ''} ${product.description || ''} ${featChunk}`,
                    { allowBareLargeNumber: true }
                );
                if (n != null) power = `${n} BTU`;
            }
        }
        
        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 (
            !energyClass &&
            (product.description || product.name || (product.features && product.features.length))
        ) {
            const featChunk = (product.features || []).join(' ').slice(0, 2500);
            const searchText = `${product.name || ''} ${product.description || ''} ${featChunk}`.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}"`);
    }
    
    const warrantyFromSpecs =
        product.specifications &&
        product.specifications.warranty &&
        String(product.specifications.warranty).trim();
    const warrantyLabel = warrantyFromSpecs || 'От производителя';

    const productWarranty = document.getElementById('productWarranty');
    if (productWarranty) {
        productWarranty.textContent = warrantyLabel;
        console.log(`[Product Detail] Warranty card: "${warrantyLabel}"`);
    }
    
    // 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
    const guaranteeWarrantyTitle = document.getElementById('guaranteeWarrantyTitle');
    const guaranteeWarrantyText = document.getElementById('guaranteeWarrantyText');
    if (guaranteeWarrantyTitle && guaranteeWarrantyText) {
        guaranteeWarrantyTitle.textContent = 'Гаранция';
        guaranteeWarrantyText.textContent = warrantyLabel;
        console.log(`[Product Detail] Service guarantee card: "Гаранция" / "${warrantyLabel}"`);
    }
    
    // Price - handle old price if available, add VAT text, and convert currency if needed
    const productPrice = document.getElementById('productPrice');
    const productPriceEuro = document.getElementById('productPriceEuro');
    const priceMain = productPrice?.closest('.product-price-main');
    
    // EUR to BGN exchange rate (fixed rate: 1 EUR = 1.95583 BGN)
    const EUR_TO_BGN_RATE = 1.95583;
    
    // Currency handling: Bulclima prices are in EUR, Bittel prices are in BGN
    const isBittel = product.distributor === 'bittel';
    const isBulclima = product.distributor === 'bulclima' || !product.distributor;
    
    if (productPrice && priceMain) {
        const priceValue = product.price ? parseFloat(product.price) : 0;
        const oldPriceValue = product.oldPrice ? parseFloat(product.oldPrice) : 0;
        
        if (priceValue > 0) {
            let priceEuro, priceBgn, oldPriceEuro, oldPriceBgn;
            
            if (isBittel) {
                // Bittel prices are already in BGN, convert to EUR for display
                priceBgn = priceValue;
                priceEuro = priceBgn / EUR_TO_BGN_RATE;
                oldPriceBgn = oldPriceValue > 0 ? oldPriceValue : 0;
                oldPriceEuro = oldPriceBgn > 0 ? oldPriceBgn / EUR_TO_BGN_RATE : 0;
            } else {
                // Bulclima prices are in EUR, convert to BGN
                priceEuro = priceValue;
                priceBgn = priceEuro * EUR_TO_BGN_RATE;
                oldPriceEuro = oldPriceValue > 0 ? oldPriceValue : 0;
                oldPriceBgn = oldPriceEuro > 0 ? oldPriceEuro * EUR_TO_BGN_RATE : 0;
            }
            
            if ((isBittel && oldPriceBgn > priceBgn && oldPriceBgn > 0) || 
                (isBulclima && oldPriceEuro > priceEuro && oldPriceEuro > 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;">${oldPriceEuro.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;">${oldPriceBgn.toFixed(2)} лв.</span>
                            </div>
                            <div style="display: flex; align-items: baseline; gap: var(--spacing-xs);">
                        <span class="price-amount" id="productPrice">${priceEuro.toFixed(2)} €</span>
                                <span class="price-separator">/</span>
                                <span class="price-amount-euro-value" id="productPriceEuro">${priceBgn.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 = `${priceEuro.toFixed(2)} €`;
                    euroElement.textContent = `${priceBgn.toFixed(2)} лв.`;
                } else {
                    // If wrapper doesn't exist, create it
                    priceMain.innerHTML = `
                        <div class="price-amount-wrapper">
                            <span class="price-amount" id="productPrice">${priceEuro.toFixed(2)} €</span>
                            <span class="price-separator">/</span>
                            <span class="price-amount-euro-value" id="productPriceEuro">${priceBgn.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}` : '';
    }

    const distLinkWrap = document.getElementById('productDistributorLinkWrap');
    const distLink = document.getElementById('productDistributorLink');
    if (distLinkWrap && distLink) {
        const url = product.link && String(product.link).trim();
        if (url) {
            distLink.href = url;
            distLinkWrap.hidden = false;
        } else {
            distLink.removeAttribute('href');
            distLinkWrap.hidden = true;
        }
    }
    
    // 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 (specs.area) {
            specsItems.push({
                label: 'Площ / обхват',
                value: specs.area,
                icon: 'bi-house-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>
            `;
        }
    }
    
    const specTablesHost = document.getElementById('productSpecTablesHost');
    if (specTablesHost) {
        if (product.specTables && product.specTables.length > 0) {
            specTablesHost.innerHTML = product.specTables
                .map((table) => {
                    const cap = table.caption
                        ? `<h4 class="product-spec-table-title">${escapeHtml(table.caption)}</h4>`
                        : '';
                    const body = table.rows
                        .map((r) => {
                            if (r.label) {
                                return `<tr><th scope="row">${escapeHtml(r.label)}</th><td>${escapeHtml(r.value)}</td></tr>`;
                            }
                            return `<tr><td colspan="2">${escapeHtml(r.value)}</td></tr>`;
                        })
                        .join('');
                    return `${cap}<div class="product-table-scroll"><table class="product-data-table"><tbody>${body}</tbody></table></div>`;
                })
                .join('');
        } else {
            specTablesHost.innerHTML = '';
        }
    }

    const specTablesHeading = document.getElementById('productSpecTablesHeading');
    if (specTablesHeading) {
        specTablesHeading.hidden = !(product.specTables && product.specTables.length > 0);
    }
    
    const tabBtnDocuments = document.getElementById('tabBtnDocuments');
    const documentsInner = document.getElementById('productDocumentsInner');
    if (tabBtnDocuments && documentsInner) {
        if (product.documents && product.documents.length > 0) {
            tabBtnDocuments.hidden = false;
            documentsInner.innerHTML = `
                <p class="product-documents-intro">Материали за сваляне:</p>
                <ul class="product-documents-list">
                    ${product.documents
                        .map(
                            (d) => `
                        <li>
                            <a href="${escapeHtml(d.url)}" target="_blank" rel="noopener noreferrer" class="product-doc-link">
                                <i class="bi bi-file-earmark-arrow-down" aria-hidden="true"></i>
                                <span>${escapeHtml(d.title)}</span>
                            </a>
                        </li>`
                        )
                        .join('')}
                </ul>`;
        } else {
            tabBtnDocuments.hidden = true;
            documentsInner.innerHTML = '';
        }
    }
    
    // Populate Features List
    const featuresList = document.getElementById('featuresList');
    if (featuresList) {
        // Clear existing content
        featuresList.innerHTML = '';
        
        let featuresToDisplay = [];
        
        if (product.features && product.features.length > 0) {
            featuresToDisplay = product.features;
        } else {
            const desc = product.description || '';
            if (desc && !desc.includes('<')) {
                const items = desc
                    .split(/\s{4,}|[;。\n]/)
                    .map((item) => item.trim())
                    .filter((item) => item.length > 0 && item.length > 10);
                if (items.length > 1) {
                    featuresToDisplay = items;
                }
            }
        }
        
        if (product.featuresRich && product.featuresRich.length > 0) {
            product.featuresRich.forEach((f) => {
                const div = document.createElement('div');
                div.className = 'characteristic-item characteristic-item--rich';
                if (f.iconUrl) {
                    const img = document.createElement('img');
                    img.src = f.iconUrl;
                    img.alt = '';
                    img.className = 'characteristic-icon-img';
                    img.loading = 'lazy';
                    img.referrerPolicy = 'no-referrer';
                    div.appendChild(img);
                }
                const span = document.createElement('span');
                span.textContent = f.text;
                div.appendChild(span);
                featuresList.appendChild(div);
            });
        } else if (featuresToDisplay.length > 0) {
            featuresToDisplay.forEach((feature) => {
                const div = document.createElement('div');
                div.className = 'characteristic-item';
                div.textContent = feature;
                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) {
        const plain = String(product.description || '').replace(/<[^>]*>/g, '').replace(/\s+/g, ' ').trim();
        metaDescription.content = `${product.name} - ${product.brand || ''}. ${plain ? plain.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);

/**
 * Simple direct API test
 * Call window.testDirectAPI() in browser console
 */
window.testDirectAPI = async function() {
    console.log('========================================');
    console.log('DIRECT API TEST - No proxies, no caching');
    console.log('========================================');
    
    // Test 1: Bulclima Brands
    console.log('\n1️⃣  Testing Bulclima Brands...');
    try {
        const bulclimaUrl = 'https://www.bulclima.com/tools/api/fullInfo/';
        const proxiedUrl = 'https://corsproxy.io/?' + encodeURIComponent(bulclimaUrl);
        console.log('URL:', proxiedUrl);
        
        const resp1 = await fetch(proxiedUrl, { method: 'GET' });
        console.log('Status:', resp1.status);
        const text1 = await resp1.text();
        console.log('Response length:', text1.length);
        console.log('Response preview:', text1.substring(0, 300));
        if (text1.includes('<brand')) {
            const parser = new DOMParser();
            const xml = parser.parseFromString(text1, 'text/xml');
            const brandCount = xml.querySelectorAll('brand').length;
            console.log('✓ Brands found:', brandCount);
        }
    } catch (e) {
        console.error('✗ Bulclima brands error:', e.message);
    }
    
    // Test 2: Bittel JSON
    console.log('\n2️⃣  Testing Bittel JSON...');
    try {
        const KEYS = {
            bittelKey: 'b6a9278e9e8796f985c820a2b7d22dbb'
        };
        const bittelUrl = `https://dealers.bittel.bg/bg/api/json_v3/${KEYS.bittelKey}?page=1`;
        const proxiedUrl2 = 'https://corsproxy.io/?' + encodeURIComponent(bittelUrl);
        console.log('URL (truncated):', bittelUrl.substring(0, 100) + '...');
        
        const resp2 = await fetch(proxiedUrl2, { method: 'GET' });
        console.log('Status:', resp2.status);
        const text2 = await resp2.text();
        console.log('Response length:', text2.length);
        console.log('Response preview:', text2.substring(0, 300));
        
        try {
            const json = JSON.parse(text2);
            console.log('✓ JSON parsed');
            console.log('JSON structure:', Object.keys(json));
            if (json.info) console.log('Info:', json.info);
            
            // Find products array
            let productArray = null;
            for (const key in json) {
                if (Array.isArray(json[key]) && key !== 'info') {
                    console.log(`Found array: ${key} with ${json[key].length} items`);
                    productArray = json[key];
                    break;
                }
            }
            if (productArray) {
                console.log('✓ Products found:', productArray.length);
                if (productArray.length > 0) {
                    console.log('Sample product:', productArray[0]);
                }
            }
        } catch (e) {
            console.error('JSON parse error:', e.message);
        }
    } catch (e) {
        console.error('✗ Bittel JSON error:', e.message);
    }
    
    console.log('\n========================================');
};

/**
 * Test function to diagnose API issues
 * Call window.testAPIs() in browser console to run
 */
window.testAPIs = async function() {
    console.log('========================================');
    console.log('TESTING API CONNECTIONS');
    console.log('========================================');
    
    // Test Bulclima
    if (USE_BULCLIMA) {
        console.log('[TEST] Testing Bulclima...');
        try {
            console.log('[TEST] Fetching brands...');
            const brands = await fetchBrands();
            console.log('[TEST] Bulclima brands fetched:', brands ? brands.length : 0, 'brands');
            if (brands && brands.length > 0) {
                console.log('[TEST] Sample brand:', brands[0]);
                console.log('[TEST] Fetching products from first brand...');
                const products = await fetchBrandProducts(brands[0].id);
                console.log('[TEST] Sample brand products:', products ? products.length : 0, 'products');
                if (products && products.length > 0) {
                    console.log('[TEST] Sample product:', products[0]);
                }
            } else {
                console.warn('[TEST] No brands returned from Bulclima!');
            }
        } catch (error) {
            console.error('[TEST] Bulclima error:', error);
        }
    }
    
    console.log('---');
    
    // Test Bittel
    if (USE_BITTEL) {
        console.log('[TEST] Testing Bittel...');
        console.log('[TEST] API Format:', BITTEL_API_FORMAT);
        console.log('[TEST] Using proxy:', USE_CORS_PROXY_BITTEL);
        try {
            console.log('[TEST] Fetching page 1...');
            const result = await fetchBittelProducts(1);
            console.log('[TEST] Bittel page 1 result:', result);
            console.log('[TEST] Bittel page 1:', {
                products: result.products ? result.products.length : 0,
                totalPages: result.totalPages,
                totalProducts: result.totalProducts,
                hasMore: result.hasMore
            });
            if (result.products && result.products.length > 0) {
                console.log('[TEST] Sample Bittel product:', result.products[0]);
            } else {
                console.warn('[TEST] No products returned from Bittel page 1!');
            }
        } catch (error) {
            console.error('[TEST] Bittel error:', error);
        }
    }
    
    console.log('---');
    
    // Test getAllProducts
    console.log('[TEST] Getting all products...');
    const allProducts = await getAllProducts();
    console.log('[TEST] Total products from all distributors:', allProducts.length);
    const bulclimaCount = allProducts.filter(p => p.distributor === 'bulclima').length;
    const bittelCount = allProducts.filter(p => p.distributor === 'bittel').length;
    console.log('[TEST] Bulclima count:', bulclimaCount);
    console.log('[TEST] Bittel count:', bittelCount);
    
    if (bulclimaCount === 0) console.error('[TEST] ⚠️  BULCLIMA: NO PRODUCTS!');
    if (bittelCount === 0) console.error('[TEST] ⚠️  BITTEL: NO PRODUCTS!');
    
    console.log('========================================');
    return { allProducts, bulclimaCount, bittelCount };
};

// 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')
        });
    }
}
