<?php
/**
 * Referrals rewards drawer view.
 *
 * @package Awesomemotive\Rewardswp\Views\Admin\Parts
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Views\Admin\Parts;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractView;
use Awesomemotive\Rewardswp\Helpers\IconHelper;
use Awesomemotive\Rewardswp\Interfaces\IntegrationInterface;
use Awesomemotive\Rewardswp\Interfaces\ScriptDataProviderInterface;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use Awesomemotive\Rewardswp\Services\RewardTypesService;
use Awesomemotive\Rewardswp\Settings\Options\Points\PointsEnabledOption;
use Awesomemotive\Rewardswp\Settings\Options\Referrals\EnabledOption as ReferralsEnabledOption;
use Awesomemotive\Rewardswp\Settings\Options\Referrals\RewardsOption;
use function Awesomemotive\Rewardswp\Helpers\can_access_rewardswp_feature;
use function Awesomemotive\Rewardswp\Helpers\get_option_value;
use function Awesomemotive\Rewardswp\Helpers\get_view_component;
use function Awesomemotive\Rewardswp\Helpers\kses;
use function Awesomemotive\Rewardswp\Helpers\svg_kses;
use function Awesomemotive\Rewardswp\Helpers\is_rewardswp_pro_plan;
use function Awesomemotive\Rewardswp\Helpers\get_upgrade_url;
use function Awesomemotive\Rewardswp\Helpers\get_points_currency_plural;
use function Awesomemotive\Rewardswp\Helpers\get_points_currency_singular;
use function Awesomemotive\Rewardswp\Helpers\get_site_currency_symbol;

/**
 * Referrals Rewards View with Drawer UI
 *
 * @since 1.1.0
 */
class ReferralsRewardsDrawerView extends AbstractView implements ViewInterface, ScriptDataProviderInterface {

	/**
	 * Build the data structure supplied to the frontend drawer component.
	 *
	 * @since 1.1.0
	 *
	 * @return array
	 */
	public function get_script_data(): array {
		// Get reward types from service and filter by integration.
		$reward_types = $this->reward_types_service->get_reward_types_data();
		$reward_types = $this->get_filtered_reward_types( $reward_types );

		$rewards = get_option_value( RewardsOption::class );

		// Hide friend reward if user doesn't have access (but keep advocate).
		if ( ! can_access_rewardswp_feature( 'friend_reward' ) && isset( $rewards['friend'] ) ) {
			$rewards['friend'] = null;
		}

		// Dynamically build arrays from reward types.
		$reward_titles       = [];
		$reward_descriptions = [];
		$icon_map            = [];
		$reward_defaults     = [];

		foreach ( $reward_types as $type => $reward_data ) {
			$reward_titles[ $type ]       = $reward_data['title'];
			$reward_descriptions[ $type ] = $reward_data['advocate_title'];
			$reward_defaults[ $type ]     = $reward_data['defaults'];

			// Override defaults for free_product in Referrals.
			if ( 'free_product' === $type ) {
				// Default product_value to 0 (no limit).
				if ( empty( $reward_defaults[ $type ]['product_value'] ) ) {
					$reward_defaults[ $type ]['product_value'] = 0;
				}
				// Always unlimited for Referrals - field is hidden in the UI.
				$reward_defaults[ $type ]['redemption_limit'] = 'unlimited';
			}

			// Extract SVG from icon HTML.
			$icon_map[ $type ] = $reward_data['icon'];
		}

		return [
			'rewards'                  => $rewards,
			'currencySymbol'           => get_site_currency_symbol(),
			'currencySingular'         => get_points_currency_singular(),
			'currencyPlural'           => get_points_currency_plural(),
			'advocateAddTitle'         => __( 'Add Advocate Reward', 'rewardswp' ),
			'friendAddTitle'           => __( 'Add Friend Reward', 'rewardswp' ),
			'addSubtitle'              => __( 'Choose a reward type', 'rewardswp' ),
			'advocateConfigSubtitle'   => __( 'Configure advocate reward', 'rewardswp' ),
			'friendConfigSubtitle'     => __( 'Configure friend reward', 'rewardswp' ),
			'advocateEditSubtitle'     => __( 'Edit advocate reward', 'rewardswp' ),
			'friendEditSubtitle'       => __( 'Edit friend reward', 'rewardswp' ),
			'removeConfirmMessage'     => __( 'Are you sure you want to remove this reward?', 'rewardswp' ),
			'offText'                  => __( 'off', 'rewardswp' ),
			'freeShippingText'         => __( 'Free shipping on next order', 'rewardswp' ),
			'freeProductText'          => __( 'Free product selection', 'rewardswp' ),
			'rewardTitles'             => $reward_titles,
			'rewardDescriptions'       => $reward_descriptions,
			'rewardDefaults'           => $reward_defaults,
			'iconMap'                  => $icon_map,
			'friendRequiresPro'        => ! can_access_rewardswp_feature( 'friend_reward' ),
			'pointsProgramEnabled'     => get_option_value( PointsEnabledOption::class ),
			'referralsProgramEnabled'  => get_option_value( ReferralsEnabledOption::class ),
		];
	}

