<?php

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

/**
 * @var array $data  Dashboard data from DashboardController::get_data().
 */

$kpis         = $data['kpis'];
$chart_data   = $data['chart_data'];
$heatmap_data = $data['heatmap_data'];   // null for free users
$top_users    = $data['top_users'];       // null for free users
$recent_links = $data['recent_links'];
$last_updated = $data['last_updated'];
$days         = $data['days'];
$is_pro       = $data['is_pro'];

$upgrade_url = 'https://kaizencoders.com/magic-link#pricing?utm_source=dashboard&utm_medium=magic-link-in-app&utm_campaign=pro-upgrade';
$base_url    = admin_url( 'admin.php?page=magic-link' );
$refresh_url = wp_nonce_url( add_query_arg( [ 'days' => $days, 'refresh' => 1 ], $base_url ), 'kc_ml_dashboard_refresh' );

$icon_colors = [
	'indigo' => 'bg-indigo-100 text-indigo-600',
	'green'  => 'bg-green-100 text-green-600',
	'blue'   => 'bg-blue-100 text-blue-600',
	'purple' => 'bg-purple-100 text-purple-600',
];

$status_colors = [
	'used'    => 'bg-green-100 text-green-700',
	'active'  => 'bg-blue-100 text-blue-700',
	'expired' => 'bg-gray-100 text-gray-500',
];

