<?php
/**
 * Template name: HOME NEW
 *
 * @package far_loop
 */

get_header();

$fields = array_fill_keys( array(
	'dates',
	'subtitle',
	'hero_style',
	'featured_video',
	'custom_video',
	'custom_video_caption',
	'linked_image',
	'linked_image_link',
	'linked_image_caption',
	'sections',
), null );

foreach ( $fields as $field => $value ) {
	$fields[ $field ] = get_field( $field );
}
?>



<canvas id="bird-canvas"></canvas>
<div id="save-info"></div>


<div class="u_pt-3 u_pt-md-6">

		<?php
		$header_display = get_field('home_header_layout'); 
		if ($header_display == 'image') { ?>

		<div class="home-hero home-hero-image">
			<!-- Image Home -->
			<div class="grid u_mt-4 header-home-image">
					<div class="header-home-video__wrapper">
						<figure class="cover-image"><img src="<?php the_field('home_header_image'); ?>"></figure>

							<?php 
							$display_dates = get_field('display_dates'); // 'show' | 'hide'
							if ( $display_dates !== 'hide' ) :
						

							// Fechas (solo imprimimos las que existan)
							$dates_fair      = trim((string) get_field('date_fair'));
							$dates_festival  = trim((string) get_field('date_festival'));
							$dates_symposium = trim((string) get_field('dates_symposium'));
							?>
							
							<?php
							// Recoge y normaliza el layout
							$dates_layout_raw = get_field('dates_header_layout'); // return format = value
							$dates_layout = strtolower( trim( (string) $dates_layout_raw ) );

							// Aceptamos sólo estos tres; por defecto 'row'
							$allowed = array( 'column', 'row', 'banner' );
							if ( ! in_array( $dates_layout, $allowed, true ) ) {
								$dates_layout = 'row';
							}
							?>
							<div class="festival-dates-header-home layout-<?php echo esc_attr( $dates_layout ); ?>">
							<?php switch ( $dates_layout ) :

								case 'banner': ?>

									<div class="container-scroll-dates">
									<div class="rail">
										<div class="text-banner">
										<span>
											<?php if ( !empty($dates_fair) ) : ?>
											<span class="date-scroll__title"><?php esc_html_e('Fair', 'far_loop'); ?> </span>
											<span class="date-scroll__date"><?php echo esc_html($dates_fair); ?></span>
											<span class="date-scroll__separator">•</span>
											<?php endif; ?>
											<?php if ( !empty($dates_festival) ) : ?>
											<span class="date-scroll__title"><?php esc_html_e('Festival', 'far_loop'); ?> </span>
											<span class="date-scroll__date"><?php echo esc_html($dates_festival); ?></span>
											<span class="date-scroll__separator">•</span>
											<?php endif; ?>
											<?php if ( !empty($dates_symposium) ) : ?>
											<span class="date-scroll__title"><?php esc_html_e('Symposium', 'far_loop'); ?> </span>
											<span class="date-scroll__date"><?php echo esc_html($dates_symposium); ?></span>
											<span class="date-scroll__separator">•</span>
											<?php endif; ?>
										</span>
										<!-- duplicamos el mismo texto para efecto continuo -->
										<span>
											<?php if ( !empty($dates_fair) ) : ?>
											<span class="date-scroll__title"><?php esc_html_e('Fair', 'far_loop'); ?> </span>
											<span class="date-scroll__date"><?php echo esc_html($dates_fair); ?></span>
											<span class="date-scroll__separator">•</span>
											<?php endif; ?>
											<?php if ( !empty($dates_festival) ) : ?>
											<span class="date-scroll__title"><?php esc_html_e('Festival', 'far_loop'); ?> </span>
											<span class="date-scroll__date"><?php echo esc_html($dates_festival); ?></span>
											<span class="date-scroll__separator">•</span>
											<?php endif; ?>
											<?php if ( !empty($dates_symposium) ) : ?>
											<span class="date-scroll__title"><?php esc_html_e('Symposium', 'far_loop'); ?> </span>
											<span class="date-scroll__date"><?php echo esc_html($dates_symposium); ?></span>
											<span class="date-scroll__separator">•</span>
											<?php endif; ?>
										</span>
										</div>
									</div>
									</div>

								<?php break;

								case 'column': ?>
	
								<!-- ===== Diseño en columnas (tabla vertical) ===== -->
								<table class="home-hero__dates">
									<tbody>
									<?php if ( !empty($dates_fair) ) : ?>
									<tr class="-fair">
										<th><span><?php esc_html_e('Fair', 'far_loop'); ?></span></th>
										<td><?php echo esc_html($dates_fair); ?></td>
									</tr>
									<?php endif; ?>

									<?php if ( !empty($dates_festival) ) : ?>
									<tr class="-festival">
										<th><span><?php esc_html_e('Festival', 'far_loop'); ?></span></th>
										<td><?php echo esc_html($dates_festival); ?></td>
									</tr>
									<?php endif; ?>

									<?php if ( !empty($dates_symposium) ) : ?>
									<tr class="-symposium">
										<th><span><?php esc_html_e('Symposium', 'far_loop'); ?></span></th>
										<td><?php echo esc_html($dates_symposium); ?></td>
									</tr>
									<?php endif; ?>
									</tbody>
								</table>

								<?php break;

								case 'row':
								default: ?>
								<!-- ===== Diseño en filas (tres bloques alineados) ===== -->
								<div class="home-hero__dates-row">
									<?php if ( !empty($dates_fair) ) : ?>
									<div class="date-card -fair">
									<div class="date-card__title"><?php esc_html_e('Fair', 'far_loop'); ?></div>
									<div class="date-card__date"><?php echo esc_html($dates_fair); ?></div>
									</div>
									<?php endif; ?>

									<?php if ( !empty($dates_festival) ) : ?>
									<div class="date-card -festival">
									<div class="date-card__title"><?php esc_html_e('Festival', 'far_loop'); ?></div>
									<div class="date-card__date"><?php echo esc_html($dates_festival); ?></div>
									</div>
									<?php endif; ?>

									<?php if ( !empty($dates_symposium) ) : ?>
									<div class="date-card -symposium">
									<div class="date-card__title"><?php esc_html_e('Symposium', 'far_loop'); ?></div>
									<div class="date-card__date"><?php echo esc_html($dates_symposium); ?></div>
									</div>
									<?php endif; ?>
								</div>
								<?php break; ?>

							<?php endswitch; ?>
							</div>


							<?php endif; ?>



					</div>	
			</div>	
		</div>	

		<?php } elseif ($header_display == 'video') { ?>	

		<?php 
		$video_url  = get_field('home_header_video'); // URL del archivo
		$video_text = get_field('home_header_text'); 
		?>

		<div class="home-hero home-hero-video">	
		<?php if ( $video_url ) : ?>
			<div class="grid header-home-video">
				<div class="header-home-video__wrapper">
					<video autoplay muted loop playsinline class="header-home-video__video">
					<source src="<?php echo esc_url($video_url); ?>" type="video/mp4">
					<?php esc_html_e('Your browser does not support the video tag.', 'far_loop'); ?>
					</video>
					<?php if ( $video_text ) : ?>
					<div class="header-home-video__overlay">
						<?php echo $video_text; ?>
					</div>
					<?php endif; ?>


							<?php 
							$display_dates = get_field('display_dates'); // 'show' | 'hide'
							if ( $display_dates !== 'hide' ) :

							// 'column' (por defecto) o 'row'
							$dates_layout = get_field('dates_header_layout');
							if ( ! in_array($dates_layout, array('column','row', 'banner'), true) ) {
								$dates_layout = 'column';
							}

							// Fechas (solo imprimimos las que existan)
							$dates_fair      = trim((string) get_field('date_fair'));
							$dates_festival  = trim((string) get_field('date_festival'));
							$dates_symposium = trim((string) get_field('dates_symposium'));
							?>
							
							<div class="festival-dates-header-home layout-<?php echo esc_attr($dates_layout); ?>">
								
								<?php if ( $dates_layout === 'column' ) : ?>
								<!-- ===== Diseño en columnas (tabla vertical, como ahora) ===== -->
								<table class="home-hero__dates">
									<tbody>
									<?php if ( $dates_fair ) : ?>
										<tr class="-fair">
										<th><span><?php esc_html_e('Fair', 'far_loop'); ?></span></th>
										<td><?php echo esc_html($dates_fair); ?></td>
										</tr>
									<?php endif; ?>

									<?php if ( $dates_festival ) : ?>
										<tr class="-festival">
										<th><span><?php esc_html_e('Festival', 'far_loop'); ?></span></th>
										<td><?php echo esc_html($dates_festival); ?></td>
										</tr>
									<?php endif; ?>

									<?php if ( $dates_symposium ) : ?>
										<tr class="-symposium">
										<th><span><?php esc_html_e('Symposium', 'far_loop'); ?></span></th>
										<td><?php echo esc_html($dates_symposium); ?></td>
										</tr>
									<?php endif; ?>
									</tbody>
								</table>


								<?php elseif ( $dates_layout === 'banner' ) : ?>

								<!-- ===== Diseño scroll/marquee ===== -->
								<div class="container-scroll-dates">
								<div class="rail">
									<div class="text-banner">
									<span>
										<?php if ( !empty($dates_fair) ) : ?>
										<span class="date-scroll__title"><?php esc_html_e('Fair', 'far_loop'); ?> </span>
										<span class="date-scroll__date"><?php echo esc_html($dates_fair); ?></span>
										<span class="date-scroll__separator">•</span>
										<?php endif; ?>
										<?php if ( !empty($dates_festival) ) : ?>
										<span class="date-scroll__title"><?php esc_html_e('Festival', 'far_loop'); ?> </span>
										<span class="date-scroll__date"><?php echo esc_html($dates_festival); ?></span>
										<span class="date-scroll__separator">•</span>
										<?php endif; ?>
										<?php if ( !empty($dates_symposium) ) : ?>
										<span class="date-scroll__title"><?php esc_html_e('Symposium', 'far_loop'); ?> </span>
										<span class="date-scroll__date"><?php echo esc_html($dates_symposium); ?></span>
										<span class="date-scroll__separator">•</span>
										<?php endif; ?>
									</span>
									<!-- duplicamos el mismo texto para efecto continuo -->
									<span>
										<?php if ( !empty($dates_fair) ) : ?>
										<span class="date-scroll__title"><?php esc_html_e('Fair', 'far_loop'); ?> </span>
										<span class="date-scroll__date"><?php echo esc_html($dates_fair); ?></span>
										<span class="date-scroll__separator">•</span>
										<?php endif; ?>
										<?php if ( !empty($dates_festival) ) : ?>
										<span class="date-scroll__title"><?php esc_html_e('Festival', 'far_loop'); ?> </span>
										<span class="date-scroll__date"><?php echo esc_html($dates_festival); ?></span>
										<span class="date-scroll__separator">•</span>
										<?php endif; ?>
										<?php if ( !empty($dates_symposium) ) : ?>
										<span class="date-scroll__title"><?php esc_html_e('Symposium', 'far_loop'); ?> </span>
										<span class="date-scroll__date"><?php echo esc_html($dates_symposium); ?></span>
										<span class="date-scroll__separator">•</span>
										<?php endif; ?>
									</span>
									</div>
								</div>
								</div>

								<?php else : ?>
								<!-- ===== Diseño en filas (tres bloques alineados) ===== -->
								<div class="home-hero__dates-row">
									<?php if ( $dates_fair ) : ?>
									<div class="date-card -fair">
										<div class="date-card__title"><?php esc_html_e('Fair', 'far_loop'); ?></div>
										<div class="date-card__date"><?php echo esc_html($dates_fair); ?></div>
									</div>
									<?php endif; ?>

									<?php if ( $dates_festival ) : ?>
									<div class="date-card -festival">
										<div class="date-card__title"><?php esc_html_e('Festival', 'far_loop'); ?></div>
										<div class="date-card__date"><?php echo esc_html($dates_festival); ?></div>
									</div>
									<?php endif; ?>

									<?php if ( $dates_symposium ) : ?>
									<div class="date-card -symposium">
										<div class="date-card__title"><?php esc_html_e('Symposium', 'far_loop'); ?></div>
										<div class="date-card__date"><?php echo esc_html($dates_symposium); ?></div>
									</div>
									<?php endif; ?>
								</div>
								<?php endif; ?>

							</div>
							<?php endif; ?>




				</div>
			</div>
		<?php endif; ?>
		</div>

		<?php } else { ?> 

		<div class="home-hero home-hero-slide">
			<!-- Slide Home -->
			<div class="slide-home-container">
				<div class="swiper-container">
					<div class="swiper-wrapper">
						<?php if( have_rows('slide_home') ): 
								while( have_rows('slide_home') ): the_row(); 
									$image = get_sub_field('image_slide_home'); ?>
								
										<div class="swiper-slide">
											<?php if($image): ?>
												<img class="image-slide-home" src="<?php echo $image; ?>" />
											<?php endif; ?>
										</div>
									<?php endwhile; ?>
								


							
							<?php endif; ?>
					</div>	
					
							<?php 
							$display_dates = get_field('display_dates'); // 'show' | 'hide'
							if ( $display_dates !== 'hide' ) :

							// 'column' (por defecto) o 'row'
							$dates_layout = get_field('dates_header_layout');
							if ( ! in_array($dates_layout, array('column','row'), true) ) {
								$dates_layout = 'column';
							}

							// Fechas (solo imprimimos las que existan)
							$dates_fair      = trim((string) get_field('date_fair'));
							$dates_festival  = trim((string) get_field('date_festival'));
							$dates_symposium = trim((string) get_field('dates_symposium'));
							?>
							
							<div class="festival-dates-header-home layout-<?php echo esc_attr($dates_layout); ?>">
								
								<?php if ( $dates_layout === 'column' ) : ?>
								<!-- ===== Diseño en columnas (tabla vertical, como ahora) ===== -->
								<table class="home-hero__dates">
									<tbody>
									<?php if ( $dates_fair ) : ?>
										<tr class="-fair">
										<th><span><?php esc_html_e('Fair', 'far_loop'); ?></span></th>
										<td><?php echo esc_html($dates_fair); ?></td>
										</tr>
									<?php endif; ?>

									<?php if ( $dates_festival ) : ?>
										<tr class="-festival">
										<th><span><?php esc_html_e('Festival', 'far_loop'); ?></span></th>
										<td><?php echo esc_html($dates_festival); ?></td>
										</tr>
									<?php endif; ?>

									<?php if ( $dates_symposium ) : ?>
										<tr class="-symposium">
										<th><span><?php esc_html_e('Symposium', 'far_loop'); ?></span></th>
										<td><?php echo esc_html($dates_symposium); ?></td>
										</tr>
									<?php endif; ?>
									</tbody>
								</table>

								<?php elseif ( $dates_layout === 'banner' ) : ?>

									<!-- ===== Diseño scroll/marquee ===== -->
									<div class="container-scroll-dates">
									<div class="rail">
										<div class="text-banner">
										<span>
											<?php if ( !empty($dates_fair) ) : ?>
											<span class="date-scroll__title"><?php esc_html_e('Fair', 'far_loop'); ?> </span>
											<span class="date-scroll__date"><?php echo esc_html($dates_fair); ?></span>
											<span class="date-scroll__separator">•</span>
											<?php endif; ?>
											<?php if ( !empty($dates_festival) ) : ?>
											<span class="date-scroll__title"><?php esc_html_e('Festival', 'far_loop'); ?> </span>
											<span class="date-scroll__date"><?php echo esc_html($dates_festival); ?></span>
											<span class="date-scroll__separator">•</span>
											<?php endif; ?>
											<?php if ( !empty($dates_symposium) ) : ?>
											<span class="date-scroll__title"><?php esc_html_e('Symposium', 'far_loop'); ?> </span>
											<span class="date-scroll__date"><?php echo esc_html($dates_symposium); ?></span>
											<span class="date-scroll__separator">•</span>
											<?php endif; ?>
										</span>
										<!-- duplicamos el mismo texto para efecto continuo -->
										<span>
											<?php if ( !empty($dates_fair) ) : ?>
											<span class="date-scroll__title"><?php esc_html_e('Fair', 'far_loop'); ?> </span>
											<span class="date-scroll__date"><?php echo esc_html($dates_fair); ?></span>
											<span class="date-scroll__separator">•</span>
											<?php endif; ?>
											<?php if ( !empty($dates_festival) ) : ?>
											<span class="date-scroll__title"><?php esc_html_e('Festival', 'far_loop'); ?> </span>
											<span class="date-scroll__date"><?php echo esc_html($dates_festival); ?></span>
											<span class="date-scroll__separator">•</span>
											<?php endif; ?>
											<?php if ( !empty($dates_symposium) ) : ?>
											<span class="date-scroll__title"><?php esc_html_e('Symposium', 'far_loop'); ?> </span>
											<span class="date-scroll__date"><?php echo esc_html($dates_symposium); ?></span>
											<span class="date-scroll__separator">•</span>
											<?php endif; ?>
										</span>
										</div>
									</div>
									</div>

								<?php else : ?>
								<!-- ===== Diseño en filas (tres bloques alineados) ===== -->
								<div class="home-hero__dates-row">
									<?php if ( $dates_fair ) : ?>
									<div class="date-card -fair">
										<div class="date-card__title"><?php esc_html_e('Fair', 'far_loop'); ?></div>
										<div class="date-card__date"><?php echo esc_html($dates_fair); ?></div>
									</div>
									<?php endif; ?>

									<?php if ( $dates_festival ) : ?>
									<div class="date-card -festival">
										<div class="date-card__title"><?php esc_html_e('Festival', 'far_loop'); ?></div>
										<div class="date-card__date"><?php echo esc_html($dates_festival); ?></div>
									</div>
									<?php endif; ?>

									<?php if ( $dates_symposium ) : ?>
									<div class="date-card -symposium">
										<div class="date-card__title"><?php esc_html_e('Symposium', 'far_loop'); ?></div>
										<div class="date-card__date"><?php echo esc_html($dates_symposium); ?></div>
									</div>
									<?php endif; ?>
								</div>
								<?php endif; ?>

							</div>
							<?php endif; ?>
				</div>
			</div>

				<?php $slide_text = get_field('home_header_text'); 
				if ( $slide_text ) : ?>
					<div class="header-home-slide__overlay">
						<?php echo $slide_text; ?>
					</div>
				<?php endif; ?>
		</div>


	<?php } ?> 	


	




		<!-- BLOCK NEWS -->
		<div class="l_container u_pt-3">
			<?php $page_for_posts = get_option( 'page_for_posts' ); ?>
			<!-- 
				<div class="view-all-home-new">
					<a href="<?php echo esc_url( get_permalink( $page_for_posts ) ); ?>" class="home-pillar__cta">
						<span class="home-pillar__cta-text"><?php _e('View all news', 'far_loop');?></span>
					</a>
				</div>
			-->		

			<?php
			$columns_class = get_field('columns_news_home'); // 'four', 'three' o 'mixed'
			if ( ! $columns_class ) {
			$columns_class = 'four'; // fallback por defecto si no está definido
			}
			?>
			<div class="<?php echo esc_attr( $columns_class ); ?>-cols-home-news">
				<?php get_template_part( 'template-parts/front-page-featured-new' ); ?>
			</div>
		</div>


		<?php
		$agenda_visibility = get_field('agenda_home_visibility'); // devuelve 'show' o 'hide'
		?>









		<?php if ( $agenda_visibility !== 'hide' ) : ?>
		<!-- BLOCK AGENDA -->
		<div class="l_container u_pt-2 block-agenda-home">

			<h3 class="section-heading delta"><span class="u_text-underline">Agenda</span></h3>

			<?php
				$featured_events = get_field('agenda_featured_activities'); // array de WP_Post
				if ( ! empty($featured_events) && is_array($featured_events) ) : ?>
				
				<!-- Vista Texto -->
				<div class="agenda-grid-text agenda-view-text">
					<?php
					global $post;
					$old_post = $post;

					foreach ( $featured_events as $event_post ) :
					// Normalizar a objeto
					$post = is_object($event_post) ? $event_post : get_post((int)$event_post);
					if ( ! $post ) { continue; }
					setup_postdata($post);

					// ======= Fecha / clase de fecha =======
					$dates            = get_field('dates', $post->ID); // repeater
					$event_start_date = '';
					if ( ! empty($dates) && is_array($dates) && ! empty($dates[0]['start_date']) ) {
						$event_start_date = $dates[0]['start_date']; // se asume ISO y/o strtotime-compatible
					}
					$date_class = '';
					if ( $event_start_date ) {
						$date_label = date_i18n( 'j M', strtotime( $event_start_date ) );
						$date_class = strtolower( str_replace( ' ', '-', $date_label ) );
					}

					// ======= Taxonomías / clases por categoría =======
					$terms            = get_the_terms( get_the_ID(), 'activity-type' );
					$category_classes = '';
					$parent_class     = 'festival'; // por defecto

					if ( $terms && ! is_wp_error( $terms ) ) {
						foreach ( $terms as $term ) {
						$slug              = $term->slug;
						$category_classes .= ' ' . sanitize_html_class( $slug );

						if ( in_array( $slug, array( 'panel', 'conference', 'talk' ), true ) ) {
							$parent_class = 'symposium';
						} elseif ( in_array( $slug, array( 'professional-meeting', 'professional-meetings' ), true ) ) {
							$parent_class = 'fair';
						}
						}
					}

					// ======= Output item (igual que ejemplo) =======
					echo '<div class="agenda-text-item agenda-list' 
							. esc_attr( $category_classes )
							. ( $date_class ? ' ' . esc_attr( $date_class ) : '' )
							. ' ' . esc_attr( $parent_class )
							. '">';

					// Partial existente (si lo tienes). Si no, puedes reemplazar por markup inline.
					get_template_part( 'template-parts/content-agenda-text' );

					echo '</div>';

					endforeach;

					wp_reset_postdata();
					$post = $old_post;
					?>
				</div>

				<?php endif; ?>

		</div>
		<?php endif; ?>






		<?php
		$fair_video_home_visibility = get_field('fair_video_home_visibility'); // 'show' | 'hide'
		if ( $fair_video_home_visibility !== 'hide' ) : ?>
		<div class="l_container u_pt-2 block-videofair-home">
			<h3 class="section-heading delta section-heading-slide"><span class="u_text-underline">Loop Fair Video Selection</span></h3>
		<?php
		$videos_sel = get_field('fair_home_video_selection'); // array de posts/IDs
		if ( ! empty($videos_sel) && is_array($videos_sel) ) :

			// Normalizamos a posts
			$videos = [];
			foreach ( $videos_sel as $v ) {
			$videos[] = is_object($v) ? $v : get_post((int)$v);
			}
			$videos = array_filter($videos);

			if ( ! empty($videos) ) :
			// IDs únicos para esta instancia
			$root_id  = 'fair-home-vid-' . uniqid();
			$swiper_id= $root_id . '-swiper';
			$prev_id  = $root_id . '-prev';
			$next_id  = $root_id . '-next';
			$count    = count($videos);
		?>
			<!-- === FAIR HOME VIDEOS (SLIDE) === -->
			<div class="awards-past awards-past--slider" data-fair-videos-swiper-root="<?php echo esc_attr($root_id); ?>">
				<div class="swiper awards-past-swiper video-fair-home-swiper"
					id="<?php echo esc_attr($swiper_id); ?>"
					data-items-count="<?php echo esc_attr($count); ?>"
					style="opacity:0; transition:opacity .2s;">

				<!-- Controles -->
				<div class="swiper-nav">
					<button class="swiper-btn prev" id="<?php echo esc_attr($prev_id); ?>" aria-label="<?php esc_attr_e('Previous','far_loop'); ?>">&larr;</button>
					<button class="swiper-btn next" id="<?php echo esc_attr($next_id); ?>" aria-label="<?php esc_attr_e('Next','far_loop'); ?>">&rarr;</button>
				</div>

				<div class="swiper-wrapper">
					<?php foreach ( $videos as $video ) :
					$vid_id  = (int) $video->ID;
					$url     = get_permalink($vid_id);

					// Imagen de portada
					$cover   = get_field('cover_image', $vid_id);
					$src     = (!empty($cover) && !empty($cover['url'])) ? $cover['url'] : get_template_directory_uri().'/img/horizontal-placeholder.svg';

					// Año
					$year    = get_field('year', $vid_id);

					// Autores
					$authors = get_field('author', $vid_id);
					$authors_string = function_exists('get_authors_string') ? get_authors_string($authors) : '';

					// Gallery (nombre + ciudad)
					$gallery = get_field('gallery', $vid_id);
					$gallery_string = '';
					if ( $gallery ) {
						$gid     = is_object($gallery) ? $gallery->ID : (int)$gallery;
						$g_title = get_the_title($gid);
						$addr    = get_field('address', $gid);
						$g_city  = (!empty($addr[0]['city'])) ? $addr[0]['city'] : '';
						$gallery_string = trim( $g_title . ( $g_city ? " ($g_city)" : '' ) );
					}

					// Edición (si existe; aquí no hay $term->name)
					$editions = get_the_terms($vid_id, 'edition');
					$edition_label = (!empty($editions) && !is_wp_error($editions)) ? $editions[0]->name : '';
					?>
					<div class="swiper-slide">
						<div class="archive-item">
						<a href="<?php echo esc_url($url); ?>" class="archive-new-thumb">
							<div class="archive-thumb__image-container award">
							<img src="<?php echo esc_url($src); ?>" alt="<?php echo esc_attr(get_the_title($vid_id)); ?>">
							</div>
							<div class="archive-thumb__text">
							<h3 class="archive-thumb__title">
								<?php echo esc_html( get_the_title($vid_id) ); ?>
								<?php if ( !empty($year) ) echo ' (' . esc_html($year) . ')'; ?>
							</h3>

							<div class="archive-thumb__label">
								<?php if ( $authors_string ): ?>
								<div class="awards-past-thumb__title"><?php echo esc_html($authors_string); ?></div>
								<?php endif; ?>
								<?php if ( $gallery_string ): ?>
								<!-- <div class="awards-past-thumb__title awards-past-thumb__galery"><?php echo esc_html($gallery_string); ?></div>-->
								<?php endif; ?>
							</div>

							<?php if ( $edition_label ) : ?>
								<div class="archive-thumb__year"><?php echo esc_html($edition_label); ?></div>
							<?php endif; ?>
							</div>
						</a>
						</div>
					</div>
					<?php endforeach; ?>
				</div><!-- /.swiper-wrapper -->
				</div><!-- /.swiper -->
			</div><!-- /.awards-past -->





		<?php
			endif;
		endif;?>
		</div>
		<?php endif;?>












		<?php
