<?php
namespace BLR\Backline\Modules\Contacts;

use BLR\Backline\Modules\Outreach\Module as OutreachModule;

if (!defined('ABSPATH')) {
	exit;
}

final class FanSignup {
	public const SHORTCODE = 'blr_fan_signup';
	public const ACTION = 'blr_ba_fan_signup';
	public const CONFIRM_ACTION = 'blr_ba_confirm_newsletter';
	public const QUERY_STATUS = 'blr_fan_signup_status';
	public const QUERY_FORM = 'blr_fan_signup_form';
	private const CONFIRM_CONTACT_QUERY = 'blr_contact';
	private const CONFIRM_TOKEN_QUERY = 'blr_confirm_token';
	private const HONEYPOT_FIELD = 'blr_website_url_confirm';
	private const ISSUED_AT_FIELD = 'blr_form_issued_at';
	private const FORM_TOKEN_FIELD = 'blr_form_token';
	private const RATE_LIMIT_KEY_PREFIX = 'blr_ba_signup_rl_';
	private const EMAIL_COOLDOWN_KEY_PREFIX = 'blr_ba_signup_cd_';
	private const DEFAULT_MIN_SUBMIT_SECONDS = 3;
	private const DEFAULT_MAX_FORM_AGE_SECONDS = 7200;
	private const DEFAULT_RATE_LIMIT_WINDOW_SECONDS = 900;
	private const DEFAULT_RATE_LIMIT_MAX_ATTEMPTS = 5;
	private const DEFAULT_EMAIL_COOLDOWN_SECONDS = 300;
	private static bool $assets_enqueued = false;

	public static function register(): void {
		add_shortcode(self::SHORTCODE, [self::class, 'render_shortcode']);
		add_action('init', [self::class, 'handle_confirmation']);
		add_action('init', [self::class, 'handle_submission']);
	}