	/**
	 * Icon helper instance.
	 *
	 * @since 1.1.0
	 * @var IconHelper
	 */
	private IconHelper $icon_helper;

	/**
	 * Reward types service instance.
	 *
	 * @since 1.1.0
	 * @var RewardTypesService
	 */
	private RewardTypesService $reward_types_service;

	/**
	 * Integration instance.
	 *
	 * @since 1.1.0
	 * @var IntegrationInterface
	 */
	private IntegrationInterface $integration;

	/**
	 * Constructor.
	 *
	 * @since 1.1.0
	 * @param IconHelper           $icon_helper Icon helper instance.
	 * @param RewardTypesService   $reward_types_service Reward types service instance.
	 * @param IntegrationInterface $integration Integration instance.
	 */
	public function __construct( IconHelper $icon_helper, RewardTypesService $reward_types_service, IntegrationInterface $integration ) {
		$this->icon_helper          = $icon_helper;
		$this->reward_types_service = $reward_types_service;
		$this->integration          = $integration;
	}

	/**
	 * Filter reward types based on integration compatibility.
	 *
	 * @since 1.1.0
	 *
	 * @param array $reward_types The reward types to filter.
	 *
	 * @return array The filtered reward types.
	 */
	private function get_filtered_reward_types( array $reward_types ): array {
		$source = $this->integration->get_source();

		$filtered_reward_types = [];
		foreach ( $reward_types as $type => $reward_data ) {
			$available_for = $reward_data['available_for'] ?? [];

			// Skip if not available for current integration.
			// Show all if no integration, or if available_for is empty (available for all),
			// or if current source is in available_for array.
			if ( ! empty( $available_for )
				&& ! in_array( $source, $available_for, true )
				&& 'unknown' !== $source
			) {
				continue;
			}

			$filtered_reward_types[ $type ] = $reward_data;
		}

		return $filtered_reward_types;
	}

	/**
	 * Render the template.
	 *
	 * @since 1.1.0
	 * @param array $args
	 * @return void
	 */
	public function render( array $args = [] ): void {
		echo wp_kses( $this->get_contents( $args ), kses() );
	}

