<?php
/**
 * Single Event template.
 *
 * Reads event data from JSON (by slug) rather than post meta,
 * since the mock API layer is the source of truth.
 *
 * Sections: Hero, Sticky BOOK NOW, Tabs (Details/Visit/Access/Cast),
 * Performance dates, Cross-sell.
 *
 * @package Northfield_Theatre
 * @since 1.0.0
 */

get_header();

// Get event by slug from URL.
$event_slug = get_query_var( 'nt_event' ) ?: get_post_field( 'post_name', get_the_ID() );
$event      = northfield_get_event_by_slug( $event_slug );

if ( ! $event ) {
	// Fallback: try from post meta.
	$json_id = get_post_meta( get_the_ID(), '_nt_event_json_id', true );
	if ( $json_id ) {
		$event = northfield_get_event( $json_id );
	}
}

if ( ! $event ) {
	get_template_part( '404' );
	return;
}

$instances    = northfield_get_instances( $event['id'] );
$ticket_types = northfield_get_event_ticket_types( $event['id'] );
$first_date   = northfield_get_event_first_date( $event['id'] );
$last_date    = northfield_get_event_last_date( $event['id'] );
$date_display = northfield_format_event_date_range( $first_date, $last_date );
$price_display = northfield_format_event_price_range( $event );

// Category gradient for hero background.
$category_gradients = array(
	'Drama'  => 'linear-gradient(135deg, #4A1942 0%, #1B4D3E 100%)',
	'Comedy' => 'linear-gradient(135deg, #92400E 0%, #E8A33D 100%)',
	'Music'  => 'linear-gradient(135deg, #312E81 0%, #6D28D9 100%)',
	'Dance'  => 'linear-gradient(135deg, #164E63 0%, #0891B2 100%)',
	'Family' => 'linear-gradient(135deg, #14532D 0%, #22C55E 100%)',
	'Other'  => 'linear-gradient(135deg, #78350F 0%, #D97706 100%)',
);
$hero_bg = isset( $category_gradients[ $event['category'] ] ) ? $category_gradients[ $event['category'] ] : $category_gradients['Other'];
$has_image = ! empty( $event['image'] ) && file_exists( NORTHFIELD_DIR . '/assets/images/' . $event['image'] );

// Cross-sell: get 3 related events from the same category.
$related = northfield_get_events( array(
	'category' => $event['category'],
	'limit'    => 4,
	'orderby'  => 'date',
) );
$related = array_filter( $related, function ( $e ) use ( $event ) {
	return $e['id'] !== $event['id'];
} );
$related = array_slice( array_values( $related ), 0, 3 );

// Running time display.
$hours   = floor( $event['runTime'] / 60 );
$minutes = $event['runTime'] % 60;
$run_time_display = '';
if ( $hours > 0 && $minutes > 0 ) {
	$run_time_display = sprintf( __( '%dh %dm', 'northfield-theatre' ), $hours, $minutes );
} elseif ( $hours > 0 ) {
	$run_time_display = sprintf( __( '%d hours', 'northfield-theatre' ), $hours );
} else {
	$run_time_display = sprintf( __( '%d minutes', 'northfield-theatre' ), $minutes );
}
?>

<!-- Hero Banner -->
<section class="event-hero" style="background: <?php echo esc_attr( $hero_bg ); ?>">
	<?php if ( $has_image ) : ?>
		<img class="event-hero__image" src="<?php echo esc_url( NORTHFIELD_URI . '/assets/images/' . $event['image'] ); ?>" alt="" loading="eager" />
	<?php endif; ?>
	<div class="event-hero__overlay"></div>
	<div class="event-hero__content container">
		<span class="badge badge--category"><?php echo esc_html( $event['category'] ); ?></span>
		<h1 class="event-hero__title"><?php echo esc_html( $event['name'] ); ?></h1>
		<p class="event-hero__meta">
			<?php if ( $date_display ) : ?>
				<span class="event-hero__date"><?php echo esc_html( $date_display ); ?></span>
			<?php endif; ?>
			<span class="event-hero__venue"><?php echo esc_html( $event['venue'] ); ?></span>
			<?php if ( $price_display ) : ?>
				<span class="event-hero__price"><?php echo esc_html( $price_display ); ?></span>
			<?php endif; ?>
		</p>
	</div>
</section>

<!-- Sticky BOOK NOW bar -->
<div class="book-bar" id="book-bar">
	<div class="book-bar__inner container">
		<div class="book-bar__info">
			<span class="book-bar__title"><?php echo esc_html( $event['name'] ); ?></span>
			<span class="book-bar__price"><?php echo esc_html( $price_display ); ?></span>
		</div>
		<?php if ( $event['saleStatus'] === 'OnSale' ) : ?>
			<a href="#performances" class="btn btn--primary book-bar__btn">
				<?php esc_html_e( 'Book Now', 'northfield-theatre' ); ?>
			</a>
		<?php else : ?>
			<span class="badge badge--soldout"><?php esc_html_e( 'Sold Out', 'northfield-theatre' ); ?></span>
		<?php endif; ?>
	</div>