	public static function render_shortcode($atts): string {
		$atts = shortcode_atts([
			'button_text' => __('Sign Up', 'blr-backline'),
			'success_message' => __('Thanks — you\'re confirmed and on the list.', 'blr-backline'),
			'confirm_sent_message' => __('Check your email to confirm your signup.', 'blr-backline'),
			'duplicate_message' => __('You\'re already confirmed on the list.', 'blr-backline'),
			'error_message' => __('Please enter a valid email address.', 'blr-backline'),
			'nonce_error_message' => __('Security check failed. Please try again.', 'blr-backline'),
			'invalid_form_message' => __('We could not validate that form submission. Please try again.', 'blr-backline'),
			'too_fast_message' => __('Please wait a moment and try again.', 'blr-backline'),
			'expired_form_message' => __('This form expired. Please submit it again.', 'blr-backline'),
			'invalid_confirm_message' => __('That confirmation link is invalid. Please sign up again.', 'blr-backline'),
			'expired_confirm_message' => __('That confirmation link expired. Please sign up again.', 'blr-backline'),
			'throttled_message' => __('Too many signup attempts were detected. Please wait a few minutes and try again.', 'blr-backline'),
			'source' => 'website',
			'tag' => 'newsletter',
			'show_name' => 'yes',
			'class' => '',
		], $atts, self::SHORTCODE);

		$form_id = self::build_form_id($atts);
		$status = '';
		$status_form = '';
		$issued_at = time();
		$form_token = self::build_form_token($form_id, $issued_at);

		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Read-only query args used only to display post-redirect status messages.
		if (isset($_GET[self::QUERY_STATUS])) {
			$status = sanitize_key((string) wp_unslash($_GET[self::QUERY_STATUS]));
		}

		if (isset($_GET[self::QUERY_FORM])) {
			$status_form = sanitize_text_field((string) wp_unslash($_GET[self::QUERY_FORM]));
		}
		// phpcs:enable WordPress.Security.NonceVerification.Recommended

		$message = '';
		$message_class = '';
		if ($status !== '' && hash_equals($form_id, $status_form)) {
			if ($status === 'confirm_sent') {
				$message = (string) $atts['confirm_sent_message'];
				$message_class = 'blr-fan-signup__message--success';
			} elseif ($status === 'confirmed' || $status === 'success') {
				$message = (string) $atts['success_message'];
				$message_class = 'blr-fan-signup__message--success';
			} elseif ($status === 'exists') {
				$message = (string) $atts['duplicate_message'];
				$message_class = 'blr-fan-signup__message--success';
			} elseif ($status === 'invalid_email') {
				$message = (string) $atts['error_message'];
				$message_class = 'blr-fan-signup__message--error';
			} elseif ($status === 'invalid_nonce') {
				$message = (string) $atts['nonce_error_message'];
				$message_class = 'blr-fan-signup__message--error';
			} elseif ($status === 'invalid_form') {
				$message = (string) $atts['invalid_form_message'];
				$message_class = 'blr-fan-signup__message--error';
			} elseif ($status === 'too_fast') {
				$message = (string) $atts['too_fast_message'];
				$message_class = 'blr-fan-signup__message--error';
			} elseif ($status === 'expired_form') {
				$message = (string) $atts['expired_form_message'];
				$message_class = 'blr-fan-signup__message--error';
			} elseif ($status === 'invalid_confirm') {
				$message = (string) $atts['invalid_confirm_message'];
				$message_class = 'blr-fan-signup__message--error';
			} elseif ($status === 'expired_confirm') {
				$message = (string) $atts['expired_confirm_message'];
				$message_class = 'blr-fan-signup__message--error';
			} elseif ($status === 'throttled') {
				$message = (string) $atts['throttled_message'];
				$message_class = 'blr-fan-signup__message--error';
			} else {
				$message = __('Something went wrong. Please try again.', 'blr-backline');
				$message_class = 'blr-fan-signup__message--error';
			}
		}

		self::enqueue_assets();

		$current_url = self::current_url();
		$show_name = strtolower((string) $atts['show_name']) !== 'no';
		$classes = ['blr-fan-signup'];
		if ((string) $atts['class'] !== '') {
			$classes[] = sanitize_html_class((string) $atts['class']);
		}

		ob_start();
		?>
		<div class="<?php echo esc_attr(implode(' ', $classes)); ?>">
			<?php if ($message !== '') : ?>
				<div class="blr-fan-signup__message <?php echo esc_attr($message_class); ?>">
					<?php echo esc_html($message); ?>
				</div>
			<?php endif; ?>

			<form method="post" action="<?php echo esc_url($current_url); ?>" class="blr-fan-signup__form">
				<input type="hidden" name="blr_action" value="<?php echo esc_attr(self::ACTION); ?>">
				<input type="hidden" name="blr_return_url" value="<?php echo esc_url($current_url); ?>">
				<input type="hidden" name="blr_form_id" value="<?php echo esc_attr($form_id); ?>">
				<input type="hidden" name="blr_source" value="<?php echo esc_attr(sanitize_text_field((string) $atts['source'])); ?>">
				<input type="hidden" name="blr_tag" value="<?php echo esc_attr(sanitize_text_field((string) $atts['tag'])); ?>">
				<input type="hidden" name="<?php echo esc_attr(self::ISSUED_AT_FIELD); ?>" value="<?php echo esc_attr((string) $issued_at); ?>">
				<input type="hidden" name="<?php echo esc_attr(self::FORM_TOKEN_FIELD); ?>" value="<?php echo esc_attr($form_token); ?>">
				<div class="blr-fan-signup__hp-wrap" aria-hidden="true">
					<label for="<?php echo esc_attr($form_id . '-website'); ?>"><?php echo esc_html__('Leave this field empty', 'blr-backline'); ?></label>
					<input type="text" id="<?php echo esc_attr($form_id . '-website'); ?>" name="<?php echo esc_attr(self::HONEYPOT_FIELD); ?>" value="" tabindex="-1" autocomplete="new-password" inputmode="none" class="blr-fan-signup__hp">
				</div>
				<?php wp_nonce_field('blr_ba_fan_signup_submit', '_wpnonce_blr_fan_signup'); ?>

				<?php if ($show_name) : ?>
					<p class="blr-fan-signup__field">
						<label for="<?php echo esc_attr($form_id . '-first-name'); ?>"><?php echo esc_html__('First name', 'blr-backline'); ?></label>
						<input type="text" id="<?php echo esc_attr($form_id . '-first-name'); ?>" name="blr_first_name" value="" autocomplete="given-name">
					</p>
				<?php endif; ?>

				<p class="blr-fan-signup__field">
					<label for="<?php echo esc_attr($form_id . '-email'); ?>"><?php echo esc_html__('Email', 'blr-backline'); ?></label>
					<input type="email" id="<?php echo esc_attr($form_id . '-email'); ?>" name="blr_email" value="" required autocomplete="email">
				</p>

				<p class="blr-fan-signup__actions">
					<button type="submit" class="blr-fan-signup__button btn btn-primary"><?php echo esc_html((string) $atts['button_text']); ?></button>
				</p>
			</form>
		</div>
		<?php

		return (string) ob_get_clean();
	}