$videocloop_home_visibility = get_field('videocloop_home_visibility'); // 'show' | 'hide'
if ( $videocloop_home_visibility !== 'hide' ) : ?>
  <div class="l_container u_pt-5 videocloop-home-wrapper">
    <h3 class="section-heading delta section-heading-slide">
      <span class="u_text-underline">VIDEOCLOOP Selection</span>
    </h3>
    <?php
    $videos_sel = get_field('videocloop_home_video_selection'); // array de posts/IDs
    if ( ! empty($videos_sel) && is_array($videos_sel) ) :

      // Normalizar a posts
      $videos = [];
      foreach ( $videos_sel as $v ) {
        $post_obj = is_object($v) ? $v : get_post((int)$v);
        if ( $post_obj ) $videos[] = $post_obj;
      }

      if ( ! empty($videos) ) :
        // IDs únicos para esta instancia
        $root_id   = 'videocloop-home-vid-' . uniqid();
        $swiper_id = $root_id . '-swiper';
        $prev_id   = $root_id . '-prev';
        $next_id   = $root_id . '-next';
        $count     = count($videos);
    ?>
      <!-- === VIDEOcloop HOME VIDEOS (SLIDE) === -->
      <div class="awards-past awards-past--slider" data-videocloop-videos-swiper-root="<?php echo esc_attr($root_id); ?>">
        <div class="swiper awards-past-swiper videocloop-home-swiper"
             id="<?php echo esc_attr($swiper_id); ?>"
             data-items-count="<?php echo esc_attr($count); ?>"
             style="opacity:0; transition:opacity .2s;">

			<!-- Controles -->
			<div class="swiper-nav">
				<button class="swiper-btn prev" id="<?php echo esc_attr($prev_id); ?>" aria-label="<?php esc_attr_e('Previous','far_loop'); ?>">&larr;</button>
				<button class="swiper-btn next" id="<?php echo esc_attr($next_id); ?>" aria-label="<?php esc_attr_e('Next','far_loop'); ?>">&rarr;</button>
			</div>

			<div class="swiper-wrapper">
				<?php foreach ( $videos as $video ) :
					$vid_id = (int) $video->ID;

					// Forzamos la URL al patrón /videocloop/video/{slug}/
					$slug = is_object($video) ? $video->post_name : get_post_field('post_name', $vid_id);
					$target_path = '/videocloop/video/' . $slug . '/';
					$url = home_url( $target_path );

					// Si usas WPML y quieres asegurar el idioma actual:
					if ( defined('ICL_LANGUAGE_CODE') && function_exists('apply_filters') ) {
						$url = apply_filters( 'wpml_permalink', $url, ICL_LANGUAGE_CODE );
					}

					// Imagen de portada
					$cover = get_field('cover_image', $vid_id);
					$src   = (!empty($cover['url'])) ? $cover['url'] : get_template_directory_uri().'/img/horizontal-placeholder.svg';

					// Año
					$year  = get_field('year', $vid_id);

					// Autores
					$authors = get_field('author', $vid_id);
					$authors_string = function_exists('get_authors_string') ? get_authors_string($authors) : '';

					// Edición
					$editions = get_the_terms($vid_id, 'edition');
					$edition_label = (!empty($editions) && !is_wp_error($editions)) ? $editions[0]->name : '';
				?>
					<div class="swiper-slide">
						<div class="archive-item">
							<a href="<?php echo esc_url($url); ?>" class="archive-new-thumb">
								<div class="archive-thumb__image-container award">
									<img src="<?php echo esc_url($src); ?>" alt="<?php echo esc_attr(get_the_title($vid_id)); ?>">
								</div>
								<div class="archive-thumb__text">
									<h3 class="archive-thumb__title">
										<?php echo esc_html( get_the_title($vid_id) ); ?>
										<?php if ( !empty($year) ) echo ' (' . esc_html($year) . ')'; ?>
									</h3>

									<div class="archive-thumb__label">
										<?php if ( $authors_string ): ?>
											<div class="awards-past-thumb__title"><?php echo esc_html($authors_string); ?></div>
										<?php endif; ?>
									</div>

									<?php if ( $edition_label ) : ?>
										<div class="archive-thumb__year"><?php echo esc_html($edition_label); ?></div>
									<?php endif; ?>
								</div>
							</a>
						</div>
					</div>
				<?php endforeach; ?>
			</div><!-- /.swiper-wrapper -->



        </div><!-- /.swiper -->
      </div><!-- /.awards-past -->



    <?php
      endif;
    endif; ?>
  </div>
