<?php
/**
 * Template name: Loop Festival
 *
 * @package far_loop
 */

get_header();

$fields = array_fill_keys( array(
	'featured_image',
	'dates_string',
	'agenda',
	'description',
), null );

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

//$pages = array( 'exhibitions', 'activities', 'city-screen' );

?>

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


	<div id="mainContainer" class="l_container">
			<?php

			if ( is_page() ) {
			global $post;

			$is_past_edition = false;
			$view_year       = null;

			if ( $post && ! empty( $post->post_name ) ) {
				if ( preg_match( '/^loop-festival-(\d{4})$/', $post->post_name, $m ) ) {
				$is_past_edition = true;
				$view_year       = (int) $m[1];
				}
			}

			if ( $is_past_edition ) {
				$min_year       = 2006;
				$now_year       = (int) date('Y');
				$max_links_show = 5;
				$base_slug      = 'loop-festival-';

				$found_years = array();
				for ( $y = $now_year; $y >= $min_year; $y-- ) {
				$slug     = $base_slug . $y;
				$the_page = get_page_by_path( $slug, OBJECT, 'page' );
				if ( $the_page instanceof WP_Post ) {
					$found_years[] = $y;
				}
				}
				if ( ! in_array( $now_year, $found_years, true ) ) {
				array_unshift( $found_years, $now_year );
				}
				$found_years = array_values( array_unique( $found_years ) );
				rsort( $found_years, SORT_NUMERIC );

				if ( ! empty( $found_years ) ) {
				$display_years = array_slice( $found_years, 0, $max_links_show );
				$more_years    = array_slice( $found_years, $max_links_show );
				$has_more      = ! empty( $more_years );
				?>
				<div class="nav-past-editions">
					<ul class="same-page-nav past-editions" id="past-editions-menu">
					<span class="past-editions-title"><?php _e( 'Past Editions', 'far_loop' );?></span>

					<?php foreach ( $display_years as $y ) :
						$url = home_url( '/' . $base_slug . $y . '/' );
						$active_class = ( (int) $view_year === (int) $y ) ? ' is-active' : '';
					?>
						<li class="same-page-nav__item year-item">
						<a class="<?php echo esc_attr( trim( $active_class ) ); ?>" href="<?php echo esc_url( $url ); ?>">
							<?php echo esc_html( $y ); ?>
						</a>
						</li>
					<?php endforeach; ?>

					<?php if ( $has_more ) : ?>
						<li class="same-page-nav__item past-editions-more">
						<a href="#" tabindex="-1" aria-expanded="false" aria-controls="past-editions-extra">…</a>
						</li>

						<?php foreach ( $more_years as $y ) :
						$url = home_url( '/' . $base_slug . $y . '/' );
						$active_class = ( (int) $view_year === (int) $y ) ? ' is-active' : '';
						?>
						<li class="same-page-nav__item extra-year year-item is-collapsed" id="past-editions-extra" hidden>
							<a class="<?php echo esc_attr( trim( $active_class ) ); ?>" href="<?php echo esc_url( $url ); ?>">
							<?php echo esc_html( $y ); ?>
							</a>
						</li>
						<?php endforeach; ?>
					<?php endif; ?>
					</ul>
				</div>
				<?php
				}
			}
			}
			?>
	</div>  


	<div class="l_container u_mv-2" id="festival-overview">



			<div class="grid">
				<!-- same-page-nav module-->
				<ul class="same-page-nav">
					<?php if( have_rows('sections') ): ?>
					<?php while( have_rows('sections') ): the_row(); ?>
						<li class="same-page-nav__item">
						<a href="#" data-soft-scroll="#festival-<?php echo get_row_index(); ?>" class="same-page-nav__link">
							<?php the_sub_field('title'); ?>
						</a>
						</li>
					<?php endwhile; ?>
					<?php endif; ?>
				</ul>
			</div>




		<?php if ( ! empty( $fields['featured_image'] ) ) : ?>

			<figure class="cover-image"><img src="<?php echo esc_url( $fields['featured_image']['url'] ); ?>" alt="<?php echo esc_html( $fields['featured_image']['caption'] ); ?>">
				<figcaption class="cover-image__caption"><?php echo esc_html( $fields['featured_image']['caption'] ); ?></figcaption>
			</figure>

		<?php endif; ?>

		<div class="grid">
			<div data-sticky-sidebar class="col--sm--three--seventh col--tb--three--seventh col--md--two--fifth">
		
				<div class="info-card">
					<dl class="info-card__list">
						<dt class="info-card__key"><span class="info-card__key-text"><?php esc_html_e( 'Dates', 'far_loop' ); ?></span></dt>
						<dd class="info-card__value"><?php echo esc_html( $fields['dates_string'] ); ?></dd>
						<?php if ( $fields['agenda'] ) : ?>
						<dt class="info-card__key"><span class="info-card__key-text"><?php esc_html_e( 'Agenda', 'far_loop' ); ?></span></dt>
						<?php // translators: link. ?>
						<dd class="info-card__value"><?php printf( esc_html_x( 'Download the Festival’s agenda %s. (pdf)', 'link', 'far_loop' ), '<a href="' . esc_html( $fields['agenda']['url'] ) . '" target="_blank">' . esc_html__( 'here', 'far_loop' ) . '</a>' ); ?></dd>
						<?php endif; ?>

						<dt class="info-card__key"><span class="info-card__key-text">Locations</span></dt>
						<dd class="info-card__value"><a href="#" data-soft-scroll="#map">Map of locations</a></dd>
					</dl>
				</div>
			</div>
			<div class="col--sm--four--seventh col--tb--four--seventh col--md--three--fifth">
				<div class="wysiwyg">
					<?php echo wp_kses_post( $fields['description'] ); ?>
				</div>
			</div>
		</div>
	</div>


			<div class="l_container">
			<?php
			$festival_display = get_field('festival_activities_display'); // 'show' | 'hide'
			if ($festival_display !== 'hide'):
				if (have_rows('sections')): ?>
				<div class="festival-sections">
					<?php while (have_rows('sections')): the_row();
					$title      = get_sub_field('title');
					$category   = get_sub_field('category');   // objeto de tax si se usa
					$activities = get_sub_field('activities'); // array de posts activity
					?>
					<section id="festival-<?php echo get_row_index(); ?>" class="festival-section u_mb-4">
						<?php if (!empty($title)): ?>
						<h3 class="section-heading delta section-sticky"><span class="u_text-underline"><?php echo esc_html($title); ?></span></h3>
						<?php endif; ?>

						<?php if (!empty($activities)): ?>
						<div class="archive-grid">
							<?php foreach ($activities as $act):
							$act_id = is_object($act) ? (int)$act->ID : (int)$act;

							// ===== Imagen destacada desde ACF 'featured_image' (array) =====
							$fi  = get_field('featured_image', $act_id);
							$src = '';
							if (is_array($fi)) {
								if (!empty($fi['sizes']['large'])) {
								$src = $fi['sizes']['large'];
								} elseif (!empty($fi['sizes']['medium_large'])) {
								$src = $fi['sizes']['medium_large'];
								} elseif (!empty($fi['url'])) {
								$src = $fi['url'];
								}
							}
							if (!$src) {
								$src = get_template_directory_uri() . '/img/horizontal-placeholder.svg';
							}

							// ===== Title =====
							$the_title = get_the_title($act_id);

							// ===== Venue (post_object) =====
							$venue_obj   = get_field('venue', $act_id);
							$venue_title = '';
							if ($venue_obj) {
								$venue_id    = is_object($venue_obj) ? (int)$venue_obj->ID : (int)$venue_obj;
								if ($venue_id) {
								$venue_title = get_the_title($venue_id);
								}
							}

							// ===== Dates (repeater) =====
							// Admite subcampos 'start_date'/'end_date' (ISO/fecha) o un único 'date'
							$dates_rows = get_field('dates', $act_id);
							$dates_out  = array();

							if (is_array($dates_rows)) {
								foreach ($dates_rows as $row) {
								$start_raw = isset($row['start_date']) ? $row['start_date'] : (isset($row['date']) ? $row['date'] : '');
								$end_raw   = isset($row['end_date']) ? $row['end_date'] : '';

								// Normalizar a timestamp si es posible
								$start_ts = $start_raw ? strtotime($start_raw) : false;
								$end_ts   = $end_raw   ? strtotime($end_raw)   : false;

								if ($start_ts && $end_ts && date('Ymd', $start_ts) !== date('Ymd', $end_ts)) {
									// Rango de fechas
									$dates_out[] = date_i18n(get_option('date_format'), $start_ts) . ' – ' . date_i18n(get_option('date_format'), $end_ts);
								} elseif ($start_ts) {
									// Fecha única
									$dates_out[] = date_i18n(get_option('date_format'), $start_ts);
								} elseif ($start_raw) {
									// Texto tal cual si no parsea
									$dates_out[] = esc_html($start_raw);
								}
								}
							}

							$dates_text = !empty($dates_out) ? implode(' · ', $dates_out) : '';
							$permalink  = get_permalink($act_id);
							?>
							<div class="archive-item">
								<a class="archive-new-thumb" href="<?php echo esc_url($permalink); ?>">
								<div class="archive-thumb__image-container activity">
									<img src="<?php echo esc_url($src); ?>" alt="<?php echo esc_attr($the_title); ?>">
								</div>
								<div class="archive-thumb__text">
									<h3 class="archive-thumb__title">
									<?php echo esc_html($the_title); ?>
									</h3>

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

									<?php if ($dates_text): ?>
									<div class="archive-thumb__year">
										<?php echo esc_html($dates_text); ?>
									</div>
									<?php endif; ?>
								</div>
								</a>
							</div>
							<?php endforeach; ?>
						</div>
						<?php endif; ?>
					</section>
					<?php endwhile; ?>
				</div>
				<?php endif;
			endif; ?>
			</div>



	<!-- 
	<div class="places-map-horizontal-full-width" id="map">
		<?php get_template_part( 'page-templates/locations/content' ); ?>
	</div>
	-->