	public static function handle_confirmation(): void {
		// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Confirmation links are validated with a one-time token, not a nonce.
		if (!isset($_GET['blr_action'])) {
			return;
		}

		$action = sanitize_key((string) wp_unslash($_GET['blr_action']));
		if ($action !== self::CONFIRM_ACTION) {
			return;
		}

		$contact_id = isset($_GET[self::CONFIRM_CONTACT_QUERY]) ? absint(wp_unslash($_GET[self::CONFIRM_CONTACT_QUERY])) : 0;
		$token = isset($_GET[self::CONFIRM_TOKEN_QUERY]) ? sanitize_text_field((string) wp_unslash($_GET[self::CONFIRM_TOKEN_QUERY])) : '';
		$return_url = isset($_GET['blr_return_url']) ? esc_url_raw((string) wp_unslash($_GET['blr_return_url'])) : home_url('/');
		$return_url = self::sanitize_local_return_url($return_url);
		$form_id = isset($_GET['blr_form_id']) ? sanitize_text_field((string) wp_unslash($_GET['blr_form_id'])) : '';
		// phpcs:enable WordPress.Security.NonceVerification.Recommended

		if ($contact_id <= 0 || $token === '') {
			self::redirect_with_status($return_url, 'invalid_confirm', $form_id);
		}

		$validation = NewsletterDoubleOptIn::validate_confirmation_token($contact_id, $token);
		if ($validation === 'already_confirmed') {
			self::redirect_with_status($return_url, 'confirmed', $form_id);
		}

		if ($validation === 'expired') {
			NewsletterDoubleOptIn::clear_confirmation_token($contact_id);
			self::redirect_with_status($return_url, 'expired_confirm', $form_id);
		}

		if ($validation !== 'valid') {
			self::redirect_with_status($return_url, 'invalid_confirm', $form_id);
		}

		NewsletterDoubleOptIn::confirm_subscription($contact_id);
		OutreachModule::flush_contact_meta_option_caches();

		$email = (string) get_post_meta($contact_id, 'blr_contact_email', true);
		do_action('blr_backline_fan_signup_confirmed', $contact_id, $email);

		self::redirect_with_status($return_url, 'confirmed', $form_id);
	}