</div>

<!-- Event Content -->
<div class="event-detail container">
	<div class="event-detail__layout">
		<div class="event-detail__main">
			<!-- Tab Navigation -->
			<nav class="event-tabs" aria-label="<?php esc_attr_e( 'Event information', 'northfield-theatre' ); ?>">
				<div class="event-tabs__list" role="tablist">
					<button class="event-tabs__tab event-tabs__tab--active" role="tab" id="tab-details" aria-selected="true" aria-controls="panel-details" tabindex="0">
						<?php esc_html_e( 'Details', 'northfield-theatre' ); ?>
					</button>
					<button class="event-tabs__tab" role="tab" id="tab-visit-info" aria-selected="false" aria-controls="panel-visit-info" tabindex="-1">
						<?php esc_html_e( 'Visit Info', 'northfield-theatre' ); ?>
					</button>
					<button class="event-tabs__tab" role="tab" id="tab-access" aria-selected="false" aria-controls="panel-access" tabindex="-1">
						<?php esc_html_e( 'Access', 'northfield-theatre' ); ?>
					</button>
				</div>
			</nav>

			<!-- Details Panel -->
			<div class="event-tabs__panel" role="tabpanel" id="panel-details" aria-labelledby="tab-details" tabindex="0">
				<div class="event-description entry-content">
					<?php
					// Convert \n\n to paragraphs.
					$paragraphs = preg_split( '/\n\n+/', $event['description'] );
					foreach ( $paragraphs as $para ) {
						echo '<p>' . esc_html( trim( $para ) ) . '</p>';
					}
					?>
				</div>

				<!-- Event details sidebar info -->
				<div class="event-info-box">
					<dl class="event-info-list">
						<?php if ( $run_time_display ) : ?>
							<div class="event-info-list__item">
								<dt><?php esc_html_e( 'Running time', 'northfield-theatre' ); ?></dt>
								<dd><?php echo esc_html( $run_time_display ); ?></dd>
							</div>
						<?php endif; ?>
						<?php if ( ! empty( $event['ageGuidance'] ) ) : ?>
							<div class="event-info-list__item">
								<dt><?php esc_html_e( 'Age guidance', 'northfield-theatre' ); ?></dt>
								<dd><?php echo esc_html( $event['ageGuidance'] ); ?></dd>
							</div>
						<?php endif; ?>
						<div class="event-info-list__item">
							<dt><?php esc_html_e( 'Venue', 'northfield-theatre' ); ?></dt>
							<dd><?php echo esc_html( $event['venue'] ); ?></dd>
						</div>
						<?php if ( ! empty( $event['warnings'] ) ) : ?>
							<div class="event-info-list__item">
								<dt><?php esc_html_e( 'Content warnings', 'northfield-theatre' ); ?></dt>
								<dd><?php echo esc_html( implode( ', ', $event['warnings'] ) ); ?></dd>
							</div>
						<?php endif; ?>
					</dl>
				</div>
			</div>

			<!-- Visit Info Panel -->
			<div class="event-tabs__panel" role="tabpanel" id="panel-visit-info" aria-labelledby="tab-visit-info" tabindex="0" hidden>
				<h2><?php esc_html_e( 'Visiting Northfield Theatre', 'northfield-theatre' ); ?></h2>
				<p><?php esc_html_e( 'Northfield Theatre is located in the centre of Northfield, West Yorkshire. We are a 10-minute walk from Northfield railway station.', 'northfield-theatre' ); ?></p>
				<h3><?php esc_html_e( 'Doors & Latecomers', 'northfield-theatre' ); ?></h3>
				<p><?php esc_html_e( 'Doors open 45 minutes before the performance. Latecomers will be admitted at a suitable break in the performance.', 'northfield-theatre' ); ?></p>
				<h3><?php esc_html_e( 'Interval Drinks', 'northfield-theatre' ); ?></h3>
				<p><?php esc_html_e( 'Pre-order your interval drinks at the Foyer Bar before the show to avoid the queue.', 'northfield-theatre' ); ?></p>
				<p><a href="<?php echo esc_url( home_url( '/visit/' ) ); ?>" class="btn btn--outline btn--sm"><?php esc_html_e( 'Full visit information', 'northfield-theatre' ); ?></a></p>
			</div>

			<!-- Access Panel -->
			<div class="event-tabs__panel" role="tabpanel" id="panel-access" aria-labelledby="tab-access" tabindex="0" hidden>
				<h2><?php esc_html_e( 'Access Information', 'northfield-theatre' ); ?></h2>
				<p><?php esc_html_e( 'Northfield Theatre is committed to making our programme accessible to everyone.', 'northfield-theatre' ); ?></p>
				<ul>
					<li><?php esc_html_e( 'Wheelchair accessible seating available in the stalls and circle', 'northfield-theatre' ); ?></li>
					<li><?php esc_html_e( 'Infrared hearing system available — collect a headset from the box office', 'northfield-theatre' ); ?></li>
					<li><?php esc_html_e( 'Assistance dogs welcome in the auditorium', 'northfield-theatre' ); ?></li>
					<li><?php esc_html_e( 'Large print cast sheets available on request', 'northfield-theatre' ); ?></li>
				</ul>
				<?php if ( ! empty( $event['warnings'] ) ) : ?>
					<h3><?php esc_html_e( 'Content Warnings', 'northfield-theatre' ); ?></h3>
					<ul>
						<?php foreach ( $event['warnings'] as $warning ) : ?>
							<li><?php echo esc_html( $warning ); ?></li>
						<?php endforeach; ?>
					</ul>
				<?php endif; ?>
				<p><a href="<?php echo esc_url( home_url( '/access/' ) ); ?>" class="btn btn--outline btn--sm"><?php esc_html_e( 'Full access information', 'northfield-theatre' ); ?></a></p>
			</div>
		</div>

		<!-- Performance Dates Sidebar -->
		<aside class="event-detail__sidebar" id="performances">
			<h2 class="event-detail__sidebar-title"><?php esc_html_e( 'Performances', 'northfield-theatre' ); ?></h2>
			<div class="performance-list">
				<?php foreach ( $instances as $instance ) :
					$inst_date = new DateTime( $instance['datetime'] );
					$avail_class = 'performance__availability--' . strtolower( $instance['availability'] );
					$avail_labels = array(
						'Available' => __( 'Available', 'northfield-theatre' ),
						'LastFew'   => __( 'Last few', 'northfield-theatre' ),
						'SoldOut'   => __( 'Sold out', 'northfield-theatre' ),
					);
					$avail_label = isset( $avail_labels[ $instance['availability'] ] ) ? $avail_labels[ $instance['availability'] ] : $instance['availability'];
					$badge_class = array(
						'Available' => 'badge--available',
						'LastFew'   => 'badge--low',
						'SoldOut'   => 'badge--soldout',
					);
					$badge = isset( $badge_class[ $instance['availability'] ] ) ? $badge_class[ $instance['availability'] ] : '';
				?>
					<div class="performance-item">
						<div class="performance-item__date">
							<span class="performance-item__day"><?php echo esc_html( $inst_date->format( 'D' ) ); ?></span>
							<span class="performance-item__daynum"><?php echo esc_html( $inst_date->format( 'j M' ) ); ?></span>
							<span class="performance-item__time"><?php echo esc_html( $inst_date->format( 'g:ia' ) ); ?></span>
						</div>
						<div class="performance-item__status">
							<span class="badge <?php echo esc_attr( $badge ); ?>"><?php echo esc_html( $avail_label ); ?></span>
						</div>
						<div class="performance-item__action">
							<?php if ( $instance['saleStatus'] === 'OnSale' ) : ?>
								<button class="btn btn--primary btn--sm book-btn"
								        data-event-id="<?php echo esc_attr( $event['id'] ); ?>"
								        data-instance-id="<?php echo esc_attr( $instance['id'] ); ?>"
								        data-event-name="<?php echo esc_attr( $event['name'] ); ?>"
								        data-datetime="<?php echo esc_attr( $instance['datetime'] ); ?>"
								        data-venue="<?php echo esc_attr( $instance['venue'] ); ?>">
									<?php esc_html_e( 'Book', 'northfield-theatre' ); ?>
								</button>
							<?php else : ?>
								<span class="btn btn--sm" style="opacity: 0.4; pointer-events: none;"><?php esc_html_e( 'Sold out', 'northfield-theatre' ); ?></span>
							<?php endif; ?>
						</div>
					</div>
				<?php endforeach; ?>
			</div>
		</aside>
	</div>
