/**
 * China Payments - Multi-Currency Frontend (WooCommerce Blocks)
 *
 * Appends CNY equivalent prices to WooCommerce Block-rendered price elements.
 * The PHP woocommerce_get_price_html filter works for classic pages,
 * but Blocks render prices via React/JS and bypass PHP filters.
 */
(function () {
    'use strict';

    if (typeof window.chinaPaymentsMultiCurrency === 'undefined') {
        return;
    }

    var config = window.chinaPaymentsMultiCurrency;
    var rate = parseFloat(config.rate);
    var currency = config.storeCurrency || 'USD';
    var isProcessing = false;

    if (!rate || rate <= 0 || currency === 'CNY') {
        return;
    }

    /**
     * Format a number as CNY.
     */
    function formatCNY(amount) {
        return '¥' + amount.toFixed(2);
    }

    /**
     * Extract numeric price from text (handles $10.00, 10.00, etc.)
     */
    function extractPrice(text) {
        // Remove currency symbols and thousands separators, extract number
        var cleaned = text.replace(/[^0-9.,]/g, '');
        // Handle comma as thousands separator (e.g. 1,234.56)
        cleaned = cleaned.replace(/,(\d{3})/g, '$1');
        // Handle comma as decimal separator (e.g. 10,50) if no dot present
        if (cleaned.indexOf('.') === -1 && cleaned.indexOf(',') !== -1) {
            cleaned = cleaned.replace(',', '.');
        }
        var num = parseFloat(cleaned);
        return isNaN(num) ? null : num;
    }

    /**
     * Process a single price element and append CNY.
     */
    function processPriceElement(el) {
        // Skip if already processed
        if (el.querySelector('.china-payments-cny-equivalent')) {
            return;
        }
        // Skip if inside admin
        if (el.closest('#wpadminbar') || el.closest('[data-china-payments-component]')) {
            return;
        }

        // Get the last price amount in the element (for sale prices, this is the current price).
        // In some WooCommerce Blocks versions the container element IS the money-amount node
        // itself (the price class sits directly on the totals value, e.g. shipping/fee/tax
        // rows), so fall back to the element's own text when there is no descendant money node.
        var moneySelector = '.wc-block-formatted-money-amount, .wc-block-components-formatted-money-amount, .amount';
        var priceSpans = el.querySelectorAll(moneySelector);
        var priceText;
        if (priceSpans.length > 0) {
            priceText = priceSpans[priceSpans.length - 1].textContent;
        } else if (el.matches && el.matches(moneySelector)) {
            priceText = el.textContent;
        } else {
            return;
        }
        var price = extractPrice(priceText);

        if (price === null || price <= 0) {
            return;
        }

        var cnyAmount = price * rate;
        var cnySpan = document.createElement('span');
        cnySpan.className = 'china-payments-cny-equivalent';
        cnySpan.textContent = ' (~' + formatCNY(cnyAmount) + ')';

        // Append after the price element or the last amount span
        el.appendChild(cnySpan);
    }

    /**
     * Find and process all WooCommerce Block price elements.
     */
    function processAllPrices() {
        if (isProcessing) {
            return;
        }
        isProcessing = true;

        requestAnimationFrame(function () {
            // WooCommerce Blocks price selectors
            var selectors = [
                '.wc-block-components-product-price',     // Block product prices
                '.wc-block-cart-item__prices',             // Cart item prices
                '.wc-block-components-totals-item__value', // Totals (subtotal, shipping, fees, taxes, total)
                '.wc-block-components-order-summary-item__total-price', // Order summary items
                '.wc-block-components-shipping-rates-control__option-price', // Selectable shipping rate options
                '.wc-block-formatted-money-amount',        // Any formatted money
            ];

            // Process price containers
            var containerSelectors = [
                '.wc-block-components-product-price',
                '.wc-block-cart-item__prices',
                '.wc-block-components-totals-item__value',
                '.wc-block-components-order-summary-item__total-price',
                '.wc-block-components-shipping-rates-control__option-price',
            ];

            containerSelectors.forEach(function (selector) {
                document.querySelectorAll(selector).forEach(function (el) {
                    processPriceElement(el);
                });
            });

            // Also process standalone formatted money amounts that aren't inside a container
            document.querySelectorAll('.wc-block-formatted-money-amount, .wc-block-components-formatted-money-amount').forEach(function (el) {
                var parent = el.parentElement;
                if (parent && !parent.querySelector('.china-payments-cny-equivalent')) {
                    // Only if the parent doesn't already have CNY appended
                    var isInContainer = false;
                    for (var i = 0; i < containerSelectors.length; i++) {
                        if (el.closest(containerSelectors[i])) {
                            isInContainer = true;
                            break;
                        }
                    }
                    if (!isInContainer) {
                        var price = extractPrice(el.textContent);
                        if (price && price > 0) {
                            var cnySpan = document.createElement('span');
                            cnySpan.className = 'china-payments-cny-equivalent';
                            cnySpan.textContent = ' (~' + formatCNY(price * rate) + ')';
                            el.parentNode.insertBefore(cnySpan, el.nextSibling);
                        }
                    }
                }
            });

            isProcessing = false;
        });
    }

    /**
     * Set up MutationObserver to catch dynamically rendered prices.
     */
    function setupObserver() {
        var target = document.querySelector('#content, .site-content, main, .entry-content, body');
        if (!target) {
            target = document.body;
        }

        var observer = new MutationObserver(function (mutations) {
            var shouldProcess = false;
            for (var i = 0; i < mutations.length; i++) {
                if (mutations[i].addedNodes.length > 0) {
                    shouldProcess = true;
                    break;
                }
            }
            if (shouldProcess) {
                processAllPrices();
            }
        });

        observer.observe(target, {
            childList: true,
            subtree: true,
        });
    }

    // Output the CNY styles if not already present
    if (!document.querySelector('#china-payments-cny-style')) {
        var style = document.createElement('style');
        style.id = 'china-payments-cny-style';
        style.textContent = '.china-payments-cny-equivalent{color:#888;font-size:0.85em;white-space:nowrap;}';
        document.head.appendChild(style);
    }

    // Initial pass
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', function () {
            processAllPrices();
            setupObserver();
        });
    } else {
        processAllPrices();
        setupObserver();
    }

    // Re-process after fetch (for cart updates, quantity changes, etc.)
    var origFetch = window.fetch;
    window.fetch = function () {
        return origFetch.apply(this, arguments).then(function (response) {
            setTimeout(processAllPrices, 300);
            setTimeout(processAllPrices, 800);
            return response;
        });
    };
})();
