<?php
/**
 * Extra integrations (Gravity, Jetpack, bbPress, BuddyPress, UM, MemberPress, EDD checkout/register, PMP, MC4WP)
 * plus optimizer compatibility and resource hints — mirrors common Simple Turnstile coverage without a separate admin menu.
 *
 * @package CloudflareTurnstile
 */

namespace CloudflareTurnstile;

use WP_PowerSuite\Captcha\Shared\CaptchaRuntime;

final class ExtendedIntegrations {

	private static bool $booted = false;

	public static function boot( Module $m ): void {
		if ( self::$booted ) {
			return;
		}
		self::$booted = true;

		$s = $m->getCaptchaSettings();

		if ( ! empty( $s['perf_compat'] ) ) {
			self::perf_compat();
		}
		if ( ! empty( $s['resource_hints'] ) && CaptchaRuntime::hasAnyFrontendProtection( $s ) ) {
			add_filter( 'wp_resource_hints', [ self::class, 'resource_hints' ], 10, 2 );
			if ( CaptchaRuntime::needsWpLoginScreenAssets( $s ) ) {
				add_action( 'login_head', [ self::class, 'login_preconnect' ], 1 );
			}
		}

		if ( ! empty( $s['blocksy_compat'] ) && CaptchaRuntime::needsWpLoginScreenAssets( $s ) ) {
			add_action(
				'wp_enqueue_scripts',
				static function () use ( $s ) {
					if ( ! CaptchaRuntime::needsWpLoginScreenAssets( $s ) ) {
						return;
					}
					$t = wp_get_theme();
					if ( ! $t || $t->get( 'TextDomain' ) !== 'blocksy' ) {
						return;
					}
					if ( ! defined( 'WP_POWERSUITE_PLUGIN_URL' ) ) {
						return;
					}
					wp_enqueue_script(
						'wpps-turnstile-blocksy',
						WP_POWERSUITE_PLUGIN_URL . 'modules/cloudflare-turnstile/assets/blocksy-compat.js',
						[ Module::SCRIPT_HANDLE ],
						Module::MODULE_VERSION,
						true
					);
				},
				25
			);
		}

		if ( ! empty( $s['integration_gravity'] ) && class_exists( 'GFForms' ) ) {
			add_filter(
				'gform_submit_button',
				static function ( $button, $form ) use ( $m ) {
					if ( ! is_array( $form ) || empty( $form['id'] ) ) {
						return $button;
					}
					ob_start();
					$m->renderWidget(
						'gravity_' . absint( $form['id'] ),
						$m->disableSubmitPair( 'turnstileGravityCallback', '.gform_button' )
					);
					return (string) ob_get_clean() . $button;
				},
				10,
				2
			);
			add_filter(
				'gform_validation',
				static function ( $result ) use ( $m ) {
					if ( empty( $result['form']['id'] ) || ! is_array( $result ) ) {
						return $result;
					}
					$form_id = absint( $result['form']['id'] );
					// Multi-page: only enforce on the final submit. The target page must be
					// resolved the way Gravity Forms resolves it, never from the raw POST field.
					if ( ! self::gravityIsFinalSubmit( $result['form'], $form_id ) ) {
						return $result;
					}
					if ( ! $m->verifySubmittedToken( 'gravity_' . $form_id ) ) {
						$result['is_valid'] = false;
						if ( ! isset( $result['form']['validation_message'] ) || $result['form']['validation_message'] === '' ) {
							$result['form']['validation_message'] = __( 'Please complete the security verification.', 'wp-powersuite' );
						}
					}
					return $result;
				},
				10
			);
		}

		if ( ! empty( $s['integration_jetpack'] ) ) {
			add_filter(
				'jetpack_contact_form_html',
				static function ( $html ) use ( $m ) {
					if ( ! is_string( $html ) || $html === '' ) {
						return $html;
					}
					ob_start();
					$m->renderWidget(
						'jetpack_contact',
						$m->disableSubmitPair( 'turnstileJetpackCallback', '.wp-block-jetpack-contact-form button[type="submit"]' )
					);
					$inject = (string) ob_get_clean();

					return self::injectBeforeSubmit( $html, $inject );
				},
				10
			);
			add_filter(
				'jetpack_contact_form_is_spam',
				static function ( $spam ) use ( $m ) {
					if ( $spam ) {
						return $spam;
					}
					return ! $m->verifySubmittedToken( 'jetpack_contact' );
				},
				10
			);
		}

		if ( ! empty( $s['integration_bbpress'] ) ) {
			add_action(
				'bbp_theme_before_topic_form_submit_wrapper',
				static function () use ( $m ) {
					$m->renderWidget(
						'bbpress_topic',
						$m->disableSubmitPair( 'turnstileBBPressCreateCallback', '#bbp_topic_submit' )
					);
				}
			);
			add_action(
				'bbp_theme_before_reply_form_submit_wrapper',
				static function () use ( $m ) {
					$m->renderWidget(
						'bbpress_reply',
						$m->disableSubmitPair( 'turnstileBBPressReplyCallback', '#bbp_reply_submit' )
					);
				}
			);
			add_action(
				'bbp_new_topic_pre_extras',
				static function () use ( $m ) {
					if ( 'POST' !== strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ?? '' ) ) ) ) {
						return;
					}
					if ( ! $m->verifySubmittedToken( 'bbpress_topic' ) ) {
						bbp_add_error( 'bbp_turnstile', __( 'Please complete the security verification.', 'wp-powersuite' ) );
					}
				}
			);
			add_action(
				'bbp_new_reply_pre_extras',
				static function () use ( $m ) {
					if ( 'POST' !== strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ?? '' ) ) ) ) {
						return;
					}
					if ( ! $m->verifySubmittedToken( 'bbpress_reply' ) ) {
						bbp_add_error( 'bbp_turnstile', __( 'Please complete the security verification.', 'wp-powersuite' ) );
					}
				}
			);
		}

		if ( ! empty( $s['integration_buddypress'] ) && class_exists( 'BuddyPress' ) ) {
			add_action(
				'bp_before_registration_submit_buttons',
				static function () use ( $m ) {
					$m->renderWidget(
						'buddypress_register',
						$m->disableSubmitPair( 'turnstileBPCallback', '#buddypress #signup-form .submit' )
					);
				}
			);
			add_action(
				'bp_signup_validate',
				static function () use ( $m ) {
					if ( 'POST' !== strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ?? '' ) ) ) ) {
						return;
					}
					if ( ! $m->verifySubmittedToken( 'buddypress_register' ) ) {
						wp_die( esc_html__( 'Please complete the security verification.', 'wp-powersuite' ), '', [ 'response' => 403, 'back_link' => true ] );
					}
				}
			);
		}

		if ( ! empty( $s['integration_ultimate_member'] ) && class_exists( 'UM' ) ) {
			add_action(
				'um_after_login_fields',
				static function () use ( $m ) {
					$m->renderWidget(
						'ultimate_member_login',
						$m->disableSubmitPair( 'turnstileUMCallback', '#um-submit-btn' )
					);
				}
			);
			add_action(
				'um_after_register_fields',
				static function () use ( $m ) {
					$m->renderWidget(
						'ultimate_member_register',
						$m->disableSubmitPair( 'turnstileUMCallback', '#um-submit-btn' )
					);
				}
			);
			add_action(
				'um_after_password_reset_fields',
				static function () use ( $m ) {
					$m->renderWidget(
						'ultimate_member_reset',
						$m->disableSubmitPair( 'turnstileUMCallback', '#um-submit-btn' )
					);
				}
			);
			add_action(
				'um_submit_form_errors_hook_login',
				static function () use ( $m ) {
					if ( ! $m->verifySubmittedToken( 'ultimate_member_login' ) ) {
						UM()->form()->add_error( 'turnstile', __( 'Please complete the security verification.', 'wp-powersuite' ) );
					}
				},
				20
			);
			add_action(
				'um_submit_form_errors_hook__registration',
				static function () use ( $m ) {
					if ( ! $m->verifySubmittedToken( 'ultimate_member_register' ) ) {
						UM()->form()->add_error( 'turnstile', __( 'Please complete the security verification.', 'wp-powersuite' ) );
					}
				},
				20
			);
			add_action(
				'um_reset_password_errors_hook',
				static function () use ( $m ) {
					if ( ! $m->verifySubmittedToken( 'ultimate_member_reset' ) ) {
						UM()->form()->add_error( 'turnstile', __( 'Please complete the security verification.', 'wp-powersuite' ) );
					}
				},
				20
			);
		}

		if ( ! empty( $s['integration_memberpress'] ) && class_exists( 'MeprAppCtrl' ) ) {
			add_action(
				'mepr-login-form-before-submit',
				static function () use ( $m ) {
					$m->renderWidget(
						'memberpress_login',
						$m->disableSubmitPair( 'turnstileMEPRCallback', '.mepr-submit' )
					);
				}
			);
			add_action(
				'mepr-checkout-before-submit',
				static function () use ( $m ) {
					$m->renderWidget(
						'memberpress_checkout',
						$m->disableSubmitPair( 'turnstileMEPRCallback', '.mepr-submit' )
					);
				}
			);
			add_filter(
				'mepr-validate-login',
				static function ( $errors ) use ( $m ) {
					if ( ! $m->verifySubmittedToken( 'memberpress_login' ) ) {
						$errors[] = __( 'Please complete the security verification.', 'wp-powersuite' );
					}
					return $errors;
				}
			);
			add_filter(
				'mepr-validate-signup',
				static function ( $errors ) use ( $m ) {
					if ( ! $m->verifySubmittedToken( 'memberpress_checkout' ) ) {
						$errors[] = __( 'Please complete the security verification.', 'wp-powersuite' );
					}
					return $errors;
				},
				20
			);
		}

		if ( ! empty( $s['integration_edd'] ) && function_exists( 'EDD' ) ) {
			add_action(
				'edd_login_fields_after',
				static fn () => $m->renderWidget( 'edd_login', $m->disableSubmitPair( 'turnstileEDDLoginCallback', '#edd_login_submit' ) )
			);
			add_action(
				'edd_register_form_fields_before_submit',
				static fn () => $m->renderWidget( 'edd_register', $m->disableSubmitPair( 'turnstileEDDRegisterCallback', '#edd_register_form .edd-submit' ) )
			);
			add_action(
				'edd_purchase_form_before_submit',
				static fn () => $m->renderWidget( 'edd_checkout', $m->disableSubmitPair( 'turnstileEDDCheckoutCallback', '.edd-submit' ) )
			);
			add_filter(
				'authenticate',
				static function ( $user ) use ( $m ) {
					if ( isset( $_POST['edd_login_nonce'] ) && function_exists( 'edd_is_checkout' ) && ! edd_is_checkout() ) {
						if ( ! $m->verifySubmittedToken( 'edd_login' ) ) {
							return new \WP_Error( 'turnstile_failed', __( 'Please complete the security verification.', 'wp-powersuite' ) );
						}
					}
					return $user;
				},
				21,
				1
			);
			add_action(
				'edd_process_register_form',
				static function () use ( $m ) {
					if ( function_exists( 'edd_is_checkout' ) && edd_is_checkout() ) {
						return;
					}
					if ( ! $m->verifySubmittedToken( 'edd_register' ) ) {
						edd_set_error( 'turnstile', __( 'Please complete the security verification.', 'wp-powersuite' ) );
					}
				}
			);
			add_action(
				'edd_pre_process_purchase',
				static function () use ( $m ) {
					if ( ! isset( $_POST['edd-process-checkout-nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['edd-process-checkout-nonce'] ) ), 'edd-process-checkout' ) ) {
						return;
					}
					if ( ! $m->verifySubmittedToken( 'edd_checkout' ) ) {
						edd_set_error( 'turnstile', __( 'Please complete the security verification.', 'wp-powersuite' ) );
					}
				}
			);
		}

		if ( ! empty( $s['integration_pmp'] ) && defined( 'PMPRO_VERSION' ) ) {
			// Checkout / account creation during membership purchase.
			add_action(
				'pmpro_checkout_before_submit_button',
				static fn () => $m->renderWidget( 'pmp', $m->disableSubmitPair( 'turnstilePMProCallback', '.pmpro_btn-submit' ) )
			);
			// ONLY runs on submit — pmpro_checkout_after_parameters_set fires on page load
			// and was painting the error before the visitor ever clicked Submit.
			add_filter(
				'pmpro_registration_checks',
				static function ( $ok ) use ( $m ) {
					if ( ! $m->verifySubmittedToken( 'pmp' ) ) {
						pmpro_setMessage( __( 'Please complete the security verification.', 'wp-powersuite' ), 'pmpro_error' );
						return false;
					}
					return $ok;
				}
			);

			// Frontend login ([pmpro_login] / login page) uses wp_login_form → login_form_middle.
			// protect_login only hooks wp-login.php `login_form`, so it does NOT cover this form.
			add_filter(
				'login_form_middle',
				static function ( $content, $args = [] ) use ( $m ) {
					unset( $args );
					if ( ! self::isPmproLoginPage() ) {
						return $content;
					}
					if ( str_contains( (string) $content, 'cf-turnstile' ) || str_contains( (string) $content, 'wpps-turnstile-widget' ) ) {
						return $content;
					}
					ob_start();
					$m->renderWidget(
						'pmp_login',
						$m->disableSubmitPair( 'turnstilePMProCallback', '.pmpro_btn-submit, #wp-submit' )
					);
					return $content . (string) ob_get_clean();
				},
				10,
				2
			);
			add_filter(
				'authenticate',
				static function ( $user ) use ( $m ) {
					if ( empty( $_POST['pmpro_login_form_used'] ) ) {
						return $user;
					}
					if ( $user instanceof \WP_Error ) {
						return $user;
					}
					if ( ! $m->verifySubmittedToken( 'pmp_login' ) ) {
						return new \WP_Error(
							'turnstile_failed',
							__( 'Please complete the security verification.', 'wp-powersuite' )
						);
					}
					return $user;
				},
				21,
				1
			);

			// Lost-password request form on the PMPro login page.
			// protect_password_reset only hooks wp-login.php `lostpassword_form`.
			add_action(
				'pmpro_lost_password_before_submit_button',
				static function () use ( $m ) {
					$m->renderWidget(
						'pmp_lostpassword',
						$m->disableSubmitPair( 'turnstilePMProCallback', '.pmpro_btn-submit, #wp-submit' )
					);
				}
			);
			add_action(
				'lostpassword_post',
				static function ( $errors ) use ( $m ) {
					if ( empty( $_POST['pmpro_login_form_used'] ) ) {
						return;
					}
					if ( ! ( $errors instanceof \WP_Error ) ) {
						return;
					}
					if ( ! $m->verifySubmittedToken( 'pmp_lostpassword' ) ) {
						$errors->add(
							'turnstile_failed',
							__( 'Please complete the security verification.', 'wp-powersuite' )
						);
					}
				},
				10,
				1
			);

			// Set-new-password form (after email link) has no dedicated PMPro action hook.
			// Match core `resetpass` action when protect_password_reset is on so validateResetPassForm works.
			add_filter(
				'the_content',
				static function ( $content ) use ( $m, $s ) {
					if ( ! is_string( $content ) || ! self::isPmproLoginPage() ) {
						return $content;
					}
					if ( ! str_contains( $content, 'id="resetpassform"' ) ) {
						return $content;
					}
					if ( str_contains( $content, 'cf-turnstile' ) || str_contains( $content, 'wpps-turnstile-widget' ) ) {
						return $content;
					}
					$action = ! empty( $s['protect_password_reset'] ) ? 'resetpass' : 'pmp_resetpass';
					ob_start();
					$m->renderWidget(
						$action,
						$m->disableSubmitPair( 'turnstilePMProCallback', '#resetpass-button, .pmpro_btn-submit' )
					);
					$inject = (string) ob_get_clean();
					if ( $inject === '' ) {
						return $content;
					}
					$replaced = preg_replace(
						'/(<input\b[^>]*\bid\s*=\s*["\']resetpass-button["\'][^>]*>)/i',
						$inject . '$1',
						$content,
						1
					);
					return is_string( $replaced ) ? $replaced : $content;
				},
				20
			);
			if ( empty( $s['protect_password_reset'] ) ) {
				add_action(
					'validate_password_reset',
					static function ( $errors, $user ) use ( $m ) {
						unset( $user );
						if ( ! isset( $_POST['pass1'] ) || ! ( $errors instanceof \WP_Error ) ) {
							return;
						}
						if ( ! $m->verifySubmittedToken( 'pmp_resetpass' ) ) {
							$errors->add(
								'turnstile_failed',
								__( 'Please complete the security verification.', 'wp-powersuite' )
							);
						}
					},
					10,
					2
				);
			}
		}

		// MC4WP: shortcode-only (same approach as Simple Cloudflare Turnstile).
		// Do not gate on MC4WP_VERSION here — PowerSuite may boot before that constant exists.
		// MC4WP does not run do_shortcode on form fields by itself, so we must.
		if ( ! empty( $s['integration_mc4wp'] ) ) {
			$shortcode = 'wpps-mc4wp-turnstile';
			$render_mc4wp = static function () use ( $m ) {
				ob_start();
				$m->renderWidget(
					'mc4wp',
					$m->disableSubmitPair(
						'turnstileMC4WPCallback',
						'.mc4wp-form-fields input[type=submit], .mc4wp-form-fields button[type=submit], .mc4wp-form button[type=submit], .mc4wp-form input[type=submit]'
					)
				);
				return (string) ob_get_clean();
			};

			add_shortcode(
				$shortcode,
				static function () use ( $render_mc4wp ) {
					return $render_mc4wp();
				}
			);

			// Expand shortcodes inside MC4WP form markup (required; MC4WP only applies mc4wp_form_content).
			add_filter( 'mc4wp_form_content', 'do_shortcode', 11 );

			add_filter(
				'mc4wp_form_errors',
				static function ( $errors, $form ) use ( $m, $shortcode ) {
					$post = ( is_object( $form ) && ! empty( $form->ID ) ) ? get_post( (int) $form->ID ) : null;
					if ( ! $post instanceof \WP_Post || ! has_shortcode( (string) $post->post_content, $shortcode ) ) {
						return $errors;
					}
					if ( ! $m->verifySubmittedToken( 'mc4wp' ) ) {
						$errors[] = 'wpps_turnstile';
					}
					return $errors;
				},
				10,
				2
			);
			add_filter(
				'mc4wp_form_messages',
				static function ( $messages ) {
					$filtered = apply_filters(
						'wpps_captcha_error_message',
						__( 'Please complete the security verification.', 'wp-powersuite' ),
						'mc4wp',
						'cloudflare-turnstile'
					);
					$messages['wpps_turnstile'] = is_string( $filtered ) && $filtered !== ''
						? $filtered
						: __( 'Please complete the security verification.', 'wp-powersuite' );
					return $messages;
				}
			);
		}
	}

	/**
	 * Whether the current front-end request is the PMPro login page.
	 */
	private static function isPmproLoginPage(): bool {
		if ( function_exists( 'pmpro_is_login_page' ) && pmpro_is_login_page() ) {
			return true;
		}
		if ( ! function_exists( 'pmpro_getOption' ) ) {
			return false;
		}
		$page_id = (int) pmpro_getOption( 'login_page_id' );
		if ( $page_id <= 0 ) {
			return false;
		}
		$current = (int) get_queried_object_id();
		if ( $current <= 0 && function_exists( 'get_the_ID' ) ) {
			$current = (int) get_the_ID();
		}
		return $current === $page_id;
	}

	/**
	 * Whether this Gravity Forms request is the submit that saves the entry.
	 *
	 * Must mirror Gravity Forms' own resolution rather than reading
	 * `gform_target_page_number_{id}` directly: {@see \GFFormDisplay::get_target_page()}
	 * clamps any page number above the form's last page down to 0, which Gravity Forms
	 * treats as a final submit. Trusting the raw field therefore let a request post an
	 * out-of-range page number to skip verification while the entry was still saved.
	 *
	 * Fails closed (verify) whenever Gravity Forms' internals are unavailable.
	 *
	 * @param array<string, mixed> $form    Form object from the validation result.
	 * @param int                  $form_id Form ID.
	 */
	private static function gravityIsFinalSubmit( array $form, int $form_id ): bool {
		if (
			$form_id === 0
			|| ! class_exists( '\GFFormDisplay' )
			|| ! method_exists( '\GFFormDisplay', 'get_target_page' )
			|| ! method_exists( '\GFFormDisplay', 'get_source_page' )
		) {
			return true;
		}

		$source       = (int) \GFFormDisplay::get_source_page( $form_id );
		$field_values = isset( $_POST['gform_field_values'] ) ? wp_unslash( $_POST['gform_field_values'] ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Gravity Forms owns nonce handling for its own submission.

		return (int) \GFFormDisplay::get_target_page( $form, $source, $field_values ) === 0;
	}

	/**
	 * Insert Turnstile markup immediately before the first submit control.
	 *
	 * MC4WP form content is the inner fields HTML (no wrapping `<form>`), and submit
	 * controls vary (`input`, `button type=submit`, or bare `<button>` which defaults
	 * to submit). Fall back to appending so the widget is never silently omitted.
	 */
	private static function injectBeforeSubmit( string $html, string $inject ): string {
		if ( $inject === '' ) {
			return $html;
		}
		if ( preg_match( '/<input\b[^>]*\btype\s*=\s*["\']?submit["\']?[^>]*\/?>/i', $html ) ) {
			return (string) preg_replace(
				'/(<input\b[^>]*\btype\s*=\s*["\']?submit["\']?[^>]*\/?>)/i',
				$inject . '$1',
				$html,
				1
			);
		}
		if ( preg_match( '/<button\b[^>]*\btype\s*=\s*["\']?submit["\']?[^>]*>/i', $html ) ) {
			return (string) preg_replace(
				'/(<button\b[^>]*\btype\s*=\s*["\']?submit["\']?[^>]*>)/i',
				$inject . '$1',
				$html,
				1
			);
		}
		// HTML default for <button> inside a form is type=submit.
		if ( preg_match( '/<button\b(?![^>]*\btype\s*=)[^>]*>/i', $html ) ) {
			return (string) preg_replace(
				'/(<button\b(?![^>]*\btype\s*=)[^>]*>)/i',
				$inject . '$1',
				$html,
				1
			);
		}
		if ( stripos( $html, '</form>' ) !== false ) {
			return (string) preg_replace( '/(<\/form>)/i', $inject . '$1', $html, 1 );
		}

		return $html . $inject;
	}

	private static function perf_compat(): void {
		add_filter(
			'sgo_javascript_combine_exclude',
			static function ( $list ) {
				$list   = is_array( $list ) ? $list : [];
				$list[] = 'turnstile';
				$list[] = 'wpps-cloudflare-turnstile';
				return $list;
			}
		);
		add_filter(
			'sgo_javascript_combine_excluded_external_paths',
			static function ( $list ) {
				$list   = is_array( $list ) ? $list : [];
				$list[] = 'turnstile';
				return $list;
			}
		);
		add_filter(
			'litespeed_optimize_js_excludes',
			static function ( $list ) {
				$list   = is_array( $list ) ? $list : [];
				$list[] = 'turnstile';
				return $list;
			}
		);
		add_filter(
			'autoptimize_filter_js_exclude',
			static function ( $exclude ) {
				$p = 'challenges.cloudflare.com/turnstile,turnstile,wpps-turnstile';
				return $exclude ? $exclude . ',' . $p : $p;
			}
		);
		add_filter(
			'perfmatters_delay_js_exclusions',
			static function ( $list ) {
				$list   = is_array( $list ) ? $list : [];
				$list[] = 'challenges.cloudflare.com/turnstile';
				return $list;
			}
		);
		add_filter(
			'rocket_exclude_js',
			static function ( $list ) {
				$list   = is_array( $list ) ? $list : [];
				$list[] = 'turnstile';
				return $list;
			}
		);
		add_filter(
			'rocket_delay_js_exclusions',
			static function ( $list ) {
				$list   = is_array( $list ) ? $list : [];
				$list[] = 'turnstile';
				return $list;
			}
		);
		add_filter(
			'rocket_minify_excluded_external_js',
			static function ( $list ) {
				$list   = is_array( $list ) ? $list : [];
				$list[] = 'challenges.cloudflare.com/turnstile';
				return $list;
			}
		);
	}

	/**
	 * @param array<int, string|array<string, string>> $urls URLs.
	 * @return array<int, string|array<string, string>>
	 */
	public static function resource_hints( array $urls, string $relation_type ): array {
		if ( is_admin() ) {
			return $urls;
		}
		$origin = 'https://challenges.cloudflare.com';
		if ( 'preconnect' === $relation_type ) {
			foreach ( $urls as $hint ) {
				$href = is_array( $hint ) ? ( $hint['href'] ?? '' ) : $hint;
				if ( str_starts_with( (string) $href, $origin ) ) {
					return $urls;
				}
			}
			$urls[] = [ 'href' => $origin, 'crossorigin' => true ];
		}
		if ( 'dns-prefetch' === $relation_type && ! in_array( $origin, $urls, true ) ) {
			$urls[] = $origin;
		}
		return $urls;
	}

	public static function login_preconnect(): void {
		echo '<link rel="preconnect" href="' . esc_url( 'https://challenges.cloudflare.com' ) . '" crossorigin>' . "\n"; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- safe URL.
	}
}