?>
<div class="wrap kc-ml-dashboard">
	<div class="max-w-screen-xl mx-auto px-4 sm:px-6 lg:px-8 py-6">

		<!-- Header -->
		<div class="flex flex-wrap items-center justify-between gap-4 mb-6">
			<div>
				<h1 class="text-2xl font-bold text-gray-900"><?php esc_html_e( 'Magic Link Dashboard', 'magic-link' ); ?></h1>
				<p class="text-sm text-gray-500 mt-0.5">
					<?php
					printf(
						/* translators: %s: human-friendly time */
						esc_html__( 'Last updated: %s ago', 'magic-link' ),
						esc_html( human_time_diff( $last_updated ) )
					);
					?>
				</p>
			</div>
			<div class="flex items-center gap-3">
				<!-- Time filter -->
				<div class="inline-flex rounded-lg border border-gray-200 bg-white text-sm shadow-sm overflow-hidden">
					<?php foreach ( [ 7, 30 ] as $d ) :
						$is_active    = $days === $d;
						$is_pro_only  = $d > 7 && ! $is_pro;
						?>
						<?php if ( $is_pro_only ) : ?>
							<a href="<?php echo esc_url( $upgrade_url ); ?>" target="_blank"
							   class="relative px-4 py-2 font-medium text-gray-400 cursor-pointer flex items-center gap-1"
							   title="<?php esc_attr_e( 'Available in PRO', 'magic-link' ); ?>">
								<?php printf( esc_html__( '%d days', 'magic-link' ), $d ); ?>
								<svg class="w-3 h-3 text-indigo-400" fill="currentColor" viewBox="0 0 20 20">
									<path fill-rule="evenodd" d="M5 9V7a5 5 0 0110 0v2a2 2 0 012 2v5a2 2 0 01-2 2H5a2 2 0 01-2-2v-5a2 2 0 012-2zm8-2v2H7V7a3 3 0 016 0z" clip-rule="evenodd"/>
								</svg>
							</a>
						<?php else : ?>
							<a href="<?php echo esc_url( add_query_arg( 'days', $d, $base_url ) ); ?>"
							   class="px-4 py-2 font-medium transition-colors <?php echo $is_active ? 'bg-indigo-600 text-white' : 'text-gray-600 hover:bg-gray-50'; ?>">
								<?php printf( esc_html__( '%d days', 'magic-link' ), $d ); ?>
							</a>
						<?php endif; ?>
					<?php endforeach; ?>
				</div>
				<!-- Refresh -->
				<a href="<?php echo esc_url( $refresh_url ); ?>"
				   class="inline-flex items-center gap-1.5 rounded-lg border border-gray-200 bg-white px-3 py-2 text-sm font-medium text-gray-600 shadow-sm hover:bg-gray-50 transition-colors">
					<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
						<path stroke-linecap="round" stroke-linejoin="round" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"/>
					</svg>
					<?php esc_html_e( 'Refresh', 'magic-link' ); ?>
				</a>
			</div>
		</div>

		<!-- KPI Cards -->
		<div class="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-4 mb-6">
			<?php foreach ( $kpis as $kpi ) :
				$color_classes = isset( $icon_colors[ $kpi['color'] ] ) ? $icon_colors[ $kpi['color'] ] : 'bg-gray-100 text-gray-600';
				?>
				<div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 flex items-start gap-4">
					<div class="flex-shrink-0 p-2.5 rounded-xl <?php echo esc_attr( $color_classes ); ?>">
						<?php echo kc_ml_dashboard_icon( $kpi['icon'] ); // phpcs:ignore ?>
					</div>
					<div class="min-w-0">
						<p class="text-sm font-medium text-gray-500 truncate"><?php echo esc_html( $kpi['title'] ); ?></p>
						<p class="mt-0.5 text-2xl font-bold text-gray-900"><?php echo esc_html( number_format_i18n( $kpi['count'] ) ); ?></p>
						<?php if ( ! empty( $kpi['sub'] ) ) : ?>
							<p class="mt-0.5 text-xs text-gray-400"><?php echo esc_html( $kpi['sub'] ); ?></p>
						<?php endif; ?>
					</div>
				</div>
			<?php endforeach; ?>
		</div>

		<!-- Area Chart: Generated vs Used -->
		<div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 mb-6">
			<div class="flex items-center justify-between mb-4">
				<h2 class="text-base font-semibold text-gray-800">
					<?php
					printf(
						/* translators: %d: number of days */
						esc_html__( 'Link Activity — Last %d Days', 'magic-link' ),
						$days
					);
					?>
				</h2>
				<?php if ( ! $is_pro ) : ?>
					<a href="<?php echo esc_url( $upgrade_url ); ?>" target="_blank"
					   class="inline-flex items-center gap-1 text-xs font-medium text-indigo-600 hover:text-indigo-700">
						<?php esc_html_e( 'Upgrade for 30-day view', 'magic-link' ); ?> &rarr;
					</a>
				<?php endif; ?>
			</div>
			<div id="kc-ml-area-chart"></div>
		</div>

		<!-- Heatmap -->
		<div class="bg-white rounded-2xl border border-gray-100 shadow-sm p-5 mb-6">
			<h2 class="text-base font-semibold text-gray-800 mb-4"><?php esc_html_e( 'Activity Heatmap — Last 52 Weeks', 'magic-link' ); ?></h2>
			<?php if ( $is_pro ) : ?>
				<div id="kc-ml-heatmap-chart" class="overflow-x-auto"></div>
			<?php else : ?>
				<?php kc_ml_pro_upgrade_card(
					__( 'Activity Heatmap', 'magic-link' ),
					__( 'See a full year of magic link activity at a glance. Identify trends and peak usage periods with the activity heatmap.', 'magic-link' ),
					$upgrade_url
				); ?>
			<?php endif; ?>
		</div>

		<!-- Top Users + Recent Links -->
		<div class="grid grid-cols-1 gap-6 lg:grid-cols-2">

			<!-- Top Users -->
			<div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
				<div class="px-5 pt-5 pb-3 border-b border-gray-50 flex items-center justify-between">
					<h2 class="text-base font-semibold text-gray-800"><?php esc_html_e( 'Top Users', 'magic-link' ); ?></h2>
					<?php if ( ! $is_pro ) : ?>
						<?php kc_ml_pro_badge(); ?>
					<?php endif; ?>
				</div>
				<?php if ( ! $is_pro ) : ?>
					<?php kc_ml_pro_upgrade_card(
						__( 'Top Users', 'magic-link' ),
						__( 'Discover which users rely on magic links the most. View generation counts, usage counts, and per-user use rates.', 'magic-link' ),
						$upgrade_url
					); ?>
				<?php elseif ( empty( $top_users ) ) : ?>
					<p class="px-5 py-8 text-center text-sm text-gray-400"><?php esc_html_e( 'No data yet.', 'magic-link' ); ?></p>
				<?php else : ?>
					<div class="overflow-x-auto">
						<table class="min-w-full divide-y divide-gray-50 text-sm">
							<thead>
								<tr class="text-left text-xs font-medium text-gray-400 uppercase tracking-wider">
									<th class="px-5 py-3"><?php esc_html_e( 'User', 'magic-link' ); ?></th>
									<th class="px-5 py-3 text-center"><?php esc_html_e( 'Generated', 'magic-link' ); ?></th>
									<th class="px-5 py-3 text-center"><?php esc_html_e( 'Used', 'magic-link' ); ?></th>
									<th class="px-5 py-3 text-center"><?php esc_html_e( 'Rate', 'magic-link' ); ?></th>
								</tr>
							</thead>
							<tbody class="divide-y divide-gray-50">
								<?php foreach ( $top_users as $user ) :
									$gen      = (int) $user->generated_count;
									$used_cnt = (int) $user->used_count;
									$rate     = $gen > 0 ? round( ( $used_cnt / $gen ) * 100 ) : 0;
									$name     = ! empty( $user->display_name ) ? $user->display_name : __( '(Deleted)', 'magic-link' );
									?>
									<tr class="hover:bg-gray-50 transition-colors">
										<td class="px-5 py-3">
											<div class="font-medium text-gray-800 truncate max-w-[160px]"><?php echo esc_html( $name ); ?></div>
											<div class="text-xs text-gray-400 truncate max-w-[160px]"><?php echo esc_html( isset( $user->user_email ) ? $user->user_email : '' ); ?></div>
										</td>
										<td class="px-5 py-3 text-center font-medium text-gray-700"><?php echo esc_html( number_format_i18n( $gen ) ); ?></td>
										<td class="px-5 py-3 text-center text-gray-600"><?php echo esc_html( number_format_i18n( $used_cnt ) ); ?></td>
										<td class="px-5 py-3 text-center">
											<span class="inline-block rounded-full px-2 py-0.5 text-xs font-medium <?php echo $rate >= 50 ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'; ?>">
												<?php echo esc_html( $rate . '%' ); ?>
											</span>
										</td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					</div>
				<?php endif; ?>
			</div>

			<!-- Recent Links -->
			<div class="bg-white rounded-2xl border border-gray-100 shadow-sm">
				<div class="px-5 pt-5 pb-3 border-b border-gray-50">
					<h2 class="text-base font-semibold text-gray-800"><?php esc_html_e( 'Recent Links', 'magic-link' ); ?></h2>
				</div>
				<?php if ( empty( $recent_links ) ) : ?>
					<p class="px-5 py-8 text-center text-sm text-gray-400"><?php esc_html_e( 'No links yet.', 'magic-link' ); ?></p>
				<?php else : ?>
					<div class="overflow-x-auto">
						<table class="min-w-full divide-y divide-gray-50 text-sm">
							<thead>
								<tr class="text-left text-xs font-medium text-gray-400 uppercase tracking-wider">
									<th class="px-5 py-3"><?php esc_html_e( 'User', 'magic-link' ); ?></th>
									<th class="px-5 py-3"><?php esc_html_e( 'Created', 'magic-link' ); ?></th>
									<th class="px-5 py-3 text-center"><?php esc_html_e( 'Status', 'magic-link' ); ?></th>
								</tr>
							</thead>
							<tbody class="divide-y divide-gray-50">
								<?php foreach ( $recent_links as $link ) :
									$name   = ! empty( $link->display_name ) ? $link->display_name : __( '(Deleted)', 'magic-link' );
									$status = isset( $link->status ) ? $link->status : 'expired';
									$badge  = isset( $status_colors[ $status ] ) ? $status_colors[ $status ] : 'bg-gray-100 text-gray-500';
									?>
									<tr class="hover:bg-gray-50 transition-colors">
										<td class="px-5 py-3">
											<div class="font-medium text-gray-800 truncate max-w-[160px]"><?php echo esc_html( $name ); ?></div>
											<div class="text-xs text-gray-400 truncate max-w-[160px]"><?php echo esc_html( isset( $link->user_email ) ? $link->user_email : '' ); ?></div>
										</td>
										<td class="px-5 py-3 text-gray-500 whitespace-nowrap">
											<?php echo esc_html( date_i18n( get_option( 'date_format' ) . ' H:i', strtotime( $link->created_at ) ) ); ?>
										</td>
										<td class="px-5 py-3 text-center">
											<span class="inline-block rounded-full px-2 py-0.5 text-xs font-medium <?php echo esc_attr( $badge ); ?>">
												<?php echo esc_html( ucfirst( $status ) ); ?>
											</span>
										</td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					</div>
					<?php if ( ! $is_pro ) : ?>
						<div class="px-5 py-3 border-t border-gray-50 flex items-center justify-between bg-gray-50 rounded-b-2xl">
							<p class="text-xs text-gray-400"><?php esc_html_e( 'Showing 3 most recent links.', 'magic-link' ); ?></p>
							<a href="<?php echo esc_url( $upgrade_url ); ?>" target="_blank"
							   class="inline-flex items-center gap-1 text-xs font-medium text-indigo-600 hover:text-indigo-700">
								<?php esc_html_e( 'See all with PRO', 'magic-link' ); ?> &rarr;
							</a>
						</div>
					<?php endif; ?>
				<?php endif; ?>
			</div>

		</div><!-- /grid -->
	</div><!-- /max-w-screen-xl -->
