/**
 * WPForms builder: Square connection modal + payment panel toggles.
 */
( function ( $ ) {
	'use strict';

	try {
		const cfg = window.shc4wc_wpforms_builder || {};
		const gatewaySlug = cfg.gatewaySlug || 'payments_square_connect';
		const fieldType = cfg.fieldType || 'shc4wc-square';
		const isConnected = !! cfg.isConnected;

		const SHC4WCWPFormsBuilder = {
			init() {
				const $builder = $( '#wpforms-builder' );

				if ( ! $builder.length ) {
					return;
				}

				$builder.on( 'wpformsBuilderReady', SHC4WCWPFormsBuilder.ready );
			},

			ready() {
				SHC4WCWPFormsBuilder.bindUIActions();

				if ( isConnected && typeof WPFormsBuilderPaymentsUtils !== 'undefined' ) {
					WPFormsBuilderPaymentsUtils.initPaymentLite(
						'.wpforms-panel-content-section-' + gatewaySlug
					);
				}
			},

			bindUIActions() {
				if ( isConnected ) {
					return;
				}

				const $builder = $( '#wpforms-builder' );
				const $fieldBtn = $( '#wpforms-add-fields-' + fieldType );

				$fieldBtn.on( 'click', SHC4WCWPFormsBuilder.connectionCheck );
				$builder.on( 'wpformsPanelSectionSwitch', SHC4WCWPFormsBuilder.onPanelSectionSwitch );
			},

			connectionCheck( e ) {
				const $btn = $( this );

				if ( $btn.hasClass( 'wpforms-add-fields-button-disabled' ) ) {
					return false;
				}

				if ( ! $btn.hasClass( 'shc4wc-square-connection-required' ) ) {
					return true;
				}

				if ( e ) {
					e.preventDefault();
					e.stopImmediatePropagation();
				}

				SHC4WCWPFormsBuilder.showModal();
				return false;
			},

			onPanelSectionSwitch( e, section ) {
				if ( section !== gatewaySlug || isConnected ) {
					return;
				}

				if ( e && typeof e.preventDefault === 'function' ) {
					e.preventDefault();
				}

				SHC4WCWPFormsBuilder.showModal();
			},

			showModal() {
				if ( typeof wpforms_builder === 'undefined' || typeof $.alert !== 'function' ) {
					if ( cfg.connectUrl ) {
						window.location.href = cfg.connectUrl;
					}
					return;
				}

				const content = wpforms_builder.shc4wc_square_connection_required || '<p>' + ( wpforms_builder.heads_up || 'Heads up!' ) + '</p>';
				const confirmText = wpforms_builder.shc4wc_square_connect_button || 'Connect With Square';

				$.alert( {
					title: wpforms_builder.heads_up || 'Heads up!',
					content: content,
					icon: 'fa fa-exclamation-circle',
					type: 'orange',
					boxWidth: '450px',
					buttons: {
						confirm: {
							text: confirmText,
							btnClass: 'btn-confirm',
							keys: [ 'enter' ],
							action() {
								window.location.href = cfg.connectUrl;
							},
						},
						cancel: {
							text: wpforms_builder.cancel || 'Cancel',
						},
					},
				} );
			},
		};

		SHC4WCWPFormsBuilder.init();
	} catch ( error ) {
		if ( window.console && window.console.error ) {
			window.console.error( 'SHC4WC WPForms builder script error:', error );
		}
	}
}( jQuery ) );