	/**
	 * Get the view contents (main section view).
	 *
	 * @since 1.1.0
	 * @param array $args Arguments for the view.
	 * @return string The view contents.
	 */
	public function get_contents( array $args = [] ): string {
		ob_start();

		$rewards = get_option_value( RewardsOption::class );
		?>

		<!-- Referrals Section -->
		<div class="py-5"
			x-data="referralsSection">
			<div class="gap-8 md:flex md:items-start">
				<!-- Left Column -->
				<div class="md:w-1/3 flex-none">
					<p class="text-sm text-gray-500">
						<?php esc_html_e( 'Reward advocates and their friends', 'rewardswp' ); ?>
					</p>
				</div>

				<!-- Right Column - Reward Cards -->
				<div class="md:w-2/3">
					<div class="space-y-4">
						<!-- Advocate Reward Card -->
						<div class="bg-white border border-gray-200 rounded-lg p-6">
							<div class="flex justify-between items-start mb-4">
								<div>
									<h3 class="text-sm font-semibold text-gray-900">
										<?php esc_html_e( 'Advocate Reward', 'rewardswp' ); ?>
									</h3>
									<template x-if="!$store.referrals.rewards.advocate">
										<p class="mt-1 text-sm text-gray-500">
											<?php esc_html_e( 'Add a reward for advocates who refer friends.', 'rewardswp' ); ?>
										</p>
									</template>
								</div>
							</div>

							<!-- No reward state -->
							<template x-if="!$store.referrals.rewards.advocate">
								<div>
									<button
										type="button"
										x-on:click="openDrawer('advocate')"
										class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-blue-600 border border-transparent rounded-md shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
									>
										<?php esc_html_e( 'Add Reward', 'rewardswp' ); ?>
									</button>
								</div>
							</template>

							<!-- Has reward state -->
							<template x-if="$store.referrals.rewards.advocate">
								<div class="flex items-start cursor-pointer" x-on:click="editReward('advocate', $store.referrals.rewards.advocate)">
									<div class="mr-4 flex-shrink-0 text-gray-800">
										<span class="size-7" x-html="getIcon($store.referrals.rewards.advocate.type)"></span>
									</div>
									<div class="flex-1 min-w-0">
										<div class="flex justify-between items-center">
											<div>
												<div class="flex items-center gap-2">
													<h3 class="text-sm font-medium text-gray-900" x-text="getTitle($store.referrals.rewards.advocate, 'advocate')"></h3>
													<!-- Out of Stock badge for free_product -->
													<?php
													echo wp_kses(
														get_view_component(
															'badge',
															[
																'text'   => esc_html__( 'Out of Stock', 'rewardswp' ),
																'style'  => 'warning',
																'x-show' => "\$store.referrals.rewards.advocate?.type === 'free_product' && \$store.referrals.rewards.advocate?.products_included?.[0]?.in_stock === false",
															]
														),
														kses()
													);
													?>
												</div>
												<div class="mt-1 text-sm text-gray-700" x-text="getDescription($store.referrals.rewards.advocate, 'advocate')"></div>
											</div>
											<div class="flex items-center space-x-4">
												<?php
												echo wp_kses(
													get_view_component(
														'button',
														[
															'text'  => esc_html__( 'Edit', 'rewardswp' ),
															'type'  => 'button',
															'style' => 'secondary',
															'size'  => 'sm',
															'click' => '$event.stopPropagation(); editReward(\'advocate\', $store.referrals.rewards.advocate)',
														]
													),
													kses()
												);
												?>
												<button
													type="button"
													x-on:click.stop="removeReward('advocate')"
													class="text-gray-400 hover:text-red-600"
												>
													<?php echo wp_kses( $this->icon_helper->get_icon( 'trash', 'w-5 h-5' ), svg_kses() ); ?>
												</button>
											</div>
										</div>
									</div>
								</div>
							</template>
						</div>

						<!-- Friend Reward Card -->
						<div class="bg-white border border-gray-200 rounded-lg p-6">
							<div class="flex justify-between items-start mb-4">
								<div>
									<h3 class="text-sm font-semibold text-gray-900 flex items-center gap-2">
										<?php esc_html_e( 'Friend Reward', 'rewardswp' ); ?>
										<?php
										echo wp_kses(
											get_view_component(
												'badge',
												[
													'style'  => 'pro',
													'x-show' => '$store.referrals.friendRequiresPro',
												]
											),
											kses()
										);
										?>
									</h3>
									<template x-if="!$store.referrals.rewards.friend">
										<p class="mt-1 text-sm text-gray-500">
											<?php esc_html_e( "Reward for friend's first order.", 'rewardswp' ); ?>
										</p>
									</template>
								</div>
							</div>

							<!-- No reward state -->
							<template x-if="!$store.referrals.rewards.friend">
								<div>
									<button
										type="button"
										x-on:click="openDrawer('friend')"
										class="inline-flex items-center px-4 py-2 text-sm font-medium text-white bg-blue-600 border border-transparent rounded-md shadow-sm hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
									>
										<?php esc_html_e( 'Add Reward', 'rewardswp' ); ?>
									</button>
								</div>
							</template>

							<!-- Has reward state -->
							<template x-if="$store.referrals.rewards.friend">
								<div class="flex items-start cursor-pointer" x-on:click="editReward('friend', $store.referrals.rewards.friend)">
									<div class="mr-4 flex-shrink-0 text-gray-800">
										<span class="size-7" x-html="getIcon($store.referrals.rewards.friend.type)"></span>
									</div>
									<div class="flex-1 min-w-0">
										<div class="flex justify-between items-center">
											<div>
												<div class="flex items-center gap-2">
													<h3 class="text-sm font-medium text-gray-900" x-text="getTitle($store.referrals.rewards.friend, 'friend')"></h3>
													<!-- Out of Stock badge for free_product -->
													<?php
													echo wp_kses(
														get_view_component(
															'badge',
															[
																'text'   => esc_html__( 'Out of Stock', 'rewardswp' ),
																'style'  => 'warning',
																'x-show' => "\$store.referrals.rewards.friend?.type === 'free_product' && \$store.referrals.rewards.friend?.products_included?.[0]?.in_stock === false",
															]
														),
														kses()
													);
													?>
												</div>
												<div class="mt-1 text-sm text-gray-700" x-text="getDescription($store.referrals.rewards.friend, 'friend')"></div>
											</div>
											<div class="flex items-center space-x-4">
												<?php
												echo wp_kses(
													get_view_component(
														'button',
														[
															'text'  => esc_html__( 'Edit', 'rewardswp' ),
															'type'  => 'button',
															'style' => 'secondary',
															'size'  => 'sm',
															'click' => '$event.stopPropagation(); editReward(\'friend\', $store.referrals.rewards.friend)',
														]
													),
													kses()
												);
												?>
												<button
													type="button"
													x-on:click.stop="removeReward('friend')"
													class="text-gray-400 hover:text-red-600"
												>
													<?php echo wp_kses( $this->icon_helper->get_icon( 'trash', 'w-5 h-5' ), svg_kses() ); ?>
												</button>
											</div>
										</div>
									</div>
								</div>
							</template>
						</div>
					</div>
				</div>
			</div>

			<!-- Hidden form inputs -->
			<div style="display: none;">
				<template x-if="$store.referrals.rewards.advocate">
					<div>
						<input type="hidden" name="rewardswp_settings[referrals][rewards][advocate][name]" x-bind:value="$store.referrals.rewards.advocate.name">
						<input type="hidden" name="rewardswp_settings[referrals][rewards][advocate][type]" x-bind:value="$store.referrals.rewards.advocate.type">
						<input type="hidden" name="rewardswp_settings[referrals][rewards][advocate][reward_amount]" x-bind:value="$store.referrals.rewards.advocate.reward_amount">
						<input type="hidden" name="rewardswp_settings[referrals][rewards][advocate][minimum_order_amount]" x-bind:value="$store.referrals.rewards.advocate.minimum_order_amount || 0">
						<input type="hidden" name="rewardswp_settings[referrals][rewards][advocate][reward_expiration]" x-bind:value="$store.referrals.rewards.advocate.reward_expiration">
						<input type="hidden" name="rewardswp_settings[referrals][rewards][advocate][products_included]" x-bind:value="JSON.stringify($store.referrals.rewards.advocate.products_included || [])">
						<input type="hidden" name="rewardswp_settings[referrals][rewards][advocate][reward_description]" x-bind:value="$store.referrals.rewards.advocate.reward_description || ''">
						<input type="hidden" name="rewardswp_settings[referrals][rewards][advocate][redemption_limit]" x-bind:value="$store.referrals.rewards.advocate.redemption_limit || '1'">
					</div>
				</template>

				<template x-if="$store.referrals.rewards.friend">
					<div>
						<input type="hidden" name="rewardswp_settings[referrals][rewards][friend][name]" x-bind:value="$store.referrals.rewards.friend.name">
						<input type="hidden" name="rewardswp_settings[referrals][rewards][friend][type]" x-bind:value="$store.referrals.rewards.friend.type">
						<input type="hidden" name="rewardswp_settings[referrals][rewards][friend][reward_amount]" x-bind:value="$store.referrals.rewards.friend.reward_amount">
						<input type="hidden" name="rewardswp_settings[referrals][rewards][friend][minimum_order_amount]" x-bind:value="$store.referrals.rewards.friend.minimum_order_amount || 0">
						<input type="hidden" name="rewardswp_settings[referrals][rewards][friend][reward_expiration]" x-bind:value="$store.referrals.rewards.friend.reward_expiration">
						<input type="hidden" name="rewardswp_settings[referrals][rewards][friend][products_included]" x-bind:value="JSON.stringify($store.referrals.rewards.friend.products_included || [])">
						<input type="hidden" name="rewardswp_settings[referrals][rewards][friend][reward_description]" x-bind:value="$store.referrals.rewards.friend.reward_description || ''">
						<input type="hidden" name="rewardswp_settings[referrals][rewards][friend][redemption_limit]" x-bind:value="$store.referrals.rewards.friend.redemption_limit || '1'">
					</div>
				</template>
			</div>
		</div>

		<?php
		return ob_get_clean();
	}

