<?php
/**
 * Video Access Page Template - Card Layout
 *
 * Displays videos for a confirmed booking in a modern card grid.
 * Access via: /mein-videokurs/?buchung={token}
 *
 * @package KursBooking
 * @since   1.3.0
 */

declare(strict_types=1);

// Prevent direct access.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Get video access content
 *
 * @param string $token Booking token.
 * @return string HTML content.
 */
function kurs_booking_get_video_access_content( string $token ): string {
	// Validate token.
	if ( empty( $token ) ) {
		return kurs_booking_video_access_error( __( 'Kein Zugangstoken angegeben.', 'kurs-booking' ) );
	}

	// Find buchung by token.
	$buchungen = get_posts(
		array(
			'post_type'   => 'kurs-buchung',
			'post_status' => 'publish',
			'meta_query'  => array(
				array(
					'key'   => '_buchung_token',
					'value' => sanitize_text_field( $token ),
				),
			),
			'numberposts' => 1,
		)
	);

	if ( empty( $buchungen ) ) {
		return kurs_booking_video_access_error( __( 'Buchung nicht gefunden. Bitte pruefen Sie Ihren Link.', 'kurs-booking' ) );
	}

	$buchung    = $buchungen[0];
	$buchung_id = $buchung->ID;

	// Check buchung status.
	$status = get_post_meta( $buchung_id, '_buchung_status', true );
	if ( 'confirmed' !== $status ) {
		return kurs_booking_video_access_error( __( 'Diese Buchung wurde noch nicht bestaetigt.', 'kurs-booking' ) );
	}

	// Get kurs or video-paket.
	$item_id = (int) get_post_meta( $buchung_id, '_buchung_kurs_id', true );
	if ( ! $item_id ) {
		return kurs_booking_video_access_error( __( 'Kein Kurs zugeordnet.', 'kurs-booking' ) );
	}

	$item = get_post( $item_id );
	if ( ! $item ) {
		return kurs_booking_video_access_error( __( 'Kurs nicht gefunden.', 'kurs-booking' ) );
	}

	// Check if video-paket or kurs.
	$is_bundle       = ( 'video-paket' === $item->post_type );
	$access_days     = 0;
	$confirmed_date  = get_post_meta( $buchung_id, '_buchung_confirmed_date', true );
	$kurs            = null;
	$contained_kurse = array();
	$videos_by_kurs  = array();

	if ( $is_bundle ) {
		// Video-Paket: Get all videos grouped by course.
		$access_days = (int) get_post_meta( $item_id, Kurs_Booking_Video_Bundle::META_ACCESS_DAYS, true );
		$kurs_ids    = Kurs_Booking_Video_Bundle::get_video_kurs_ids( $item_id );

		foreach ( $kurs_ids as $kurs_id ) {
			$kurs_obj = get_post( $kurs_id );
			if ( $kurs_obj ) {
				$contained_kurse[]           = $kurs_obj;
				$videos_by_kurs[ $kurs_id ] = Kurs_Booking_Video::get_kurs_video_ids( $kurs_id );
			}
		}
		$kurs = $item; // Use bundle as main item.
	} else {
		// Single kurs: Check if digital product.
		$produktart = get_post_meta( $item_id, '_kurs_produktart', true );
		if ( 'videokurs' !== $produktart && 'webinar' !== $produktart ) {
			return kurs_booking_video_access_error( __( 'Dieser Kurs enthaelt keine Videos.', 'kurs-booking' ) );
		}

		$access_days              = (int) get_post_meta( $item_id, '_kurs_video_access_days', true );
		$videos_by_kurs[ $item_id ] = Kurs_Booking_Video::get_kurs_video_ids( $item_id );
		$kurs                     = $item;
	}

	// Check access duration.
	if ( $access_days > 0 && $confirmed_date ) {
		$access_until = strtotime( $confirmed_date ) + ( $access_days * DAY_IN_SECONDS );
		if ( time() > $access_until ) {
			return kurs_booking_video_access_error(
				sprintf(
					/* translators: %s: expiry date */
					__( 'Ihr Video-Zugang ist am %s abgelaufen.', 'kurs-booking' ),
					wp_date( get_option( 'date_format' ), $access_until )
				)
			);
		}
	}

	// Count total videos.
	$total_videos = 0;
	foreach ( $videos_by_kurs as $video_ids ) {
		$total_videos += count( $video_ids );
	}

	if ( 0 === $total_videos ) {
		return kurs_booking_video_access_info( __( 'Noch keine Videos verfuegbar. Bitte versuchen Sie es spaeter erneut.', 'kurs-booking' ) );
	}

	// Get customer info.
	$customer_name = get_post_meta( $buchung_id, '_buchung_customer_name', true );

	// Build output.
	ob_start();
	?>
	<div class="kb-video-access">
		<!-- Header -->
		<header class="kb-video-header">
			<div class="kb-video-header-content">
				<span class="kb-video-badge"><?php echo $is_bundle ? esc_html__( 'Video-Paket', 'kurs-booking' ) : esc_html__( 'Video-Kurs', 'kurs-booking' ); ?></span>
				<h1><?php echo esc_html( $kurs->post_title ); ?></h1>
				<p class="kb-video-welcome">
					<?php
					printf(
						/* translators: %s: customer name */
						esc_html__( 'Willkommen %s! Hier sind deine Videos.', 'kurs-booking' ),
						'<strong>' . esc_html( $customer_name ) . '</strong>'
					);
					?>
				</p>
			</div>

			<div class="kb-video-stats">
				<div class="kb-video-stat">
					<span class="kb-video-stat-value"><?php echo esc_html( (string) $total_videos ); ?></span>
					<span class="kb-video-stat-label"><?php esc_html_e( 'Videos', 'kurs-booking' ); ?></span>
				</div>
				<?php if ( $is_bundle && count( $contained_kurse ) > 1 ) : ?>
					<div class="kb-video-stat">
						<span class="kb-video-stat-value"><?php echo esc_html( (string) count( $contained_kurse ) ); ?></span>
						<span class="kb-video-stat-label"><?php esc_html_e( 'Kurse', 'kurs-booking' ); ?></span>
					</div>
				<?php endif; ?>
				<div class="kb-video-stat">
					<?php if ( $access_days > 0 && $confirmed_date ) : ?>
						<?php
						$access_until = strtotime( $confirmed_date ) + ( $access_days * DAY_IN_SECONDS );
						$days_left    = (int) ceil( ( $access_until - time() ) / DAY_IN_SECONDS );
						?>
						<span class="kb-video-stat-value"><?php echo esc_html( (string) $days_left ); ?></span>
						<span class="kb-video-stat-label"><?php esc_html_e( 'Tage Zugang', 'kurs-booking' ); ?></span>
					<?php else : ?>
						<span class="kb-video-stat-value">∞</span>
						<span class="kb-video-stat-label"><?php esc_html_e( 'Unbegrenzt', 'kurs-booking' ); ?></span>
					<?php endif; ?>
				</div>
			</div>
		</header>

		<!-- Video Sections -->
		<?php
		$global_video_number = 0;
		foreach ( $videos_by_kurs as $kurs_id => $video_ids ) :
			$section_kurs = get_post( $kurs_id );
			if ( ! $section_kurs || empty( $video_ids ) ) {
				continue;
			}
			?>
			<section class="kb-video-section">
				<?php if ( $is_bundle && count( $contained_kurse ) > 1 ) : ?>
					<div class="kb-video-section-header">
						<h2><?php echo esc_html( $section_kurs->post_title ); ?></h2>
						<span class="kb-video-section-count"><?php echo esc_html( (string) count( $video_ids ) ); ?> <?php esc_html_e( 'Videos', 'kurs-booking' ); ?></span>
					</div>
				<?php endif; ?>

				<div class="kb-video-grid">
					<?php
					foreach ( $video_ids as $video_id ) :
						$video = get_post( $video_id );
						if ( ! $video ) {
							continue;
						}

						++$global_video_number;
						$video_status   = get_post_meta( $video_id, '_video_status', true );
						$video_duration = (int) get_post_meta( $video_id, '_video_duration', true );
						$video_thumb    = get_post_meta( $video_id, '_video_thumbnail_url', true );
						$is_ready       = ( 'ready' === $video_status );
						?>
						<article class="kb-video-card <?php echo $is_ready ? 'is-ready' : 'is-processing'; ?>">
							<div class="kb-video-card-thumb">
								<?php if ( $video_thumb ) : ?>
									<img src="<?php echo esc_url( $video_thumb ); ?>" alt="<?php echo esc_attr( $video->post_title ); ?>" loading="lazy">
								<?php else : ?>
									<div class="kb-video-card-placeholder">
										<svg viewBox="0 0 24 24" fill="currentColor" width="48" height="48">
											<path d="M8 5v14l11-7z"/>
										</svg>
									</div>
								<?php endif; ?>

								<span class="kb-video-card-number"><?php echo esc_html( (string) $global_video_number ); ?></span>

								<?php if ( $video_duration > 0 ) : ?>
									<span class="kb-video-card-duration"><?php echo esc_html( gmdate( 'i:s', $video_duration ) ); ?></span>
								<?php endif; ?>

								<?php if ( ! $is_ready ) : ?>
									<div class="kb-video-card-overlay">
										<div class="kb-video-card-spinner"></div>
										<span><?php esc_html_e( 'Wird verarbeitet...', 'kurs-booking' ); ?></span>
									</div>
								<?php else : ?>
									<div class="kb-video-card-play">
										<svg viewBox="0 0 24 24" fill="currentColor" width="48" height="48">
											<path d="M8 5v14l11-7z"/>
										</svg>
									</div>
								<?php endif; ?>
							</div>

							<div class="kb-video-card-body">
								<h3><?php echo esc_html( $video->post_title ); ?></h3>
								<?php if ( $video->post_excerpt ) : ?>
									<p><?php echo esc_html( $video->post_excerpt ); ?></p>
								<?php endif; ?>
							</div>

							<?php if ( $is_ready ) : ?>
								<a href="#" class="kb-video-card-link" data-video-id="<?php echo esc_attr( (string) $video_id ); ?>" data-buchung-id="<?php echo esc_attr( (string) $buchung_id ); ?>">
									<span class="screen-reader-text"><?php echo esc_html( $video->post_title ); ?> <?php esc_html_e( 'abspielen', 'kurs-booking' ); ?></span>
								</a>
							<?php endif; ?>
						</article>
					<?php endforeach; ?>
				</div>
			</section>
		<?php endforeach; ?>

		<!-- Video Player Modal -->
		<div class="kb-video-modal" id="kb-video-modal" aria-hidden="true">
			<div class="kb-video-modal-backdrop"></div>
			<div class="kb-video-modal-content">
				<button type="button" class="kb-video-modal-close" aria-label="<?php esc_attr_e( 'Schliessen', 'kurs-booking' ); ?>">
					<svg viewBox="0 0 24 24" fill="currentColor" width="24" height="24">
						<path d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/>
					</svg>
				</button>
				<div class="kb-video-modal-player" id="kb-video-modal-player">
					<!-- Video player will be inserted here -->
				</div>
				<div class="kb-video-modal-title" id="kb-video-modal-title"></div>
			</div>
		</div>

		<?php if ( $kurs->post_content ) : ?>
			<section class="kb-video-description">
				<h2><?php esc_html_e( 'Kursbeschreibung', 'kurs-booking' ); ?></h2>
				<?php echo wp_kses_post( $kurs->post_content ); ?>
			</section>
		<?php endif; ?>
	</div>

	<style>
	/* Video Access - Card Layout - Theme Integrated */
	.kb-video-access {
		max-width: 1200px;
		margin: 0 auto;
		padding: 20px;
		font-family: var(--kb-font-body, 'Source Sans Pro', -apple-system, sans-serif);
	}

	/* Header */
	.kb-video-header {
		background: linear-gradient(135deg, var(--kb-primary, #00868b) 0%, var(--kb-primary-hover, #006d71) 50%, var(--kb-secondary, #312f2d) 100%);
		border-radius: var(--kb-radius-lg, 12px);
		padding: 40px;
		margin-bottom: 40px;
		color: white;
		display: flex;
		justify-content: space-between;
		align-items: center;
		gap: 30px;
		flex-wrap: wrap;
		box-shadow: var(--kb-shadow-lg, 0 10px 15px -3px rgba(0, 0, 0, 0.1));
	}

	.kb-video-header-content {
		flex: 1;
		min-width: 280px;
	}

	.kb-video-badge {
		display: inline-block;
		background: rgba(255,255,255,0.2);
		padding: 6px 14px;
		border-radius: 20px;
		font-size: 12px;
		font-weight: 600;
		margin-bottom: 15px;
		text-transform: uppercase;
		letter-spacing: 0.5px;
	}

	.kb-video-header h1 {
		font-family: var(--kb-font-heading, 'PT Serif', Georgia, serif);
		font-size: 2em;
		font-weight: 700;
		margin: 0 0 10px 0;
		color: white;
		line-height: 1.2;
	}

	.kb-video-welcome {
		font-size: 1.1em;
		opacity: 0.95;
		margin: 0;
	}

	.kb-video-welcome strong {
		color: var(--kb-accent, #c9a227);
	}

	/* Stats */
	.kb-video-stats {
		display: flex;
		gap: 20px;
	}

	.kb-video-stat {
		text-align: center;
		padding: 15px 25px;
		background: rgba(255,255,255,0.15);
		border-radius: var(--kb-radius, 8px);
		backdrop-filter: blur(10px);
	}

	.kb-video-stat-value {
		display: block;
		font-size: 2em;
		font-weight: 700;
		color: var(--kb-accent, #c9a227);
	}

	.kb-video-stat-label {
		font-size: 0.8em;
		opacity: 0.9;
		text-transform: uppercase;
		letter-spacing: 0.5px;
	}

	/* Section */
	.kb-video-section {
		margin-bottom: 40px;
	}

	.kb-video-section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;
		padding-bottom: 15px;
		border-bottom: 2px solid var(--kb-border, #e5e7eb);
	}

	.kb-video-section-header h2 {
		font-family: var(--kb-font-heading, 'PT Serif', Georgia, serif);
		font-size: 1.4em;
		margin: 0;
		color: var(--kb-secondary, #312f2d);
	}

	.kb-video-section-count {
		background: var(--kb-bg-light, #f9fafb);
		padding: 6px 14px;
		border-radius: 20px;
		font-size: 0.85em;
		color: var(--kb-text-light, #6b7280);
		border: 1px solid var(--kb-border, #e5e7eb);
	}

	/* Video Grid */
	.kb-video-grid {
		display: grid;
		grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
		gap: 24px;
	}

	/* Video Card */
	.kb-video-card {
		position: relative;
		background: var(--kb-bg, #ffffff);
		border: 1px solid var(--kb-border, #e5e7eb);
		border-radius: var(--kb-radius, 8px);
		overflow: hidden;
		transition: all var(--kb-transition, 0.2s ease);
	}

	.kb-video-card:hover {
		transform: translateY(-6px);
		box-shadow: var(--kb-shadow-lg, 0 10px 15px -3px rgba(0, 0, 0, 0.1));
		border-color: var(--kb-primary, #00868b);
	}

	.kb-video-card.is-processing {
		opacity: 0.7;
	}

	.kb-video-card-thumb {
		position: relative;
		aspect-ratio: 16/9;
		background: linear-gradient(135deg, var(--kb-secondary, #312f2d) 0%, var(--kb-primary-hover, #006d71) 100%);
		overflow: hidden;
	}

	.kb-video-card-thumb img {
		width: 100%;
		height: 100%;
		object-fit: cover;
		transition: transform 0.4s ease;
	}

	.kb-video-card:hover .kb-video-card-thumb img {
		transform: scale(1.05);
	}

	.kb-video-card-placeholder {
		width: 100%;
		height: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		color: rgba(255,255,255,0.4);
	}

	.kb-video-card-number {
		position: absolute;
		top: 12px;
		left: 12px;
		width: 32px;
		height: 32px;
		background: var(--kb-primary, #00868b);
		color: white;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-weight: 700;
		font-size: 14px;
	}

	.kb-video-card-duration {
		position: absolute;
		bottom: 12px;
		right: 12px;
		background: rgba(0,0,0,0.8);
		color: white;
		padding: 4px 10px;
		border-radius: var(--kb-radius-sm, 4px);
		font-size: 13px;
		font-weight: 500;
	}

	.kb-video-card-play {
		position: absolute;
		inset: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		background: rgba(0, 134, 139, 0.5);
		opacity: 0;
		transition: opacity 0.3s ease;
	}

	.kb-video-card-play svg {
		width: 64px;
		height: 64px;
		color: white;
		filter: drop-shadow(0 2px 8px rgba(0,0,0,0.3));
		transition: transform 0.2s ease;
	}

	.kb-video-card:hover .kb-video-card-play {
		opacity: 1;
	}

	.kb-video-card:hover .kb-video-card-play svg {
		transform: scale(1.1);
	}

	.kb-video-card-overlay {
		position: absolute;
		inset: 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background: rgba(0,0,0,0.7);
		color: white;
		font-size: 13px;
		gap: 10px;
	}

	.kb-video-card-spinner {
		width: 36px;
		height: 36px;
		border: 3px solid rgba(255,255,255,0.2);
		border-top-color: var(--kb-primary, #00868b);
		border-radius: 50%;
		animation: kb-video-spin 1s linear infinite;
	}

	@keyframes kb-video-spin {
		to { transform: rotate(360deg); }
	}

	.kb-video-card-body {
		padding: 18px;
	}

	.kb-video-card-body h3 {
		font-family: var(--kb-font-heading, 'PT Serif', Georgia, serif);
		font-size: 1em;
		font-weight: 600;
		margin: 0 0 8px 0;
		color: var(--kb-secondary, #312f2d);
		line-height: 1.4;
	}

	.kb-video-card-body p {
		font-size: 0.9em;
		color: var(--kb-text-light, #6b7280);
		margin: 0;
		line-height: 1.5;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		overflow: hidden;
	}

	.kb-video-card-link {
		position: absolute;
		inset: 0;
		z-index: 5;
	}

	/* Modal */
	.kb-video-modal {
		position: fixed;
		inset: 0;
		z-index: 999999;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 20px;
		opacity: 0;
		visibility: hidden;
		transition: all 0.3s ease;
	}

	.kb-video-modal[aria-hidden="false"] {
		opacity: 1;
		visibility: visible;
	}

	.kb-video-modal-backdrop {
		position: absolute;
		inset: 0;
		background: rgba(49, 47, 45, 0.95);
		backdrop-filter: blur(10px);
	}

	.kb-video-modal-content {
		position: relative;
		width: 100%;
		max-width: 1000px;
		background: var(--kb-secondary, #312f2d);
		border-radius: var(--kb-radius-lg, 12px);
		overflow: hidden;
		transform: scale(0.95);
		transition: transform 0.3s ease;
	}

	.kb-video-modal[aria-hidden="false"] .kb-video-modal-content {
		transform: scale(1);
	}

	.kb-video-modal-close {
		position: absolute;
		top: -50px;
		right: 0;
		background: var(--kb-primary, #00868b);
		border: none;
		color: white;
		width: 40px;
		height: 40px;
		border-radius: 50%;
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: center;
		transition: all 0.2s ease;
		z-index: 10;
	}

	.kb-video-modal-close:hover {
		background: var(--kb-primary-hover, #006d71);
		transform: rotate(90deg);
	}

	.kb-video-modal-player {
		aspect-ratio: 16/9;
		background: #000;
		position: relative;
	}

	.kb-video-modal-player video,
	.kb-video-modal-player iframe {
		width: 100%;
		height: 100%;
	}

	/* Video.js inside modal - fill entire player area */
	.kb-video-modal-player .kurs-video-player-container {
		margin: 0;
		height: 100%;
	}

	.kb-video-modal-player .video-js {
		width: 100% !important;
		height: 100% !important;
		aspect-ratio: unset !important;
		border-radius: 0 !important;
	}

	.kb-video-modal-player .kurs-video-info {
		display: none; /* Title is shown in modal-title */
	}

	.kb-video-modal-title {
		padding: 15px 20px;
		color: white;
		font-family: var(--kb-font-heading, 'PT Serif', Georgia, serif);
		font-weight: 600;
		background: var(--kb-secondary, #312f2d);
	}

	/* Description */
	.kb-video-description {
		margin-top: 50px;
		padding-top: 40px;
		border-top: 1px solid var(--kb-border, #e5e7eb);
	}

	.kb-video-description h2 {
		font-family: var(--kb-font-heading, 'PT Serif', Georgia, serif);
		font-size: 1.5em;
		margin-bottom: 20px;
		color: var(--kb-secondary, #312f2d);
	}

	/* Error / Info States */
	.kb-video-error,
	.kb-video-info {
		max-width: 500px;
		margin: 80px auto;
		padding: 50px;
		text-align: center;
		border-radius: var(--kb-radius-lg, 12px);
	}

	.kb-video-error {
		background: var(--kb-danger-light, #fee2e2);
		border: 1px solid var(--kb-danger, #dc2626);
	}

	.kb-video-error svg { color: var(--kb-danger, #dc2626); }
	.kb-video-error h2 { color: var(--kb-danger, #dc2626); }

	.kb-video-info {
		background: var(--kb-warning-light, #fef3c7);
		border: 1px solid var(--kb-warning, #ca8a04);
	}

	.kb-video-info svg { color: var(--kb-warning, #ca8a04); }
	.kb-video-info h2 { color: var(--kb-warning, #ca8a04); }

	/* Responsive */
	@media (max-width: 768px) {
		.kb-video-header {
			flex-direction: column;
			text-align: center;
			padding: 30px 20px;
		}

		.kb-video-header h1 {
			font-size: 1.6em;
		}

		.kb-video-stats {
			width: 100%;
			justify-content: center;
		}

		.kb-video-stat {
			padding: 12px 18px;
		}

		.kb-video-stat-value {
			font-size: 1.5em;
		}

		.kb-video-grid {
			grid-template-columns: 1fr;
		}

		.kb-video-section-header {
			flex-direction: column;
			gap: 10px;
			text-align: center;
		}

		.kb-video-modal-close {
			top: 10px;
			right: 10px;
		}
	}
	</style>

	<script>
	document.addEventListener('DOMContentLoaded', function() {
		var modal = document.getElementById('kb-video-modal');
		var modalPlayer = document.getElementById('kb-video-modal-player');
		var modalTitle = document.getElementById('kb-video-modal-title');

		// Open modal on card click.
		document.querySelectorAll('.kb-video-card-link').forEach(function(link) {
			link.addEventListener('click', function(e) {
				e.preventDefault();

				var videoId = this.dataset.videoId;
				var buchungId = this.dataset.buchungId;
				var card = this.closest('.kb-video-card');
				var title = card.querySelector('h3').textContent;

				// Set title.
				modalTitle.textContent = title;

				// Load video player via shortcode (AJAX would be better, but this works for now).
				modalPlayer.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;height:100%;color:#fff;"><div class="kb-video-card-spinner" style="width:48px;height:48px;"></div></div>';

				// Show modal.
				modal.setAttribute('aria-hidden', 'false');
				document.body.style.overflow = 'hidden';

				// AJAX load video player.
				var xhr = new XMLHttpRequest();
				xhr.open('POST', '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>');
				xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
				xhr.onload = function() {
					if (xhr.status === 200) {
						modalPlayer.innerHTML = xhr.responseText;

						// Execute scripts in AJAX-loaded content (innerHTML doesn't execute scripts).
						var scripts = modalPlayer.querySelectorAll('script');
						scripts.forEach(function(oldScript) {
							var newScript = document.createElement('script');
							newScript.textContent = oldScript.textContent;
							oldScript.parentNode.replaceChild(newScript, oldScript);
						});
					}
				};
				xhr.send('action=kurs_booking_get_video_player&video_id=' + videoId + '&buchung_id=' + buchungId + '&nonce=<?php echo esc_js( wp_create_nonce( 'kurs_booking_video_player' ) ); ?>');
			});
		});

		// Close modal.
		function closeModal() {
			modal.setAttribute('aria-hidden', 'true');
			document.body.style.overflow = '';

			// Stop video.
			var video = modalPlayer.querySelector('video');
			if (video) {
				video.pause();
			}
			var iframe = modalPlayer.querySelector('iframe');
			if (iframe) {
				iframe.src = '';
			}

			// Clear player.
			setTimeout(function() {
				modalPlayer.innerHTML = '';
				modalTitle.textContent = '';
			}, 300);
		}

		modal.querySelector('.kb-video-modal-close').addEventListener('click', closeModal);
		modal.querySelector('.kb-video-modal-backdrop').addEventListener('click', closeModal);

		// ESC key.
		document.addEventListener('keydown', function(e) {
			if (e.key === 'Escape' && modal.getAttribute('aria-hidden') === 'false') {
				closeModal();
			}
		});
	});
	</script>
	<?php
	return ob_get_clean();
}

/**
 * Display error message for video access
 *
 * @param string $message Error message.
 * @return string HTML output.
 */
function kurs_booking_video_access_error( string $message ): string {
	return sprintf(
		'<div class="kb-video-error">
			<svg viewBox="0 0 24 24" fill="currentColor" width="64" height="64" style="margin-bottom:20px;">
				<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
			</svg>
			<h2 style="font-family: var(--kb-font-heading, PT Serif, serif);">%s</h2>
			<p style="color:var(--kb-text-light, #6b7280);margin:15px 0 25px;">%s</p>
			<a href="%s" class="kb-btn kb-btn--primary" style="display:inline-block;padding:12px 24px;background:var(--kb-primary, #00868b);color:white;text-decoration:none;border-radius:var(--kb-radius, 8px);font-weight:600;">%s</a>
		</div>',
		esc_html__( 'Zugriff verweigert', 'kurs-booking' ),
		esc_html( $message ),
		esc_url( home_url() ),
		esc_html__( 'Zur Startseite', 'kurs-booking' )
	);
}

/**
 * Display info message for video access
 *
 * @param string $message Info message.
 * @return string HTML output.
 */
function kurs_booking_video_access_info( string $message ): string {
	return sprintf(
		'<div class="kb-video-info">
			<svg viewBox="0 0 24 24" fill="currentColor" width="64" height="64" style="margin-bottom:20px;">
				<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
			</svg>
			<h2 style="font-family: var(--kb-font-heading, PT Serif, serif);">%s</h2>
			<p style="color:var(--kb-text-light, #6b7280);margin:0;">%s</p>
		</div>',
		esc_html__( 'Hinweis', 'kurs-booking' ),
		esc_html( $message )
	);
}

/**
 * Register video access shortcode
 */
function kurs_booking_register_video_access_shortcode(): void {
	add_shortcode( 'kurs_video_access', 'kurs_booking_video_access_shortcode' );
}
add_action( 'init', 'kurs_booking_register_video_access_shortcode' );

/**
 * Video access shortcode handler.
 *
 * Usage: [kurs_video_access]
 * Reads token from URL: ?buchung={token}
 *
 * @param array<string, string>|string $atts Shortcode attributes.
 * @return string HTML output.
 */
function kurs_booking_video_access_shortcode( array|string $atts ): string {
	$atts = shortcode_atts(
		array(
			'token' => '',
		),
		$atts,
		'kurs_video_access'
	);

	// Pre-load Video.js for AJAX modal - needed because AJAX can't enqueue scripts.
	kurs_booking_enqueue_videojs();

	// Get token from URL or attribute.
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended
	$token = ! empty( $atts['token'] ) ? $atts['token'] : ( isset( $_GET['buchung'] ) ? sanitize_text_field( wp_unslash( $_GET['buchung'] ) ) : '' );

	return kurs_booking_get_video_access_content( $token );
}

/**
 * AJAX handler for loading video player
 */
function kurs_booking_ajax_get_video_player(): void {
	// Verify nonce.
	if ( ! isset( $_POST['nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['nonce'] ) ), 'kurs_booking_video_player' ) ) {
		wp_die( esc_html__( 'Sicherheitspruefung fehlgeschlagen.', 'kurs-booking' ) );
	}

	$video_id   = isset( $_POST['video_id'] ) ? absint( $_POST['video_id'] ) : 0;
	$buchung_id = isset( $_POST['buchung_id'] ) ? absint( $_POST['buchung_id'] ) : 0;

	if ( ! $video_id || ! $buchung_id ) {
		wp_die( esc_html__( 'Ungueltige Parameter.', 'kurs-booking' ) );
	}

	// Output the video player shortcode.
	echo do_shortcode( '[kurs_video buchung_id="' . esc_attr( (string) $buchung_id ) . '" video_id="' . esc_attr( (string) $video_id ) . '"]' );
	wp_die();
}
add_action( 'wp_ajax_kurs_booking_get_video_player', 'kurs_booking_ajax_get_video_player' );
add_action( 'wp_ajax_nopriv_kurs_booking_get_video_player', 'kurs_booking_ajax_get_video_player' );