<?php endif; ?>


















		<?php
		$video_channel_visibility = get_field('video_channel_visibility'); // 'show' | 'hide'
		$video_channel_display    = get_field('video_channel_display');    // 'slide' | 'col'

		if ( $video_channel_visibility !== 'hide' ) :

		// Detectar idioma actual (Polylang o WPML)
		$current_lang = null;
		if ( function_exists('pll_current_language') ) {
			$current_lang = pll_current_language('slug');
		} elseif ( function_exists('apply_filters') ) {
			$current_lang = apply_filters('wpml_current_language', null);
		}

		// Query SOLO en el idioma actual
		$query_args = array(
			'post_type'      => 'video-conference',
			'posts_per_page' => -1,
			'orderby'        => 'date',
			'order'          => 'DESC',
			// WPML: deja que aplique su filtro de idioma
			'suppress_filters' => false,
		);

		// Polylang: especifica idioma
		if ( $current_lang && function_exists('pll_current_language') ) {
			$query_args['lang'] = $current_lang;
		}

		$videos = get_posts( $query_args );

		if ( ! empty($videos) ) :

			// Normalizamos datos para reutilizar en ambas vistas
			$items   = [];
			foreach ( $videos as $video ) {
			$cover    = get_field('cover_image', $video->ID);
			$img      = !empty($cover['url']) ? $cover['url'] : get_template_directory_uri().'/img/horizontal-placeholder.svg';
			$speakers = get_field('speakers', $video->ID);
			$items[] = [
				'url'      => get_permalink($video->ID),
				'img'      => $img,
				'title'    => get_the_title($video->ID),
				'speakers' => $speakers ? get_authors_string($speakers) : '',
			];
			}
			$count   = count($items);
			$root_id = 'video-channel-' . uniqid();
			?>
			
			<!-- VIDEO CHANNEL -->
			<div class="l_container u_pt-3 videochannel-home-wrapper">
			<h3 class="section-heading delta section-heading-slide"><span class="u_text-underline"><?php esc_html_e('Video Channel', 'far_loop'); ?></span></h3>

			<?php if ( $video_channel_display === 'col' ) : ?>
				<!-- ====== GRID (solo 3 primeros) ====== -->
				<div class="archive-grid">
				<?php
				$max = min(3, $count);
				for ( $i = 0; $i < $max; $i++ ) :
					$it = $items[$i];
				?>
					<div class="archive-item archive-item-channel-home">
					<a class="archive-new-thumb" href="<?php echo esc_url($it['url']); ?>">
						<div class="archive-thumb__image-container video-conference">
						<img src="<?php echo esc_url($it['img']); ?>" alt="<?php echo esc_attr($it['title']); ?>">
						</div>
						<div class="archive-thumb__text">
						<div class="archive-thumb__title">
							<a href="<?php echo esc_url($it['url']); ?>"><?php echo esc_html($it['title']); ?></a>
						</div>
						<?php if ( !empty($it['speakers']) ) : ?>
							<div class="archive-thumb__year"><?php echo esc_html($it['speakers']); ?></div>
						<?php endif; ?>
						</div>
					</a>
					</div>
				<?php endfor; ?>
				</div>

			<?php else : ?>
				<!-- ====== SLIDE (por defecto) ====== -->
				<div class="video-channel-swiper-outer" data-video-channel-root="<?php echo esc_attr($root_id); ?>">
				<div class="swiper video-channel-swiper video-channel-home-swiper"
					id="<?php echo esc_attr($root_id); ?>-swiper"
					data-swiper-video-channel
					data-items-count="<?php echo esc_attr($count); ?>"
					style="opacity:0; transition:opacity .2s;">
					
					<div class="video-channel-swiper__controls u_mt-1">
					<button class="video-channel-swiper__prev" id="<?php echo esc_attr($root_id); ?>-prev" type="button" aria-label="<?php esc_attr_e('Previous', 'far_loop'); ?>">&larr;</button>
					<button class="video-channel-swiper__next" id="<?php echo esc_attr($root_id); ?>-next" type="button" aria-label="<?php esc_attr_e('Next', 'far_loop'); ?>">&rarr;</button>
					</div>

					<div class="swiper-wrapper">
					<?php foreach ( $items as $it ) : ?>
						<div class="swiper-slide archive-grid">
						<article class="committee-card">
							<a class="videochannel-card__thumb archive-new-thumb" href="<?php echo esc_url($it['url']); ?>">
							<div class="archive-thumb__image-container video-conference">
								<img src="<?php echo esc_url($it['img']); ?>" alt="<?php echo esc_attr($it['title']); ?>">
							</div>
							</a>
							<div class="archive-thumb__text">
							<div class="archive-thumb__title">
								<a href="<?php echo esc_url($it['url']); ?>"><?php echo esc_html($it['title']); ?></a>
							</div>
							<?php if ( !empty($it['speakers']) ) : ?>
								<div class="archive-thumb__year"><?php echo esc_html($it['speakers']); ?></div>
							<?php endif; ?>
							</div>
						</article>
						</div>
					<?php endforeach; ?>
					</div>
				</div>
				</div>

	
			<?php endif; // slide/col ?>
			</div><!-- /.l_container -->
		<?php endif; // !empty videos ?>
		<?php endif; // visibility ?>













		<?php
			$partners_visibility = get_field('partners_slide_visibility'); // devuelve 'show' o 'hide'
		?>		

		<?php if ( $partners_visibility !== 'hide' ) : ?>
		<!-- BLOCK PARTNERS -->
		<div class="l_container u_pt-3">
		<div class="wrapper-about-partners-slide">
			<?php
			// Si quieres forzar un ID concreto de la página Partners, pásalo así:
			// get_template_part( 'template-parts/partners/partners-block', null, array('partners_id' => 123) );
			get_template_part( 'template-parts/partners-mini' );
			?>
		</div>
		</div>
		<?php endif; ?>





	<!--

	<div class="newsletter-container-home-new">
		<h2 class="newsletter-title">Stay in touch?<br>Subscribe to our newsletter!</h2>

		<form class="newsletter-form">
			<div class="form-group">
			<input type="text" name="name" placeholder="Name" required>
			</div>
			<div class="form-group">
			<input type="email" name="email" placeholder="Your e-mail" required>
			</div>
			<div class="form-submit">
			<button type="submit">Send!</button>
			</div>
		</form>
	</div>
	
	-->