</div>

<!-- Cast & Creatives -->
<?php if ( ! empty( $event['cast'] ) || ! empty( $event['creatives'] ) ) : ?>
	<section class="cast-creatives section" aria-labelledby="cast-creatives-heading">
		<div class="container">
			<h2 id="cast-creatives-heading" class="cast-creatives__heading"><?php esc_html_e( 'Cast & Creatives', 'northfield-theatre' ); ?></h2>
			<div class="cast-creatives__grid">
				<?php if ( ! empty( $event['cast'] ) ) : ?>
					<div class="cast-creatives__col">
						<h3 class="cast-creatives__subheading"><?php esc_html_e( 'Cast', 'northfield-theatre' ); ?></h3>
						<dl class="cast-creatives__list">
							<?php foreach ( $event['cast'] as $person ) : ?>
								<div class="cast-creatives__row">
									<dt><?php echo esc_html( $person['actor'] ); ?></dt>
									<?php if ( ! empty( $person['role'] ) ) : ?>
										<dd><?php echo esc_html( $person['role'] ); ?></dd>
									<?php endif; ?>
								</div>
							<?php endforeach; ?>
						</dl>
					</div>
				<?php endif; ?>
				<?php if ( ! empty( $event['creatives'] ) ) : ?>
					<div class="cast-creatives__col">
						<h3 class="cast-creatives__subheading"><?php esc_html_e( 'Creatives', 'northfield-theatre' ); ?></h3>
						<dl class="cast-creatives__list">
							<?php foreach ( $event['creatives'] as $person ) : ?>
								<div class="cast-creatives__row">
									<dt><?php echo esc_html( $person['role'] ); ?></dt>
									<dd><?php echo esc_html( $person['name'] ); ?></dd>
								</div>
							<?php endforeach; ?>
						</dl>
					</div>
				<?php endif; ?>
			</div>
		</div>
	</section>
