<?php
/*
 * Template name: Main Selection
 * @package far_loop
 */

get_header();

$fields = array_fill_keys([
	'dates_string',
	'location',
	'description',
	'committee_intro',
	'committer_members',
	'main_selection',
], null);

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

$file_id = get_field('pdf_download');
$file_url = $file_id ? wp_get_attachment_url($file_id) : '';
$file_name = $file_id ? get_the_title($file_id) : '';
$curated = get_field('field_572093a6c76a4_mgs_new_1');
?>

<div class="u_pt-3 u_pt-md-6">
	<div id="mainContainer" class="l_container">


			<?php
			/**
			 * Menú Past Editions para páginas tipo /loop-fair-YYYY/
			 * - Incluye SIEMPRE el año actual (aunque no exista la página).
			 * - El año actual enlaza a /loop-fair-YYYY/
			 */
			if ( is_page() ) {
			global $post;

			$is_past_edition = false;
			$view_year       = null;

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

			if ( $is_past_edition ) {
				$min_year       = 2010;
				$now_year       = (int) date('Y');
				$max_links_show = 7;
				$base_slug      = 'loop-fair-';

				$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 class="grid u_mh-min2p">

			<?php
			global $post;
			$slug = $post->post_name;

			// Comprobar si el slug es loop-fair-YYYY con año entre 2001 y 2024
			if ( preg_match('/^loop-fair-(\d{4})$/', $slug, $matches) ) {
				$year = intval($matches[1]);
				if ( $year >= 2001 && $year <= 2024 ) {
					// Mostrar imagen destacada
					if ( has_post_thumbnail($post->ID) ) {
						$thumb_id  = get_post_thumbnail_id($post->ID);
						$thumb_url = wp_get_attachment_image_url($thumb_id, 'full');
						$thumb_alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);
						?>
						<figure class="cover-image fair-main-image">
							<img src="<?php echo esc_url($thumb_url); ?>" alt="<?php echo esc_attr($thumb_alt ?: get_the_title($post->ID)); ?>">
							<?php if ( get_the_post_thumbnail_caption($thumb_id) ) : ?>
								<figcaption class="cover-image__caption">
									<?php echo esc_html( get_the_post_thumbnail_caption($thumb_id) ); ?>
								</figcaption>
							<?php endif; ?>
						</figure>
						<?php
					}
				} else {
					// Año fuera del rango
					if ( has_post_thumbnail($post->ID) ) {
						$thumb_id  = get_post_thumbnail_id($post->ID);
						$thumb_url = wp_get_attachment_image_url($thumb_id, 'full');
						$thumb_alt = get_post_meta($thumb_id, '_wp_attachment_image_alt', true);
						?>
						<figure class="cover-image fair-main-image">
							<img src="<?php echo esc_url($thumb_url); ?>" alt="<?php echo esc_attr($thumb_alt ?: get_the_title($post->ID)); ?>">
							<?php if ( get_the_post_thumbnail_caption($thumb_id) ) : ?>
								<figcaption class="cover-image__caption">
									<?php echo esc_html( get_the_post_thumbnail_caption($thumb_id) ); ?>
								</figcaption>
							<?php endif; ?>
						</figure>
						<?php
					}
				}
			} 
			?>


			<div data-sticky-sidebar class="col--sm--three--seventh col--md--two--fifth">
				
				<?php
				global $post;
				$slug = $post->post_name;

				// comprobar si es loop-fair-YYYY
				$is_loop_fair_year = (bool) preg_match('/^loop-fair-\d{4}$/', $slug);
				$info_card_class   = $is_loop_fair_year ? 'info-card info-card-big' : 'info-card';
				?>

				<div class="<?php echo esc_attr($info_card_class); ?>">
					<dl class="info-card__list">
						<?php if (!empty($fields['dates_string'])): ?>
							<dt class="info-card__key"><span class="info-card__key-text"><?php _e('Dates', 'far_loop'); ?></span></dt>
							<dd class="info-card__value"><?php echo esc_html($fields['dates_string']); ?></dd>
						<?php endif; ?>

						<?php if (!empty($fields['location'])): ?>
							<dt class="info-card__key"><span class="info-card__key-text"><?php _e('Location', 'far_loop'); ?></span></dt>
							<dd class="info-card__value"><?php echo esc_html($fields['location']); ?></dd>
						<?php endif; ?>

						<?php if ($file_url): ?>
							<dt class="info-card__key"><span class="info-card__key-text"><?php _e('Program', 'far_loop'); ?></span></dt>
							<dd class="info-card__value"><a download href="<?php echo esc_url($file_url); ?>">Download</a></dd>
						<?php endif; ?>
					</dl>
				</div>

				
			</div>
			<div class="col--sm--four--seventh col--md--three--fifth u_ph-1p5">
				<div class="wysiwyg">
					<?php echo apply_filters('the_content', $fields['description']); ?>
				</div>
			</div>
		</div>

		<?php if ( ! empty( $fields['main_selection'][0]['videos'] ) ) : ?>
		<div id="sectionMainSelection" class="u_mv-4">
			<h3 class="section-heading delta">
			<span class="u_text-underline"><?php _e( 'Main Selection', 'far_loop' ); ?></span>
			</h3>

			<div class="archive-grid">
			<?php foreach ( $fields['main_selection'][0]['videos'] as $artist_video ) :
				$vid_id   = is_object($artist_video) ? (int)$artist_video->ID : (int)$artist_video;
				if ( ! $vid_id ) continue;

				$url      = get_permalink( $vid_id );
				$title    = get_the_title( $vid_id );
				$cover    = get_field( 'cover_image', $vid_id );
				$src      = ( empty($cover) ? get_template_directory_uri() . '/img/horizontal-placeholder.svg' : ( $cover['url'] ?? '' ) );
				$authors  = get_field( 'author', $vid_id );
				$year     = get_field( 'year', $vid_id );
				$authors_string = function_exists('get_authors_string') ? get_authors_string($authors) : '';

				// Gallery (título y ciudad opcional)
				$gallery_string = '';
				$gallery        = get_field( 'gallery', $vid_id );
				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 (término de taxonomía 'edition', si existe)
				$editions       = get_the_terms( $vid_id, 'edition' );
				$edition_label  = ( !empty($editions) && ! is_wp_error($editions) ) ? $editions[0]->name : '';
			?>
				<div class="archive-item">
				<a href="<?php echo esc_url($url); ?>" class="archive-new-thumb">
					<div class="archive-thumb__image-container main-selection">
					<img src="<?php echo esc_url($src); ?>" alt="<?php echo esc_attr($title); ?>">
					</div>

					<div class="archive-thumb__text">
					<!-- Título -->
					<h3 class="archive-thumb__title">
						<?php echo esc_html( $title ); ?>
						<?php if ( !empty($year) ) echo ' (' . esc_html($year) . ')'; ?>
					</h3>

					<!-- Etiquetas bajo el título -->
					<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>

					<!-- Línea inferior (colección / edición) -->
					<?php
						// Si quieres replicar exactamente el ejemplo con “NombreDelTermino Edición”,
						// usamos una etiqueta fija “Main Selection” + la edición (si existe).
						$bottom_line = trim( 'Main Selection' . ( $edition_label ? ' ' . $edition_label : '' ) );
					?>
					<?php if ( $bottom_line ) : ?>
						<div class="archive-thumb__year"><?php echo esc_html( $bottom_line ); ?></div>
					<?php endif; ?>
					</div>
				</a>
				</div>
			<?php endforeach; ?>
			</div>
		</div>
		<?php endif; ?>

		<?php if (!empty($curated[0]['videos'])): ?>
			<div id="sectionCuratedSelection" class="u_mv-4">
				<h3 class="section-heading delta"><span class="u_text-underline"><?php _e('Curated Section', 'far_loop'); ?></span></h3>
				<?php foreach ($curated[0]['videos'] as $v): echo video_thumb($v); endforeach; ?>
			</div>
		<?php endif; ?>



<?php
// Helper para resolver URL de imagen desde array/ID/URL con preferencia por un size
$resolve_image_url = function( $img, $size_pref = 'squared' ) {
  if ( is_array( $img ) ) {
    if ( ! empty( $img['sizes'][ $size_pref ] ) ) return $img['sizes'][ $size_pref ];
    if ( ! empty( $img['url'] ) ) return $img['url'];
    return '';
  }
  if ( is_numeric( $img ) ) {
    $src = wp_get_attachment_image_src( (int) $img, $size_pref );
    return $src ? $src[0] : '';
  }
  if ( is_string( $img ) ) return $img;
  return '';
};
?>

<?php if ( ! empty( $fields['committee_intro'] ) ) : ?>
  <div id="sectionCommittee" class="u_mv-4">
    <div class="grid u_mh-min1p5">
      <div class="col--xl--one--half u_ph-1p5">
        <h3 class="section-heading delta">
          <span class="u_text-underline"><?php _e( 'Committee', 'far_loop' ); ?></span>
        </h3>
      </div>
      <div class="col--xl--one--half u_ph-1p5">
        <div class="u_mb-5">
          <div class="wysiwyg">
            <?php echo $fields['committee_intro']; // WYSIWYG sin <p> extra ?>
          </div>
        </div>
      </div>
    </div>

    <?php
    // OJO: el field correcto es 'committee_members' (no 'committer_members')
    $committee_members = get_field( 'committer_members' );
    if (!empty($fields['committer_members'])): 
    
    ?>
      <div class="archive-grid">
        <?php foreach ($fields['committer_members'] as $member):
          // Nombre y texto
          $name    = get_field( 'name', $member_id );
          $surname = get_field( 'surname', $member_id );
          $title   = trim( ($name ?: get_the_title($member_id)) . ' ' . ($surname ?: '') );
          $about   = get_field( 'about', $member_id );
          if ( ! $about ) $about = get_field( 'bio', $member_id ); // fallback si tu ACF usa 'bio'
          $about_excerpt = $about ? wp_trim_words( wp_strip_all_tags( $about ), 20, '…' ) : '';
          $profile_url   = get_permalink( $member_id );

          // Imagen 'portait' (por key y fallback por nombre)
          $portrait_field = get_field( 'field_56c86aeb593d5', $member_id ); // key del field
          if ( ! $portrait_field ) {
            $portrait_field = get_field( 'portait', $member_id ); // nombre del field (sic)
          }
          $src = $resolve_image_url( $portrait_field, 'squared' );
          if ( ! $src ) $src = $resolve_image_url( $portrait_field, 'medium' );
        ?>
          <div class="archive-item">
            <a href="<?php echo esc_url( $profile_url ); ?>" class="archive-new-thumb">
              <div class="archive-thumb__image-container committee">
                  <img src="<?php echo esc_url($member['portrait']['sizes']['squared']); ?>" alt="<?php echo esc_attr($member['name']); ?>">
              </div>
              <div class="archive-thumb__text">
				<div class="archive-thumb__title"><?php echo esc_html($member['name']); ?></div>
                <div class="archive-thumb__label"><?php echo esc_html($member['city']); ?></div>
                
             
                  <div class="archive-thumb__year"><?php echo esc_html($member['about']); ?></div>
           
              </div>
            </a>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>
  </div>
<?php endif; ?>



		<?php if (!empty($fields['main_selection']) && count($fields['main_selection']) > 1):
			array_shift($fields['main_selection']); ?>
			<div id="sectionPastEditions" class="u_mv-4 u_pb-2">
				<h3 class="section-heading delta"><span class="u_text-underline"><?php _e('Past editions', 'far_loop'); ?></span></h3>
				<?php foreach ($fields['main_selection'] as $edition): ?>
					<div class="past-edition">
						<a href="#" data-collapse="#pastEdition<?php echo esc_attr($edition['year']); ?>" class="past-edition__collapse-button">
							<div class="grid">
								<div class="col--md--one--half col--push--md--one--half col--vab">
									<h3 class="past-edition__year-name u_bd-bottom-black">Ed. <?php echo esc_html($edition['year']); ?></h3>
								</div>
								<div class="col--md--one--half col--pull--md--one--half col--vab">
									<div class="past-edition__collapse-label">(Click to see the <?php echo esc_html($edition['year']); ?> edition)</div>
								</div>
							</div>
						</a>
						<div id="pastEdition<?php echo esc_attr($edition['year']); ?>" class="collapse">
							<div class="u_pt-5">
								<?php foreach ($edition['videos'] as $artist_video):
									echo video_thumb($artist_video);
								endforeach; ?>
							</div>
						</div>
					</div>
				<?php endforeach; ?>
			</div>
		<?php endif; ?>
	</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(); ?>