</div>





<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/5.3.0/fabric.min.js"></script>

<script>

	const isMobile = window.innerWidth < 640;
	const canvas = new fabric.Canvas('bird-canvas', {
	isDrawingMode: false,
	selection: false,
	backgroundColor: null
	});


  function resizeCanvas() {
	canvas.setWidth(window.innerWidth);
	canvas.setHeight(window.innerHeight);
	canvas.renderAll();
	}

	window.addEventListener('resize', resizeCanvas);
	resizeCanvas(); // inicial

	let idleTimeout;
	let userInteracted = false;

	idleTimeout = setTimeout(() => {
	if (!userInteracted && !drawStarted) {
		canvas.dispose();
		document.getElementById('bird-canvas').style.display = 'none';
		window.removeEventListener('resize', resizeCanvas);
	}
	}, 2000);

	function cancelIdleTimeout() {
	if (!userInteracted) {
		userInteracted = true;
		clearTimeout(idleTimeout);
		window.removeEventListener('mousemove', cancelIdleTimeout);
		canvas.upperCanvasEl.removeEventListener('mousemove', cancelIdleTimeout);
	}
	}

	window.addEventListener('mousemove', cancelIdleTimeout, { once: true });
	canvas.upperCanvasEl.addEventListener('mousemove', cancelIdleTimeout, { once: true });