<?php endif; ?>

<!-- Cross-sell -->
<?php if ( ! empty( $related ) ) : ?>
	<section class="cross-sell section section--cream" aria-labelledby="cross-sell-heading">
		<div class="container">
			<h2 id="cross-sell-heading" class="cross-sell__title"><?php esc_html_e( 'You might also like', 'northfield-theatre' ); ?></h2>
			<div class="event-grid event-grid--3">
				<?php foreach ( $related as $rel_event ) : ?>
					<?php get_template_part( 'template-parts/content', 'event-card', array( 'event' => $rel_event ) ); ?>
				<?php endforeach; ?>
			</div>
		</div>
	</section>
<?php endif; ?>

<!-- Booking Modal -->
<div class="booking-modal" id="booking-modal" role="dialog" aria-modal="true" aria-labelledby="booking-modal-title" hidden>
	<div class="booking-modal__backdrop" id="booking-modal-backdrop"></div>
	<div class="booking-modal__dialog">
		<div class="booking-modal__header">
			<h2 class="booking-modal__title" id="booking-modal-title"><?php esc_html_e( 'Select Tickets', 'northfield-theatre' ); ?></h2>
			<button class="booking-modal__close" id="booking-modal-close" aria-label="<?php esc_attr_e( 'Close', 'northfield-theatre' ); ?>">
				<?php echo northfield_icon( 'close', 24 ); ?>
			</button>
		</div>
		<div class="booking-modal__body">
			<p class="booking-modal__event-name" id="modal-event-name"></p>
			<p class="booking-modal__datetime" id="modal-datetime"></p>

			<div class="booking-modal__tickets" id="modal-tickets">
				<?php foreach ( $ticket_types as $tt ) : ?>
					<div class="ticket-row" data-ticket-id="<?php echo esc_attr( $tt['id'] ); ?>" data-price="<?php echo esc_attr( $tt['price'] ); ?>">
						<div class="ticket-row__info">
							<span class="ticket-row__name"><?php echo esc_html( $tt['name'] ); ?></span>
							<span class="ticket-row__desc"><?php echo esc_html( $tt['description'] ); ?></span>
							<span class="ticket-row__price"><?php echo esc_html( northfield_format_price( $tt['price'] ) ); ?></span>
						</div>
						<div class="ticket-row__qty">
							<button class="ticket-row__btn ticket-row__btn--minus" aria-label="<?php esc_attr_e( 'Decrease quantity', 'northfield-theatre' ); ?>" disabled>−</button>
							<span class="ticket-row__count" aria-live="polite">0</span>
							<button class="ticket-row__btn ticket-row__btn--plus" aria-label="<?php esc_attr_e( 'Increase quantity', 'northfield-theatre' ); ?>">+</button>
						</div>
					</div>
				<?php endforeach; ?>
			</div>

			<div class="booking-modal__total">
				<span class="booking-modal__total-label"><?php esc_html_e( 'Total:', 'northfield-theatre' ); ?></span>
				<span class="booking-modal__total-amount" id="modal-total">£0.00</span>
			</div>
		</div>
		<div class="booking-modal__footer">
			<button class="btn btn--primary btn--full booking-modal__add" id="modal-add-to-basket" disabled>
				<?php esc_html_e( 'Add to Basket', 'northfield-theatre' ); ?>
			</button>
		</div>
	</div>
</div>

<script type="application/json" id="event-ticket-types">
<?php echo wp_json_encode( $ticket_types ); ?>
</script>

<?php
get_footer();