	public static function handle_submission(): void {
		if (!isset($_POST['blr_action'])) {
			return;
		}

		$action = sanitize_key((string) wp_unslash($_POST['blr_action']));
		if ($action !== self::ACTION) {
			return;
		}

		$nonce = isset($_POST['_wpnonce_blr_fan_signup']) ? sanitize_text_field((string) wp_unslash($_POST['_wpnonce_blr_fan_signup'])) : '';
		$return_url = isset($_POST['blr_return_url']) ? esc_url_raw((string) wp_unslash($_POST['blr_return_url'])) : home_url('/');
		$return_url = self::sanitize_local_return_url($return_url);
		$form_id = isset($_POST['blr_form_id']) ? sanitize_text_field((string) wp_unslash($_POST['blr_form_id'])) : '';

		if ($nonce === '' || !wp_verify_nonce($nonce, 'blr_ba_fan_signup_submit')) {
			self::redirect_with_status($return_url, 'invalid_nonce', $form_id);
		}

		$issued_at = isset($_POST[self::ISSUED_AT_FIELD]) ? absint(wp_unslash($_POST[self::ISSUED_AT_FIELD])) : 0;
		$form_token = isset($_POST[self::FORM_TOKEN_FIELD]) ? sanitize_text_field((string) wp_unslash($_POST[self::FORM_TOKEN_FIELD])) : '';

		$form_validation = self::validate_form_submission($form_id, $issued_at, $form_token);
		if ($form_validation !== 'valid') {
			self::redirect_with_status($return_url, $form_validation, $form_id);
		}

		$request_identifier = self::request_identifier();
		if (self::is_rate_limited($request_identifier, '')) {
			self::redirect_with_status($return_url, 'throttled', $form_id);
		}

		$honeypot = isset($_POST[self::HONEYPOT_FIELD]) ? sanitize_text_field((string) wp_unslash($_POST[self::HONEYPOT_FIELD])) : '';
		$legacy_honeypot = isset($_POST['blr_company_name']) ? sanitize_text_field((string) wp_unslash($_POST['blr_company_name'])) : '';
		if ($honeypot !== '' || $legacy_honeypot !== '') {
			self::register_attempt($request_identifier, '');
			self::redirect_with_status($return_url, 'confirm_sent', $form_id);
		}

		$email = isset($_POST['blr_email']) ? sanitize_email((string) wp_unslash($_POST['blr_email'])) : '';
		if ($email === '' || !is_email($email)) {
			self::register_attempt($request_identifier, '');
			self::redirect_with_status($return_url, 'invalid_email', $form_id);
		}

		$email = strtolower($email);
		if (self::is_rate_limited($request_identifier, $email)) {
			self::register_attempt($request_identifier, $email);
			self::redirect_with_status($return_url, 'throttled', $form_id);
		}

		$existing_id = self::find_existing_contact_id($email);
		$existing_status = $existing_id > 0 ? NewsletterDoubleOptIn::get_status($existing_id) : '';
		if (self::is_email_cooling_down($email)) {
			self::register_attempt($request_identifier, $email);
			$cooldown_status = $existing_status === NewsletterDoubleOptIn::STATUS_SUBSCRIBED ? 'exists' : 'confirm_sent';
			self::redirect_with_status($return_url, $cooldown_status, $form_id);
		}

		self::register_attempt($request_identifier, $email);

		$first_name = isset($_POST['blr_first_name']) ? sanitize_text_field((string) wp_unslash($_POST['blr_first_name'])) : '';
		$source = isset($_POST['blr_source']) ? sanitize_text_field((string) wp_unslash($_POST['blr_source'])) : 'website';
		$tag = isset($_POST['blr_tag']) ? sanitize_text_field((string) wp_unslash($_POST['blr_tag'])) : 'newsletter';

		$result = self::upsert_fan_contact($email, $first_name, $source, $tag, $return_url, $form_id);
		if ($result === 'exists') {
			self::mark_email_cooling_down($email);
			self::redirect_with_status($return_url, 'exists', $form_id);
		}

		if ($result !== 'confirm_sent') {
			self::redirect_with_status($return_url, 'error', $form_id);
		}

		self::mark_email_cooling_down($email);
		self::redirect_with_status($return_url, 'confirm_sent', $form_id);
	}

	private static function upsert_fan_contact(string $email, string $first_name, string $source, string $tag, string $return_url, string $form_id): string {
		$existing_id = self::find_existing_contact_id($email);
		$is_existing = $existing_id > 0;
		$contact_id = $existing_id;

		if ($is_existing) {
			$post = get_post($existing_id);
			if (!$post instanceof \WP_Post) {
				return 'error';
			}

			$existing_title = (string) $post->post_title;
			$title = $existing_title !== '' ? $existing_title : ($first_name !== '' ? $first_name : $email);

			$result = wp_update_post(wp_slash([
				'ID' => $existing_id,
				'post_title' => sanitize_text_field($title),
			]), true);
		} else {
			$title = $first_name !== '' ? $first_name : $email;
			$result = wp_insert_post(wp_slash([
				'post_status' => 'publish',
				'post_type' => 'blr_contact',
				'post_title' => sanitize_text_field($title),
			]), true);

			if (!is_wp_error($result)) {
				$contact_id = (int) $result;
			}
		}

		if (is_wp_error($result) || $contact_id <= 0) {
			return 'error';
		}

		if ($first_name !== '') {
			$existing_first_name = $is_existing ? (string) get_post_meta($contact_id, 'blr_contact_first_name', true) : '';
			if (!$is_existing || $existing_first_name === '') {
				update_post_meta($contact_id, 'blr_contact_first_name', $first_name);
			}
		}

		if ($is_existing) {
			$existing_type = (string) get_post_meta($contact_id, 'blr_contact_type', true);

			if ($existing_type === '' || $existing_type === 'Fan') {
				update_post_meta($contact_id, 'blr_contact_type', 'Fan');
			}
		} else {
			update_post_meta($contact_id, 'blr_contact_email', $email);
			update_post_meta($contact_id, 'blr_contact_type', 'Fan');
		}

		$notes = (string) get_post_meta($contact_id, 'blr_contact_notes', true);
		$note_lines = [];
		if ($source !== '') {
			$note_lines[] = sprintf(
				/* translators: %s: signup source label. */
				__('Fan signup source: %s', 'blr-backline'),
				$source
			);
		}
		if ($tag !== '') {
			$note_lines[] = sprintf(
				/* translators: %s: signup tag label. */
				__('Fan signup tag: %s', 'blr-backline'),
				$tag
			);
		}
		if (!empty($note_lines)) {
			$note_block = implode("\n", $note_lines);
			if ($notes === '') {
				$notes = $note_block;
			} elseif (strpos($notes, $note_block) === false) {
				$notes .= "\n" . $note_block;
			}
			update_post_meta($contact_id, 'blr_contact_notes', wp_kses_post($notes));
		}

		$current_status = NewsletterDoubleOptIn::get_status($contact_id);
		if ($current_status === NewsletterDoubleOptIn::STATUS_SUBSCRIBED) {
			OutreachModule::flush_contact_meta_option_caches();
			return 'exists';
		}

		$confirmation = NewsletterDoubleOptIn::issue_confirmation_token($contact_id);
		if (empty($confirmation['token'])) {
			return 'error';
		}

		$sent = self::send_confirmation_email(
			$contact_id,
			$email,
			$first_name,
			$return_url,
			$form_id,
			(string) $confirmation['token']
		);
		if (!$sent) {
			return 'error';
		}

		OutreachModule::flush_contact_meta_option_caches();

		do_action('blr_backline_fan_signup_submitted', $contact_id, $email, $first_name, $source, $tag, $is_existing);

		return 'confirm_sent';
	}

