import { useEffect, useRef, useState } from '@wordpress/element';
import { registerExpressPaymentMethod } from '@woocommerce/blocks-registry';
import { __ } from '@wordpress/i18n';
import { loadPayPalScript } from '../../../ppcp-button/resources/js/modules/Helper/PayPalScriptLoading';
import { cartHasSubscriptionProducts } from '../../../ppcp-blocks/resources/js/Helper/Subscription';
import { loadCustomScript } from '@paypal/paypal-js';
import CheckoutHandler from './Context/CheckoutHandler';
import ApplePayManager from './ApplepayManager';
import ApplePayManagerBlockEditor from './ApplepayManagerBlockEditor';
const ppcpData = wc.wcSettings.getSetting( 'ppcp-gateway_data' );
const ppcpConfig = ppcpData.scriptData;
const buttonData = wc.wcSettings.getSetting( 'ppcp-applepay_data' );
const buttonConfig = buttonData.scriptData;
const namespace = 'ppcpBlocksPaypalApplepay';
if ( typeof window.PayPalCommerceGateway === 'undefined' ) {
window.PayPalCommerceGateway = ppcpConfig;
}
const ApplePayComponent = ( { isEditing, buttonAttributes } ) => {
const [ paypalLoaded, setPaypalLoaded ] = useState( false );
const [ applePayLoaded, setApplePayLoaded ] = useState( false );
const wrapperRef = useRef( null );
useEffect( () => {
if ( isEditing ) {
return;
}
// Load ApplePay SDK
loadCustomScript( { url: buttonConfig.sdk_url } ).then( () => {
setApplePayLoaded( true );
} );
ppcpConfig.url_params.components += ',applepay';
// Load PayPal
loadPayPalScript( namespace, ppcpConfig )
.then( () => {
setPaypalLoaded( true );
} )
.catch( ( error ) => {
console.error( 'Failed to load PayPal script: ', error );
} );
}, [ isEditing ] );
useEffect( () => {
if ( isEditing || ! paypalLoaded || ! applePayLoaded ) {
return;
}
const ManagerClass = isEditing
? ApplePayManagerBlockEditor
: ApplePayManager;
buttonConfig.reactWrapper = wrapperRef.current;
new ManagerClass(
namespace,
buttonConfig,
ppcpConfig,
buttonAttributes
);
}, [ paypalLoaded, applePayLoaded, isEditing, buttonAttributes ] );
if ( isEditing ) {
return (