<?php

/*
 * Template name: Video Productions Awards
 *
 * @package far_loop
 */

get_header();

// Obtén los IDs de los términos seleccionados desde ACF
$term_ids = get_field('award_selection_prod');

// Si hay términos seleccionados, obtenemos los detalles de cada término
if ( !empty($term_ids) && is_array($term_ids) ) {
    $terms = array_map(function($term_id) {
        return get_term($term_id, 'award');
    }, $term_ids);
} else {
    $terms = array(); // En caso de que no haya términos seleccionados
}
?>

<div class="u_pt-3 u_pt-md-6">
	<div id="overview-productions" class="l_container u_mv-0">
		<div class="grid u_mh-min1 u_mb-1">




    <!--
			<?php if ( !empty( $terms ) ) : ?>
				<ul class="same-page-nav">
				<?php foreach ( $terms as $term ) : ?>
					<li class="same-page-nav__item">
						<a href="#" data-soft-scroll="#<?php echo $term->slug;?>" class="same-page-nav__link"><?php echo $term->name;?></a>
					</li>
				<?php endforeach;?>
				</ul>
				<?php endif; ?>
      -->



				<div class="cover-image fair-main-image u_ph-1p5">
						<?php 
							if ( has_post_thumbnail() ) {
							the_post_thumbnail( 'full', [ 'alt' => get_the_title() ] );
							}
						?>
				</div>




        <div class="grid">
            <div data-sticky-sidebar class="col--sm--one--half u_ph-1p5">
              <div class="page-title u_mb-3 u_mb-md-4">
                <h1 class="page-title__apex-title u_mb-0p5"><?php the_title(); ?></h1>
              </div>
              <div class="wysiwyg"><p><?php the_field('video_production_intro'); ?></p></div>
            </div>

            <div class="col--sm--one--half u_ph-1p5">
              <div class="wysiwyg"><?php the_content();?></div>
            </div>
        </div>   



		

				
	    	
		</div>

		<?php

		if ( !empty( $terms ) ) :

		foreach ( $terms as $term ) :

		$args = array(
			'post_type' => 'artist-video',
			'tax_query' => array(
				array(
					'taxonomy' => 'award',
					'field'    => 'slug',
					'terms'    => $term->slug,
				),
			),
			'nopaging' => true,
		);

		$videos = get_posts( $args );

		$editions = array();

		foreach ($videos as $key => $video) {

		    $edition = get_the_terms( $video->ID, 'edition');

		    $editions[$key] = $edition[0]->slug;

		}

		array_multisort($editions, SORT_DESC, $videos);

		?>

			<!-- awards-section module-->
			<div id="<?php echo $term->slug;?>" class="awards-section">

				<div class="grid u_mh-min1">

					<div class="col--sm--one--half u_ph-1p5">

						<h3 class="section-heading delta">
							<span class="u_text-underline"><?php echo $term->name;?></span>
						</h3>

						<div class="wysiwyg">
							<p><?php echo $term->description;?></p>
						</div>
			
							<?php
							$link = get_field( 'link', 'award_' . $term->term_id );
							if ( $link ) : ?>
							<a href="<?php echo $link;?>" class="awards-section__external-link"><span class="awards-section__external-link-text"><?php echo remove_http( $link );?></span><span class="icon icon--external-link"></span></a>
							<?php endif;?>
					</div>


					<!-- Current AWARD -->	
					<div class="col--sm--one--half u_ph-1p5">
							<?php

							$current_award = array_shift( $videos );
							$editions = get_the_terms( $current_award->ID, 'edition' );

							$url = get_permalink( $current_award->ID );
							$cover = get_field( 'cover_image', $current_award->ID );
							$src = ( empty( $cover ) ) ? get_template_directory_uri() . '/img/horizontal-placeholder.svg' : $cover['url'];
							$year = get_field( 'year', $current_award->ID );
							$authors = get_field( 'author', $current_award->ID );
							$authors_string = get_authors_string( $authors );
							$gallery = get_field( 'gallery', $current_award->ID );
							$gallery_title = $city = '';
							if ( !empty( $gallery ) ) {
								$gallery_address = get_field( 'address', $gallery->ID );
								$gallery_title = get_the_title( $gallery->ID );
								$city = $gallery_address[0]['city'];
							}

							?>

							<!-- awards-thumb module-->
							<a href="<?php echo esc_url( $url ); ?>" class="awards-past-thumb">
								<div class="awards-thumb__image">
									<img
									class="current-award-thumb"
									src="<?php echo esc_url( $src ); ?>"
									alt="<?php echo esc_attr( isset($current_award->post_title) ? $current_award->post_title : ( $term->name ?? '' ) ); ?>">
								</div>

								<div class="archive-thumb__text">
									<h2 class="awards-section__title">
									<?php
										$title_out = isset($current_award->post_title) ? $current_award->post_title : ( $term->name ?? '' );
										echo esc_html( $title_out );
										if ( ! empty( $year ) ) {
										echo ' (' . esc_html( $year ) . ')';
										}
									?>
									</h2>

									


									

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

									<?php if ( ! empty( $gallery_title ) ) : ?>
										<h5 class="awards-past-thumb__title archive-thumb__label awards-past-thumb__galery">
										<?php
											echo esc_html( $gallery_title );
											if ( ! empty( $city ) ) {
											echo ' (' . esc_html( $city ) . ')';
											}
										?>
										</h5>
									<?php endif; ?>
									</div>
								</div>
							</a>


							<div class="u_mb-3">
									<?php
									$jury = get_field( 'jury', 'award_' . $term->term_id );
									if ( !empty( $jury ) ) :
									$html = ''; ?>

									<!-- section-heading module-->
									<h2 class="awards-section__title"><?php echo $term->name . ' ' . __( 'jury', 'far_loop' );?></h2>
									

									<div class="grid u_mh-min1">

											<?php

											foreach ( $jury as $member ) :

											// Duplicate from speakers.php with modifications
											// FUTURE UNIFICATION

											$portrait = get_field( 'portait', $member );

											if ( !empty( $portrait ) ) {
												$src = $portrait['sizes']['squared'];
											} else {
												$src = get_template_directory_uri() . '/img/square-placeholder.svg';
											}

											$html .= '<div class="col--xxs--one--half col--xs--one--third col--sm--one--quarter col--tb--one--fifth u_ph-1"><a href="' . get_permalink($member) . '" class="speaker-portrait">';
											$html .= '<div class="u_mb-0p5"><img src="' . $src . '" alt="' . $member->post_title .'"></div>';
											$html .= '<h3 class="speaker-portrait__name">' . $member->post_title .'</h3></a>';
											$html .= '</div>';

											endforeach;

											echo $html; ?>

									</div>

								<?php endif; ?>

							</div>
					</div>
					<!-- #Current AWARD -->

				</div>
			


