<?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" id="festival-wrapper">

 


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



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

			<!-- Extra item Past Editions (sticky-enabled) -->
			<li class="same-page-nav__item">
			<a href="#past-editions" 
				class="same-page-nav__link" 
				data-soft-scroll="#past-editions">
				<?php esc_html_e('Past Editions', 'far_loop'); ?>
			</a>
			</li>
		</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>



			<?php
			/**
			 * Past Editions – Slider (sustituye al menú antiguo)
			 */
			if ( is_page() ) {
			global $post;

			// Detecta edición actual desde el slug tipo loop-festival-YYYY
			$current_year = null;
			if ( $post && ! empty( $post->post_name ) && preg_match( '/^loop-festival-(\d{4})$/', $post->post_name, $m ) ) {
				$current_year = (int) $m[1];
			}

			$min_year  = 2006;
			$now_year  = (int) date('Y');
			$base_slug = 'loop-festival-';

			// Reúne páginas de ediciones (excluye la edición actual)
			$editions = array(); // cada item: ['year'=>YYYY, 'page'=>WP_Post, 'thumb'=>url, 'url'=>url]

			for ( $y = $now_year; $y >= $min_year; $y-- ) {
				$slug = $base_slug . $y;

				// Con WPML: si hay traducción, busca en idioma actual
				$page = get_page_by_path( $slug, OBJECT, 'page' );
				if ( ! $page instanceof WP_Post && function_exists('icl_object_id') ) {
				// Intento 2: obtener ID de la edición en idioma default y traducir
				$default_page = get_page_by_path( $slug, OBJECT, 'page' );
				if ( $default_page instanceof WP_Post ) {
					$tr_id = icl_object_id( $default_page->ID, 'page', true );
					if ( $tr_id ) $page = get_post( $tr_id );
				}
				}

				if ( $page instanceof WP_Post ) {
				if ( $current_year && (int)$y === (int)$current_year ) {
					// Si NO quieres mostrar la edición actual en “past”, sáltala:
					continue;
				}

				// Thumbnail (featured image) o placeholder
				$thumb = get_the_post_thumbnail_url( $page->ID, 'large' );
				if ( ! $thumb ) {
					$thumb = get_template_directory_uri() . '/img/horizontal-placeholder.svg';
				}

				$url = get_permalink( $page->ID );

				$editions[] = array(
					'year'  => (int)$y,
					'page'  => $page,
					'thumb' => $thumb,
					'url'   => $url,
				);
				}
			}

			// Si hay ediciones, imprime la sección en slide
			if ( ! empty( $editions ) ) :
			?>
			<div class="l_container u_mv-5" id="past-editions">
				<h3 class="section-heading delta section-sticky">
					<span class="u_text-underline"><?php esc_html_e('Past Editions', 'far_loop'); ?></span>
				</h3>

				<div class="past-editions-swiper-outer u_mt-2">
				<div class="swiper-nav">
					<button class="swiper-btn prev past-editions-swiper__prev" type="button" aria-label="<?php esc_attr_e('Previous','far_loop'); ?>">&larr;</button>
					<button class="swiper-btn next past-editions-swiper__next" type="button" aria-label="<?php esc_attr_e('Next','far_loop'); ?>">&rarr;</button>
				</div>

				<div class="swiper past-editions-swiper" data-swiper-past-editions data-count="<?php echo esc_attr( count($editions) ); ?>" style="opacity:0; transition:opacity .2s;">
					<div class="swiper-wrapper">
					<?php foreach ( $editions as $ed ) : ?>
						<div class="swiper-slide">
						<div class="archive-item">
							<a class="archive-new-thumb" href="<?php echo esc_url( $ed['url'] ); ?>">
							<div class="archive-thumb__image-container award">
								<img src="<?php echo esc_url( $ed['thumb'] ); ?>" alt="<?php echo esc_attr( get_the_title( $ed['page']->ID ) ); ?>">
							</div>
							<div class="archive-thumb__text">
								<h3 class="archive-thumb__title">
								<?php echo esc_html( get_the_title( $ed['page']->ID ) ); ?>
								</h3>
								<div class="archive-thumb__year">
								<?php echo esc_html( $ed['year'] ); ?>
								</div>
							</div>
							</a>
						</div>
						</div>
					<?php endforeach; ?>
					</div>
				</div><!-- /.swiper -->
				</div><!-- /.outer -->
			</div>
			<?php
			endif; // !empty(editions)
			}
			?>





</div>