</div><!-- /wrap -->

<?php if ( $is_pro && ! empty( $heatmap_data ) ) : ?>
<script>
document.addEventListener('DOMContentLoaded', function () {
	var heatmapData = <?php echo wp_json_encode( $heatmap_data ); ?>;
	var heatmapEl   = document.getElementById('kc-ml-heatmap-chart');
	if ( heatmapEl && typeof ApexCharts !== 'undefined' && heatmapData.series && heatmapData.series.length ) {
		new ApexCharts( heatmapEl, {
			chart: {
				type: 'heatmap',
				height: 160,
				toolbar: { show: false },
				fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
			},
			series: heatmapData.series,
			xaxis: { labels: { show: false }, axisBorder: { show: false }, axisTicks: { show: false } },
			yaxis: { labels: { style: { colors: '#9ca3af', fontSize: '11px' } } },
			plotOptions: {
				heatmap: {
					radius: 3,
					enableShades: false,
					colorScale: { ranges: heatmapData.color_ranges },
				},
			},
			dataLabels: { enabled: false },
			legend: { show: false },
			stroke: { width: 2, colors: ['#fff'] },
			tooltip: {
				custom: function ( opts ) {
					var cell = opts.w.config.series[ opts.seriesIndex ].data[ opts.dataPointIndex ];
					if ( ! cell || cell.future ) return '';
					var count = cell.y >= 0 ? cell.y : 0;
					var label = count === 1
						? <?php echo wp_json_encode( __( '1 link', 'magic-link' ) ); ?>
						: count + ' ' + <?php echo wp_json_encode( __( 'links', 'magic-link' ) ); ?>;
					return '<div class="apexcharts-tooltip-title" style="padding:6px 10px;font-size:12px;">' + cell.x + '</div>' +
					       '<div style="padding:4px 10px 6px;font-size:13px;font-weight:600;">' + label + '</div>';
				},
			},
		} ).render();
	}
} );
</script>
<?php endif; ?>