const container = document.querySelector('.canvas-container');
if (container) {
  container.style.position = 'fixed';
  container.style.top = '0';
  container.style.left = '0';
  container.style.width = '100vw';
  container.style.height = '100vh';
  container.style.backgroundColor = 'transparent';
  container.style.zIndex = '99999999';
  container.style.pointerEvents = 'auto'; 
}





  let isDrawing = false;
  let drawStarted = false;
  let lastX = 0;
  let lastY = 0;
  let angle = 0;
  let index = 0;

  const birdSVGs = [];

  <?php
  $bird_dir = get_template_directory() . '/birds/';
  $bird_files = glob($bird_dir . '*.svg');
  foreach ($bird_files as $file) {
    $contents = file_get_contents($file);
    echo "birdSVGs.push(`" . addslashes($contents) . "`);\n";
  }
  ?>

  function getAngle(x1, y1, x2, y2) {
    return Math.atan2(y2 - y1, x2 - x1) * 180 / Math.PI;
  }

  function addSVG(x, y, angle) {
    const svgStr = birdSVGs[index % birdSVGs.length];
    index++;
    fabric.loadSVGFromString(svgStr, (objects, options) => {
      const obj = fabric.util.groupSVGElements(objects, options);
      obj.set({
        left: x,
        top: y,
        angle: angle,
        originX: 'center',
        originY: 'center',
        scaleX: 0.08,
        scaleY: 0.08,
        selectable: false,
        hasBorders: false,
        hasControls: false,
        evented: false
      });
      canvas.add(obj);
    });
  }

  canvas.on('mouse:move', function(opt) {

    const pointer = canvas.getPointer(opt.e);

    if (!drawStarted) {
      drawStarted = true;
      isDrawing = true;
      lastX = pointer.x;
      lastY = pointer.y;

      setTimeout(() => {
        isDrawing = false;
        saveDrawingAsCroppedSVG();
      }, 1000);
    }

    if (!isDrawing) return;

    const dx = pointer.x - lastX;
    const dy = pointer.y - lastY;
    const distance = Math.sqrt(dx * dx + dy * dy);
    if (distance > 60) {
      angle = getAngle(lastX, lastY, pointer.x, pointer.y);
      addSVG(pointer.x, pointer.y, angle);
      lastX = pointer.x;
      lastY = pointer.y;
    }
  });

  