	private static function send_confirmation_email(int $contact_id, string $email, string $first_name, string $return_url, string $form_id, string $token): bool {
		if ($contact_id <= 0 || $email === '' || !is_email($email) || $token === '') {
			return false;
		}

		$confirm_url = add_query_arg([
			'blr_action' => self::CONFIRM_ACTION,
			self::CONFIRM_CONTACT_QUERY => $contact_id,
			self::CONFIRM_TOKEN_QUERY => $token,
			'blr_return_url' => $return_url,
			'blr_form_id' => $form_id,
		], $return_url);
		$confirm_url = apply_filters('blr_backline_fan_signup_confirmation_url', $confirm_url, $contact_id, $email, $form_id);

		$site_name = wp_specialchars_decode(get_bloginfo('name'), ENT_QUOTES);
		$subject = sprintf(
			/* translators: %s: site name. */
			__('Confirm your signup to %s', 'blr-backline'),
			$site_name !== '' ? $site_name : __('this mailing list', 'blr-backline')
		);
		$subject = (string) apply_filters('blr_backline_fan_signup_confirmation_subject', $subject, $contact_id, $email);

		$greeting = $first_name !== ''
			? sprintf(
				/* translators: %s: first name. */
				__('Hi %s,', 'blr-backline'),
				$first_name
			)
			: __('Hi there,', 'blr-backline');

		$body_lines = [
			$greeting,
			'',
			sprintf(
				/* translators: %s: site name. */
				__('Please confirm your signup to the %s mailing list by clicking the link below:', 'blr-backline'),
				$site_name !== '' ? $site_name : __('site', 'blr-backline')
			),
			'',
			$confirm_url,
			'',
			__('If you did not request this, you can safely ignore this email.', 'blr-backline'),
		];

		$body = implode("\n", $body_lines);
		$body = (string) apply_filters('blr_backline_fan_signup_confirmation_body', $body, $contact_id, $email, $confirm_url);

		$headers = ['Content-Type: text/plain; charset=UTF-8'];

		return wp_mail($email, $subject, $body, $headers);
	}

	private static function find_existing_contact_id(string $email): int {
		if ($email === '') {
			return 0;
		}

		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query -- Targeted duplicate lookup by exact email value.
		$found = get_posts([
			'post_type' => 'blr_contact',
			'post_status' => ['publish', 'draft', 'pending', 'private'],
			'posts_per_page' => 1,
			'fields' => 'ids',
			'no_found_rows' => true,
			'meta_query' => [[
				'key' => 'blr_contact_email',
				'value' => $email,
			]],
		]);

		if (!empty($found[0])) {
			return (int) $found[0];
		}

		return 0;
	}