</div>


<script>
document.addEventListener('DOMContentLoaded', function () {
  var nav   = document.querySelector('.nav-past-editions');
  if (!nav) return;

  var menu  = nav.querySelector('#past-editions-menu');
  var more  = menu ? menu.querySelector('.past-editions-more') : null;
  var extras= menu ? menu.querySelectorAll('.extra-year') : [];

  if (!menu || !more || !extras.length) return;

  var hideTimer = null;

  function reveal() {
    if (menu.classList.contains('revealed')) return;
    menu.classList.add('revealed');
    var a = more.querySelector('a');
    if (a) a.setAttribute('aria-expanded', 'true');
    extras.forEach(function(li){ li.hidden = false; });
  }

  function hide() {
    if (!menu.classList.contains('revealed')) return;
    menu.classList.remove('revealed');
    var a = more.querySelector('a');
    if (a) a.setAttribute('aria-expanded', 'false');
    extras.forEach(function(li){ li.hidden = true; });
  }

  // Mostrar
  more.addEventListener('click', function (e) { e.preventDefault(); reveal(); });
  more.addEventListener('mouseenter', reveal);
  more.addEventListener('touchstart', function (e) { e.preventDefault(); reveal(); }, { passive: false });

  // Ocultar tras salir
  nav.addEventListener('mouseleave', function () {
    clearTimeout(hideTimer);
    hideTimer = setTimeout(hide, 3000); // 3 segundos
  });

  // Cancelar ocultado si vuelve el ratón
  nav.addEventListener('mouseenter', function () {
    clearTimeout(hideTimer);
  });
});
</script>

<?php
get_footer();