<script>
document.addEventListener('DOMContentLoaded', function () {
	var chartData = <?php echo wp_json_encode( $chart_data ); ?>;
	var areaEl    = document.getElementById('kc-ml-area-chart');
	if ( areaEl && typeof ApexCharts !== 'undefined' && chartData.dates && chartData.dates.length ) {
		new ApexCharts( areaEl, {
			chart: {
				type: 'area',
				height: 280,
				toolbar: { show: false },
				zoom: { enabled: false },
				fontFamily: '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
			},
			series: [
				{ name: <?php echo wp_json_encode( __( 'Generated', 'magic-link' ) ); ?>, data: chartData.generated },
				{ name: <?php echo wp_json_encode( __( 'Used', 'magic-link' ) ); ?>,      data: chartData.used },
			],
			xaxis: {
				categories: chartData.dates,
				type: 'datetime',
				labels: { style: { colors: '#9ca3af', fontSize: '12px' } },
				axisBorder: { show: false },
				axisTicks: { show: false },
			},
			yaxis: {
				labels: {
					style: { colors: '#9ca3af', fontSize: '12px' },
					formatter: function ( v ) { return Math.round( v ); },
				},
				min: 0,
			},
			colors: ['#6366f1', '#34d399'],
			fill: {
				type: 'gradient',
				gradient: { shadeIntensity: 1, opacityFrom: 0.35, opacityTo: 0.05, stops: [0, 90, 100] },
			},
			stroke: { curve: 'smooth', width: 2 },
			dataLabels: { enabled: false },
			legend: { position: 'top', horizontalAlign: 'right', labels: { colors: '#6b7280' } },
			tooltip: { x: { format: 'MMM dd, yyyy' } },
			grid: { borderColor: '#f3f4f6', strokeDashArray: 4 },
		} ).render();
	}
} );
</script>

