/**
 * China Payments - Chinese Localization Frontend
 *
 * Translates WooCommerce Block-rendered strings in the browser DOM.
 * PHP gettext filters only catch server-rendered strings; WooCommerce Blocks
 * use React/JS rendering, so we need this client-side approach.
 */
(function () {
    'use strict';

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

    var config = window.chinaPaymentsLocalization;
    var translations = config.translations || {};
    var isProcessing = false;

    // Build a sorted list of translations by length (longest first) for accurate matching
    var sortedKeys = Object.keys(translations).sort(function (a, b) {
        return b.length - a.length;
    });

    /**
     * Pattern-based translations for strings with dynamic numbers.
     */
    var patterns = [
        { regex: /^Showing all (\d+) results?$/i, replace: '显示全部 $1 个结果' },
        { regex: /^Showing the single result$/i, replace: '显示唯一结果' },
        { regex: /^Showing (\d+)–(\d+) of (\d+) results?$/i, replace: '显示第$1–$2项，共$3个结果' },
        { regex: /^(\d+) items?$/i, replace: '$1 件商品' },
        { regex: /^(\d+) in cart$/i, replace: '$1 在购物车中' },
        { regex: /^(\d+) products?$/i, replace: '$1 件商品' },
        { regex: /^"(.*)" has been added to your cart\.?$/i, replace: '"$1" 已加入购物车。' },
        { regex: /^\+ Add (.*)$/i, replace: '+ 添加 $1' },
    ];

    /**
     * Translate a single text node.
     */
    function translateTextNode(node) {
        var text = node.textContent;
        if (!text || text.trim().length === 0) {
            return;
        }

        var trimmed = text.trim();

        // Exact match first
        if (translations[trimmed]) {
            node.textContent = text.replace(trimmed, translations[trimmed]);
            return;
        }

        // Try case-insensitive match
        var lowerTrimmed = trimmed.toLowerCase();
        for (var i = 0; i < sortedKeys.length; i++) {
            if (sortedKeys[i].toLowerCase() === lowerTrimmed) {
                node.textContent = text.replace(trimmed, translations[sortedKeys[i]]);
                return;
            }
        }

        // Try pattern-based translations
        for (var p = 0; p < patterns.length; p++) {
            if (patterns[p].regex.test(trimmed)) {
                node.textContent = text.replace(trimmed, trimmed.replace(patterns[p].regex, patterns[p].replace));
                return;
            }
        }
    }

    /**
     * Translate attributes (placeholder, aria-label, title, value for buttons/inputs).
     */
    function translateAttributes(el) {
        var attrs = ['placeholder', 'aria-label', 'title'];

        for (var i = 0; i < attrs.length; i++) {
            var val = el.getAttribute(attrs[i]);
            if (val && translations[val.trim()]) {
                el.setAttribute(attrs[i], translations[val.trim()]);
            }
        }

        // Translate input/button values
        if ((el.tagName === 'INPUT' || el.tagName === 'BUTTON') && el.type === 'submit') {
            var v = el.value;
            if (v && translations[v.trim()]) {
                el.value = translations[v.trim()];
            }
        }
    }

    /**
     * Walk a DOM subtree and translate all text nodes and attributes.
     */
    function translateSubtree(root) {
        // Skip if inside admin bar or plugin admin
        if (root.closest && (root.closest('#wpadminbar') || root.closest('[data-china-payments-component]'))) {
            return;
        }

        var walker = document.createTreeWalker(
            root,
            NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT,
            null,
            false
        );

        var node;
        while ((node = walker.nextNode())) {
            if (node.nodeType === Node.TEXT_NODE) {
                translateTextNode(node);
            } else if (node.nodeType === Node.ELEMENT_NODE) {
                translateAttributes(node);
            }
        }
    }

    /**
     * Throttled translation pass over the whole page.
     */
    function translatePage() {
        if (isProcessing) {
            return;
        }
        isProcessing = true;

        requestAnimationFrame(function () {
            var containers = document.querySelectorAll(
                '.wp-block-woocommerce-cart, ' +
                '.wp-block-woocommerce-checkout, ' +
                '.wc-block-cart, ' +
                '.wc-block-checkout, ' +
                '.woocommerce-cart, ' +
                '.woocommerce-checkout, ' +
                '.woocommerce, ' +
                '.wc-block-components-order-summary, ' +
                '.wc-block-components-totals-wrapper, ' +
                '.woocommerce-order-received, ' +
                '.woocommerce-order, ' +
                '.woocommerce-thankyou'
            );

            if (containers.length === 0) {
                // Fallback: translate main content area
                var main = document.querySelector('#content, .site-content, main, .entry-content');
                if (main) {
                    translateSubtree(main);
                }
            } else {
                containers.forEach(function (container) {
                    translateSubtree(container);
                });
            }

            isProcessing = false;
        });
    }

    /**
     * Set up MutationObserver for dynamically rendered content.
     */
    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 shouldTranslate = false;

            for (var i = 0; i < mutations.length; i++) {
                if (mutations[i].addedNodes.length > 0) {
                    shouldTranslate = true;
                    break;
                }
                if (mutations[i].type === 'characterData') {
                    shouldTranslate = true;
                    break;
                }
            }

            if (shouldTranslate) {
                translatePage();
            }
        });

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

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

    // Re-translate after WooCommerce blocks finish rendering
    // WooCommerce blocks dispatch events when updating
    document.addEventListener('wc-blocks_render_blocks_frontend', translatePage);

    // Also translate after any AJAX/Fetch completes (for cart updates, etc.)
    var origFetch = window.fetch;
    window.fetch = function () {
        return origFetch.apply(this, arguments).then(function (response) {
            // Delay translation to let React re-render
            setTimeout(translatePage, 300);
            setTimeout(translatePage, 800);
            return response;
        });
    };

})();
