<?php
/**
 * Upgrade overlay component view.
 *
 * @package Awesomemotive\Rewardswp\Views\Admin\Components
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Views\Admin\Components;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractView;
use Awesomemotive\Rewardswp\Helpers\IconHelper;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use function Awesomemotive\Rewardswp\Helpers\get_minimum_required_plan_for_feature;
use function Awesomemotive\Rewardswp\Helpers\get_required_plans_for_feature;
use function Awesomemotive\Rewardswp\Helpers\get_upgrade_upsell_data;
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\tag_attr;

/**
 * Upgrade Overlay Component
 *
 * Displays a centered overlay card prompting users to upgrade to access a PRO feature.
 * Used for feature gating across earn actions, spend actions, and other PRO features.
 *
 * @since 1.1.0
 */
class UpgradeOverlayComponentView extends AbstractView implements ViewInterface {

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

	/**
	 * Constructor.
	 *
	 * @since 1.1.0
	 * @param IconHelper $icon_helper Icon helper instance.
	 */
	public function __construct( IconHelper $icon_helper ) {
		$this->icon_helper = $icon_helper;
	}

	/**
	 * Render the upgrade overlay component.
	 *
	 * @since 1.1.0
	 *
	 * @param array $args {
	 *     Component arguments.
	 *
	 *     @type string $icon_name      Icon name to display (e.g., 'earn-purchase'). Optional.
	 *     @type string $title          Heading text for the overlay. Required.
	 *     @type string $description    Body text explaining the feature. Required.
	 *     @type array  $features       Array of feature strings to display with checkmarks. Optional.
	 *     @type string $feature_slug   Feature slug for upgrade URL tracking (e.g., 'earn_on_purchase'). Required.
	 *     @type string $feature_name   Human-readable feature name for button text (e.g., 'Free Shipping'). Optional.
	 *     @type array  $required_plans Array of plan names required for this feature. Auto-derived from feature_slug if not provided.
	 *     @type string $location       Location context for tracking. Default 'drawer'.
	 *     @type string $x_show         Alpine.js x-show condition. Optional.
	 *     @type array  $button         Button configuration array. Supports 'text' and 'full_width' keys.
	 *     @type bool   $overlay        Whether to use absolute positioning to overlay content. Default false.
	 *     @type string $size           Card size: 'default' or 'sm'. Default 'default'.
	 * }
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		$args = wp_parse_args(
			$args,
			[
				'icon_name'    => '',
				'title'        => '',
				'description'  => '',
				'features'     => [],
				'feature_slug' => '',
				'location'     => 'drawer',
				'x_show'       => '',
				'button'       => [],
				'overlay'      => false, // Whether to use absolute positioning to overlay content.
				'size'         => 'default', // 'default' or 'sm'.
			]
		);

		// Get required plans from feature_slug if not explicitly provided.
		if ( empty( $args['required_plans'] ) && ! empty( $args['feature_slug'] ) ) {
			$args['required_plans'] = get_required_plans_for_feature( $args['feature_slug'] );
		}

		// Build button text: "Upgrade to {min_plan}" or fallback to "Upgrade Now".
		$button_text = ! empty( $args['feature_slug'] )
			/* translators: %s: Minimum required plan name (e.g., Plus, Pro) */
			? sprintf( esc_html__( 'Upgrade to %s', 'rewardswp' ), get_minimum_required_plan_for_feature( $args['feature_slug'] ) )
			: esc_html__( 'Upgrade Now', 'rewardswp' );

		// Merge button defaults.
		$args['button'] = wp_parse_args(
			$args['button'],
			[
				'text'       => $button_text,
				'full_width' => true,
			]
		);

		// Validate required fields.
		if ( empty( $args['title'] ) || empty( $args['description'] ) || empty( $args['feature_slug'] ) ) {
			return;
		}

		// Build x-show attribute if provided.
		$x_show_attr = tag_attr( 'x-show', $args['x_show'], true, false );

		// Build wrapper classes based on mode.
		$wrapper_classes = $args['overlay']
			? 'absolute inset-0 flex items-center justify-center p-6 z-10'
			: 'flex items-center justify-center h-full p-6';