function saveDrawingAsCroppedSVG() {
  canvas.discardActiveObject();

  const objects = canvas.getObjects();
  if (objects.length === 0) return;

  // 1. Calcular bounds
  let bounds = objects.reduce((acc, obj) => {
    const rect = obj.getBoundingRect(true);
    acc.left = Math.min(acc.left, rect.left);
    acc.top = Math.min(acc.top, rect.top);
    acc.right = Math.max(acc.right, rect.left + rect.width);
    acc.bottom = Math.max(acc.bottom, rect.top + rect.height);
    return acc;
  }, {
    left: Infinity,
    top: Infinity,
    right: -Infinity,
    bottom: -Infinity
  });

  const padding = 20;
  const width = bounds.right - bounds.left + padding * 2;
  const height = bounds.bottom - bounds.top + padding * 2;

  // 2. Crear canvas temporal
  const tempCanvas = new fabric.StaticCanvas(null, {
    width: width,
    height: height,
    backgroundColor: null
  });

  // 3. Clonar objetos al nuevo canvas
  const clonePromises = objects.map(obj => {
    return new Promise(resolve => {
      obj.clone(cloned => {
        cloned.set({
          left: obj.left - bounds.left + padding,
          top: obj.top - bounds.top + padding,
          angle: obj.angle,
          scaleX: obj.scaleX,
          scaleY: obj.scaleY,
          originX: obj.originX,
          originY: obj.originY,
          selectable: false,
          evented: false
        });
        tempCanvas.add(cloned);
        resolve();
      });
    });
  });

  // 4. Guardar y luego animar
  Promise.all(clonePromises).then(() => {
    const svg = tempCanvas.toSVG();

    fetch('https://fervent-sinoussi.5-196-224-241.plesk.page/save-drawing', {
      method: 'POST',
      body: JSON.stringify({ svg: svg }),
      headers: {
        'Content-Type': 'application/json'
      }
    }).then(res => res.text()).then(result => {
      document.getElementById('save-info').innerHTML = '';
      
      // ✅ Si estamos en móvil, terminar inmediatamente sin animación
      if (isMobile) {
        canvas.dispose();
        document.getElementById('bird-canvas').style.display = 'none';
        window.removeEventListener('resize', resizeCanvas);
        return;
      }

      // 🖥 En escritorio: fade-out normal
      setTimeout(function () {
        fadeOutBirdsInReverse();
      }, 2000);

    }).catch(err => {
      document.getElementById('save-info').innerHTML = '';
    });
  });
}


