// ===== init.js =====
jQuery(function($) {
    const params = window.wc_useepay_params || {};
    const containerId = 'useepay-container';
    const $doc = $(document);
    let instance = null;
    let mounted = false;
    let mounting = false;
    let retries = 0;
    const maxRetries = 25; // ~5s at 200ms
    let debounceTimer = null;

    function hasConfirmTokenHash() {
        return typeof window.location.hash === 'string'
            && window.location.hash.indexOf('#confirm-token-') === 0;
    }

    function log() {
        if (window.useepayDebug) {
            console.log.apply(console, arguments);
        }
    }

    function isUseePaySelected() {
        const val = $('input[name="payment_method"]:checked').val();
        return val === 'useepay_creditcard';
    }

    function safeUnmount() {
        try {
            if (instance && typeof instance.unmount === 'function') instance.unmount(containerId);
            else if (instance && typeof instance.destroy === 'function') instance.destroy();
        } catch (e) {} finally {
            mounted = false;
            instance = null;
            $('#' + containerId).find('.useepay-form-loading').remove();
        }
    }

    function showLoading() {
        const $container = $('#' + containerId);
        if (!$container.length) {
            return;
        }
        $container.html(`
            <div class="useepay-form-loading">
                <div class="useepay-loading-container">
                    <div class="useepay-loading-logo"></div>
                    <div class="useepay-loading-spinner"></div>
                    <div class="useepay-loading-text">
                        Loading payment form<span class="useepay-loading-dots"></span>
                    </div>
                    <div class="useepay-loading-subtext">Please wait while we prepare your secure payment environment</div>
                    <div class="useepay-secure-badge">Secure Payment</div>
                </div>
            </div>
        `);
    }

    function hideLoading() {
        const $container = $('#' + containerId);
        $container.find('.useepay-form-loading').fadeOut(300, function() {
            $(this).remove();
        });
    }

    function processHashIfPresent() {
        if (!hasConfirmTokenHash() || !instance) {
            return;
        }

        if (typeof instance.processHashOnLoad === 'function') {
            instance.processHashOnLoad();
            return;
        }

        if (typeof instance.checkExistingHash === 'function') {
            instance.checkExistingHash();
            return;
        }

        if (typeof instance.hashChangeHandler === 'function') {
            instance.hashChangeHandler();
        }
    }

    function initUseePay(force = false) {
        const $container = $('#' + containerId);

        try {
            const $dupes = $container.children('[id$="_container"]');
            if ($dupes.length > 1) $dupes.slice(1).remove();
        } catch (e) {}

        const hasIframe = $container.find('iframe').length > 0;

        if (!isUseePaySelected() && !force && !hasConfirmTokenHash()) {
            log('Useepay not selected; skip init');
            if (mounted) safeUnmount();
            return;
        }

        if (!window.UseePay || !$container.length) {
            if (retries++ < maxRetries) {
                if (retries === 1) {
                    showLoading();
                }
                log('SDK or container missing; retry', retries);
                setTimeout(function() { initUseePay(force); }, 200);
            }
            return;
        }

        if (mounting) {
            log('Mount in progress; skip');
            return;
        }

        if (mounted && !hasIframe) {
            log('Mounted flag set but iframe missing; resetting');
            mounted = false;
            instance = null;
        }

        if (mounted) {
            processHashIfPresent();
            log('Already mounted; skip duplicate init');
            return;
        }

        try {
            mounting = true;
            instance = new UseePay(params);
            instance.mount(containerId, 'credit_card');
            try { $container.data('useepayInstance', instance); } catch (_) {}
            mounted = true;
            log('UseePay mounted');
            hideLoading();
            processHashIfPresent();
        } catch (e) {
            log('UseePay mount error:', e);
            $container.html(`
                <div class="useepay-form-loading">
                    <div class="useepay-loading-container">
                        <div style="color: var(--useepay-error); font-size: 14px; text-align: center;">
                            Payment form failed to load<br>
                            <small>Please refresh the page or try another payment method</small>
                        </div>
                    </div>
                </div>
            `);
        } finally {
            mounting = false;
        }
    }

    function triggerInitDebounced() {
        clearTimeout(debounceTimer);
        debounceTimer = setTimeout(function() {
            retries = 0;
            initUseePay(false);
        }, 120);
    }

    $doc.on('change.useepay', 'input[name="payment_method"]', triggerInitDebounced);
    $doc.on('updated_checkout.useepay', triggerInitDebounced);
    $doc.on('checkout_error.useepay', function() {
        $('#' + containerId).closest('form').find('.useepay-session').remove();
    });
    $(window).on('load.useepay hashchange.useepay', triggerInitDebounced);

    triggerInitDebounced();

    if (hasConfirmTokenHash()) {
        retries = 0;
        initUseePay(true);
        try { $('input[name="payment_method"][value="useepay_creditcard"]').prop('checked', true); } catch (_) {}
    }

    if (window.MutationObserver) {
        const observer = new MutationObserver(function() {
            if ($('#' + containerId).length && (isUseePaySelected() || hasConfirmTokenHash())) {
                triggerInitDebounced();
            }
        });
        observer.observe(document.body, { childList: true, subtree: true });
    }
});
