<?php

namespace SugarCalendarBookings\Admin\Settings;

use SugarCalendarBookings\Integrations\Credits\CreditsService;
use SugarCalendarBookings\Integrations\IntegrationRegistry;
use SugarCalendarBookings\Options;
use SugarCalendarBookings\Plugin;
use SugarCalendarBookings\Support\Admin\AbstractTabPage;
use SugarCalendarBookings\Support\Admin\Notices;
use SugarCalendarBookings\Support\Helpers\Helpers;
use SugarCalendarBookings\Support\Helpers\UI;
use SugarCalendarBookings\Support\License\License;

/**
 * License & Usage Settings tab.
 *
 * @since 1.4.0
 */
class LicenseSettingsTab extends AbstractTabPage {

	/**
	 * Pre-generated palette (10 slots) from base #2271B1, hue 207°.
	 * Lightness evenly spaced 18%–82%.
	 *
	 * @since 1.4.0
	 *
	 * @var string[]
	 */
	const PALETTE = [
		'#0F314D',
		'#14446B',
		'#1A5789',
		'#206AA7',
		'#267DC5',
		'#3A92D9',
		'#58A2DF',
		'#76B3E5',
		'#94C4EB',
		'#B2D4F0',
	];

	/**
	 * Option key for the persistent integration → color index map.
	 *
	 * @since 1.4.0
	 *
	 * @var string
	 */
	const COLOR_MAP_OPTION = 'sugar_calendar_bookings_integration_color_map';

	/**
	 * Page title.
	 *
	 * @since 1.4.0
	 *
	 * @return string
	 */
	public static function get_title() {

		return esc_html__( 'License & Usage', 'sugar-calendar-bookings-scheduling-appointments-lite' );
	}

	/**
	 * Page slug.
	 *
	 * @since 1.4.0
	 *
	 * @return string
	 */
	public static function get_slug() {

		return 'settings';
	}

	/**
	 * Page view slug.
	 *
	 * @since 1.4.0
	 *
	 * @return string
	 */
	public static function get_view_slug() {

		return 'license';
	}

	/**
	 * Priority in menu position.
	 *
	 * @since 1.4.0
	 *
	 * @return int
	 */
	public static function get_priority() {

		return 5;
	}

	/**
	 * Display page.
	 *
	 * @since 1.4.0
	 */
	public function display_content() {

		ob_start();

		$options = Plugin::get( Options::class );

		$this->display_license_field( $options );

		$this->display_usage_section();

		UI::form_wrapper( ob_get_clean(), false );

		// Add confirmation modal markup for license verification.
		UI::confirmation_modal();
	}

	/**
	 * Get script data for the page.
	 *
	 * @since 1.4.0
	 *
	 * @return array
	 */
	public function get_script_data() {

		return [
			'license' => [
				'ajax_url' => admin_url( 'admin-ajax.php' ),
				'nonce'    => wp_create_nonce( 'sugar_calendar_bookings_pro_license_nonce' ),
			],
		];
	}

	/**
	 * Get post data processing rules.
	 *
	 * @since 1.4.0
	 *
	 * @return array
	 */
	public function get_post_data_processing_rules() {

		return [
			'license.key' => 'string',
		];
	}

	/**
	 * Handle POST requests.
	 *
	 * @since 1.4.0
	 *
	 * @param array $post_data Post data.
	 */
	public function handle_post( $post_data = [] ) {

		Plugin::get( Options::class )->update( $post_data );

		Plugin::get( Notices::class )->success(
			esc_html__( 'Settings successfully saved.', 'sugar-calendar-bookings-scheduling-appointments-lite' )
		);
	}