	private static function validate_form_submission(string $form_id, int $issued_at, string $form_token): string {
		if ($form_id === '' || $issued_at <= 0 || $form_token === '') {
			return 'invalid_form';
		}

		$expected_token = self::build_form_token($form_id, $issued_at);
		if (!hash_equals($expected_token, $form_token)) {
			return 'invalid_form';
		}

		$age = time() - $issued_at;
		if ($age < self::min_submit_seconds()) {
			return 'too_fast';
		}

		if ($age > self::max_form_age_seconds()) {
			return 'expired_form';
		}

		return 'valid';
	}

	private static function build_form_token(string $form_id, int $issued_at): string {
		return wp_hash($form_id . '|' . $issued_at . '|' . self::ACTION);
	}

	private static function min_submit_seconds(): int {
		$seconds = (int) apply_filters('blr_backline_fan_signup_min_submit_seconds', self::DEFAULT_MIN_SUBMIT_SECONDS);

		return max(0, $seconds);
	}

	private static function max_form_age_seconds(): int {
		$seconds = (int) apply_filters('blr_backline_fan_signup_max_form_age_seconds', self::DEFAULT_MAX_FORM_AGE_SECONDS);

		return max(self::min_submit_seconds() + 1, $seconds);
	}

	private static function rate_limit_window_seconds(): int {
		$seconds = (int) apply_filters('blr_backline_fan_signup_rate_limit_window_seconds', self::DEFAULT_RATE_LIMIT_WINDOW_SECONDS);

		return max(60, $seconds);
	}

	private static function rate_limit_max_attempts(): int {
		$attempts = (int) apply_filters('blr_backline_fan_signup_rate_limit_max_attempts', self::DEFAULT_RATE_LIMIT_MAX_ATTEMPTS);

		return max(1, $attempts);
	}

	private static function email_cooldown_seconds(): int {
		$seconds = (int) apply_filters('blr_backline_fan_signup_email_cooldown_seconds', self::DEFAULT_EMAIL_COOLDOWN_SECONDS);

		return max(0, $seconds);
	}

	private static function request_identifier(): string {
		$remote_addr = '';

		if (isset($_SERVER['REMOTE_ADDR'])) {
			// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Normalized immediately for rate-limiting fingerprint generation.
			$remote_addr = sanitize_text_field((string) wp_unslash($_SERVER['REMOTE_ADDR']));
		}

		if ($remote_addr === '') {
			return 'unknown';
		}

		$validated_ip = filter_var($remote_addr, FILTER_VALIDATE_IP);
		if (!is_string($validated_ip) || $validated_ip === '') {
			return 'unknown';
		}

		return strtolower($validated_ip);
	}

	private static function is_rate_limited(string $request_identifier, string $email): bool {
		if (self::attempt_count(self::rate_limit_key('ip', $request_identifier)) >= self::rate_limit_max_attempts()) {
			return true;
		}

		if ($email !== '' && self::attempt_count(self::rate_limit_key('email', $email)) >= self::rate_limit_max_attempts()) {
			return true;
		}

		return false;
	}

	private static function register_attempt(string $request_identifier, string $email): void {
		self::increment_attempt_counter(self::rate_limit_key('ip', $request_identifier));

		if ($email !== '') {
			self::increment_attempt_counter(self::rate_limit_key('email', $email));
		}
	}

	private static function increment_attempt_counter(string $transient_key): void {
		$payload = get_transient($transient_key);
		$count = 0;

		if (is_array($payload) && isset($payload['count'])) {
			$count = absint($payload['count']);
		}

		set_transient($transient_key, [
			'count' => $count + 1,
		], self::rate_limit_window_seconds());
	}

	private static function attempt_count(string $transient_key): int {
		$payload = get_transient($transient_key);

		if (!is_array($payload) || !isset($payload['count'])) {
			return 0;
		}

		return absint($payload['count']);
	}

	private static function rate_limit_key(string $bucket, string $value): string {
		$value = strtolower(trim($value));
		if ($value === '') {
			$value = 'unknown';
		}

		return self::RATE_LIMIT_KEY_PREFIX . $bucket . '_' . md5(wp_hash($value));
	}

	private static function email_cooldown_key(string $email): string {
		return self::EMAIL_COOLDOWN_KEY_PREFIX . md5(wp_hash(strtolower(trim($email))));
	}

	private static function is_email_cooling_down(string $email): bool {
		if ($email === '' || self::email_cooldown_seconds() <= 0) {
			return false;
		}

		return get_transient(self::email_cooldown_key($email)) !== false;
	}