<script>
document.addEventListener('DOMContentLoaded', function () {
  const menu = document.querySelector('#festival-sticky-nav');
  if (!menu) return;

  function computeHeaderOffset() {
    const adminBar = document.getElementById('wpadminbar');
    const adminH   = adminBar ? adminBar.offsetHeight : 0;
    const header   = document.querySelector('.site-header, header, .main-header');
    const isFixed  = header && getComputedStyle(header).position === 'fixed';
    const headH    = isFixed ? header.offsetHeight : 0;
    const off      = adminH + headH + 10;
    document.documentElement.style.setProperty('--sticky-top', (adminH + headH + 20) + 'px');
    return off;
  }
  let HEADER_OFF = computeHeaderOffset();
  window.addEventListener('resize', () => { HEADER_OFF = computeHeaderOffset(); });

  const entries = [];
  menu.querySelectorAll('.same-page-nav__item .same-page-nav__link').forEach((a, idx) => {
    const sel = a.getAttribute('data-soft-scroll') || a.getAttribute('href');
    if (!sel || sel.charAt(0) !== '#') return;
    const section = document.querySelector(sel);
    if (!section) return;
    const heading = section.querySelector('.section-heading.section-sticky') || section.querySelector('h3');
    const li      = a.closest('.same-page-nav__item');
    if (heading && li) {
      heading.classList.remove('is-live','is-past');
      entries.push({ idx, id: sel, li, a, section, heading });
    } else if (li) {
      li.remove();
    }
  });
  if (!entries.length) return;

  function smoothTo(el) {
    const y = window.scrollY + el.getBoundingClientRect().top - HEADER_OFF;
    window.scrollTo({ top: y, behavior: 'smooth' });
  }

  // Nuevo: ya no hay “live pegado”.
  // Todo lo que ya ha cruzado la línea del menú (trigger) pasa a is-past (estático).
  function setStates(activeIdx) {
    entries.forEach((e,i) => {
      e.heading.classList.remove('is-live','is-past');
      if (i <= activeIdx) {
        e.heading.classList.add('is-past'); // visible + estático
      }
      // Menú: ocultamos los ya alcanzados; subrayamos el siguiente
      e.li.classList.toggle('is-hidden', i <= activeIdx);
      e.li.classList.toggle('is-next',   i === activeIdx + 1);
    });
  }

  entries.forEach(e => {
    e.a.addEventListener('click', function (ev) {
      ev.preventDefault();
      // No cambiamos el estado antes: lo hará el scroll para que el título
      // NO aparezca antes de tiempo.
      smoothTo(e.section);
    });
  });

  // El disparador es el borde superior del menú (alineación exacta)
  function computeActiveIndex() {
    const menuRect = menu.getBoundingClientRect();
    const triggerY = menuRect.top;
    let active = -1;
    for (let i = 0; i < entries.length; i++) {
      const hTop = entries[i].heading.getBoundingClientRect().top;
      if (hTop <= triggerY) active = i;
      else break;
    }
    return active;
  }

  let ticking = false;
  function updateByScroll() {
    const idx = computeActiveIndex();
    setStates(idx);
  }
  function onScroll() {
    if (ticking) return;
    ticking = true;
    requestAnimationFrame(() => {
      updateByScroll();
      ticking = false;
    });
  }

  // Estado inicial y listeners
  updateByScroll();
  document.addEventListener('scroll', onScroll, { passive: true });

  const mo = new MutationObserver(() => { updateByScroll(); });
  mo.observe(menu, { attributes:true, childList:true, subtree:true });
});
</script>

<script>
(function () {
  function initPastEditionsSwiper(){
    document.querySelectorAll('[data-swiper-past-editions]').forEach(function(el){
      if (el.__inited) return;
      el.__inited = true;

      const outer = el.closest('.past-editions-swiper-outer') || document;
      const nextEl = outer.querySelector('.past-editions-swiper__next');
      const prevEl = outer.querySelector('.past-editions-swiper__prev');

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

      const sw = new Swiper(el, {
        slidesPerView: 1.2,
        spaceBetween: 15,
        watchOverflow: true,
        observer: true,
        observeParents: true,
        preloadImages: false,
        lazy: { loadOnTransitionStart: true },
        navigation: (nextEl && prevEl) ? { nextEl, prevEl } : undefined,
        breakpoints: {
          640:  { slidesPerView: 2.2, spaceBetween: 15 },
          1024: { slidesPerView: 3.2, spaceBetween: 24 },
          1366: { slidesPerView: 4.2, spaceBetween: 32 }
        },
        on: {
          init(){ el.style.opacity = '1'; },
          imagesReady(){ this.update(); }
        }
      });

      const refresh = () => { sw.update(); sw.updateSlides(); sw.updateSize(); };
      const imgs = el.querySelectorAll('img');
      imgs.forEach(img => {
        if (img.complete) refresh();
        img.addEventListener('load',  refresh, { once:true });
        img.addEventListener('error', refresh, { once:true });
      });
      if (document.fonts && document.fonts.ready) document.fonts.ready.then(refresh);
      window.addEventListener('load', refresh);
      setTimeout(refresh, 400);
      setTimeout(refresh, 1200);
    });
  }

  function ensureAndInit(){
    if (window.__ensureSwiper) {
      window.__ensureSwiper().then(() => requestAnimationFrame(initPastEditionsSwiper));
    } else if (window.Swiper) {
      requestAnimationFrame(initPastEditionsSwiper);
    } else {
      // Carga mínima por si no tienes loader global
      const css = document.createElement('link');
      css.rel='stylesheet'; css.href='https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.css';
      document.head.appendChild(css);
      const js  = document.createElement('script');
      js.src='https://cdn.jsdelivr.net/npm/swiper@9/swiper-bundle.min.js';
      js.onload = () => requestAnimationFrame(initPastEditionsSwiper);
      document.head.appendChild(js);
    }
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', ensureAndInit);
  } else {
    ensureAndInit();
  }
})();
</script>

<?php
get_footer();