		// Build card classes based on size.
		$card_classes = 'sm' === $args['size']
			? 'bg-white rounded-2xl shadow-xl px-10 py-8 max-w-md w-full ring-1 ring-gray-300/50'
			: 'bg-white rounded-lg shadow-2xl p-8 max-w-md w-full ring-1 ring-gray-300/50';
		?>
		<!-- Upgrade Overlay Card -->
		<div <?php echo $x_show_attr; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?> class="<?php echo esc_attr( $wrapper_classes ); ?>">
			<div class="<?php echo esc_attr( $card_classes ); ?>">
				<?php $this->render_card_content( $args ); ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Render the card content (shared between both rendering modes).
	 *
	 * @since 1.1.0
	 * @param array $args Component arguments.
	 * @return void
	 */
	private function render_card_content( array $args ): void {
		$is_small = 'sm' === $args['size'];

		// Get centralized upsell data.
		$upsell_data = get_upgrade_upsell_data( $args['feature_slug'], $args['location'] );

		// Size-based classes.
		$title_classes       = $is_small ? 'text-lg font-semibold text-gray-900 mb-3' : 'text-xl font-semibold text-gray-900 mb-3';
		$description_classes = $is_small ? 'text-slate-600 mb-4 text-pretty' : 'text-gray-600 mb-6 text-pretty';
		$button_size         = $is_small ? 'md' : 'xl';
		$button_classes      = '';
		if ( $args['button']['full_width'] ) {
			$button_classes .= ' w-full';
		}
		?>
	<div class="text-center text-base">
		<?php if ( ! empty( $args['icon_name'] ) ) : ?>
		<!-- Icon -->
		<div class="mx-auto flex items-center justify-center mb-4 text-gray-700">
			<span class="[&>svg]:size-12">
				<?php echo wp_kses( $this->icon_helper->get_icon( $args['icon_name'], 'size-12' ), svg_kses() ); ?>
			</span>
		</div>
		<?php endif; ?>

		<!-- Title -->
		<h3 class="<?php echo esc_attr( $title_classes ); ?>">
			<?php echo esc_html( $args['title'] ); ?>
		</h3>

		<!-- Description -->
		<p class="<?php echo esc_attr( $description_classes ); ?>">
			<?php echo esc_html( $args['description'] ); ?>
		</p>

		<!-- Features List -->
		<?php if ( ! empty( $args['features'] ) && is_array( $args['features'] ) ) : ?>
		<ul class="text-left space-y-2 mb-6">
			<?php foreach ( $args['features'] as $feature ) : ?>
			<li class="flex items-start gap-3">
				<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="flex-shrink-0 text-green-500 size-5 mt-0.5"><path d="M21.801 10A10 10 0 1 1 17 3.335"></path><path d="m9 11 3 3L22 4"></path></svg>
				<span class="text-gray-700"><?php echo esc_html( $feature ); ?></span>
			</li>
			<?php endforeach; ?>
		</ul>
		<?php endif; ?>

		<!-- Plan Requirement Notice -->
		<?php if ( ! empty( $args['feature_slug'] ) ) : ?>
		<p class="text-sm text-gray-500 mb-4">
			<?php
			// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- HTML is escaped in get_upgrade_upsell_data().
			echo $upsell_data['required_plan'];
			?>
		</p>
		<?php endif; ?>

		<!-- Upgrade Button -->
		<?php
		echo wp_kses(
			get_view_component(
				'button',
				[
					'text'               => $args['button']['text'],
					'type'               => 'anchor',
					'href'               => $upsell_data['button_url'],
					'size'               => $button_size,
					'additional_classes' => trim( $button_classes ),
				]
			),
			kses()
		);
		?>

		<!-- Compare Plans Link -->
		<?php if ( ! empty( $args['feature_slug'] ) ) : ?>
		<div class="mt-3">
			<a href="<?php echo esc_url( $upsell_data['compare_url'] ); ?>"
				target="_blank"
				rel="noopener noreferrer"
				class="text-sm text-gray-500 hover:text-gray-700 hover:underline hover:underline-offset-4">
				<?php esc_html_e( 'Compare plans', 'rewardswp' ); ?>
			</a>
		</div>
		<?php endif; ?>
	</div>
		<?php
	}
}