<?php
$video_production_display = get_field('video_production_display'); // "grid" o "slide"

// IDs únicos por bloque
$root_id   = 'video-production-' . uniqid();
$swiper_id = $root_id . '-swiper';
$prev_id   = $root_id . '-prev';
$next_id   = $root_id . '-next';
$pag_id    = $root_id . '-pagination';
?>

<div class="u_mb-3">
  <h2 class="awards-section__title">
    <?php echo esc_html($term->name) . ' ' . esc_html__('past editions','far_loop'); ?>
  </h2>

  <?php if ( !empty($videos) ) : ?>

    <?php if ( $video_production_display === 'slide' ) : ?>
      <!-- === SLIDE === -->
      <div class="awards-past awards-past--slider" data-awards-swiper-root="<?php echo esc_attr($root_id); ?>">
        <div class="swiper awards-past-swiper"
             id="<?php echo esc_attr($swiper_id); ?>"
             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="Previous">&larr;</button>
            <button class="swiper-btn next" id="<?php echo esc_attr($next_id); ?>" aria-label="Next">&rarr;</button>
          </div>

          <div class="swiper-wrapper">
            <?php foreach ( $videos as $video ) :
              $url     = get_permalink($video->ID);
              $cover   = get_field('cover_image', $video->ID);
              $src     = (empty($cover)) ? get_template_directory_uri() . '/img/horizontal-placeholder.svg' : ($cover['url'] ?? '');
              $year    = get_field('year', $video->ID);
              $authors = get_field('author', $video->ID);
              $authors_string = function_exists('get_authors_string') ? get_authors_string($authors) : '';

              // Gallery
              $gallery = get_field('gallery', $video->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
              $editions = get_the_terms($video->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($video->ID)); ?>">
                    </div>
                    <div class="archive-thumb__text">
                      <h3 class="archive-thumb__title">
                        <?php echo esc_html( get_the_title($video->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($term->name) . ' ' . esc_html($edition_label); ?>
                        </div>
                      <?php endif; ?>
                    </div>
                  </a>
                </div>
              </div>
            <?php endforeach; ?>
          </div>
        </div>
      </div>

    <?php else : ?>
      <!-- === GRID === -->
      <div class="archive-grid">
        <?php foreach ( $videos as $video ) :
          $url     = get_permalink($video->ID);
          $cover   = get_field('cover_image', $video->ID);
          $src     = (empty($cover)) ? get_template_directory_uri() . '/img/horizontal-placeholder.svg' : ($cover['url'] ?? '');
          $year    = get_field('year', $video->ID);
          $authors = get_field('author', $video->ID);
          $authors_string = function_exists('get_authors_string') ? get_authors_string($authors) : '';

          // Gallery
          $gallery = get_field('gallery', $video->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
          $editions = get_the_terms($video->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 award">
                <img src="<?php echo esc_url($src); ?>" alt="<?php echo esc_attr(get_the_title($video->ID)); ?>">
              </div>
              <div class="archive-thumb__text">
                <h3 class="archive-thumb__title">
                  <?php echo esc_html( get_the_title($video->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($term->name) . ' ' . esc_html($edition_label); ?>
                  </div>
                <?php endif; ?>
              </div>
            </a>
          </div>
        <?php endforeach; ?>
      </div>
    <?php endif; ?>

  <?php endif; // !empty($videos) ?>
</div><!-- /.u_mb-3 -->




			</div>

		<?php endforeach; endif; ?>


	</div>
</div>





<script>
(function(){
  // ---------- Loader único de Swiper ----------
  window.__ensureSwiper = window.__ensureSwiper || (function(){
    let 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')) {
          const 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')) {
          const 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 {
          const i = setInterval(function(){
            if (window.Swiper) { clearInterval(i); resolve(); }
          }, 30);
        }
      });
      return p;
    };
  })();

  // ---------- Utilidades ----------
  function desktopPV(count){ return (count <= 4) ? 4 : 4.3; }

  function showHideNav(sw, count, pvDesk){
    const needScroll = count > pvDesk;
    const nav = sw.navigation;
    if (nav) {
      if (nav.nextEl) nav.nextEl.style.display = needScroll ? '' : 'none';
      if (nav.prevEl) nav.prevEl.style.display = needScroll ? '' : 'none';
    }
    if (sw.pagination && sw.pagination.el) {
      sw.pagination.el.style.display = needScroll ? '' : 'none';
    }
  }

  // ---------- Init para todas las instancias ----------
  function initVideoProductionSwipers(){
    // Buscar TODOS los contenedores root que hayas renderizado:
    // Usamos el mismo data-atributo que en tu markup: data-awards-swiper-root
    document.querySelectorAll('[data-awards-swiper-root]').forEach(function(root){
      const rootId = root.getAttribute('data-awards-swiper-root');
      if (!rootId) return;

      // Dentro de cada root, encontrar el .awards-past-swiper (tu contenedor Swiper)
      const el = root.querySelector('.awards-past-swiper');
      if (!el || el.__inited) return; // evitar doble init
      el.__inited = true;

      // Determinar navegación en el contexto del root
      // (en tu markup usas .swiper-btn.prev y .swiper-btn.next dentro del root)
      const nextEl = root.querySelector('.swiper-btn.next');
      const prevEl = root.querySelector('.swiper-btn.prev');

      // Contar slides para decidir PV en desktop
      const count  = el.querySelectorAll('.swiper-slide').length || 0;
      const pvDesk = desktopPV(count);

      // Inicializar Swiper
      const sw = new Swiper(el, {
        slidesPerView: 1.1,
        spaceBetween: 15,
        watchSlidesProgress: true,
        observer: true,
        observeParents: true,
        preloadImages: false,
        lazy: { loadOnTransitionStart: true },
        navigation: {
          nextEl: nextEl || null,
          prevEl: prevEl || null
        },
        // Si algún bloque necesita paginación, podrías añadir:
        // pagination: { el: root.querySelector('.swiper-pagination'), clickable: true },
        breakpoints: {
          640:  { slidesPerView: 1.1, spaceBetween: 15 },
          768:  { slidesPerView: 2.2, spaceBetween: 15 },
          1024: { slidesPerView: pvDesk, spaceBetween: 15 },
          1400: { slidesPerView: pvDesk, spaceBetween: 15 },
          1800: { slidesPerView: pvDesk, spaceBetween: 36 }
        },
        on: {
          init(){
            el.style.opacity = '1';
            showHideNav(this, count, pvDesk);
          },
          resize(){
            this.update();
            showHideNav(this, this.slides.length, pvDesk);
          }
        }
      });

      // Refrescos robustos
      const imgs = el.querySelectorAll('img');
      imgs.forEach(function(img){
        const once = ()=>{ sw.update(); showHideNav(sw, sw.slides.length, pvDesk); };
        if (img.complete) { once(); }
        img.addEventListener('load', once, { once:true });
        img.addEventListener('error', once, { once:true });
      });

      if (document.fonts && document.fonts.ready) {
        document.fonts.ready.then(function(){
          sw.update(); showHideNav(sw, sw.slides.length, pvDesk);
        });
      }
      window.addEventListener('load', function(){
        sw.update(); showHideNav(sw, sw.slides.length, pvDesk);
      });
      setTimeout(function(){ sw.update(); showHideNav(sw, sw.slides.length, pvDesk); }, 400);
      setTimeout(function(){ sw.update(); showHideNav(sw, sw.slides.length, pvDesk); }, 1200);
    });
  }

  function boot(){ window.__ensureSwiper().then(function(){ requestAnimationFrame(initVideoProductionSwipers); }); }
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
  } else {
    boot();
  }
})();
</script>

<?php get_footer(); ?>