const settings = window.wc.wcSettings.getSetting( 'stablezact_data', {} );

const label = window.wp.htmlEntities.decodeEntities( settings.title ) || 'Pay with Cryptocurrency';
const { createElement, useEffect } = window.wp.element;

const Content = (props) => {
    const { eventRegistration, emitResponse } = props;
    const { onPaymentSetup } = eventRegistration;

    // Trigger the CoinleyVanilla SDK modal during payment setup and resolve once the
    // payment completes. onPaymentSetup replaces the deprecated onPaymentProcessing; the
    // real payment data (tx hash / payment id) is returned from processStablezactCheckout.
    useEffect(() => {
        const unsubscribe = onPaymentSetup(() => {
            // Create a promise that will be resolved when payment is complete
            return new Promise((resolve) => {
                // For blocks, we need to trigger CoinleyVanilla SDK directly

                // Get order total from WooCommerce blocks store
                let orderTotal = 100.00; // Default demo amount

                try {
                    // Try to get the actual total from WooCommerce blocks store
                    const store = window.wp?.data?.select('wc/store/cart');
                    if (store) {
                        const cartTotals = store.getCartTotals();
                        if (cartTotals && cartTotals.total_price) {
                            orderTotal = parseFloat((cartTotals.total_price / 100).toFixed(2)); // Convert from cents
                        }
                    }
                } catch (e) {
                    // Could not get cart total from store, using demo amount
                }

                // Use USD converted amount if available from stablezactParams
                if (window.stablezactParams && window.stablezactParams.total) {
                    orderTotal = parseFloat(window.stablezactParams.total);
                }

                // Get customer email from store if available
                let customerEmail = 'customer@example.com'; // Default
                try {
                    const store = window.wp?.data?.select('wc/store/cart');
                    const billingAddress = store?.getBillingAddress?.();
                    if (billingAddress?.email) {
                        customerEmail = billingAddress.email;
                    }
                } catch (e) {
                    // Could not get customer email, using default
                }

                // Wrap resolve so ANY resolution (SDK success or failure) also
                // cancels the safety-net timeout below. Without this, once the
                // timeout fires resolve({ERROR}) the promise is settled, and a
                // later SDK success can never update the checkout (it stays failed).
                let fallbackTimer = null;
                const settleOnce = (result) => {
                    if (fallbackTimer) { clearTimeout(fallbackTimer); fallbackTimer = null; }
                    resolve(result);
                };

                // Trigger CoinleyVanilla SDK directly
                setTimeout(() => {
                    // Trigger the CoinleyVanilla integration
                    if (window.coinleyVanillaActive && typeof window.processStablezactCheckout === 'function') {
                        window.processStablezactCheckout(orderTotal, customerEmail, settleOnce, emitResponse);
                    } else {
                        // Fallback to direct SDK call if available
                        window.triggerCoinleyVanillaCheckout && window.triggerCoinleyVanillaCheckout({
                            amount: orderTotal,
                            customerEmail: customerEmail,
                            orderId: 'blocks_' + Date.now()
                        }, settleOnce, emitResponse);
                    }
                }, 100);

                // Note: CoinleyVanilla SDK handles all callbacks directly in processStablezactCheckout
                // No need for custom event listeners - the resolve function is called directly

                // Safety-net timeout ONLY (e.g. the SDK never calls back at all).
                // It MUST outlast the SDK's own payment window (~15 min for the
                // transfer/deposit flow) or a slow-but-valid transfer gets falsely
                // failed. The SDK drives normal success/failure via settleOnce.
                // Honor a longer merchant-configured payment_timeout (ms) if set.
                const fallbackMs = Math.max(parseInt(settings.payment_timeout, 10) || 0, 1200000); // ≥ 20 min
                fallbackTimer = setTimeout(() => {
                    fallbackTimer = null;
                    resolve({
                        type: emitResponse.responseTypes.ERROR,
                        message: 'Payment process timeout. Please try again.'
                    });
                }, fallbackMs);

            });
        });

        return unsubscribe;
    }, [onPaymentSetup, emitResponse.responseTypes]);

    const description = window.wp.htmlEntities.decodeEntities(settings.description || '');

    // Just show description, no form fields (DePay style)
    return createElement('div', {
        className: 'stablezact-payment-description'
    }, [
        // Description
        description && createElement('div', {
            key: 'description',
            dangerouslySetInnerHTML: { __html: description },
            style: { margin: '10px 0', color: '#666' }
        }),

        // Test mode notice
        settings.testmode === 'yes' && createElement('div', {
            key: 'testmode',
            style: {
                background: '#fff3cd',
                border: '1px solid #ffeaa7',
                padding: '10px',
                margin: '10px 0',
                borderRadius: '4px',
                color: '#856404'
            }
        }, [
            createElement('strong', { key: 'testmode-label' }, 'TEST MODE ENABLED'),
            ' - Use test cryptocurrencies only'
        ])
    ]);
};

const Block_Gateway = {
    name: 'stablezact',
    label: label,
    content: Object( window.wp.element.createElement )( Content, null ),
    edit: Object( window.wp.element.createElement )( Content, null ),
    canMakePayment: () => true,
    ariaLabel: label,
    supports: {
        features: settings.supports || [],
    },
};

window.wc.wcBlocksRegistry.registerPaymentMethod( Block_Gateway );