<?php

// ─────────────────────────────────────────────────────────────────────────────
// Helpers (local to this template)
// ─────────────────────────────────────────────────────────────────────────────

function kc_ml_pro_badge() {
	echo '<span class="inline-flex items-center gap-1 rounded-full bg-indigo-100 px-2 py-0.5 text-xs font-semibold text-indigo-700">';
	echo '<svg class="w-3 h-3" fill="currentColor" viewBox="0 0 20 20"><path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/></svg>';
	echo 'PRO</span>';
}

function kc_ml_pro_upgrade_card( $title, $desc, $upgrade_url ) {
	?>
	<div class="flex flex-col items-center justify-center py-10 px-6 text-center">
		<div class="mb-3 inline-flex items-center gap-1.5 rounded-full bg-indigo-50 px-3 py-1 text-xs font-semibold text-indigo-700">
			<svg class="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 20 20">
				<path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z"/>
			</svg>
			<?php esc_html_e( 'PRO Feature', 'magic-link' ); ?>
		</div>
		<h3 class="text-sm font-semibold text-gray-800 mb-1"><?php echo esc_html( $title ); ?></h3>
		<p class="text-xs text-gray-500 mb-4 max-w-xs"><?php echo esc_html( $desc ); ?></p>
		<a href="<?php echo esc_url( $upgrade_url ); ?>" target="_blank"
		   class="inline-flex items-center gap-1.5 rounded-lg bg-indigo-600 px-4 py-2 text-sm font-medium text-white hover:bg-indigo-700 transition-colors">
			<?php esc_html_e( 'Upgrade to PRO', 'magic-link' ); ?>
			<svg class="w-4 h-4" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
				<path stroke-linecap="round" stroke-linejoin="round" d="M14 5l7 7m0 0l-7 7m7-7H3"/>
			</svg>
		</a>
	</div>
	<?php
}

function kc_ml_dashboard_icon( $name ) {
	$icons = [
		'link'  => '<svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1"/></svg>',
		'check' => '<svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>',
		'clock' => '<svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>',
		'users' => '<svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/></svg>',
	];
	return isset( $icons[ $name ] ) ? $icons[ $name ] : '';
}
