<?php
/**
 * Reports view for admin interface.
 *
 * @package Awesomemotive\Rewardswp\Views\Admin
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Views\Admin;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractView;
use Awesomemotive\Rewardswp\Factories\ViewsFactory;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use Awesomemotive\Rewardswp\Helpers\IconHelper;
use Awesomemotive\Rewardswp\Services\DashboardService;
use Awesomemotive\Rewardswp\Views\Admin\Parts\ExportDrawerView;
use Awesomemotive\Rewardswp\Views\Admin\Components\DrawerComponentView;
use Awesomemotive\Rewardswp\Views\Admin\Components\BadgeComponentView;
use Awesomemotive\Rewardswp\Views\Admin\Components\UpgradeOverlayComponentView;
use Awesomemotive\Rewardswp\Views\Admin\Components\ChartEmptyStateComponentView;
use function Awesomemotive\Rewardswp\Helpers\svg_kses;
use function Awesomemotive\Rewardswp\Helpers\is_rewardswp_pro_plan;
use function Awesomemotive\Rewardswp\Helpers\get_rewardswp_plan_tier;
use function Awesomemotive\Rewardswp\Helpers\get_upgrade_url;
use function Awesomemotive\Rewardswp\Helpers\tooltip;
use function Awesomemotive\Rewardswp\Helpers\can_access_rewardswp_feature;
use function Awesomemotive\Rewardswp\Helpers\get_minimum_required_plan_for_feature;
use function Awesomemotive\Rewardswp\Helpers\get_view_component;
use function Awesomemotive\Rewardswp\Helpers\kses;
use function Awesomemotive\Rewardswp\Helpers\get_site_currency_symbol;
use function Awesomemotive\Rewardswp\Helpers\format_currency;

class ReportsView extends AbstractView implements ViewInterface {
	private IconHelper $icon_helper;
	private DashboardService $dashboard_service;
	private ViewsFactory $views_factory;

	public function __construct( IconHelper $icon_helper, DashboardService $dashboard_service, ViewsFactory $views_factory ) {
		$this->icon_helper       = $icon_helper;
		$this->dashboard_service = $dashboard_service;
		$this->views_factory     = $views_factory;
	}

	/**
	 * Get the store timezone in a human-readable format.
	 *
	 * @since 1.0.0
	 *
	 * @return string Formatted timezone string.
	 */
	private function get_formatted_timezone(): string {
		$timezone = wp_timezone();
		$now      = new \DateTime( 'now', $timezone );

		$location = $timezone->getName();
		if ( strpos( $location, '/' ) !== false ) {
			$location = str_replace( '_', ' ', substr( $location, strrpos( $location, '/' ) + 1 ) );
		}

		$abbreviation = $now->format( 'T' );

		return sprintf( '%s (%s)', $location, $abbreviation );
	}

	public function render( array $args = [] ): void {
		// Get current plan for date range config.
		$current_plan      = get_rewardswp_plan_tier();
		$date_range_config = $this->dashboard_service->get_date_range_config( $current_plan );

		// Sanitize and validate range parameter.
		$range_raw      = filter_input( INPUT_GET, 'range', FILTER_UNSAFE_RAW );
		$range_param    = is_string( $range_raw ) ? sanitize_text_field( wp_unslash( $range_raw ) ) : '';
		$allowed_ranges = array_keys( $this->dashboard_service->get_date_ranges() );
		$selected_range = in_array( $range_param, $allowed_ranges, true ) ? $range_param : $date_range_config['default'];

		// Get active tab from URL or default to 'overview'.
		$tab_raw    = filter_input( INPUT_GET, 'tab', FILTER_UNSAFE_RAW );
		$tab_param  = is_string( $tab_raw ) ? sanitize_text_field( wp_unslash( $tab_raw ) ) : '';
		$active_tab = 'export' === $tab_param ? 'export' : 'overview';

		// Get KPI data for the selected range.
		$kpi_data     = $this->dashboard_service->get_kpi_data( $selected_range );
		$revenue_data = $kpi_data['rewards-applied-revenue'] ?? [];

		// Aggregate sparkline data based on granularity (daily/weekly/monthly).
		$chart_data  = $this->dashboard_service->aggregate_sparkline_for_reports(
			$revenue_data['sparkline'] ?? [],
			$selected_range
		);
		$granularity = $this->dashboard_service->get_granularity_for_range( $selected_range );

		// Member growth data.
		$member_growth_data       = $this->dashboard_service->get_member_growth_data( $selected_range );
		$member_growth_chart_data = $this->dashboard_service->aggregate_member_growth_for_reports(
			$member_growth_data['sparkline'] ?? [],
			$selected_range
		);

		// Orders using rewards data (Basic+ only, via feature matrix).
		$show_orders_chart          = can_access_rewardswp_feature( 'orders_using_rewards_chart' );
		$orders_using_rewards_data  = [];
		$orders_using_rewards_chart = [];
		if ( $show_orders_chart ) {
			$orders_using_rewards_data  = $this->dashboard_service->get_orders_using_rewards_data( $selected_range );
			$orders_using_rewards_chart = $this->dashboard_service->aggregate_orders_using_rewards_for_reports(
				$orders_using_rewards_data['sparkline'] ?? [],
				$selected_range
			);
		}

		// Get KPI definitions for tooltip text.
		$kpi_definitions = $this->dashboard_service->get_kpi_definitions();
		$revenue_kpi_def = $kpi_definitions['rewards-applied-revenue'] ?? [];

		$args = wp_parse_args(
			$args,
			[
				'page_title' => esc_html__( 'Reports', 'rewardswp' ),
			]
		);
		?>

		<div x-data="{ activeTab: '<?php echo esc_js( $active_tab ); ?>', dateRangeOpen: false, setActiveTab(tab) { this.activeTab = tab; } }">

			<div
				class="rewardswp-container max-[782px]:ml-[-10px] ml-[-20px]"
			>

				<?php
				/**
				 * Reports navigation.
				 */
				$tabs = [
					'overview' => [
						'label'    => esc_html__( 'Overview', 'rewardswp' ),
						'href'     => '#overview',
						'pro_only' => false,
					],
					'export'   => [
						'label'    => esc_html__( 'Export', 'rewardswp' ),
						'href'     => '#export',
						'pro_only' => false,
					],
				];

				$common_classes   = 'px-4 py-5 text-sm whitespace-nowrap focus:outline-none focus:border-b-2 focus:border-blue-500';
				$active_classes   = 'text-blue-600 border-b-2 border-blue-500 ';
				$inactive_classes = 'text-gray-800 hover:text-gray-600';

				$store_timezone = $this->get_formatted_timezone();
				?>
				<div id="rewardswp-admin-settings-sentinel" class="absolute top-0 left-0 right-0"></div>


				<div class="px-8 pt-5 mx-auto max-w-7xl sr-only">
					<div class="mb-6 flex flex-col gap-4 md:flex-row md:items-start md:justify-between">
						<h1 class="text-2xl font-semibold text-slate-900"><?php echo esc_html( $args['page_title'] ); ?></h1>
					</div>
				</div>

				<div id="rewardswp-admin-settings-header" class="transition-shadow duration-250 shadow-gray-800/10 sticky max-[601px]:top-0 max-[783px]:top-[46px] top-[32px] bg-[#f0f0f1] z-10 border-b border-gray-300">
					<div class="px-8 flex justify-between items-center mx-auto max-w-7xl">
						<nav class="flex font-semibold overflow-x-auto scrollbar" aria-label="<?php esc_attr_e( 'Tabs', 'rewardswp' ); ?>">
							<?php foreach ( $tabs as $tab_key => $tab ) : ?>
								<?php
								if ( $tab['pro_only'] && ! is_rewardswp_pro_plan() ) {
									continue;
								}
								$tab_url = add_query_arg(
									[
										'page'  => 'rewardswp-reports',
										'tab'   => $tab_key,
										'range' => $selected_range,
									],
									admin_url( 'admin.php' )
								);
								?>
								<a
									x-on:click.prevent="setActiveTab( '<?php echo esc_js( $tab_key ); ?>' ); history.pushState(null, '', '<?php echo esc_js( $tab_url ); ?>')"
									x-bind:class="{ '<?php echo esc_attr( $active_classes ); ?>': activeTab === '<?php echo esc_js( $tab_key ); ?>', '<?php echo esc_attr( $inactive_classes ); ?>': activeTab !== '<?php echo esc_js( $tab_key ); ?>' }"
									href="<?php echo esc_url( $tab_url ); ?>"
									class="<?php echo esc_attr( $common_classes ); ?>"
								>
									<?php echo esc_html( $tab['label'] ); ?>
									<?php if ( 'export' === $tab_key && ! can_access_rewardswp_feature( 'exports' ) ) : ?>
										<?php echo wp_kses( get_view_component( 'badge', [ 'style' => 'pro' ] ), kses() ); ?>
									<?php endif; ?>
								</a>
							<?php endforeach; ?>
						</nav>

						<!-- Global Date Range Picker -->
						<?php if ( $date_range_config['show_picker'] ) : ?>
							<div class="flex items-center gap-3">
								<span class="text-sm text-gray-500"><?php echo esc_html( $store_timezone ); ?></span>
								<div class="relative inline-block text-left">
									<button type="button"
										x-on:click="dateRangeOpen = !dateRangeOpen"
										class="cursor-pointer inline-flex items-center justify-center w-full px-3 py-1.5 text-sm font-medium text-gray-700 bg-white border border-gray-200 rounded-md hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
										<?php echo esc_html( $this->dashboard_service->get_date_ranges()[ $selected_range ]['label'] ?? __( 'Last 30 days', 'rewardswp' ) ); ?>
										<?php echo wp_kses( $this->icon_helper->get_icon( 'chevron-down', 'w-4 h-4 ml-2' ), svg_kses() ); ?>
									</button>

									<div x-show="dateRangeOpen"
										x-cloak
										x-on:click.outside="dateRangeOpen = false"
										x-transition
										class="absolute right-0 z-10 mt-1 w-40 origin-top-right rounded-md bg-white border border-gray-200 shadow-lg">
										<div class="p-1">
											<?php
											foreach ( $date_range_config['ranges'] as $range_key ) :
												$range_data = $this->dashboard_service->get_date_ranges()[ $range_key ];
												$base_url   = add_query_arg(
													[
														'page'  => 'rewardswp-reports',
														'range' => $range_key,
													],
													admin_url( 'admin.php' )
												);
												?>
												<a href="<?php echo esc_url( $base_url ); ?>"
													x-on:click.prevent="window.location.href = '<?php echo esc_js( $base_url ); ?>' + '&tab=' + activeTab"
													class="cursor-pointer block px-3 py-2 text-sm text-gray-700 rounded-md hover:bg-gray-100 <?php echo $selected_range === $range_key ? 'bg-gray-50 font-medium' : ''; ?>">
													<?php echo esc_html( $range_data['label'] ); ?>
												</a>
											<?php endforeach; ?>
										</div>
									</div>
								</div>
							</div>
						<?php else : ?>
							<div class="flex items-center gap-2 text-sm text-gray-500">
								<span><?php echo esc_html( $store_timezone ); ?></span>
								<span class="text-gray-400">·</span>
								<span><?php echo esc_html( __( 'Last 30 days', 'rewardswp' ) ); ?></span>
							</div>
						<?php endif; ?>

					</div>
				</div>

				<!-- Overview Tab Content -->
				<div class="px-8 pt-5 mx-auto max-w-7xl" x-show="activeTab === 'overview'">

					<!-- Rewards-applied Revenue Chart -->
					<div class="bg-white border border-gray-900/8 rounded-xl p-6 h-full flex flex-col min-h-[250px]">
						<div class="mb-6">
							<p class="text-lg text-gray-900 inline-block border-b border-dashed border-gray-300 cursor-help mb-4"
								data-tippy-content="
								<?php
								echo esc_attr(
									tooltip(
										[
											'<strong>' . __( 'Revenue influenced by RewardsWP', 'rewardswp' ) . '</strong>',
											__( 'Net sales from orders that used a RewardsWP incentive (points redemption or referral reward), excluding tax & shipping. Refunds in this period are subtracted.', 'rewardswp' ),
											'<strong>' . __( 'Why it matters', 'rewardswp' ) . '</strong>',
											__( 'This is the clearest $ value showing how much your rewards and referrals are driving sales.', 'rewardswp' ),
										],
									)
								);
								?>
								"
								data-tippy-allowhtml="true"><?php esc_html_e( 'Rewards-applied revenue', 'rewardswp' ); ?></p>
							<p class="text-3xl font-bold text-gray-900"><?php echo wp_kses_post( $revenue_data['value_html'] ?? format_currency( 0 ) ); ?></p>
							<p class="text-sm text-gray-500 mt-1">
								<?php echo esc_html( $this->dashboard_service->get_date_ranges()[ $selected_range ]['label'] ?? __( 'Last 30 days', 'rewardswp' ) ); ?>
								<?php if ( ! empty( $revenue_data['delta'] ) ) : ?>
									<span class="text-gray-400 mx-1">·</span>
									<span class="<?php echo esc_attr( $revenue_data['delta_class'] ?? 'text-gray-500' ); ?>"><?php echo esc_html( $revenue_data['delta'] ); ?></span>
									<?php esc_html_e( 'vs previous period', 'rewardswp' ); ?>
								<?php endif; ?>
							</p>
						</div>
						<div class="relative">
							<div id="revenue-chart" class="preserve-styles"
								data-chart-data="<?php echo esc_attr( wp_json_encode( $chart_data ) ); ?>"
								data-granularity="<?php echo esc_attr( $granularity ); ?>">
							</div>
							<?php if ( count( $chart_data ) < 2 ) : ?>
								<?php
								$this->views_factory->get_view( ChartEmptyStateComponentView::class )->render(
									[
										'overlay' => true,
									]
								);
								?>
							<?php endif; ?>
						</div>
					</div>

					<script>
					var rewardswpCurrencySymbol = '<?php echo esc_js( get_site_currency_symbol() ); ?>';
					var rewardswpCurrencyDecimals = <?php echo esc_js( \Awesomemotive\Rewardswp\Helpers\get_currency_format( \Awesomemotive\Rewardswp\Helpers\get_site_currency() )['decimals'] ); ?>;
					<?php $rwp_currency_position = \Awesomemotive\Rewardswp\Helpers\get_currency_position(); ?>
					var rewardswpCurrencyAfter = <?php echo ( 'after' === ( $rwp_currency_position['position'] ?? 'before' ) ) ? 'true' : 'false'; ?>;
					var rewardswpCurrencySpace = <?php echo ! empty( $rwp_currency_position['space'] ) ? 'true' : 'false'; ?>;
					// Assemble a symbol and amount honoring the store's currency position (e.g. "5 €" vs "€5").
					function rewardswpMoney( amount ) {
						var sep = rewardswpCurrencySpace ? ' ' : '';
						return rewardswpCurrencyAfter
							? amount + sep + rewardswpCurrencySymbol
							: rewardswpCurrencySymbol + sep + amount;
					}
					document.addEventListener('DOMContentLoaded', function() {
						var chartContainer = document.querySelector("#revenue-chart");
						if (!chartContainer) return;

						var chartData = [];
						try {
							chartData = JSON.parse(chartContainer.dataset.chartData || '[]');
						} catch (e) {
							console.error('Failed to parse chart data:', e);
						}

						var granularity = chartContainer.dataset.granularity || 'daily';

						// For weekly/monthly, use category x-axis with pre-formatted labels.
						// For daily, use datetime x-axis.
						var useCategories = (granularity === 'weekly' || granularity === 'monthly');
						var categories = [];
						var seriesData = [];

						if (useCategories) {
							// Extract labels and full data objects for category x-axis.
							// Keep refunds data for custom tooltip.
							chartData.forEach(function(point) {
								var date = new Date(point.x);
								var label;
								if (granularity === 'weekly') {
									label = date.toLocaleDateString('en-US', { day: 'numeric', month: 'short' });
								} else {
									label = date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
								}
								categories.push(label);
								seriesData.push({
								x: label,
								y: point.y,
								refunds: point.refunds || 0,
								date: granularity === 'weekly' ? 'Week of ' + label : label
							});
						});
						} else {
							// Daily: use {x, y} format with timestamps, add formatted date for tooltip.
							seriesData = chartData.map(function(point) {
								var date = new Date(point.x);
								return {
									x: point.x,
									y: point.y,
									refunds: point.refunds || 0,
									date: date.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })
								};
							});
						}

						// Custom tooltip function for rich HTML display matching dashboard style.
						var customTooltip = function({series, seriesIndex, dataPointIndex, w}) {
							var dataPoint = w.globals.initialSeries[seriesIndex].data[dataPointIndex];
							var revenue = dataPoint.y;
							var refunds = dataPoint.refunds || 0;
							var dateLabel = dataPoint.date;
							var refundLabel = granularity === 'weekly' ? 'Refunds posted this week' : (granularity === 'monthly' ? 'Refunds posted this month' : 'Refunds posted today');

							return '<div class="apexcharts-tooltip-custom min-w-3xs">' +
								'<div class="px-3 py-2 bg-white">' +
								'<div class="text-xs text-gray-600 mb-1">' + dateLabel + '</div>' +
								'<div class="text-sm font-semibold text-gray-900 mb-0.5">' + rewardswpMoney(revenue.toLocaleString('en-US', {minimumFractionDigits: rewardswpCurrencyDecimals, maximumFractionDigits: rewardswpCurrencyDecimals})) + '</div>' +
								'<div class="text-xs text-gray-600 mb-0.5">' + refundLabel + ': ' + rewardswpMoney(refunds.toLocaleString('en-US', {minimumFractionDigits: rewardswpCurrencyDecimals, maximumFractionDigits: rewardswpCurrencyDecimals})) + '</div>' +
								'<div class="text-xs text-gray-500"><?php echo esc_js( __( 'Net excl. tax & shipping', 'rewardswp' ) ); ?></div>' +
								'</div>' +
								'</div>';
						};

						var chartOptions = {
							series: [{
								name: '<?php echo esc_js( __( 'Revenue', 'rewardswp' ) ); ?>',
								data: seriesData
							}],
							chart: {
								type: 'area',
								height: 200,
								animations: {
									enabled: chartData.length >= 2
								},
								toolbar: {
									show: false
								},
								zoom: {
									enabled: true,
									type: 'x',
									autoScaleYaxis: true
								},
								dropShadow: {
									enabled: false
								}
							},
							dataLabels: {
								enabled: false
							},
							stroke: {
								curve: 'smooth',
								width: 2
							},
							fill: {
								type: 'gradient',
								gradient: {
									shadeIntensity: 1,
									opacityFrom: 0.4,
									opacityTo: 0.1,
									stops: [0, 100]
								}
							},
							colors: ['#3B82F6'],
							xaxis: useCategories ? {
								type: 'category',
								categories: categories,
								labels: {
									style: {
										colors: '#9CA3AF',
										fontSize: '11px'
									},
									rotate: 0,
									hideOverlappingLabels: true
								},
								axisBorder: {
									show: false
								},
								axisTicks: {
									show: false
								},
								tooltip: {
									enabled: false
								}
							} : {
								type: 'datetime',
								labels: {
									style: {
										colors: '#9CA3AF',
										fontSize: '11px'
									},
									datetimeUTC: false,
									format: 'dd MMM',
									rotate: 0,
									hideOverlappingLabels: true
								},
								tickAmount: 6,
								axisBorder: {
									show: false
								},
								axisTicks: {
									show: false
								},
								tooltip: {
									enabled: false
								}
							},
							yaxis: {
								labels: {
									style: {
										colors: '#9CA3AF',
										fontSize: '11px'
									},
									formatter: function(value) {
										if (value >= 1000) {
											return rewardswpMoney((value / 1000).toFixed(1) + 'k');
										}
										return rewardswpMoney(value.toFixed(0));
									}
								},
								tickAmount: 4
							},
							grid: {
								borderColor: '#E5E7EB',
								strokeDashArray: 4,
								xaxis: {
									lines: {
										show: false
									}
								}
							},
							tooltip: {
								enabled: true,
								custom: customTooltip
							}
						};

						var revenueChart = null;
						if (typeof ApexCharts !== 'undefined' && chartData.length > 0) {
							// Add double-click to reset zoom
							chartOptions.chart.events = {
								click: function(event) {
									if (event.detail === 2 && revenueChart) {
										revenueChart.resetSeries();
									}
								}
							};
							revenueChart = new ApexCharts(chartContainer, chartOptions);
							revenueChart.render();
						}
					});
					</script>

					<!-- Member Growth Chart -->
					<div class="bg-white border border-gray-900/8 rounded-xl p-6 h-full flex flex-col mt-6">
						<div class="mb-6">
							<p class="text-lg text-gray-900 inline-block border-b border-dashed border-gray-300 cursor-help mb-4"
								data-tippy-content="
								<?php
								echo esc_attr(
									tooltip(
										[
											'<strong>' . __( 'Members who joined your rewards program', 'rewardswp' ) . '</strong>',
											__( 'Bars show new members per day; the line shows your total members over time.', 'rewardswp' ),
											__( 'The % change compares new members to the previous period. Imported customers are not counted as new members here.', 'rewardswp' ),
											'<strong>' . __( 'Why it matters', 'rewardswp' ) . '</strong>',
											__( 'Growing membership fuels future redemptions and referral revenue.', 'rewardswp' ),
										],
									)
								);
								?>
								"
								data-tippy-allowhtml="true"><?php esc_html_e( 'Member growth', 'rewardswp' ); ?></p>
							<p class="text-sm text-gray-500 mt-1">
								<?php echo esc_html( $this->dashboard_service->get_date_ranges()[ $selected_range ]['label'] ?? __( 'Last 30 days', 'rewardswp' ) ); ?>
								<?php if ( isset( $member_growth_data['total_new'] ) ) : ?>
									<span class="text-gray-400 mx-1">·</span>
									<?php
									printf(
										/* translators: %s: number of new members */
										esc_html__( '%s new members', 'rewardswp' ),
										esc_html( number_format( $member_growth_data['total_new'] ) )
									);
									?>
								<?php endif; ?>
								<?php if ( ! empty( $member_growth_data['delta'] ) ) : ?>
									<span class="text-gray-400 mx-1">·</span>
									<span class="<?php echo esc_attr( $member_growth_data['delta_class'] ?? 'text-gray-500' ); ?>"><?php echo esc_html( $member_growth_data['delta'] ); ?></span>
									<?php esc_html_e( 'vs previous period', 'rewardswp' ); ?>
								<?php endif; ?>
							</p>
						</div>
						<div id="member-growth-chart" class="preserve-styles"
							data-chart-data="<?php echo esc_attr( wp_json_encode( $member_growth_chart_data ) ); ?>"
							data-granularity="<?php echo esc_attr( $granularity ); ?>">
						</div>
					</div>

					<script>
					document.addEventListener('DOMContentLoaded', function() {
						var chartContainer = document.querySelector("#member-growth-chart");
						if (!chartContainer) return;

						var chartData = [];
						try {
							chartData = JSON.parse(chartContainer.dataset.chartData || '[]');
						} catch (e) {
							console.error('Failed to parse member growth chart data:', e);
						}

						var granularity = chartContainer.dataset.granularity || 'daily';
						var useCategories = (granularity === 'weekly' || granularity === 'monthly');

						var categories = [];
						var newMembersSeries = [];
						var totalMembersSeries = [];

						chartData.forEach(function(point) {
							var date = new Date(point.x);
							var label;
							if (granularity === 'weekly') {
								label = date.toLocaleDateString('en-US', { day: 'numeric', month: 'short' });
							} else if (granularity === 'monthly') {
								label = date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
							} else {
								label = date.toLocaleDateString('en-US', { weekday: 'short', day: 'numeric', month: 'short' });
							}

							if (useCategories) {
								categories.push(label);
							}

							var xVal = useCategories ? label : point.x;
							newMembersSeries.push({ x: xVal, y: point.new_members, date: label });
							totalMembersSeries.push({ x: xVal, y: point.total_members, date: label });
						});

						var customTooltip = function({series, seriesIndex, dataPointIndex, w}) {
							var newMembers = w.config.series[1].data[dataPointIndex].y;
							var totalMembers = w.config.series[0].data[dataPointIndex].y;
							var dateLabel = w.config.series[0].data[dataPointIndex].date;

							return '<div class="apexcharts-tooltip-custom min-w-3xs">' +
								'<div class="px-3 py-2 bg-white">' +
								'<div class="text-xs text-gray-600 mb-1">' + dateLabel + '</div>' +
								'<div class="text-sm text-gray-900 mb-0.5"><?php echo esc_js( __( 'New members:', 'rewardswp' ) ); ?> ' + newMembers + '</div>' +
								'<div class="text-sm font-semibold text-gray-900"><?php echo esc_js( __( 'Total members:', 'rewardswp' ) ); ?> ' + totalMembers.toLocaleString() + '</div>' +
								'</div></div>';
						};

						var chartOptions = {
							series: [
								{ name: '<?php echo esc_js( __( 'Total members', 'rewardswp' ) ); ?>', type: 'line', data: totalMembersSeries },
								{ name: '<?php echo esc_js( __( 'New members', 'rewardswp' ) ); ?>', type: 'column', data: newMembersSeries }
							],
							chart: {
								type: 'line',
								height: 200,
								toolbar: {
									show: false
								},
								zoom: {
									enabled: true,
									type: 'x',
									autoScaleYaxis: true
								},
								dropShadow: { enabled: false }
							},
							dataLabels: { enabled: false },
							stroke: {
								width: [2, 0],
								curve: 'smooth'
							},
							fill: {
								type: 'solid',
								opacity: [1, 1]
							},
							plotOptions: {
								bar: {
									columnWidth: '60%',
									borderRadius: 4,
									borderRadiusApplication: 'end'
								}
							},
							colors: ['#3B82F6', '#34D399'],
							states: {
								hover: {
									filter: { type: 'none' }
								},
								active: {
									filter: { type: 'none' }
								}
							},
							xaxis: useCategories ? {
								type: 'category',
								categories: categories,
								labels: {
									style: { colors: '#9CA3AF', fontSize: '11px' },
									rotate: 0,
									hideOverlappingLabels: true
								},
								axisBorder: { show: false },
								axisTicks: { show: false },
								tooltip: { enabled: false }
							} : {
								type: 'datetime',
								labels: {
									style: { colors: '#9CA3AF', fontSize: '11px' },
									datetimeUTC: false,
									format: 'dd MMM',
									rotate: 0,
									hideOverlappingLabels: true
								},
								tickAmount: 6,
								axisBorder: { show: false },
								axisTicks: { show: false },
								tooltip: { enabled: false }
							},
							yaxis: {
								labels: {
									style: { colors: '#9CA3AF', fontSize: '11px' },
									formatter: function(value) {
										return Math.round(value);
									}
								},
								tickAmount: 4
							},
							grid: {
								borderColor: '#E5E7EB',
								strokeDashArray: 4,
								xaxis: { lines: { show: false } }
							},
							tooltip: {
								enabled: true,
								custom: customTooltip
							},
							legend: {
								show: true,
								position: 'top',
								horizontalAlign: 'right',
								floating: true,
								offsetY: -8,
								offsetX: 0,
								labels: {
									colors: '#6B7280'
								},
								markers: {
									width: 8,
									height: 8,
									radius: 2
								},
								itemMargin: {
									horizontal: 12
								}
							}
						};

						var memberGrowthChart = null;
						if (typeof ApexCharts !== 'undefined' && chartData.length > 0) {
							// Add double-click to reset zoom
							chartOptions.chart.events = {
								click: function(event) {
									if (event.detail === 2 && memberGrowthChart) {
										memberGrowthChart.resetSeries();
									}
								}
							};
							memberGrowthChart = new ApexCharts(chartContainer, chartOptions);
							memberGrowthChart.render();
						}
					});
					</script>

					<!-- Orders Using Rewards Chart -->
					<?php if ( $show_orders_chart ) : ?>
					<div class="bg-white border border-gray-900/8 rounded-xl p-6 h-full flex flex-col mt-6">
						<div class="mb-6">
							<p class="text-lg text-gray-900 inline-block border-b border-dashed border-gray-300 cursor-help mb-4"
								data-tippy-content="
								<?php
								echo esc_attr(
									tooltip(
										[
											'<strong>' . __( 'Orders using rewards', 'rewardswp' ) . '</strong>',
											__( 'Percentage of orders where a customer redeemed points or used a referral reward at checkout. This shows how often members actually use rewards on their orders, not just earn them.', 'rewardswp' ),
											'<strong>' . __( 'Why it matters', 'rewardswp' ) . '</strong>',
											__( 'Higher usage means members see real value in your rewards and are more likely to stay active and return.', 'rewardswp' ),
										],
									)
								);
								?>
								"
								data-tippy-allowhtml="true">
								<?php esc_html_e( 'Orders using rewards', 'rewardswp' ); ?>
							</p>
							<p class="text-sm text-gray-500 mt-1">
								<?php echo esc_html( $this->dashboard_service->get_date_ranges()[ $selected_range ]['label'] ?? __( 'Last 30 days', 'rewardswp' ) ); ?>
								<?php if ( isset( $orders_using_rewards_data['average_percentage'] ) ) : ?>
									<span class="text-gray-400 mx-1">·</span>
									<?php
									printf(
										/* translators: %s: percentage of orders */
										esc_html__( '%s%% of orders used rewards', 'rewardswp' ),
										esc_html( $orders_using_rewards_data['average_percentage'] )
									);
									?>
								<?php endif; ?>
								<?php if ( ! empty( $orders_using_rewards_data['delta'] ) ) : ?>
									<span class="text-gray-400 mx-1">·</span>
									<span class="<?php echo esc_attr( $orders_using_rewards_data['delta_class'] ?? 'text-gray-500' ); ?>"><?php echo esc_html( $orders_using_rewards_data['delta'] ); ?></span>
									<?php esc_html_e( 'vs previous period', 'rewardswp' ); ?>
								<?php endif; ?>
							</p>
						</div>
						<div id="orders-rewards-chart" class="preserve-styles"
							data-chart-data="<?php echo esc_attr( wp_json_encode( $orders_using_rewards_chart ) ); ?>"
							data-granularity="<?php echo esc_attr( $granularity ); ?>">
						</div>
					</div>
					<?php else : ?>
					<!-- Locked chart card for Lite users -->
						<?php
						// Generate dummy chart data for preview with realistic variation.
						$dummy_chart_data = [];
						$start_date       = strtotime( '-29 days', strtotime( 'today' ) );
						$base_percentage  = 22; // Starting baseline.
						$trend            = 0.15; // Slight upward trend per day.

						for ( $i = 0; $i < 30; $i++ ) {
							$date = $start_date + ( $i * DAY_IN_SECONDS );

							// Base trend with slight growth.
							$trending_base = $base_percentage + ( $trend * $i );

							// Add weekly pattern (weekends slightly lower).
							$day_of_week    = (int) gmdate( 'N', $date );
							$weekend_factor = ( $day_of_week >= 6 ) ? -3 : 0;

							// Add some randomness for natural variation.
							$noise = ( wp_rand( -30, 30 ) / 10 );

							// Occasional spike (roughly 1 in 7 days).
							$spike = ( wp_rand( 1, 7 ) === 1 ) ? wp_rand( 5, 10 ) : 0;

							$percentage   = max( 12, min( 45, $trending_base + $weekend_factor + $noise + $spike ) );
							$total_orders = wp_rand( 25, 55 );
							$orders_with  = (int) round( $total_orders * ( $percentage / 100 ) );

							$dummy_chart_data[] = [
								'x'                   => $date * 1000,
								'y'                   => round( $percentage, 1 ),
								'orders_with_rewards' => $orders_with,
								'total_orders'        => $total_orders,
							];
						}
						?>
					<div class="bg-white border border-gray-900/8 rounded-xl p-6 h-full flex flex-col mt-6">

							<div class="flex items-center gap-2 mb-4">
							<p class="text-lg text-gray-900 inline-block border-b border-dashed border-gray-300 cursor-help"
								data-tippy-content="
								<?php
								echo esc_attr(
									tooltip(
										[
											'<strong>' . __( 'Orders using rewards', 'rewardswp' ) . '</strong>',
											__( 'Percentage of orders where a customer redeemed points or used a referral reward at checkout. This shows how often members actually use rewards on their orders, not just earn them.', 'rewardswp' ),
											'<strong>' . __( 'Why it matters', 'rewardswp' ) . '</strong>',
											__( 'Higher usage means members see real value in your rewards and are more likely to stay active and return.', 'rewardswp' ),
										],
									)
								);
								?>
								"
								data-tippy-allowhtml="true">
								<?php esc_html_e( 'Orders using rewards', 'rewardswp' ); ?>
							</p>
								<?php $this->views_factory->get_view( BadgeComponentView::class )->render( [ 'style' => 'pro' ] ); ?>
							</div>

							<p class="text-sm text-gray-500 mt-1">
								<?php echo esc_html( $this->dashboard_service->get_date_ranges()[ $selected_range ]['label'] ?? __( 'Last 30 days', 'rewardswp' ) ); ?>
							</p>

						<div class="relative">
							<div class="blur-[5px] pointer-events-none">
								<div id="orders-rewards-chart-preview" class="py-10 preserve-styles"
									data-chart-data="<?php echo esc_attr( wp_json_encode( $dummy_chart_data ) ); ?>">
								</div>
							</div>
							<?php
							$this->views_factory->get_view( UpgradeOverlayComponentView::class )->render(
								[
									'size'         => 'sm',
									'title'        => __( 'Orders using rewards', 'rewardswp' ),
									'description'  => __(
										'See reward usage over time to measure program engagement.',
										'rewardswp'
									),
									'feature_slug' => 'orders_using_rewards_chart',
									'location'     => 'reports',
									'button'       => [ 'full_width' => false ],
									'overlay'      => true,
								]
							);
							?>
						</div>
					</div>
					<script>
					document.addEventListener('DOMContentLoaded', function() {
						var chartContainer = document.querySelector("#orders-rewards-chart-preview");
						if (!chartContainer) return;

						var chartData = [];
						try {
							chartData = JSON.parse(chartContainer.dataset.chartData || '[]');
						} catch (e) {
							return;
						}

						var seriesData = chartData.map(function(point) {
							return { x: point.x, y: point.y };
						});

						var chartOptions = {
							series: [{ name: 'Orders using rewards', data: seriesData }],
							chart: {
								type: 'area',
								height: 200,
								toolbar: { show: false },
								zoom: { enabled: false },
								animations: { enabled: true }
							},
							dataLabels: { enabled: false },
							stroke: { curve: 'smooth', width: 2 },
							fill: {
								type: 'gradient',
								gradient: { shadeIntensity: 1, opacityFrom: 0.4, opacityTo: 0.1, stops: [0, 100] }
							},
							colors: ['#3B82F6'],
							xaxis: {
								type: 'datetime',
								labels: {
									style: { colors: '#9CA3AF', fontSize: '11px' },
									datetimeUTC: false,
									format: 'dd MMM',
									hideOverlappingLabels: true
								},
								axisBorder: { show: false },
								axisTicks: { show: false }
							},
							yaxis: {
								min: 10,
								max: 50,
								labels: {
									style: { colors: '#9CA3AF', fontSize: '11px' },
									formatter: function(value) { return value + '%'; }
								},
								tickAmount: 4
							},
							grid: {
								borderColor: '#E5E7EB',
								strokeDashArray: 4,
								xaxis: { lines: { show: false } }
							},
							tooltip: { enabled: false }
						};

						if (typeof ApexCharts !== 'undefined' && chartData.length > 0) {
							new ApexCharts(chartContainer, chartOptions).render();
						}
					});
					</script>
					<?php endif; ?>

					<?php if ( $show_orders_chart ) : ?>
					<script>
					document.addEventListener('DOMContentLoaded', function() {
						var chartContainer = document.querySelector("#orders-rewards-chart");
						if (!chartContainer) return;

						var chartData = [];
						try {
							chartData = JSON.parse(chartContainer.dataset.chartData || '[]');
						} catch (e) {
							console.error('Failed to parse orders rewards chart data:', e);
						}

						var granularity = chartContainer.dataset.granularity || 'daily';
						var useCategories = (granularity === 'weekly' || granularity === 'monthly');
						var categories = [];
						var seriesData = [];

						if (useCategories) {
							chartData.forEach(function(point) {
								var date = new Date(point.x);
								var label;
								if (granularity === 'weekly') {
									label = date.toLocaleDateString('en-US', { day: 'numeric', month: 'short' });
								} else {
									label = date.toLocaleDateString('en-US', { month: 'short', year: 'numeric' });
								}
								categories.push(label);
								seriesData.push({
									x: label,
									y: point.y,
									orders_with_rewards: point.orders_with_rewards,
									total_orders: point.total_orders,
									date: granularity === 'weekly' ? 'Week of ' + label : label
								});
							});
						} else {
							seriesData = chartData.map(function(point) {
								var date = new Date(point.x);
								return {
									x: point.x,
									y: point.y,
									orders_with_rewards: point.orders_with_rewards,
									total_orders: point.total_orders,
									date: date.toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' })
								};
							});
						}

						var customTooltip = function({series, seriesIndex, dataPointIndex, w}) {
							var dataPoint = w.globals.initialSeries[seriesIndex].data[dataPointIndex];
							var percentage = dataPoint.y;
							var ordersWithRewards = dataPoint.orders_with_rewards;
							var totalOrders = dataPoint.total_orders;
							var dateLabel = dataPoint.date;

							return '<div class="apexcharts-tooltip-custom min-w-3xs">' +
								'<div class="px-3 py-2 bg-white">' +
								'<div class="text-xs text-gray-600 mb-1">' + dateLabel + '</div>' +
								'<div class="text-sm font-semibold text-gray-900 mb-0.5"><?php echo esc_js( __( 'Orders using rewards:', 'rewardswp' ) ); ?> ' + percentage + '%</div>' +
								'<div class="text-xs text-gray-600">' + ordersWithRewards + ' <?php echo esc_js( __( 'of', 'rewardswp' ) ); ?> ' + totalOrders + ' <?php echo esc_js( __( 'orders used a reward', 'rewardswp' ) ); ?></div>' +
								'</div></div>';
						};

						var chartOptions = {
							series: [{
								name: '<?php echo esc_js( __( 'Orders using rewards', 'rewardswp' ) ); ?>',
								data: seriesData
							}],
							chart: {
								type: 'area',
								height: 200,
								toolbar: {
									show: false
								},
								zoom: {
									enabled: true,
									type: 'x',
									autoScaleYaxis: false
								},
								dropShadow: {
									enabled: false
								}
							},
							dataLabels: {
								enabled: false
							},
							stroke: {
								curve: 'smooth',
								width: 2
							},
							fill: {
								type: 'gradient',
								gradient: {
									shadeIntensity: 1,
									opacityFrom: 0.4,
									opacityTo: 0.1,
									stops: [0, 100]
								}
							},
							colors: ['#3B82F6'],
							xaxis: useCategories ? {
								type: 'category',
								categories: categories,
								labels: {
									style: {
										colors: '#9CA3AF',
										fontSize: '11px'
									},
									rotate: 0,
									hideOverlappingLabels: true
								},
								axisBorder: {
									show: false
								},
								axisTicks: {
									show: false
								},
								tooltip: {
									enabled: false
								}
							} : {
								type: 'datetime',
								labels: {
									style: {
										colors: '#9CA3AF',
										fontSize: '11px'
									},
									datetimeUTC: false,
									format: 'dd MMM',
									rotate: 0,
									hideOverlappingLabels: true
								},
								tickAmount: 6,
								axisBorder: {
									show: false
								},
								axisTicks: {
									show: false
								},
								tooltip: {
									enabled: false
								}
							},
							yaxis: {
								min: 0,
								max: 100,
								labels: {
									style: {
										colors: '#9CA3AF',
										fontSize: '11px'
									},
									formatter: function(value) {
										return value + '%';
									}
								},
								tickAmount: 4
							},
							grid: {
								borderColor: '#E5E7EB',
								strokeDashArray: 4,
								xaxis: {
									lines: {
										show: false
									}
								}
							},
							tooltip: {
								enabled: true,
								custom: customTooltip
							}
						};

						var ordersRewardsChart = null;
						if (typeof ApexCharts !== 'undefined' && chartData.length > 0) {
							chartOptions.chart.events = {
								click: function(event) {
									if (event.detail === 2 && ordersRewardsChart) {
										ordersRewardsChart.resetSeries();
									}
								}
							};
							ordersRewardsChart = new ApexCharts(chartContainer, chartOptions);
							ordersRewardsChart.render();
						}
					});
					</script>
					<?php endif; ?>
				</div>

				<!-- Export Tab Content -->
				<div class="px-8 pt-5 mx-auto max-w-7xl" x-show="activeTab === 'export'" x-cloak>

					<?php
					$can_export   = can_access_rewardswp_feature( 'exports' );
					$admin_email  = get_option( 'admin_email' );
					$current_user = wp_get_current_user();
					$user_email   = $current_user->user_email;
					$export_types = [
						'members'   => [
							'label'       => __( 'Members', 'rewardswp' ),
							'description' => __( 'Member details, join dates, referral codes, and current points balance', 'rewardswp' ),
							'icon'        => $this->icon_helper->get_icon( 'earn-signup', 'size-8 text-gray-700' ),
						],
						'points'    => [
							'label'       => __( 'Points Activity', 'rewardswp' ),
							'description' => __( 'All points transactions including earnings, redemptions, and expirations', 'rewardswp' ),
							'icon'        => $this->icon_helper->get_icon( 'points-activity', 'size-8 text-gray-700' ),
						],
						'referrals' => [
							'label'       => __( 'Referrals', 'rewardswp' ),
							'description' => __( 'Referral records with advocate details, order info, and conversion status', 'rewardswp' ),
							'icon'        => $this->icon_helper->get_icon( 'earn-referral', 'size-8 text-gray-700' ),
						],
						'rewards'   => [
							'label'       => __( 'Rewards', 'rewardswp' ),
							'description' => __( 'Reward claims, types, amounts, and redemption status', 'rewardswp' ),
							'icon'        => $this->icon_helper->get_icon( 'reward-redemption', 'size-8 text-gray-700' ),
						],
					];
					?>

					<div x-data
						<!-- Export Type Cards -->
						<div class="mb-8">
							<h2 class="text-lg font-medium text-gray-900 mb-4"><?php esc_html_e( 'Export Data', 'rewardswp' ); ?></h2>
							<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
								<?php foreach ( $export_types as $type => $config ) : ?>
									<button
										type="button"
										x-on:click="$store.exportDrawer.open('<?php echo esc_js( $type ); ?>')"
										class="cursor-pointer group relative bg-white border border-gray-200 rounded-xl p-6 text-left hover:ring-2 hover:ring-blue-500 hover:ring-offset-2 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2 h-full flex flex-col"
									>
										<div class="flex items-start justify-between mb-4">
											<div class="flex-shrink-0 h-8 flex items-start">
												<?php echo wp_kses( $config['icon'], svg_kses() ); ?>
											</div>
										</div>
										<h3 class="text-base font-semibold text-gray-900 mb-1"><?php echo esc_html( $config['label'] ); ?></h3>
										<p class="text-sm text-gray-500 flex-grow"><?php echo esc_html( $config['description'] ); ?></p>
									</button>
								<?php endforeach; ?>
							</div>
						</div>

						<!-- Export History -->
						<div class="bg-white border border-gray-200 rounded-xl overflow-hidden">
							<div class="px-6 py-4 border-b border-gray-200">
								<div class="flex items-center justify-between">
									<h3 class="text-base font-semibold text-gray-900"><?php esc_html_e( 'Export History', 'rewardswp' ); ?></h3>
									<?php
									/*
									Refresh button temporarily hidden
									<button
										type="button"
										x-on:click="$store.exportDrawer.loadHistory()"
										x-show="$store.exportDrawer.history.length > 0"
										class="cursor-pointer text-sm text-blue-600 hover:text-blue-700 font-medium"
									>
										<?php esc_html_e( 'Refresh', 'rewardswp' ); ?>
									</button>
									*/
									?>
								</div>
								<p class="text-sm text-gray-500 mt-1" x-show="$store.exportDrawer.history.length > 0"><?php esc_html_e( 'Downloads are available for 7 days', 'rewardswp' ); ?></p>
							</div>

							<!-- Loading State (show during initial load OR manual refresh when no history) -->
							<div x-show="(!$store.exportDrawer.hasLoadedOnce || $store.exportDrawer.isLoadingHistory) && $store.exportDrawer.history.length === 0" class="p-8 text-center">
								<svg class="animate-spin h-8 w-8 text-blue-600 mx-auto" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
									<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
									<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
								</svg>
								<p class="mt-3 text-sm text-gray-500"><?php esc_html_e( 'Loading export history...', 'rewardswp' ); ?></p>
							</div>

							<!-- Empty State / Upsell (only show after first load confirms no history) -->
							<?php if ( ! can_access_rewardswp_feature( 'exports' ) ) : ?>
								<!-- Lite User Upsell -->
								<div class="text-center py-12" x-show="$store.exportDrawer.hasLoadedOnce && !$store.exportDrawer.isLoadingHistory && $store.exportDrawer.history.length === 0" x-cloak>
									<div class="mx-auto flex items-center justify-center">
										<?php echo wp_kses( $this->icon_helper->get_icon( 'data-export', 'size-10 text-gray-400' ), svg_kses() ); ?>
									</div>
									<p class="mt-3 text-sm text-gray-500">
										<?php
										printf(
											/* translators: %s: Minimum required plan name */
											esc_html__( 'Export history is available on %s.', 'rewardswp' ),
											'<span class="font-semibold text-gray-700">' . esc_html( get_minimum_required_plan_for_feature( 'exports' ) ) . '+</span>'
										);
										?>
									</p>
									<?php
									$min_plan = get_minimum_required_plan_for_feature( 'exports' );
									// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Output is escaped within the component
									echo wp_kses(
										get_view_component(
											'button',
											[
												'text' => sprintf(
													/* translators: %s: Minimum required plan name */
													__( 'Upgrade to %s', 'rewardswp' ),
													$min_plan
												),
												'type' => 'anchor',
												'href' => add_query_arg( 'feature', 'exports', get_upgrade_url( 'upgrade_to_basic', 'export_history', $min_plan, 'exports' ) ),
												'size' => 'sm',
												'additional_classes' => 'mt-4',
											]
										),
										kses()
									);
									?>
									<div class="mt-3">
										<a href="
										<?php
										echo esc_url(
											add_query_arg(
												[
													'feature' => 'exports',
													'compare' => 'true',
												],
												get_upgrade_url( 'compare_plans', 'export_history', $min_plan, 'exports' )
											)
										);
										?>
													"
											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>
								</div>
							<?php else : ?>
								<!-- Basic+ User Empty State -->
								<?php
								// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Output is escaped within the component
								echo get_view_component(
									'empty-state',
									[
										'icon'        => 'data-export',
										'title'       => __( 'No exports yet', 'rewardswp' ),
										'description' => __( 'Click an export type above to get started.', 'rewardswp' ),
										'x_show'      => '$store.exportDrawer.hasLoadedOnce && !$store.exportDrawer.isLoadingHistory && $store.exportDrawer.history.length === 0',
										'x_cloak'     => true,
									]
								);
								?>
							<?php endif; ?>

							<!-- History Table -->
							<div x-show="$store.exportDrawer.history.length > 0" x-cloak class="overflow-x-auto">
								<table class="min-w-full divide-y divide-gray-200">
									<tbody class="bg-white divide-y divide-gray-200">
										<template x-for="job in $store.exportDrawer.history" x-bind:key="job.id">
											<tr>
												<td class="px-6 py-4">
													<div class="text-sm font-medium text-gray-900" x-text="job.typeName"></div>
													<div class="text-sm text-gray-500" x-text="job.rangeLabel"></div>
													<div class="text-xs text-gray-400 mt-0.5">
														<span x-text="'<?php echo esc_js( __( 'Created by', 'rewardswp' ) ); ?> ' + job.createdBy"></span>
														<span x-show="job.fileSize"> · </span>
														<span x-text="job.fileSize" x-show="job.fileSize"></span>
													</div>
												</td>
												<td class="px-6 py-4 whitespace-nowrap">
													<span class="text-sm text-gray-500" x-text="job.createdAtHuman"></span>
												</td>
												<td class="px-6 py-4 whitespace-nowrap">
													<span
														class="inline-flex items-center rounded-md px-2 py-1 text-xs font-medium"
														x-bind:class="$store.exportDrawer.getStatusClass(job.status)"
														x-text="job.statusLabel"
													></span>
													<template x-if="job.status === 'processing' || job.status === 'pending'">
														<svg class="inline-block ml-1 animate-spin h-3 w-3 text-blue-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
															<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
															<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
														</svg>
													</template>
												</td>
												<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
													<template x-if="job.status === 'completed'">
														<button
															type="button"
															x-on:click="$store.exportDrawer.downloadExport(job.id)"
															class="cursor-pointer text-blue-600 hover:text-blue-900"
														>
															<?php esc_html_e( 'Download CSV', 'rewardswp' ); ?>
														</button>
													</template>
													<template x-if="job.status === 'failed'">
														<button
															type="button"
															x-on:click="$store.exportDrawer.retryExport(job.id)"
															class="cursor-pointer text-blue-600 hover:text-blue-900"
														>
															<?php esc_html_e( 'Retry', 'rewardswp' ); ?>
														</button>
													</template>
												</td>
											</tr>
										</template>
									</tbody>
								</table>
							</div>
						</div>
					</div>

					<?php
					/**
					 * Export Drawer
					 */
					$export_drawer = $this->views_factory->get_view( DrawerComponentView::class );
					if ( $export_drawer instanceof DrawerComponentView ) {
						$export_drawer->render(
							[
								'alpine_var'       => 'exportDrawer',
								'title_key'        => 'getTypeLabel()',
								'subtitle'         => __( 'Export to CSV', 'rewardswp' ),
								'content_callback' => function () {
									$this->views_factory->get_view( ExportDrawerView::class )->render();
								},
							]
						);
					}
					?>
				</div>


			</div>

		</div>

		<?php
	}
}
