document.addEventListener('DOMContentLoaded', function () {
    const products = {};
    const priceElements = document.querySelectorAll('.price');

    // Existing logic for IDs
    priceElements.forEach(function (priceEl) {
        const productWrapper = priceEl.closest('.product') || priceEl.closest('.type-product');
        let productId = null;

        if (productWrapper) {
            productWrapper.classList.forEach(cls => {
                if (cls.startsWith('post-') || cls.startsWith('product-')) {
                    const idMatch = cls.match(/\d+/);
                    if (idMatch) {
                        productId = idMatch[0];
                    }
                }
            });

            if (!productId) {
                const atcButton = productWrapper.querySelector('[data-product_id]');
                if (atcButton) {
                    productId = atcButton.getAttribute('data-product_id');
                }
            }

            if (!productId) {
                const singleCartButton = productWrapper.querySelector('button[name="add-to-cart"]');
                if (singleCartButton) {
                    productId = singleCartButton.value;
                }
            }
        }

        if (productId) {
            if (!products[productId]) {
                products[productId] = [];
            }
            products[productId].push(priceEl);
        }
    });

    const ids = Object.keys(products);
    const hasIds = ids.length > 0;

    // New logic for Tags
    const tagElements = document.querySelectorAll('[data-live-tag]');
    const tags = new Set();

    tagElements.forEach(el => {
        const tag = el.getAttribute('data-live-tag');
        if (tag) tags.add(tag);
    });

    const hasTags = tags.size > 0;

    let baseUrl = typeof kaz_live_prices_data !== 'undefined'
        ? kaz_live_prices_data.rest_url
        : '/wp-json/kaz/v1/live-prices';

    // Fetch prices by IDs
    if (hasIds) {
        fetch(`${baseUrl}?ids=${ids.join(',')}`)
            .then(response => response.json())
            .then(data => {
                if (data && typeof data === 'object') {
                    for (const id in data) {
                        if (products[id] && data[id]) {
                            products[id].forEach(priceEl => {
                                priceEl.innerHTML = data[id];
                            });
                        }
                    }
                }
            })
            .catch(error => console.error('Error fetching live prices for IDs:', error));
    }

    // Fetch prices by Tags
    if (hasTags) {
        // Join all unique tags/SKUs with commas for a single API request
        const tagsString = Array.from(tags).join(',');

        fetch(`${baseUrl}?tag=${tagsString}`)
            .then(response => response.json())
            .then(data => {
                if (data && typeof data === 'object') {
                    // Update DOM for each tag that was returned
                    tags.forEach(tag => {
                        const tagKey = 'tag_' + tag;
                        if (data[tagKey]) {
                            document.querySelectorAll(`[data-live-tag="${tag}"]`).forEach(el => {
                                el.innerHTML = data[tagKey];
                            });
                        }
                    });
                }
            })
            .catch(error => console.error(`Error fetching live prices for tags:`, error));
    }
});