	/**
	 * Get drawer content callback.
	 *
	 * @since 1.1.0
	 * @return callable
	 */
	public function get_drawer_content_callback(): callable {
		$reward_types_service = $this->reward_types_service;

		return function () use ( $reward_types_service ) {
			$reward_types = $reward_types_service->get_reward_types_data();
			$reward_types = $this->get_filtered_reward_types( $reward_types );

			// Filter out 'points' type for friend rewards - points are only for advocates.
			// We'll filter this dynamically in the template based on drawer.actionId.
			?>

		<div x-show="$store.drawer.type === 'referral'" class="relative h-full">

		<div x-show="$store.drawer.type === 'referral' && $store.drawer.view === 'list'">
			<div class="space-y-3"
				x-bind:class="{ 'blur-xs pointer-events-none': $store.drawer.isUpgrade && $store.drawer.actionId === 'friend' }"
				x-bind:inert="$store.drawer.isUpgrade && $store.drawer.actionId === 'friend'">
					<?php foreach ( $reward_types as $type => $reward_data ) : ?>
						<?php
						$feature_slug = $reward_data['feature_slug'] ?? '';
						// Map redeem_X to advocate_reward_X for advocate context.
						// e.g., 'redeem_free_product' -> 'advocate_reward_free_product'
						// e.g., 'redeem_fixed_discount' -> 'advocate_reward_fixed'
						// e.g., 'redeem_percentage_discount' -> 'advocate_reward_percentage'
						$advocate_feature_slug = str_replace( [ 'redeem_', '_discount' ], [ 'advocate_reward_', '' ], $feature_slug );
						?>
						<button type="button"
							x-show="!($store.drawer.actionId === 'friend' && '<?php echo esc_js( $type ); ?>' === 'points')"
							x-on:click="$dispatch('select-referral-reward', {
								rewardType: '<?php echo esc_js( $type ); ?>',
								rewardDefaults: <?php echo esc_attr( wp_json_encode( $reward_data['defaults'] ) ); ?>,
								featureSlug: '<?php echo esc_js( $feature_slug ); ?>'
							})"
							class="w-full text-left p-4 rounded-lg border border-gray-200 hover:bg-gray-50 cursor-pointer transition-all relative">