	/**
	 * Display the usage section below the license field.
	 *
	 * Shows integration and AI credit usage cards when data is available.
	 *
	 * @since 1.4.0
	 */
	private function display_usage_section(): void {

		$credits = Plugin::get( CreditsService::class )->get_credits();

		if ( $credits === null ) {
			return;
		}

		$is_monthly = ! empty( $credits['resets_at'] );

		?>
		<div class="scb-usage-section">
			<?php
			UI::heading(
				$is_monthly
					? [
						'title'       => sprintf(
							/* translators: %1$s - billing period month and year. */
							esc_html__( 'Usage for %1$s', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
							esc_html( $this->get_usage_period_label( $credits ) )
						),
						'description' => sprintf(
							wp_kses( /* translators: %1$s - URL to the usage credits documentation page. */
								__( 'Usage credits allow you to access advanced features such as Integrations. These limits depend on your license type and can be increased by upgrading. Remember, <strong>usage resets every month on the 1st.</strong> <a href="%1$s" target="_blank" rel="noopener noreferrer">Learn more</a>', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
								[
									'strong' => [],
									'a'      => [
										'href'   => [],
										'target' => [],
										'rel'    => [],
									],
								]
							),
							esc_url( Helpers::get_utm_url( 'https://sugarcalendar.com/docs/bookings/understanding-integration-credits-and-usage-limits/', [ 'content' => 'usage-credits' ] ) )
						),
					]
					: [
						'title'       => esc_html__( 'Lifetime Usage', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
						'description' => sprintf(
							wp_kses( /* translators: %1$s - URL to the usage credits documentation page. */
								__( 'Usage credits allow you to access advanced features such as Integrations. These limits depend on your license type and can be increased by upgrading. <a href="%1$s" target="_blank" rel="noopener noreferrer">Learn more</a>', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
								[
									'a' => [
										'href'   => [],
										'target' => [],
										'rel'    => [],
									],
								]
							),
							esc_url( Helpers::get_utm_url( 'https://sugarcalendar.com/docs/bookings/understanding-integration-credits-and-usage-limits/', [ 'content' => 'usage-credits' ] ) )
						),
					]
			);
			?>

			<div class="scb-usage-cards">
				<?php $this->render_usage_card( $credits ); ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Get the usage period label (e.g., "March 2026").
	 *
	 * @since 1.4.0
	 *
	 * @param array $credits Credits data.
	 *
	 * @return string
	 */
	private function get_usage_period_label( array $credits ): string {

		if ( ! empty( $credits['resets_at'] ) ) {
			$reset_time = strtotime( $credits['resets_at'] );

			if ( $reset_time !== false ) {
				return wp_date( 'F Y', strtotime( '-1 day', $reset_time ) );
			}
		}

		return wp_date( 'F Y' );
	}

	/**
	 * Render a usage card.
	 *
	 * @since 1.4.0
	 *
	 * @param array $credits Credits data.
	 */
	private function render_usage_card( array $credits ): void {

		$used       = (int) $credits['used'];
		$total      = (int) $credits['total'];
		$percentage = (float) $credits['percentage'];
		$is_maxed   = $credits['is_maxed'];

		$card_class = 'scb-usage-card';

		if ( $is_maxed ) {
			$card_class .= ' scb-usage-card--maxed';
		}

		?>
		<div class="<?php echo esc_attr( $card_class ); ?>">
			<div class="scb-usage-card__body">
				<div class="scb-usage-card__header">
					<div class="scb-usage-card__icon">
						<?php UI::svg_icon( 'tools', true ); ?>
					</div>
					<div class="scb-usage-card__info">
						<div class="scb-usage-card__label-row">
							<span class="scb-usage-card__label">
								<?php esc_html_e( 'Integration Usage', 'sugar-calendar-bookings-scheduling-appointments-lite' ); ?>
							</span>
							<?php if ( $is_maxed ) : ?>
								<span class="scb-usage-card__badge"><?php esc_html_e( 'Out of Usage!', 'sugar-calendar-bookings-scheduling-appointments-lite' ); ?></span>
							<?php endif; ?>
						</div>
						<div class="scb-usage-card__stats">
							<span class="scb-usage-card__count">
								<span class="scb-usage-card__used"><?php echo esc_html( number_format_i18n( $used ) ); ?></span>
								<span class="scb-usage-card__total">/ <?php echo esc_html( number_format_i18n( $total ) ); ?></span>
							</span>
							<span class="scb-usage-card__percentage">
								<?php
								$decimals = fmod( (float) $percentage, 1.0 ) === 0.0 ? 0 : 1;
								printf(
									/* translators: %1$s - percentage of credits used. */
									esc_html__( '%1$s%% used', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
									esc_html( number_format_i18n( (float) $percentage, $decimals ) )
								);
								?>
							</span>
						</div>
					</div>
				</div>

				<?php
				$segments = $this->build_usage_segments( $credits );

				$this->render_usage_bar( $credits, $segments );
				?>

				<?php $this->render_license_fallback_note(); ?>

				<?php if ( $is_maxed ) : ?>
					<p class="scb-usage-card__maxed-text">
						<?php esc_html_e( 'You\'ve hit your usage limit for this month! Features that use credits will be temporarily disabled until your usage reset or your limit is increased.', 'sugar-calendar-bookings-scheduling-appointments-lite' ); ?>
					</p>
					<?php if ( $credits['show_upgrade'] ) : ?>
						<a href="<?php echo esc_url( $this->get_usage_upgrade_url() ); ?>"
							class="scb-usage-card__upgrade-btn"
							target="_blank"
							rel="noopener noreferrer">
							+
							<?php esc_html_e( 'Upgrade For More', 'sugar-calendar-bookings-scheduling-appointments-lite' ); ?>
						</a>
					<?php endif; ?>
				<?php endif; ?>
			</div>

			<?php $this->render_usage_legend( $credits, $segments ); ?>
		</div>
		<?php
	}

	/**
	 * Render the segmented usage progress bar with tooltips.
	 *
	 * @since 1.4.0
	 *
	 * @param array $credits  Credits data including usage breakdown.
	 * @param array $segments Pre-built usage segments.
	 */
	private function render_usage_bar( array $credits, array $segments ): void {

		?>
		<div class="scb-usage-card__bar">
			<?php if ( ! empty( $segments ) ) : ?>
				<?php foreach ( $segments as $segment ) : ?>
					<div
						class="scb-usage-card__bar-segment"
						style="width: <?php echo esc_attr( $segment['percentage'] ); ?>%; background: <?php echo esc_attr( $segment['color'] ); ?>;"
						data-usage-segment
						data-name="<?php echo esc_attr( $segment['name'] ); ?>"
						data-count="<?php echo esc_attr( $segment['count'] ); ?>"
						data-color="<?php echo esc_attr( $segment['color'] ); ?>">
					</div>
				<?php endforeach; ?>
			<?php else : ?>
				<div class="scb-usage-card__bar-fill" style="width: <?php echo esc_attr( $credits['percentage'] ); ?>%"></div>
			<?php endif; ?>

			<div class="scb-usage-card__tooltip" style="display: none;" data-usage-tooltip>
				<div class="scb-usage-card__tooltip-arrow"></div>
				<div class="scb-usage-card__tooltip-header">
					<span class="scb-usage-card__tooltip-dot" data-tooltip-dot></span>
					<span class="scb-usage-card__tooltip-name" data-tooltip-name></span>
				</div>
				<span class="scb-usage-card__tooltip-credits" data-tooltip-credits></span>
			</div>
		</div>
		<?php
	}

	/**
	 * Render a note explaining that integrations use Lite credits until the license is activated.
	 *
	 * Only shown when the Pro plugin is active but no valid license is on record.
	 *
	 * @since 1.4.0
	 */
	private function render_license_fallback_note(): void {

		if ( ! sugar_calendar_bookings()->is_pro() ) {
			return;
		}

		if ( Plugin::get( License::class )->is_valid() ) {
			return;
		}

		?>
		<p class="scb-usage-card__license-note">
			<?php
			echo wp_kses(
				sprintf( /* translators: %1$s - anchor tag opening for the license key field; %2$s - anchor tag closing. */
					__( 'Your license isn\'t active, so integrations are using Lite credit limits. %1$sActivate your license%2$s to unlock your Pro credits.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					'<a href="#scbookings-setting-license-key">',
					'</a>'
				),
				[
					'a' => [
						'href' => [],
					],
				]
			);
			?>
		</p>
		<?php
	}

	/**
	 * Render the usage legend footer with per-integration breakdown.
	 *
	 * @since 1.4.0
	 *
	 * @param array $credits  Credits data.
	 * @param array $segments Pre-built usage segments.
	 */
	private function render_usage_legend( array $credits, array $segments ): void {

		if ( empty( $segments ) ) {
			return;
		}

		$total = (int) $credits['total'];

		?>
		<div class="scb-usage-card__legend-wrapper">
			<div class="scb-usage-card__legend">
				<?php foreach ( $segments as $segment ) : ?>
					<?php
					$percentage = $total > 0 ? round( ( $segment['count'] / $total ) * 100, 1 ) : 0;
					$decimals   = fmod( (float) $percentage, 1.0 ) === 0.0 ? 0 : 1;
					?>
					<div class="scb-usage-card__legend-series">
						<div class="scb-usage-card__legend-label">
							<span class="scb-usage-card__legend-dot" style="background: <?php echo esc_attr( $segment['color'] ); ?>;"></span>
							<span class="scb-usage-card__legend-name"><?php echo esc_html( $segment['name'] ); ?></span>
						</div>
						<span class="scb-usage-card__legend-value"><?php echo esc_html( number_format_i18n( $segment['count'] ) ); ?></span>
						<span class="scb-usage-card__legend-percent">(<?php echo esc_html( number_format_i18n( (float) $percentage, $decimals ) ); ?>%)</span>
					</div>
				<?php endforeach; ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Build usage segments sorted by color index for stable bar ordering.
	 *
	 * Each integration keeps its assigned color permanently.
	 * Segments are ordered by index (leftmost = lowest index).
	 *
	 * @since 1.4.0
	 *
	 * @param array $credits Credits data including usage breakdown.
	 *
	 * @return array Segments with slug, name, count, percentage, color.
	 */
	private function build_usage_segments( array $credits ): array {

		$usage = $credits['usage'] ?? [];

		if ( empty( $usage ) ) {
			return [];
		}

		$total     = (int) $credits['total'];
		$color_map = $this->get_color_map( array_column( $usage, 'slug' ) );
		$segments  = [];

		foreach ( $usage as $entry ) {
			$index      = $color_map[ $entry['slug'] ] ?? 0;
			$segments[] = [
				'slug'       => $entry['slug'],
				'name'       => $this->get_integration_display_name( $entry['slug'] ),
				'count'      => (int) $entry['count'],
				'percentage' => $total > 0 ? ( $entry['count'] / $total ) * 100 : 0,
				'color'      => self::PALETTE[ $index % count( self::PALETTE ) ],
				'index'      => $index,
			];
		}

		// Sort by index so bar segments are always in stable order.
		usort( $segments, fn( $a, $b ) => $a['index'] <=> $b['index'] );

		return $segments;
	}

	/**
	 * Get the persistent integration → color index map.
	 *
	 * Assigns new integrations the next available index and persists the map.
	 *
	 * @since 1.4.0
	 *
	 * @param string[] $slugs Integration slugs present in current usage data.
	 *
	 * @return array<string, int> Map of slug → palette index.
	 */
	private function get_color_map( array $slugs ): array {

		$map = get_option( self::COLOR_MAP_OPTION, [] );

		if ( ! is_array( $map ) ) {
			$map = [];
		}

		$changed = false;

		foreach ( $slugs as $slug ) {
			if ( ! isset( $map[ $slug ] ) ) {
				// Assign the next available index to ensure stable, persistent color ordering.
				$map[ $slug ] = ! empty( $map ) ? max( $map ) + 1 : 0;
				$changed      = true;
			}
		}

		if ( $changed ) {
			update_option( self::COLOR_MAP_OPTION, $map, false );
		}

		return $map;
	}

	/**
	 * Get the display name for an integration slug.
	 *
	 * @since 1.4.0
	 *
	 * @param string $slug Integration slug.
	 *
	 * @return string Display name.
	 */
	private function get_integration_display_name( string $slug ): string {

		$integration = Plugin::get( IntegrationRegistry::class )->get_by_slug( $slug );

		if ( $integration !== null ) {
			return $integration->get_name();
		}

		// Fallback: humanize the slug.
		return ucwords( str_replace( '_', ' ', $slug ) );
	}

	/**
	 * Get the upgrade URL for usage section.
	 *
	 * @since 1.4.0
	 *
	 * @return string
	 */
	private function get_usage_upgrade_url(): string {

		return Helpers::get_utm_url(
			'https://sugarcalendar.com/pricing/bookings/',
			[
				'source'  => 'WordPress',
				'medium'  => 'settings-license',
				'content' => 'usage-credits-upgrade',
			]
		);
	}

	/**
	 * Display license field for both Lite and Pro versions.
	 *
	 * @since 1.4.0
	 *
	 * @param Options $options Options instance.
	 */
	private function display_license_field( $options ) { // phpcs:ignore Generic.Metrics.CyclomaticComplexity.TooHigh

		UI::heading(
			[
				'title'       => esc_html__( 'License', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
				'description' => esc_html__( 'Your license key provides access to updates and support.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
			]
		);

		$is_pro = sugar_calendar_bookings()->is_pro();

		// Show educational notice for Lite version only.
		if ( ! $is_pro ) {
			$this->display_education_notice();
		}

		$license_key  = $options->get( 'license.key', '' );
		$license_type = $options->get( 'license.type', 'lite' );

		$is_expired       = $options->get( 'license.is_expired', false );
		$is_disabled      = $options->get( 'license.is_disabled', false );
		$is_invalid       = $options->get( 'license.is_invalid', false );
		$is_limit_reached = $options->get( 'license.is_limit_reached', false );
		$is_valid         = $is_pro && ! empty( $license_key ) && ! $is_expired && ! $is_disabled && ! $is_invalid && ! $is_limit_reached;

		$license_classes = 'sugar-calendar-bookings-setting-field-license';

		if ( $is_valid ) {
			$license_classes .= ' license-valid';
		}

		?>
		<div id="sugar-calendar-bookings-setting-field-license" class="<?php echo esc_attr( $license_classes ); ?>">
			<?php wp_nonce_field( 'sugar_calendar_bookings_pro_license_nonce', 'sugar-calendar-bookings-setting-license-nonce' ); ?>

			<div class="sugar-calendar-bookings-setting-field-row">
				<?php
				$is_pro = sugar_calendar_bookings()->is_pro();

				// Different button behavior for Lite vs Pro.
				if ( ! $is_pro ) {
					// Lite version: Always show Verify Key upgrade button (ignore DB values).
					UI::text_input_with_button(
						[
							'id'          => 'scbookings-setting-license-key',
							'name'        => [ 'license', 'key' ],
							'value'       => '',
							'label'       => esc_html__( 'License Key', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
							'placeholder' => esc_html__( 'Paste license key here', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
							'description' => $this->display_license_description_and_status( '', $license_type, false, false, false, false, false ),
							'type'        => 'password',
							'button'      => [
								'id'    => 'scbookings-setting-license-key-button',
								'text'  => esc_html__( 'Verify Key', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
								'class' => 'sugar-calendar-bookings-btn sugar-calendar-bookings-btn-primary sugar-calendar-bookings-btn-md',
							],
						]
					);
				} else {
					// Pro version OR Lite with existing key: Show verify/remove button.
					UI::text_input_with_button(
						[
							'id'          => 'license_key',
							'name'        => [ 'license', 'key' ],
							'value'       => $license_key,
							'label'       => esc_html__( 'License Key', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
							'placeholder' => esc_html__( 'Paste license key here', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
							'description' => $this->display_license_description_and_status( $license_key, $license_type, $is_valid, $is_expired, $is_disabled, $is_invalid, $is_limit_reached ),
							'type'        => 'password',
							'button'      => [
								'id'    => empty( $license_key ) ? 'sugar-calendar-bookings-setting-license-key-verify' : 'sugar-calendar-bookings-setting-license-key-deactivate',
								'text'  => empty( $license_key ) ? esc_html__( 'Verify Key', 'sugar-calendar-bookings-scheduling-appointments-lite' ) : esc_html__( 'Remove Key', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
								'class' => empty( $license_key ) ? 'sugar-calendar-bookings-btn sugar-calendar-bookings-btn-secondary sugar-calendar-bookings-btn-md' : 'sugar-calendar-bookings-btn sugar-calendar-bookings-btn-tertiary sugar-calendar-bookings-btn-md',
							],
						]
					);
				}
				?>
			</div>

		</div>
		<?php
	}

	/**
	 * Display license description and status messages.
	 *
	 * @since 1.4.0
	 *
	 * @param string $license_key      License key.
	 * @param string $license_type     License type.
	 * @param bool   $is_valid         Is license valid.
	 * @param bool   $is_expired       Is license expired.
	 * @param bool   $is_disabled      Is license disabled.
	 * @param bool   $is_invalid       Is license invalid.
	 * @param bool   $is_limit_reached Is license limit reached.
	 *
	 * @return string License description and status HTML.
	 */
	private function display_license_description_and_status( $license_key, $license_type, $is_valid, $is_expired, $is_disabled, $is_invalid, $is_limit_reached ) { // phpcs:ignore Generic.Metrics.CyclomaticComplexity.TooHigh

		if ( empty( $license_key ) ) {
			return sprintf(
				wp_kses( /* translators: %1$s - Sugar Calendar account dashboard URL; %2$s - pricing page URL. */
					__( 'Your license key can be found in your <a href="%1$s" target="_blank" rel="noopener noreferrer">Sugar Calendar Account Dashboard</a>. Don\'t have a license? <a href="%2$s" target="_blank" rel="noopener noreferrer">Sign up today!</a>', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					[
						'a' => [
							'href'   => [],
							'target' => [],
							'rel'    => [],
						],
					]
				),
				esc_url( 'https://sugarcalendar.com/account/' ),
				esc_url(
					Helpers::get_utm_url(
						'https://sugarcalendar.com/pricing/bookings/',
						[
							'source'  => 'WordPress',
							'medium'  => 'settings-license',
							'content' => 'license-description',
						]
					)
				)
			);
		}

		$status_messages = '';

		// Add status-specific messages.
		if ( $is_valid ) {
			$status_messages .= sprintf(
				'<p class="desc license-type">%s</p>',
				sprintf(
				/* translators: %1$s - license type. */
					esc_html__( 'Your license key level is %1$s.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					'<span class="license-plan-name">' . esc_html( $license_type ) . '</span>'
				)
			);

			$status_messages .= sprintf(
				'<p class="desc license-refresh-hint">%s</p>',
				wp_kses(
					__( 'If your license has been upgraded or is incorrect, then please <a href="#" id="sugar-calendar-bookings-setting-license-key-refresh">force a refresh</a>.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					[
						'a' => [
							'href' => [],
							'id'   => [],
						],
					]
				)
			);
		} elseif ( $is_expired ) {
			$status_messages .= sprintf(
				'<p class="type">%s</p>',
				wp_kses(
					__( '<b>Your license has expired.</b> An active license is needed to access some of the Pro features, plugin updates (including security improvements), and our world class support!', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					[
						'b' => [],
					]
				)
			);

			$status_messages .= sprintf(
				'<p class="desc">%s</p>',
				wp_kses(
					__( 'If your license has been upgraded or is incorrect, then please <a href="#" id="sugar-calendar-bookings-setting-license-key-refresh">force a refresh</a>.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					[
						'a' => [
							'href' => [],
							'id'   => [],
						],
					]
				)
			);
		} elseif ( $is_disabled ) {
			$status_messages .= sprintf(
				'<p class="type">%s</p>',
				wp_kses(
					__( '<b>Your license key has been disabled.</b> Please use a different key to continue receiving automatic updates.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					[
						'b' => [],
					]
				)
			);
		} elseif ( $is_invalid ) {
			$status_messages .= sprintf(
				'<p class="type">%s</p>',
				wp_kses(
					__( '<b>Your license key is invalid.</b> The key no longer exists or the user associated with the key has been deleted. Please use a different key to continue receiving automatic updates.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					[
						'b' => [],
					]
				)
			);
		} elseif ( $is_limit_reached ) {
			$status_messages .= sprintf(
				'<p class="type">%s</p>',
				sprintf(
					wp_kses( /* translators: %1$s - Sugar Calendar account area URL; %2$s - Sugar Calendar pricing page URL. */
						__( '<b>Sorry, but this license has no site activations left.</b> You can update the list of your sites or upgrade the license in the <a href="%1$s" target="_blank" rel="noopener noreferrer">Account area</a>. Or you can <a href="%2$s" target="_blank" rel="noopener noreferrer">purchase a new license key</a>.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
						[
							'b' => [],
							'a' => [
								'href'   => [],
								'target' => [],
								'rel'    => [],
							],
						]
					),
					esc_url( 'https://sugarcalendar.com/account/licenses/' ),
					esc_url(
						Helpers::get_utm_url(
							'https://sugarcalendar.com/pricing/bookings/',
							[
								'source'  => 'WordPress',
								'medium'  => 'settings-license',
								'content' => 'license-limit-reached',
							]
						)
					)
				)
			);

			$status_messages .= sprintf(
				'<p class="desc">%s</p>',
				wp_kses(
					__( 'If your license has been upgraded or is incorrect, then please <a href="#" id="sugar-calendar-bookings-setting-license-key-refresh">force a refresh</a>.', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
					[
						'a' => [
							'href' => [],
							'id'   => [],
						],
					]
				)
			);
		}

		return $status_messages;
	}

	/**
	 * Get upgrade URL with UTM parameters.
	 *
	 * @since 1.4.0
	 *
	 * @return string Upgrade URL with UTM parameters.
	 */
	private function get_upgrade_url() {

		return Helpers::get_utm_url(
			'https://sugarcalendar.com/pricing/bookings/',
			[
				'source'  => 'WordPress',
				'medium'  => 'settings-license',
				'content' => 'license-key',
			]
		);
	}

	/**
	 * Display education notice for Lite version.
	 *
	 * @since 1.4.0
	 */
	private function display_education_notice() {

		?>
		<div class="sugar-calendar-bookings__product-education__notice sugar-calendar-bookings__product-education__notice__settings-general">
			<div class="sugar-calendar-bookings__product-education__notice-content">
				<p>
					<?php
					echo wp_kses(
						__( 'You\'re using <strong>Sugar Calendar Bookings Lite</strong> - no license needed. Enjoy! 🙂', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
						[
							'strong' => [],
						]
					);
					?>
				</p>
				<p>
					<?php
					echo wp_kses(
						__( 'As a valued Sugar Calendar Bookings Lite user, you can enjoy an exclusive <strong class="sugar-calendar-bookings__product-education__notice-discount">50% OFF!</strong> automatically applied at checkout to unlock even more features!', 'sugar-calendar-bookings-scheduling-appointments-lite' ),
						[
							'strong' => [
								'class' => [],
							],
						]
					);
					?>
				</p>
				<p>
					<a
						href="<?php echo esc_url( $this->get_upgrade_url() ); ?>"
						class="sugar-calendar-bookings-btn sugar-calendar-bookings-btn-md sugar-calendar-bookings-btn-secondary"
						target="_blank"
						rel="noopener noreferrer">
						<?php esc_html_e( 'Upgrade to Pro', 'sugar-calendar-bookings-scheduling-appointments-lite' ); ?>
					</a>
				</p>
			</div>
			<div class="sugar-calendar-bookings__product-education__notice-mascot">
				<?php UI::svg_icon( 'mascot', true ); ?>
			</div>
		</div>
		<?php
	}
}