	private static function mark_email_cooling_down(string $email): void {
		if ($email === '' || self::email_cooldown_seconds() <= 0) {
			return;
		}

		set_transient(self::email_cooldown_key($email), 1, self::email_cooldown_seconds());
	}

	private static function enqueue_assets(): void {
		if (self::$assets_enqueued) {
			return;
		}

		self::$assets_enqueued = true;

		if (!wp_style_is('blr-ba-fan-signup', 'registered')) {
			wp_register_style('blr-ba-fan-signup', false, [], BLR_BA_VERSION);
		}

		wp_enqueue_style('blr-ba-fan-signup');
		wp_add_inline_style('blr-ba-fan-signup', self::inline_css());
	}

	private static function inline_css(): string {
		return <<<'CSS'
.blr-fan-signup {
	max-width: 42rem;
}

.blr-fan-signup__form {
	display: grid;
	gap: 0.875rem;
}

.blr-fan-signup__field,
.blr-fan-signup__actions {
	margin: 0;
}

.blr-fan-signup__field label {
	display: block;
	margin-bottom: 0.375rem;
	font-weight: 600;
}

.blr-fan-signup__field input {
	width: 100%;
	padding: 0.75rem 0.875rem;
	border: 1px solid rgba(127, 127, 127, 0.35);
	border-radius: 0.5rem;
	background: #fff;
	box-sizing: border-box;
}

.blr-fan-signup__button {
	padding: 0.75rem 1rem;
	border: 0;
	border-radius: 0.5rem;
	cursor: pointer;
}

.blr-fan-signup__message {
	margin-bottom: 1rem;
	padding: 0.75rem 0.875rem;
	border-radius: 0.5rem;
}

.blr-fan-signup__message--success {
	background: rgba(25, 135, 84, 0.12);
}

.blr-fan-signup__message--error {
	background: rgba(220, 53, 69, 0.12);
}

.blr-fan-signup__hp-wrap {
	position: absolute !important;
	left: -9999px !important;
	width: 1px !important;
	height: 1px !important;
	overflow: hidden !important;
	opacity: 0 !important;
	pointer-events: none !important;
}
CSS;
	}

	private static function build_form_id(array $atts): string {
		return substr(md5(wp_json_encode($atts)), 0, 12);
	}

	private static function sanitize_local_return_url(string $url): string {
		$url = esc_url_raw($url);
		if ($url === '') {
			return home_url('/');
		}

		$home_host = wp_parse_url(home_url('/'), PHP_URL_HOST);
		$url_host = wp_parse_url($url, PHP_URL_HOST);

		if (empty($url_host) || empty($home_host) || strtolower((string) $url_host) !== strtolower((string) $home_host)) {
			return home_url('/');
		}

		return $url;
	}

	private static function redirect_with_status(string $return_url, string $status, string $form_id): void {
		wp_safe_redirect(add_query_arg([
			self::QUERY_STATUS => sanitize_key($status),
			self::QUERY_FORM => sanitize_text_field($form_id),
		], $return_url));
		exit;
	}

	private static function current_url(): string {
		$request_uri = '/';

		if (isset($_SERVER['REQUEST_URI'])) {
			$request_uri = esc_url_raw((string) wp_unslash($_SERVER['REQUEST_URI']));
		}

		$path = wp_parse_url($request_uri, PHP_URL_PATH);
		$query = wp_parse_url($request_uri, PHP_URL_QUERY);
		$path = is_string($path) ? $path : '/';

		$home_path = wp_parse_url(home_url('/'), PHP_URL_PATH);
		$home_path = is_string($home_path) ? $home_path : '/';
		if ($home_path !== '/' && str_starts_with($path, $home_path)) {
			$path = substr($path, strlen($home_path));
		}

		if ($path === '') {
			$path = '/';
		}

		$url = home_url($path);

		if (is_string($query) && $query !== '') {
			$parsed = wp_parse_args($query);
			unset(
				$parsed[self::QUERY_STATUS],
				$parsed[self::QUERY_FORM],
				$parsed[self::CONFIRM_CONTACT_QUERY],
				$parsed[self::CONFIRM_TOKEN_QUERY],
				$parsed['blr_return_url'],
				$parsed['blr_form_id'],
				$parsed['blr_action']
			);

			if (!empty($parsed)) {
				$url = add_query_arg($parsed, $url);
			}
		}

		return self::sanitize_local_return_url($url);
	}
}