							<div class="flex items-start gap-4">
								<div class="flex-shrink-0 text-gray-700">
									<?php echo $reward_data['icon']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
								</div>
								<div class="flex-1">
									<h3 class="text-sm font-medium text-gray-900">
										<?php echo esc_html( $reward_data['title'] ); ?>
										<?php if ( ! empty( $advocate_feature_slug ) && ! can_access_rewardswp_feature( $advocate_feature_slug ) ) : ?>
											<span class="ml-2">
												<?php echo wp_kses( get_view_component( 'badge', [ 'style' => 'pro' ] ), kses() ); ?>
											</span>
										<?php endif; ?>
									</h3>
									<p class="mt-1 text-sm text-gray-500">
										<span x-show="$store.drawer.actionId === 'advocate'"><?php echo esc_html( $reward_data['advocate_title'] ); ?></span>
										<span x-show="$store.drawer.actionId === 'friend'"><?php echo esc_html( $reward_data['friend_title'] ); ?></span>
									</p>
								</div>
							</div>
						</button>
					<?php endforeach; ?>
				</div>
			</div>

		<!-- Referrals Config View -->
		<div x-show="$store.drawer.type === 'referral' && $store.drawer.view === 'config'">
			<template x-if="$store.drawer.selectedAction">
				<div>
					<!-- Back button for new rewards (OUTSIDE blurred div) -->
					<div x-show="$store.drawer.isNew" class="relative z-20 pb-3 border-b border-gray-200">
						<button
							x-on:click="$store.drawer.backToList()"
							class="inline-flex items-center text-sm text-gray-600 hover:text-gray-900">
							<svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
								<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
							</svg>
							<?php esc_html_e( 'Back to reward types', 'rewardswp' ); ?>
						</button>
					</div>