function fadeOutBirdsInReverse() {
  const objects = canvas.getObjects();
  const totalDuration = 3000; // 3 segundos
  const stepDuration = totalDuration / objects.length;

  objects.slice().reverse().forEach((obj, i) => {
    setTimeout(() => {
      obj.animate('opacity', 0, {
        duration: 20,
        onChange: canvas.renderAll.bind(canvas),
        onComplete: () => {
				if (i === objects.length - 1) {
				// Último pájaro
				setTimeout(() => {
					
					canvas.dispose();
					document.getElementById('bird-canvas').style.display = 'none';
					window.removeEventListener('resize', resizeCanvas);
				}, 200);
				}
        }
      });
    }, i * 20);
  });
}




</script>









<script>
(function () {
  "use strict";

  /* ============= 1) Loader único Swiper ============= */
  window.__ensureSwiper = window.__ensureSwiper || (function(){
    var p;
    return function ensureSwiper(){
      if (window.Swiper) return Promise.resolve();
      if (p) return p;
      p = new Promise(function(resolve){
        if (!document.getElementById('swiper-css-cdn')) {
          var link = document.createElement('link');
          link.id = 'swiper-css-cdn';
          link.rel = 'stylesheet';
          link.href = 'https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.css';
          document.head.appendChild(link);
        }
        if (!document.getElementById('swiper-js-cdn')) {
          var script = document.createElement('script');
          script.id  = 'swiper-js-cdn';
          script.src = 'https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.js';
          script.defer = true;
          script.onload = function(){ resolve(); };
          document.head.appendChild(script);
        } else {
          var i = setInterval(function(){
            if (window.Swiper) { clearInterval(i); resolve(); }
          }, 30);
        }
      });
      return p;
    };
  })();

  /* ============= 2) Utilidades comunes ============= */
  var inited = new WeakSet();

  function setOnce(el) {
    if (!el || inited.has(el)) return false;
    inited.add(el);
    return true;
  }

  function show(el){ if (el && el.style) el.style.opacity = '1'; }

  // devuelve PV actual según ancho
  function currentPv(pvBase, pv640, pv768, pv1024, pvDesktop) {
    var w = window.innerWidth || document.documentElement.clientWidth || 1366;
    if (w >= 1366) return pvDesktop;
    if (w >= 1024) return pv1024;
    if (w >= 768)  return pv768;
    if (w >= 640)  return pv640;
    return pvBase;
  }

  // muestra/oculta flechas/paginación con defensas
  function toggleNavSafe(sw, need) {
    if (!sw) return;

    // Navigation (Swiper transforma a elementos tras init)
    var nextEl = sw.navigation && sw.navigation.nextEl instanceof HTMLElement ? sw.navigation.nextEl : null;
    var prevEl = sw.navigation && sw.navigation.prevEl  instanceof HTMLElement ? sw.navigation.prevEl  : null;

    if (nextEl) nextEl.style.display = need ? '' : 'none';
    if (prevEl) prevEl.style.display = need ? '' : 'none';

    // Pagination
    var pagEl = (sw.pagination && sw.pagination.el) ? sw.pagination.el : null;
    if (pagEl) pagEl.style.display = need ? '' : 'none';
  }

  function finalUpdates(sw, needFn) {
    if (!sw) return;
    sw.update();
    sw.updateSlides && sw.updateSlides();
    sw.updateSize && sw.updateSize();
    if (typeof needFn === 'function') {
      toggleNavSafe(sw, needFn());
    }
  }

  /* ============= 3) FAIR HOME (data-fair-videos-swiper-root) ============= */
  function initFairHome() {
    document.querySelectorAll('[data-fair-videos-swiper-root]').forEach(function(root){
      var rootId = root.getAttribute('data-fair-videos-swiper-root');
      if (!rootId) return;

      var el = document.getElementById(rootId + '-swiper');
      if (!setOnce(el)) return;

      var nextEl = document.getElementById(rootId + '-next');
      var prevEl = document.getElementById(rootId + '-prev');

      var total  = parseInt(el.getAttribute('data-items-count') || '0', 10);

      // PV por nº de slides
      var pvDesktop = (total <= 3) ? 3 : (total === 4 ? 4 : 4.2);
      var pv1024    = (total <= 3) ? 3 : 3.2;
      var pv768     = 2.2;
      var pv640     = 1.2;
      var pvBase    = 1.2;

      var params = {
        slidesPerView: pvBase,
        spaceBetween: 15,
        watchSlidesProgress: true,
        observer: true,
        observeParents: true,
        preloadImages: false,
        lazy: { loadOnTransitionStart: true },
        breakpoints: {
          640:  { slidesPerView: pv640,  spaceBetween: 15 },
          768:  { slidesPerView: pv768,  spaceBetween: 15 },
          1366: { slidesPerView: 3.2,   spaceBetween: 32 },
          1367: { slidesPerView: pvDesktop, spaceBetween: 32 }
        },
        on: {
          init: function() {
            show(el);
            var need = function(){
              var pvNow = currentPv(pvBase, pv640, pv768, pv1024, pvDesktop);
              var count = (this && this.slides) ? this.slides.length : total;
              return count > pvNow;
            }.bind(this);
            toggleNavSafe(this, need());
          },
          resize: function() {
            var need = function(){
              var pvNow = currentPv(pvBase, pv640, pv768, pv1024, pvDesktop);
              var count = (this && this.slides) ? this.slides.length : total;
              return count > pvNow;
            }.bind(this);
            toggleNavSafe(this, need());
          }
        }
      };

      // Solo añadimos navigation si existen botones
      if (nextEl && prevEl) {
        params.navigation = { nextEl: nextEl, prevEl: prevEl };
      }

      var sw = new Swiper(el, params);

      // Refrescos
      var needFn = function(){
        var pvNow = currentPv(pvBase, pv640, pv768, pv1024, pvDesktop);
        var count = (sw && sw.slides) ? sw.slides.length : total;
        return count > pvNow;
      };

      el.querySelectorAll('img').forEach(function(img){
        var upd = function(){ finalUpdates(sw, needFn); };
        if (img.complete) upd();
        img.addEventListener('load',  upd, { once:true });
        img.addEventListener('error', upd, { once:true });
      });

      if (document.fonts && document.fonts.ready) {
        document.fonts.ready.then(function(){ finalUpdates(sw, needFn); });
      }
      window.addEventListener('load', function(){ finalUpdates(sw, needFn); });
      setTimeout(function(){ finalUpdates(sw, needFn); }, 600);
      setTimeout(function(){ finalUpdates(sw, needFn); }, 1200);
    });
  }

  /* ============= 4) VIDEOCLoop HOME (data-videocloop-videos-swiper-root) ============= */
  function initVideocloopHome() {
    document.querySelectorAll('[data-videocloop-videos-swiper-root]').forEach(function(root){
      var rootId = root.getAttribute('data-videocloop-videos-swiper-root');
      if (!rootId) return;

      var el = document.getElementById(rootId + '-swiper');
      if (!setOnce(el)) return;

      var nextEl = document.getElementById(rootId + '-next');
      var prevEl = document.getElementById(rootId + '-prev');

      var total  = parseInt(el.getAttribute('data-items-count') || '0', 10);

      var pvDesktop = (total <= 3) ? 3 : (total === 4 ? 4 : 4.2);
      var pv1024    = (total <= 3) ? 3 : 3.2;
      var pv768     = 2.2;
      var pv640     = 1.2;
      var pvBase    = 1.2;

      var params = {
        slidesPerView: pvBase,
        spaceBetween: 15,
        watchSlidesProgress: true,
        observer: true,
        observeParents: true,
        preloadImages: false,
        lazy: { loadOnTransitionStart: true },
        breakpoints: {
          640:  { slidesPerView: pv640,  spaceBetween: 15 },
          768:  { slidesPerView: pv768,  spaceBetween: 15 },
          1366: { slidesPerView: 3.2,   spaceBetween: 32 },
          1367: { slidesPerView: pvDesktop, spaceBetween: 32 }
        },
        on: {
          init: function() {
            show(el);
            var need = function(){
              var pvNow = currentPv(pvBase, pv640, pv768, pv1024, pvDesktop);
              var count = (this && this.slides) ? this.slides.length : total;
              return count > pvNow;
            }.bind(this);
            toggleNavSafe(this, need());
          },
          resize: function() {
            var need = function(){
              var pvNow = currentPv(pvBase, pv640, pv768, pv1024, pvDesktop);
              var count = (this && this.slides) ? this.slides.length : total;
              return count > pvNow;
            }.bind(this);
            toggleNavSafe(this, need());
          }
        }
      };

      if (nextEl && prevEl) {
        params.navigation = { nextEl: nextEl, prevEl: prevEl };
      }

      var sw = new Swiper(el, params);

      var needFn = function(){
        var pvNow = currentPv(pvBase, pv640, pv768, pv1024, pvDesktop);
        var count = (sw && sw.slides) ? sw.slides.length : total;
        return count > pvNow;
      };

      el.querySelectorAll('img').forEach(function(img){
        var upd = function(){ finalUpdates(sw, needFn); };
        if (img.complete) upd();
        img.addEventListener('load',  upd, { once:true });
        img.addEventListener('error', upd, { once:true });
      });

      if (document.fonts && document.fonts.ready) {
        document.fonts.ready.then(function(){ finalUpdates(sw, needFn); });
      }
      window.addEventListener('load', function(){ finalUpdates(sw, needFn); });
      setTimeout(function(){ finalUpdates(sw, needFn); }, 600);
      setTimeout(function(){ finalUpdates(sw, needFn); }, 1200);
    });
  }

  /* ============= 5) VIDEO CHANNEL (.video-channel-swiper) ============= */
  function initVideoChannel() {
    document.querySelectorAll('.video-channel-swiper').forEach(function(el){
      if (!setOnce(el)) return;

      var wrapper = el.closest('.video-channel-swiper-outer') || document;
      var nextEl  = wrapper.querySelector('.video-channel-swiper__next');
      var prevEl  = wrapper.querySelector('.video-channel-swiper__prev');

      var total   = parseInt(el.getAttribute('data-items-count') || '0', 10);
      var pvDesktop = (total <= 3) ? 3 : (total === 4 ? 4 : 4.2);
      var pv1024    = (total <= 3) ? 3 : 3.2;
      var pv768     = 2.2;
      var pv640     = 1.2;
      var pvBase    = 1.2;

      var params = {
        slidesPerView: pvBase,
        spaceBetween: 15,
        watchOverflow: true,
        watchSlidesProgress: true,
        observer: true,
        observeParents: true,
        preloadImages: false,
        lazy: { loadOnTransitionStart: true },
        breakpoints: {
          480:  { slidesPerView: pvBase, spaceBetween: 15 },
          640:  { slidesPerView: pv640,  spaceBetween: 15 },
          768:  { slidesPerView: pv768,  spaceBetween: 32 },
          1366: { slidesPerView: pv1024, spaceBetween: 32 },
          1367: { slidesPerView: pvDesktop, spaceBetween: 32 }
        },
        on: {
          init: function() {
            show(el);
            var need = function(){
              var pvNow = currentPv(pvBase, pv640, pv768, pv1024, pvDesktop);
              var count = (this && this.slides) ? this.slides.length : total;
              return count > pvNow;
            }.bind(this);
            toggleNavSafe(this, need());
          },
          resize: function() {
            var need = function(){
              var pvNow = currentPv(pvBase, pv640, pv768, pv1024, pvDesktop);
              var count = (this && this.slides) ? this.slides.length : total;
              return count > pvNow;
            }.bind(this);
            toggleNavSafe(this, need());
          }
        }
      };

      if (nextEl && prevEl) {
        params.navigation = { nextEl: nextEl, prevEl: prevEl };
      }

      var sw = new Swiper(el, params);

      var needFn = function(){
        var pvNow = currentPv(pvBase, pv640, pv768, pv1024, pvDesktop);
        var count = (sw && sw.slides) ? sw.slides.length : total;
        return count > pvNow;
      };

      el.querySelectorAll('img').forEach(function(img){
        var upd = function(){ finalUpdates(sw, needFn); };
        if (img.complete) upd();
        img.addEventListener('load',  upd, { once:true });
        img.addEventListener('error', upd, { once:true });
      });

      if (document.fonts && document.fonts.ready) {
        document.fonts.ready.then(function(){ finalUpdates(sw, needFn); });
      }
      window.addEventListener('load', function(){ finalUpdates(sw, needFn); });
      setTimeout(function(){ finalUpdates(sw, needFn); }, 600);
      setTimeout(function(){ finalUpdates(sw, needFn); }, 1200);
    });
  }

  /* ============= 6) Orquestador ============= */
  function initAllSwipers() {
    try { initFairHome(); } catch(e) { console.error(e); }
    try { initVideocloopHome(); } catch(e) { console.error(e); }
    try { initVideoChannel(); } catch(e) { console.error(e); }
  }

  function boot() { window.__ensureSwiper().then(function(){ requestAnimationFrame(initAllSwipers); }); }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
  } else {
    boot();
  }

  // reforzadores
  window.addEventListener('load', boot);
  setTimeout(boot, 500);
  setTimeout(boot, 1500);

  // por si inyectas contenido dinámico
  var moTimer = null;
  var mo = new MutationObserver(function(){
    clearTimeout(moTimer);
    moTimer = setTimeout(boot, 200);
  });
  mo.observe(document.body, { childList: true, subtree: true });

})();
</script>





<?php
get_footer();