					<!-- Config fields -->
				<div x-bind:class="{
							'divide-y divide-gray-200': $store.drawer.selectedAction?.type !== 'points',
							'blur-xs pointer-events-none': $store.drawer.isUpgrade || ($store.drawer.selectedAction?.type === 'points' && !$store.referrals.pointsProgramEnabled)
						}"
						x-bind:inert="$store.drawer.isUpgrade || ($store.drawer.selectedAction?.type === 'points' && !$store.referrals.pointsProgramEnabled)">

					<!-- Reward Amount field -->
					<div class="py-5" x-show="$store.drawer.selectedAction?.type !== 'free_shipping' && $store.drawer.selectedAction?.type !== 'free_product'">
						<div class="gap-8 md:flex md:items-center">
							<div class="md:w-2/4 flex-none">
								<label class="text-sm font-medium text-gray-900">
									<span x-show="$store.drawer.selectedAction?.type === 'fixed_discount'"><?php esc_html_e( 'Discount amount', 'rewardswp' ); ?></span>
									<span x-show="$store.drawer.selectedAction?.type === 'percentage_discount'"><?php esc_html_e( 'Discount percentage', 'rewardswp' ); ?></span>
									<?php if ( false ) : ?>
									<span x-show="$store.drawer.selectedAction?.type === 'free_product'"><?php esc_html_e( 'Product value ($)', 'rewardswp' ); ?></span>
									<?php endif; ?>
									<span x-show="$store.drawer.selectedAction?.type === 'points'"><?php esc_html_e( 'Points amount', 'rewardswp' ); ?></span>
								</label>
								<p class="mt-1 text-xs text-gray-500">
									<?php esc_html_e( 'The value of the reward.', 'rewardswp' ); ?>
								</p>
							</div>
							<div class="md:w-2/4 min-w-0">
								<!-- Currency input for fixed_discount -->
								<div class="w-full min-w-0" x-show="$store.drawer.selectedAction?.type === 'fixed_discount'">
									<?php
									echo wp_kses(
										get_view_component(
											'amount',
											[
												'x-model' => '$store.drawer.selectedAction.reward_amount',
												'name'    => 'drawer_reward_amount',
												'type'    => 'currency',
												'placeholder' => '0',
											]
										),
										kses()
									);
									?>
								</div>
								<!-- Percentage input for percentage_discount -->
								<div class="w-full min-w-0" x-show="$store.drawer.selectedAction?.type === 'percentage_discount'">
									<?php
									echo wp_kses(
										get_view_component(
											'amount',
											[
												'x-model' => '$store.drawer.selectedAction.reward_amount',
												'name'    => 'drawer_reward_amount_percent',
												'type'    => 'percentage',
												'placeholder' => '0',
											]
										),
										kses()
									);
									?>
							</div>
						<!-- Points input -->
						<div class="w-full min-w-0" x-show="$store.drawer.selectedAction?.type === 'points'">
							<?php
							echo wp_kses(
								get_view_component(
									'number',
									[
										'x-model'       => '$store.drawer.selectedAction.reward_amount',
										'integers_only' => true,
										'min'           => '1',
										'width'         => 'w-full',
									]
								),
								kses()
							);
							?>
						</div>
						</div>
					</div>
				</div>

					<!-- Product Selection (Free Product only) -->
					<div class="py-5" x-show="$store.drawer.selectedAction?.type === 'free_product'">
						<div class="gap-8 md:flex md:items-start">
							<div class="md:w-2/4 flex-none">
								<label class="text-sm font-medium text-gray-900">
									<?php esc_html_e( 'Free product selection', 'rewardswp' ); ?>
								</label>
								<p class="mt-1 text-xs text-gray-500">
									<?php esc_html_e( 'Select the product that will be given for free with this reward.', 'rewardswp' ); ?>
								</p>
							</div>
							<div class="md:w-2/4 min-w-0">
								<div
									x-bind:class="{ 'ring-2 ring-red-500 rounded-md': $store.drawer._showProductError }"
									x-on:click="$store.drawer._showProductError = false"
								>
								<?php
								echo wp_kses(
									get_view_component(
										'choices',
										[
											'x-model'     => '$store.drawer.selectedAction.products_included',
											'selected_options' => '$store.drawer.selectedAction.products_included',
											'ajax_action' => 'rewardswp_search_products',
											'nonce'       => wp_create_nonce( 'rewardswp_searchable_nonce' ),
											'placeholder' => esc_html__( 'Search for a product...', 'rewardswp' ),
										]
									),
									kses()
								);
								?>
								</div>
								<p x-show="$store.drawer._showProductError" class="mt-1 text-sm text-red-500">
									<?php esc_html_e( 'Please select a product.', 'rewardswp' ); ?>
								</p>
							</div>
						</div>
					</div>

					<!-- Reward Description (Free Product only) -->
					<div class="py-5" x-show="$store.drawer.selectedAction?.type === 'free_product'">
						<div class="gap-8 md:flex md:items-start">
							<div class="md:w-2/4 flex-none">
								<label class="text-sm font-medium text-gray-900">
									<?php esc_html_e( 'Custom product name', 'rewardswp' ); ?>
									<span class="text-gray-400 font-normal"><?php esc_html_e( '(optional)', 'rewardswp' ); ?></span>
								</label>
								<p class="mt-1 text-xs text-gray-500">
									<?php esc_html_e( 'Show a different name to customers. Great for simplifying long product titles.', 'rewardswp' ); ?>
								</p>
							</div>
							<div class="md:w-2/4 min-w-0">
								<textarea
									x-model="$store.drawer.selectedAction.reward_description"
									rows="2"
									placeholder="<?php esc_attr_e( 'e.g., Premium Gift Box', 'rewardswp' ); ?>"
									class="block w-full rounded-md bg-white px-3 py-1.5 text-base text-gray-900 outline-1 -outline-offset-1 outline-gray-300 placeholder:text-gray-400 focus:outline-2 focus:-outline-offset-2 focus:outline-blue-600 sm:text-sm/6"
								></textarea>
							</div>
						</div>
					</div>

					<?php
				/*
				 * Redemption Limit: Hidden for Referral rewards.
				 *
				 * - Friend rewards: Already limited to 1 claim per visit/IP naturally.
				 * - Advocate rewards: Always unlimited to avoid frustrating advocates.
				 *
				 * The value is forced to 'unlimited' in the defaults.
				 */
				?>

					<!-- Minimum Spend -->
					<div class="py-5" x-show="$store.drawer.selectedAction?.type !== 'points'">
						<div class="gap-8 md:flex md:items-center">
							<div class="md:w-2/4 flex-none">
								<label class="text-sm font-medium text-gray-900">
									<?php esc_html_e( 'Minimum Spend', 'rewardswp' ); ?>
								</label>
								<p class="mt-1 text-xs text-gray-500">
									<?php esc_html_e( 'Calculated from your cart subtotal excluding the free product. Set to 0 for no minimum.', 'rewardswp' ); ?>
								</p>
							</div>
							<div class="md:w-2/4 min-w-0">
								<?php
								echo wp_kses(
									get_view_component(
										'amount',
										[
											'x-bind:value' => '($store.drawer.selectedAction.minimum_order_amount === 0 || $store.drawer.selectedAction.minimum_order_amount === null || $store.drawer.selectedAction.minimum_order_amount === \'\') ? \'\' : $store.drawer.selectedAction.minimum_order_amount',
											'x-on:input'  => '$store.drawer.selectedAction.minimum_order_amount = $event.target.value === \'\' ? \'\' : (parseFloat($event.target.value) || 0)',
											'name'        => 'drawer_minimum_order',
											'type'        => 'currency',
											'placeholder' => '0',
										]
									),
									kses()
								);
								?>
							</div>
						</div>

						<!-- Warning when friend Free Product reward has no minimum spend -->
						<div x-show="$store.drawer.selectedAction?.type === 'free_product' && $store.drawer.actionId === 'friend' && (!$store.drawer.selectedAction.minimum_order_amount || $store.drawer.selectedAction.minimum_order_amount == 0)"
							 x-cloak
							 class="mt-3 flex items-start gap-2 bg-amber-50 text-amber-800 px-3 py-2 rounded-md border border-amber-200">
							<?php echo wp_kses( $this->icon_helper->get_icon( 'warning', 'w-4 h-4 flex-shrink-0 mt-0.5' ), svg_kses() ); ?>
							<span class="text-xs">
								<?php esc_html_e( 'No minimum spend required. Friends can check out with only the free product in their cart.', 'rewardswp' ); ?>
							</span>
						</div>
					</div>

					<!-- Expiration -->
					<div class="py-5" x-show="$store.drawer.selectedAction?.type !== 'points'">
						<div class="gap-8 md:flex md:items-center">
							<div class="md:w-2/4 flex-none">
								<label class="text-sm font-medium text-gray-900 flex items-center gap-2">
									<?php esc_html_e( 'Reward expiry', 'rewardswp' ); ?>
									<?php
									echo wp_kses(
										get_view_component(
											'badge',
											[
												'style'  => 'pro',
												'x-show' => '$store.config.planTier === \'lite\' && !$store.drawer.isUpgrade',
											]
										),
										kses()
									);
									?>
								</label>
								<p class="mt-1 text-xs text-gray-500">
									<?php esc_html_e( 'Set rewards to expire after a certain time.', 'rewardswp' ); ?>
								</p>
							</div>
						<div class="md:w-2/4">
							<!-- Select dropdown (disabled for users without feature access) -->
							<div x-show="!$store.config.hasReferralRewardExpiration && !$store.drawer.isUpgrade">
								<?php
								echo wp_kses(
									get_view_component(
										'select',
										[
											'x-model'  => '$store.drawer.selectedAction.reward_expiration',
											'disabled' => true,
											'options'  => [
												'never'    => esc_html__( 'Never expires', 'rewardswp' ),
												'+30 days' => esc_html__( '30 days', 'rewardswp' ),
												'+3 months' => esc_html__( '3 months', 'rewardswp' ),
												'+6 months' => esc_html__( '6 months', 'rewardswp' ),
												'+1 year'  => esc_html__( '1 year', 'rewardswp' ),
												'+2 years' => esc_html__( '2 years', 'rewardswp' ),
											],
										]
									),
									kses()
								);
								?>
							</div>

							<!-- Select dropdown (enabled for users with feature access) -->
							<div x-show="$store.config.hasReferralRewardExpiration || $store.drawer.isUpgrade">
								<?php
								echo wp_kses(
									get_view_component(
										'select',
										[
											'x-model'  => '$store.drawer.selectedAction.reward_expiration',
											'disabled' => false,
											'options'  => [
												'never'    => esc_html__( 'Never expires', 'rewardswp' ),
												'+30 days' => esc_html__( '30 days', 'rewardswp' ),
												'+3 months' => esc_html__( '3 months', 'rewardswp' ),
												'+6 months' => esc_html__( '6 months', 'rewardswp' ),
												'+1 year'  => esc_html__( '1 year', 'rewardswp' ),
												'+2 years' => esc_html__( '2 years', 'rewardswp' ),
											],
										]
									),
									kses()
								);
								?>
							</div>

							<!-- Upgrade link for users without feature access (below the select) -->
							<a x-show="!$store.config.hasReferralRewardExpiration && !$store.drawer.isUpgrade"
								x-bind:href="'<?php echo get_upgrade_url( '', 'drawer' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- JS context; esc_url() encodes & as &amp; ?>' + '&utm_content=referral_' + ($store.drawer.actionId || 'unknown') + '_expiry'"
								target="_blank"
								class="inline-flex items-center text-sm text-blue-600 hover:text-blue-700 mt-2">
							<?php esc_html_e( 'Upgrade for custom expiry', 'rewardswp' ); ?>
							<svg class="ml-1 w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
								<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
							</svg>
							</a>
						</div>
						</div>
					</div>
				</div>
			</template>

			<!-- Points Program Requirement Overlay -->
			<?php
			echo wp_kses(
				get_view_component(
					'drawer-requirement',
					[
						'icon_name' => 'reward-points',
						'x_show'    => "\$store.drawer.selectedAction?.type === 'points' && !\$store.referrals.pointsProgramEnabled",
						'messages'  => [
							[
								'condition'    => 'true',
								'title'        => __( 'Enable Points to Reward with Points', 'rewardswp' ),
								'description'  => __( 'To pay referral rewards in points, you need to enable the points program first.', 'rewardswp' ),
								'button_text'  => __( 'Go to Points Settings', 'rewardswp' ),
								'button_click' => "Alpine.store('drawer').close(); window.location.href = 'admin.php?page=rewardswp-settings&tab=points#points-status'",
							],
						],
					]
				),
				kses()
			);
			?>
		</div>

				<!-- Friend Rewards Upsell (entire context, but NOT for free_product which has its own overlay) -->
				<?php
				// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Component handles its own sanitization
				echo get_view_component(
					'upgrade-overlay',
					[
						'icon_name'    => 'gift',
						'title'        => __( 'Friend rewards', 'rewardswp' ),
						'description'  => __( 'Reward referred customers on their first purchase to help drive new sales.', 'rewardswp' ),
						'features'     => [
							__( 'Fixed amount discounts', 'rewardswp' ),
							__( 'Percentage discounts', 'rewardswp' ),
							__( 'Free shipping', 'rewardswp' ),
						// TODO: Add free products when feature is fully implemented.
						// __( 'Free products', 'rewardswp' ),
						],
						'feature_slug' => 'friend_reward',
						'feature_name' => __( 'Friend Reward', 'rewardswp' ),
						'overlay'      => true,
						'x_show'       => '$store.drawer.type === \'referral\' && $store.drawer.isUpgrade && $store.drawer.actionId === \'friend\' && $store.referrals.friendRequiresPro && $store.drawer.selectedAction?.type !== \'free_product\'',
					]
				);
				?>

				<!-- Advocate Reward Type Upsells (plan-gated reward types for advocate context) -->
				<?php
				// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Component handles its own sanitization
				echo get_view_component(
					'upgrade-overlay',
					[
						'icon_name'    => 'reward-percentage-coupon',
						'title'        => __( 'Percentage Discount rewards', 'rewardswp' ),
						'description'  => __( 'Reward advocates with a percentage discount when they refer a new customer.', 'rewardswp' ),
						'feature_slug' => 'advocate_reward_percentage',
						'feature_name' => __( 'Percentage Discount', 'rewardswp' ),
						'overlay'      => true,
						'x_show'       => '$store.drawer.type === \'referral\' && $store.drawer.isUpgrade && $store.drawer.selectedAction?.type === \'percentage_discount\'',
					]
				);

				// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Component handles its own sanitization
				echo get_view_component(
					'upgrade-overlay',
					[
						'icon_name'    => 'reward-free-shipping',
						'title'        => __( 'Free Shipping rewards', 'rewardswp' ),
						'description'  => __( 'Reward referrals with free shipping coupons.', 'rewardswp' ),
						'feature_slug' => 'advocate_reward_free_shipping',
						'feature_name' => __( 'Free Shipping', 'rewardswp' ),
						'overlay'      => true,
						'x_show'       => '$store.drawer.type === \'referral\' && $store.drawer.isUpgrade && $store.drawer.selectedAction?.type === \'free_shipping\'',
					]
				);
				?>

				<!-- Free Product Overlay (Pro-only reward type, works for both advocate and friend) -->
				<?php
				// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Component handles its own sanitization
				echo get_view_component(
					'upgrade-overlay',
					[
						'icon_name'    => 'reward-free-product',
						'title'        => __( 'Free Product rewards', 'rewardswp' ),
						'description'  => __( 'Reward referrals with free product coupons.', 'rewardswp' ),
						'feature_slug' => 'advocate_reward_free_product',
						'feature_name' => __( 'Free Product', 'rewardswp' ),
						'overlay'      => true,
						'x_show'       => '$store.drawer.type === \'referral\' && $store.drawer.isUpgrade && $store.drawer.selectedAction?.type === \'free_product\'',
					]
				);

				// Points Overlay (Pro-only reward type for advocate).
				// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Component handles its own sanitization
				echo get_view_component(
					'upgrade-overlay',
					[
						'icon_name'    => 'reward-points',
						'title'        => __( 'Points rewards', 'rewardswp' ),
						'description'  => __( 'Reward advocates with bonus points when they refer a new customer.', 'rewardswp' ),
						'feature_slug' => 'advocate_reward_points',
						'feature_name' => __( 'Points', 'rewardswp' ),
						'overlay'      => true,
						'x_show'       => '$store.drawer.type === \'referral\' && $store.drawer.isUpgrade && $store.drawer.selectedAction?.type === \'points\'',
					]
				);
				?>

			</div>

			<?php
		};
	}
}
