<?php

/*
 * Template name: Fair Page
 *
 * @package far_loop
 *
 */

get_header();

$fields = array_fill_keys( array(
	'dates_string',
  'fair_main_image',
	'location',
	'description',
	'committee_intro',
	'committee_members',
), null );

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

?>

<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-min1 u_mb-3 u_mb-md-0">
            <ul class="same-page-nav page-nav">
              <!-- <li class="same-page-nav__item"><a href="#overview" data-soft-scroll="#overview" class="same-page-nav__link"><?php _e( 'Overview', 'far_loop' );?></a></li> -->
              <li class="same-page-nav__item"><a href="#committee" data-soft-scroll="#committee" class="same-page-nav__link"><?php _e( 'Committee', 'far_loop' );?></a></li>
              <li class="same-page-nav__item"><a href="#jury" data-soft-scroll="#jury" class="same-page-nav__link"><?php _e( 'Jury', 'far_loop' );?></a></li>
              <li class="same-page-nav__item"><a href="#awards" data-soft-scroll="#awards" class="same-page-nav__link"><?php _e( 'Awards', 'far_loop' );?></a></li>
            </ul>
        </div>

      <div id="overview" class="u_mv-2">
            <!-- <h3 class="section-heading delta"><span class="u_text-underline"><?php _e( 'Overview', 'far_loop' );?></span></h3> -->



            <figure class="cover-image fair-main-image">
                <img src="<?php echo $fields['fair_main_image']['url']; ?>" alt="<?php echo $fields['fair_main_image']['caption']; ?>">
                <figcaption class="cover-image__caption"><?php echo $fields['fair_main_image']['caption']; ?></figcaption>
            </figure>

    
            <div class="grid u_mh-min1p5">

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

                  <!-- info-card module-->
                  <div class="info-card">
                    <!-- info-card list-->
                    <dl class="info-card__list">

                      <!-- info-card list item-->
                      <dt class="info-card__key"><span class="info-card__key-text"><?php _e( 'Dates', 'far_loop' );?></span></dt>
                      <dd class="info-card__value"><?php the_field('dates_string'); ?></dd>

                      <!-- info-card list item-->
                      <dt class="info-card__key"><span class="info-card__key-text"><?php _e( 'Location', 'far_loop' );?></span></dt>
                      <dd class="info-card__value"><?php the_field('location'); ?></dd>

                      
                            <!-- Download -->				
                            <?php
                              $file_id = get_field('pdf_download');
                              if ( $file_id ) {
                                $file_url = wp_get_attachment_url( $file_id );
                                $file_name = get_the_title( $file_id );
                              ?>
                              <span class="info-card_download-container">
                                <dt class="info-card__key download-programme"><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>
                              </span>
                            <?php } ?>


                    </dl>
                  </div>

              </div>

            
              <div class="col--sm--one--half u_ph-1p5">
                <!-- wysiwyg module-->
                <div class="wysiwyg">
                  <!-- wysiwyg text block-->
                  <?php echo $fields['description'];?>
                </div>
              </div>

            </div>

      </div>     




      <!-- ====== COMMITTEE BLOCK ====== -->  
      <?php
      $committee_intro    = get_field('committee_intro');
      $committee_members  = get_field('committee_members'); // Post Object(s)
      $committee_display  = get_field('comittee_display'); // grid | slide

      if ( $committee_intro ) : ?>


        <div id="committee" class="u_mv-4">


          <div class="grid u_mh-min1p5">
            <div data-sticky-sidebar class="col--sm--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--sm--one--half u_ph-1p5">
              <div class="u_mb-5">
                <div class="wysiwyg">
                  <?php echo $committee_intro; ?>
                </div>
              </div>
            </div>
          </div>

          <?php if ( ! empty( $committee_members ) && is_array( $committee_members ) ) : ?>

            <?php if ( $committee_display === 'slide' ) : ?>

                <?php $members_count = count($committee_members); ?>
                <!-- Slider Committee (Swiper) -->
                <div class="committee-swiper-outer u_mt-3">
                  <div class="swiper committee-swiper" 
                      data-swiper-committee 
                      data-members-count="<?php echo esc_attr($members_count); ?>">

                    <!-- Controles -->
                    <div class="committee-swiper__controls u_mt-1">
                      <button class="committee-swiper__prev" type="button" aria-label="<?php esc_attr_e('Anterior', 'far_loop'); ?>">&larr;</button>
                      <button class="committee-swiper__next" type="button" aria-label="<?php esc_attr_e('Siguiente', 'far_loop'); ?>">&rarr;</button>
                    </div>

                    <div class="swiper-wrapper">
                      <?php foreach ( $committee_members as $member_obj ) :
                        $member_id = is_object($member_obj) ? (int)$member_obj->ID : (int)$member_obj;
                        $name  = get_the_title($member_id);
                        $city  = get_field('city', $member_id);
                        $about = get_field('about', $member_id) ?: get_field('bio', $member_id);
                        $portrait_field = get_field('portait', $member_id);
                        $portrait_url   = '';
                        if ( is_array($portrait_field) ) {
                          $portrait_url = $portrait_field['sizes']['full'] ?? $portrait_field['url'];
                        } elseif ( is_numeric($portrait_field) ) {
                          $src = wp_get_attachment_image_src((int)$portrait_field, 'full');
                          $portrait_url = $src[0] ?? '';
                        } elseif ( is_string($portrait_field) ) {
                          $portrait_url = $portrait_field;
                        }
                      ?>
                        <div class="swiper-slide archive-grid">
                          <article class="committee-card">
                            <div class="committee-card__thumb portrait">
                              <?php if ( $portrait_url ) : ?>
                                <img src="<?php echo esc_url($portrait_url); ?>" alt="<?php echo esc_attr($name); ?>">
                              <?php endif; ?>
                            </div>
                            <div class="archive-thumb__text">
                              <?php if ( $city ) : ?><div class="archive-thumb__label"><?php echo esc_html($city); ?></div><?php endif; ?>
                              <?php if ( $name ) : ?><div class="archive-thumb__title"><?php echo esc_html($name); ?></div><?php endif; ?>
                              <?php if ( $about ) : ?><p class="committee-member-potrait__bio"><?php echo wp_kses_post($about); ?></p><?php endif; ?>
                            </div>
                          </article>
                        </div>
                      <?php endforeach; ?>
                    </div>
                  </div>
                </div>



            <?php else : ?>
              <!-- Grid Committee -->
              <div class="archive-grid">
                <?php
                foreach ( $committee_members as $member_obj ) :
                  $member_id = is_object( $member_obj ) ? (int) $member_obj->ID : (int) $member_obj;

                  $name  = get_the_title( $member_id );
                  $city  = get_field( 'city', $member_id );
                  $about = get_field( 'about', $member_id ) ?: get_field( 'bio', $member_id );
                  $portrait_field = get_field( 'portait', $member_id );
                  $portrait_url   = '';
                  if ( is_array($portrait_field) ) {
                    $portrait_url = $portrait_field['sizes']['full'] ?? $portrait_field['url'];
                  } elseif ( is_numeric($portrait_field) ) {
                    $src = wp_get_attachment_image_src( (int) $portrait_field, 'full' );
                    $portrait_url = $src[0] ?? '';
                  } elseif ( is_string($portrait_field) ) {
                    $portrait_url = $portrait_field;
                  }
                ?>
                  <div class="archive-item">
                    <div class="archive-new-thumb">
                      <div class="archive-thumb__image-container portrait">
                        <?php if ( $portrait_url ) : ?>
                          <img src="<?php echo esc_url($portrait_url); ?>" alt="<?php echo esc_attr($name); ?>">
                        <?php endif; ?>
                      </div>
                      <div class="archive-thumb__text">
                        <?php if ( $city ) : ?><div class="archive-thumb__label"><?php echo esc_html($city); ?></div><?php endif; ?>
                        <?php if ( $name ) : ?><h3 class="archive-thumb__title"><?php echo esc_html($name); ?></h3><?php endif; ?>
                        <?php if ( $about ) : ?><p class="committee-member-potrait__bio"><?php echo wp_kses_post($about); ?></p><?php endif; ?>
                      </div>
                    </div>
                  </div>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>

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










        <!-- ====== JURY BLOCK ====== -->

        <?php
        // Recojo los términos (award_repeater) para la navegación "same-page"
        $awards_repeater = get_field('award_repeater');
        $selected_terms  = array();

        if ( $awards_repeater ) {
          foreach ( $awards_repeater as $row ) {
            $term_id = $row['award_selection_general'] ?? 0;
            if ( $term_id ) {
              $term = get_term( (int) $term_id, 'award' );
              if ( $term && ! is_wp_error($term) ) {
                $selected_terms[] = $term;
              }
            }
          }
          usort($selected_terms, fn($a,$b) => $a->term_id - $b->term_id);
        }

        // Helper imagen (array/id/url) con preferencia por 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
        $jury_display = get_field('jury_display'); // 'grid' | 'slide'
        $jury_intro   = get_field('jury_intro');   // WYSIWYG
        $jury_members = get_field('jury_members'); // array de Post Objects
        ?>

        <div id="jury" class="u_mv-4 awards-section">

          <div class="grid u_mh-min1p5">
            <div data-sticky-sidebar class="col--sm--one--half u_ph-1p5">
              <h3 class="section-heading delta">
                <span class="u_text-underline"><?php _e( 'Jury', 'far_loop' ); ?></span>
              </h3>
            </div>
            <div class="col--sm--one--half u_ph-1p5">
              <div class="u_mb-5">
                <div class="wysiwyg">
                  <?php echo $jury_intro; ?>
                </div>
              </div>
            </div>
          </div>

          <?php if ( !empty($jury_members) && is_array($jury_members) ) : ?>
            <?php
            // Normalizamos a IDs y contamos
            $jury_ids = array_map(
              fn($m) => is_object($m) ? (int)$m->ID : (int)$m,
              $jury_members
            );
            $members_count = count($jury_ids);
            $is_slide      = ($jury_display === 'slide');
            ?>

            <?php if ( ! $is_slide ) : ?>
              <!-- GRID -->
              <div class="archive-grid">
                <?php foreach ( $jury_ids as $member_id ) :
                  $name     = get_field('name', $member_id);
                  $surname  = get_field('surname', $member_id);
                  $title    = trim( ($name ?: get_the_title($member_id)) . ' ' . ($surname ?: '') );
                  $about    = get_field('biography', $member_id);
                  $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 name)
                  $portrait_field = get_field('field_56c86aeb593d5', $member_id);
                  if ( ! $portrait_field ) $portrait_field = get_field('portait', $member_id);
                  $src = $resolve_image_url($portrait_field, 'full');
                  if ( ! $src ) $src = $resolve_image_url($portrait_field, 'full');
                ?>
                  <div class="archive-item">
                    <a href="<?php echo esc_url($profile_url); ?>" class="archive-new-thumb">
                      <div class="archive-thumb__image-container portrait">
                        <?php if ($src): ?>
                          <img src="<?php echo esc_url($src); ?>" alt="<?php echo esc_attr($title ?: 'Jury'); ?>">
                        <?php endif; ?>
                      </div>
                      <div class="archive-thumb__text">
                        <!-- <div class="archive-thumb__label"><?php _e('Jury', 'far_loop'); ?></div> -->
                        <h3 class="archive-thumb__title"><?php echo esc_html($title ?: __('Jury', 'far_loop')); ?></h3>
                        <!-- 
                        <?php if ($about_excerpt): ?>
                          <div class="archive-thumb__year"><?php echo esc_html($about_excerpt); ?></div>
                        <?php endif; ?>
                        -->
                      </div>
                    </a>
                  </div>
                <?php endforeach; ?>
              </div>

            <?php else : ?>
              <!-- SLIDE (Swiper) con ajuste <=4 => mostrar enteros -->
              <div class="jury-swiper-outer u_mt-3">
                <div class="swiper jury-swiper"
                    data-swiper-jury
                    data-members-count="<?php echo esc_attr($members_count); ?>">

                  <div class="jury-swiper__controls u_mt-1">
                    <button class="jury-swiper__prev" type="button" aria-label="<?php esc_attr_e('Previous', 'far_loop'); ?>">&larr;</button>
                    <button class="jury-swiper__next" type="button" aria-label="<?php esc_attr_e('Next', 'far_loop'); ?>">&rarr;</button>
                  </div>

                  <div class="swiper-wrapper">
                    <?php foreach ( $jury_ids as $member_id ) :
                      $name     = get_field('name', $member_id);
                      $surname  = get_field('surname', $member_id);
                      $title    = trim( ($name ?: get_the_title($member_id)) . ' ' . ($surname ?: '') );
                      $about    = get_field('biography', $member_id);
                      $about_excerpt = $about ? wp_trim_words( wp_strip_all_tags($about), 20, '…' ) : '';
                      $profile_url = get_permalink($member_id);

                      $portrait_field = get_field('field_56c86aeb593d5', $member_id);
                      if ( ! $portrait_field ) $portrait_field = get_field('portait', $member_id);
                      $src = $resolve_image_url($portrait_field, 'full');
                      if ( ! $src ) $src = $resolve_image_url($portrait_field, 'full');
                    ?>
                      <div class="swiper-slide archive-grid">
                        <article class="committee-card">
                          <a class="committee-card__thumb archive-new-thumb" href="<?php echo esc_url($profile_url); ?>">
                            <div class="archive-thumb__image-container portrait">
                              <?php if ($src): ?>
                                <img src="<?php echo esc_url($src); ?>" alt="<?php echo esc_attr($title ?: 'Jury'); ?>">
                              <?php endif; ?>
                            </div>
                          </a>
                          <div class="archive-thumb__text">
                            <!-- <div class="archive-thumb__label"><?php _e('Jury', 'far_loop'); ?></div> -->
                            <div class="archive-thumb__title">
                              <a href="<?php echo esc_url($profile_url); ?>"><?php echo esc_html($title ?: __('Jury', 'far_loop')); ?></a>
                            </div>
                            <!-- 
                            <?php if ($about_excerpt): ?>
                              <div class="archive-thumb__year"><?php echo esc_html($about_excerpt); ?></div>
                            <?php endif; ?>
                            -->
                          </div>
                        </article>
                      </div>
                    <?php endforeach; ?>
                  </div>
                </div>
              </div>




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









        <!-- ====== AWARDS BLOCK ====== -->

      <div id="awards">
              <?php
              // ====== AWARDS (con display global slide|grid para "past editions") ======

              // Selector global (slide | grid). Por defecto grid.
              $awards_display = get_field('awards_display');
              $awards_display = in_array($awards_display, ['slide','grid'], true) ? $awards_display : 'grid';

              $__awards_slider_index = 0; // para IDs únicos por sección

              if ( have_rows('award_repeater') ) :
                while ( have_rows('award_repeater') ) : the_row();

                  // Texto descriptivo
                  $description_award = get_sub_field('description_award');
                  $description_award = wpautop($description_award);
                  $description_award = str_replace(['<p>','</p>'], '', $description_award);

                  // Término seleccionado (obligatorio)
                  $award_selection_general = get_sub_field('award_selection_general');
                  if ( ! $award_selection_general ) continue;

                  $term = get_term( (int) $award_selection_general, 'award' );
                  if ( ! $term || is_wp_error($term) ) continue;

                  // Videos del término (todos, sin paginar)
                  $args = array(
                    'post_type' => 'artist-video',
                    'tax_query' => array(
                      array(
                        'taxonomy' => 'award',
                        'field'    => 'term_id',
                        'terms'    => (int) $award_selection_general,
                      ),
                    ),
                    'nopaging' => true,
                  );
                  $videos = get_posts($args);

                  // “Current award” = primer vídeo si existe
                  $first_video = null;
                  if ( !empty($videos) ) {
                    $first_video = array_shift($videos); // el resto quedan como “past editions”
                  }

                  // IDs únicos para el slide de “past editions” (si aplica)
                  $__awards_slider_index++;
                  $root_id   = 'awardsPastSwiper-' . sanitize_html_class($term->slug) . '-' . $__awards_slider_index;
                  $swiper_id = $root_id . '-swiper';
                  $prev_id   = $root_id . '-prev';
                  $next_id   = $root_id . '-next';
                  $pagi_id   = $root_id . '-pagination';
                  ?>

                  <div id="<?php echo esc_attr($term->slug); ?>" class="awards-section">
                    <div class="grid u_mh-min1">

                      <!-- Columna título + descripción -->
                      <div data-sticky-sidebar class="col--sm--one--half u_ph-1p5 u_pb-4">
                        <h3 class="section-heading delta">
                          <span class="u_text-underline"><?php echo esc_html($term->name); ?></span>
                        </h3>
                        <div class="wysiwyg">
                          <p><?php echo $description_award; // safe: ya formateado arriba ?></p>
                        </div>
                      </div>

                      <!-- Columna current award -->
                      <div class="col--sm--one--half u_ph-1p5">
                        <div class="current-award">
                          <?php if ( $first_video ) :
                            $url     = get_permalink($first_video->ID);
                            $cover   = get_field('cover_image', $first_video->ID);
                            $src     = (empty($cover)) ? get_template_directory_uri() . '/img/horizontal-placeholder.svg' : ($cover['url'] ?? '');
                            $year    = get_field('year', $first_video->ID);
                            $authors = get_field('author', $first_video->ID);
                            $authors_string = function_exists('get_authors_string') ? get_authors_string($authors) : '';

                            // Gallery
                            $gallery        = get_field('gallery', $first_video->ID);
                            $gallery_title  = '';
                            $city           = '';
                            if ( $gallery ) {
                              $gid = is_object($gallery)? $gallery->ID : (int)$gallery;
                              $gallery_title = get_the_title($gid);
                              $addr = get_field('address', $gid);
                              if ( !empty($addr[0]['city']) ) $city = $addr[0]['city'];
                            }
                            ?>
                            
                            <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(get_the_title($first_video->ID)); ?>">
                              </div>

                              <div class="archive-thumb__text">
                                <h3 class="archive-thumb__title">
                                  <?php echo esc_html( get_the_title($first_video->ID) ); ?>
                                  <?php if ( !empty($year) ) echo ' (' . esc_html($year) . ')'; ?>
                                </h3>

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


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

                    </div><!-- /.grid -->

                    <!-- ===== Past editions (grid o slide global) ===== -->
                    <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 ( $awards_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 (para mostrar debajo)
                                  $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 (comportamiento original) === -->
                          <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><!-- /.awards-section -->

                <?php endwhile; ?>
              <?php endif; ?>


        </div>











        <?php
        /* ====== FILM SELECTION BLOCK ====== */

        $film_visibility = get_field( 'film_visibility' ); // button/toggle (show|hide|1|0…)
        $film_display    = get_field( 'film_display' );    // 'grid' | 'slide'
        $film_intro      = get_field( 'film_intro' );      // WYSIWYG
        $film_posts      = get_field( 'film_selection' );  // Post Object(s)

        $visible = false;
        if ( is_string( $film_visibility ) ) {
            $visible = ( strtolower( trim( $film_visibility ) ) === 'visible' );
        } elseif ( is_bool( $film_visibility ) ) {
            // por si en algún entorno llega booleano
            $visible = $film_visibility;
        }

        // 2) Normaliza posts a array de WP_Post
        $items = array();
        if ( is_array( $film_posts ) ) {
          foreach ( $film_posts as $p ) {
            if ( $p instanceof WP_Post ) {
              $items[] = $p;
            } elseif ( is_numeric( $p ) ) {
              $obj = get_post( (int) $p );
              if ( $obj instanceof WP_Post ) $items[] = $obj;
            }
          }
        }

        // 3) Helpers protegidos (evita "Cannot redeclare")
        if ( ! function_exists( 'far_loop_film_thumb_url' ) ) {
          function far_loop_film_thumb_url( $pid ) {
            // Featured
            $thumb = get_the_post_thumbnail_url( $pid, 'large' );
            if ( $thumb ) return $thumb;

            // ACF cover_image (array|id|url)
            $cover = get_field( 'cover_image', $pid );
            if ( is_array( $cover ) && ! empty( $cover['url'] ) ) {
              return ! empty( $cover['sizes']['large'] ) ? $cover['sizes']['large'] : $cover['url'];
            } elseif ( is_numeric( $cover ) ) {
              $src = wp_get_attachment_image_src( (int) $cover, 'large' );
              if ( ! empty( $src[0] ) ) return $src[0];
            } elseif ( is_string( $cover ) && filter_var( $cover, FILTER_VALIDATE_URL ) ) {
              return $cover;
            }

            // ACF 'stills' (si existe)
            $stills = get_field( 'stills', $pid );
            if ( is_array( $stills ) ) {
              foreach ( $stills as $s ) {
                if ( ! empty( $s['url'] ) ) return $s['url'];
              }
            }

            // Placeholder
            return get_template_directory_uri() . '/img/horizontal-placeholder.svg';
          }
        }

        if ( ! function_exists( 'far_loop_film_authors' ) ) {
          function far_loop_film_authors( $pid ) {
            $authors = get_field( 'author', $pid );
            if ( function_exists( 'get_authors_string' ) ) {
              return get_authors_string( $authors );
            }
            if ( is_array( $authors ) ) {
              $names = array();
              foreach ( $authors as $a ) {
                $names[] = is_object( $a ) ? get_the_title( $a->ID ) : get_the_title( (int) $a );
              }
              return implode( ', ', array_filter( $names ) );
            }
            return '';
          }
        }

        // 4) Render solo si procede (sin cortar el template)
        if ( $visible && ! empty( $items ) ) :
          $layout = ( $film_display === 'slide' ) ? 'slide' : 'grid';
          ?>
          <div id="film-selection" class="u_mv-4">
            <div class="grid u_mh-min1p5">
              <div data-sticky-sidebar class="col--sm--one--half u_ph-1p5">
                <h3 class="section-heading delta">
                  <span class="u_text-underline"><?php esc_html_e( 'Film Selection', 'far_loop' ); ?></span>
                </h3>
              </div>
              <div class="col--sm--one--half u_ph-1p5">
                <?php if ( ! empty( $film_intro ) ) : ?>
                  <div class="u_mb-5">
                    <div class="wysiwyg">
                      <?php echo wp_kses_post( $film_intro ); ?>
                    </div>
                  </div>
                <?php endif; ?>
              </div>
            </div>

            <?php if ( $layout === 'slide' ) : ?>
              <?php $count = count( $items ); ?>
              <div class="film-selection-swiper-outer u_mt-3">
                <div class="film-selection-swiper__controls u_mt-1">
                  <button class="film-selection-swiper__prev" type="button" aria-label="<?php esc_attr_e('Previous','far_loop'); ?>">&larr;</button>
                  <button class="film-selection-swiper__next" type="button" aria-label="<?php esc_attr_e('Next','far_loop'); ?>">&rarr;</button>
                </div>

                <div class="swiper film-selection-swiper"
                    data-swiper-film-selection
                    data-items-count="<?php echo esc_attr( $count ); ?>">
                  <div class="swiper-wrapper">
                    <?php foreach ( $items as $post_obj ) :
                      $pid     = (int) $post_obj->ID;
                      $title   = get_the_title( $pid );
                      $year    = get_field( 'year', $pid );
                      $img     = far_loop_film_thumb_url( $pid );
                      $authors = far_loop_film_authors( $pid );
                      $url     = get_permalink( $pid ); // o home_url('/videocloop/video/'.$post_obj->post_name.'/');
                    ?>
                      <div class="swiper-slide">
                        <div class="archive-item">
                          <a class="archive-new-thumb" href="<?php echo esc_url( $url ); ?>">
                            <div class="archive-thumb__image-container films">
                              <img src="<?php echo esc_url( $img ); ?>" alt="<?php echo esc_attr( $title ); ?>">
                            </div>
                            <div class="archive-thumb__text">
                              <?php if ( $authors ) : ?>
                                <div class="archive-thumb__label"><?php echo esc_html( $authors ); ?></div>
                              <?php endif; ?>
                              <h3 class="archive-thumb__title">
                                <?php echo esc_html( $title ); ?>
                                <?php if ( $year ) echo ' (' . esc_html( $year ) . ')'; ?>
                              </h3>
                            </div>
                          </a>
                        </div>
                      </div>
                    <?php endforeach; ?>
                  </div>
                </div>
              </div>

            <?php else : ?>
              <div class="archive-grid">
                <?php foreach ( $items as $post_obj ) :
                  $pid     = (int) $post_obj->ID;
                  $title   = get_the_title( $pid );
                  $year    = get_field( 'year', $pid );
                  $img     = far_loop_film_thumb_url( $pid );
                  $authors = far_loop_film_authors( $pid );
                  $url     = get_permalink( $pid );
                ?>
                  <div class="archive-item">
                    <a class="archive-new-thumb" href="<?php echo esc_url( $url ); ?>">
                      <div class="archive-thumb__image-container artist-video">
                        <img src="<?php echo esc_url( $img ); ?>" alt="<?php echo esc_attr( $title ); ?>">
                      </div>
                      <div class="archive-thumb__text">
                        <?php if ( $authors ) : ?>
                          <div class="archive-thumb__label"><?php echo esc_html( $authors ); ?></div>
                        <?php endif; ?>
                        <h3 class="archive-thumb__title">
                          <?php echo esc_html( $title ); ?>
                          <?php if ( $year ) echo ' (' . esc_html( $year ) . ')'; ?>
                        </h3>
                      </div>
                    </a>
                  </div>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>
        <?php
        endif; // $visible && !empty($items)
        ?>














    </div>
  </div>

<script>
/* ================================
   Past Editions: mostrar/ocultar años extra
================================== */
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>

<script>
/* ==========================================
   Swiper: loader único + orquestador seguro
========================================== */
(function () {
  /* 0) 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){
        // CSS
        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);
        }
        // JS
        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 {
          // Si ya existe, espera a que window.Swiper esté disponible
          const i = setInterval(function(){
            if (window.Swiper) { clearInterval(i); resolve(); }
          }, 30);
        }
      });

      return p;
    };
  })();

  /* 1) Utilidades comunes */
  const instances = new WeakMap(); // Evita doble init por elemento

  function setOnceInited(el) {
    if (el.__inited) return false;
    el.__inited = true;
    return true;
  }

  function pvDesktopByCount(count) {
    return (count <= 4) ? Math.max(count, 1) : 4.2;
  }

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

  function finalUpdates(sw) {
    if (!sw) return;
    // Refrescos de layout
    sw.update();
    sw.updateSlides();
    sw.updateSize();
  }

  // Devuelve { navigation: { nextEl, prevEl } } sólo si existen
  function buildNavigationConfig(root) {
    if (!root) return {};
    const nextEl = root.querySelector('.swiper-btn.next, .jury-swiper__next, .committee-swiper__next, .video-channel-swiper__next');
    const prevEl = root.querySelector('.swiper-btn.prev, .jury-swiper__prev, .committee-swiper__prev, .video-channel-swiper__prev');
    if (!nextEl || !prevEl) return {};
    return { navigation: { nextEl, prevEl } };
  }

  // Oculta/muestra navegación y paginación de forma segura
  function safeToggleNav(sw, need) {
    if (!sw) return;

    // navigation puede no existir:
    const nextEl = sw.navigation && sw.navigation.nextEl instanceof HTMLElement ? sw.navigation.nextEl : null;
    const 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';

    // paginación segura:
    const pagEl = sw.pagination && sw.pagination.el ? sw.pagination.el : null;
    if (pagEl) pagEl.style.display = need ? '' : 'none';
  }

  /* 2) Committee (una instancia) */
  function initCommitteeSwiper() {
    const el = document.querySelector('[data-swiper-committee]');
    if (!el || !setOnceInited(el)) return;

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

    // wrapper para controles
    const wrapper = document; // o el que toque según tu HTML
    const navCfg  = buildNavigationConfig(wrapper);

    const sw = new Swiper(el, {
      slidesPerView: slidesViewDesktop,
      spaceBetween: 32,
      watchOverflow: true,
      observer: true,
      observeParents: true,
      preloadImages: false,
      lazy: { loadOnTransitionStart: true },
      // Si existen controles, se añaden:
      ...navCfg,
      breakpoints: {
        0:    { slidesPerView: 1.2, spaceBetween: 15 },
        480:  { slidesPerView: 1.2, spaceBetween: 15 },
        640:  { slidesPerView: 2.2, spaceBetween: 15 },
        768:  { slidesPerView: 3.2, spaceBetween: 15 },
        1024: { slidesPerView: 3.2, spaceBetween: 32 },
        1200: { slidesPerView: slidesViewDesktop, spaceBetween: 32 }
      },
      on: {
        init() {
          showIfHidden(el);
          const needScroll = count > (this.params.slidesPerView || slidesViewDesktop);
          safeToggleNav(this, needScroll);
        },
        resize() {
          const needScroll = this.slides.length > (this.params.slidesPerView || slidesViewDesktop);
          safeToggleNav(this, needScroll);
        }
      }
    });

    document.fonts && document.fonts.ready && document.fonts.ready.then(()=>finalUpdates(sw));
    window.addEventListener('load', ()=>finalUpdates(sw));
    setTimeout(()=>finalUpdates(sw), 400);
    setTimeout(()=>finalUpdates(sw), 1200);

    instances.set(el, sw);
  }

  /* 3) Jury (múltiples instancias) */
  function initJurySwipers() {
    document.querySelectorAll('[data-swiper-jury]').forEach(function(el){
      if (!setOnceInited(el)) return;

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

      const wrapper = el.closest('.jury-swiper-outer') || document;
      const navCfg  = buildNavigationConfig(wrapper);

      const sw = new Swiper(el, {
        slidesPerView: slidesViewDesktop,
        spaceBetween: 32,
        watchOverflow: true,
        observer: true,
        observeParents: true,
        preloadImages: false,
        lazy: { loadOnTransitionStart: true },
        ...navCfg,
        breakpoints: {
          0:    { slidesPerView: (count <= 1 ? 1 : 1.2), spaceBetween: 15 },
          480:  { slidesPerView: (count <= 2 ? Math.min(count,2) : 1.2), spaceBetween: 15 },
          640:  { slidesPerView: (count <= 3 ? Math.min(count,3) : 2.2), spaceBetween: 15 },
          768:  { slidesPerView: (count <= 4 ? Math.max(count,1) : 3.2), spaceBetween: 32 },
          1024: { slidesPerView: (count <= 4 ? Math.max(count,1) : 3.2), spaceBetween: 32 },
          1366: { slidesPerView: slidesViewDesktop, spaceBetween: 32 }
        },
        on: {
          init() {
            showIfHidden(el);
            const needScroll = count > (this.params.slidesPerView || slidesViewDesktop);
            safeToggleNav(this, needScroll);
          },
          resize() {
            const needScroll = this.slides.length > (this.params.slidesPerView || slidesViewDesktop);
            safeToggleNav(this, needScroll);
          }
        }
      });

      document.fonts && document.fonts.ready && document.fonts.ready.then(()=>finalUpdates(sw));
      window.addEventListener('load', ()=>finalUpdates(sw));
      setTimeout(()=>finalUpdates(sw), 400);
      setTimeout(()=>finalUpdates(sw), 1200);

      instances.set(el, sw);
    });
  }

  /* 4) Awards (múltiples instancias, PV dinámico) */
  function initAwardsSwipers() {
    document.querySelectorAll('[data-awards-swiper-root]').forEach(function (node) {
      const rootId = node.getAttribute('data-awards-swiper-root');
      if (!rootId) return;

      const swiperSel = '#'+rootId+'-swiper';
      const el = document.querySelector(swiperSel);
      if (!el || !setOnceInited(el)) return;

      const wrapper = el.closest('.awards-past') || node || document;
      const navCfg  = buildNavigationConfig(wrapper);

      const pagEl = wrapper.querySelector('#'+rootId+'-pagination') || null;

      const totalSlides = el.querySelectorAll('.swiper-slide').length || 0;

      // PV por número de slides
      let pvDesktop, pv1024;
      if (totalSlides <= 3) {
        pvDesktop = 3;   pv1024 = 3;
      } else if (totalSlides === 4) {
        pvDesktop = 4;   pv1024 = 3.2;
      } else {
        pvDesktop = 4.2; pv1024 = 3.2;
      }
      const pv768  = 2.2;
      const pv640  = 1.2;
      const pvBase = 1.1;

      function currentPv() {
        const 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;
      }

      const params = {
        slidesPerView: pvBase,
        spaceBetween: 15,
        watchSlidesProgress: true,
        observer: true,
        observeParents: true,
        preloadImages: false,
        lazy: { loadOnTransitionStart: true },
        ...navCfg,
        breakpoints: {
          640:  { slidesPerView: pv640,  spaceBetween: 15 },
          768:  { slidesPerView: pv768,  spaceBetween: 15 },
          1024: { slidesPerView: pv1024, spaceBetween: 32 },
          1366: { slidesPerView: pvDesktop, spaceBetween: 32 }
        },
        on: {
          init() {
            showIfHidden(el);
            safeToggleNav(this, totalSlides > currentPv());
          },
          resize() {
            safeToggleNav(this, this.slides.length > currentPv());
          }
        }
      };

      // Añade paginación SOLO si existe
      if (pagEl) params.pagination = { el: pagEl, clickable: true };

      const sw = new Swiper(el, params);

      const refresh = () => { finalUpdates(sw); safeToggleNav(sw, sw.slides.length > currentPv()); };

      // Actualizaciones robustas
      const imgs = el.querySelectorAll('img');
      imgs.forEach(img => {
        if (img.complete) refresh();
        img.addEventListener('load',  refresh, { once:true });
        img.addEventListener('error', refresh, { once:true });
      });

      document.fonts && document.fonts.ready && document.fonts.ready.then(refresh);
      window.addEventListener('load', refresh);
      setTimeout(refresh, 400);
      setTimeout(refresh, 1200);
      setTimeout(refresh, 2200);

      instances.set(el, sw);
    });
  }

  
function initFilmSelectionSwiper(){
    document.querySelectorAll('[data-swiper-film-selection]').forEach(function(el){
      if (el.__inited) return;
      el.__inited = true;

      const wrapper = el.closest('.film-selection-swiper-outer') || document;
      const nextEl  = wrapper.querySelector('.film-selection-swiper__next');
      const prevEl  = wrapper.querySelector('.film-selection-swiper__prev');

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

      const sw = new Swiper(el, {
        slidesPerView: 1.2,
        spaceBetween: 15,
        watchSlidesProgress: true,
        observer: true,
        observeParents: true,
        preloadImages: false,
        lazy: { loadOnTransitionStart: true },
        navigation: (nextEl && prevEl) ? { nextEl, prevEl } : undefined,
        breakpoints: {
          640:  { slidesPerView: 1.2, spaceBetween: 15 },
          768:  { slidesPerView: 2.2, spaceBetween: 15 },
          1366: { slidesPerView: 3.2, spaceBetween: 32 },
          1367: { slidesPerView: pvDesk, spaceBetween: 32 }
        },
        on: {
          init(){
            el.style.opacity = '1';
            const need = total > pvDesk;
            safeToggleNav(this, need);
          },
          resize(){
            const need = (this.slides ? this.slides.length : total) > (this.params.slidesPerView || pvDesk);
            safeToggleNav(this, need);
          }
        }
      });

      // Actualizaciones robustas
      const imgs = el.querySelectorAll('img');
      const refresh = () => { finalUpdates(sw); safeToggleNav(sw, (sw.slides ? sw.slides.length : total) > (sw.params.slidesPerView || pvDesk)); };
      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);
    });
  }















  /* 5) Orquestador */
  function initAll() {
    initCommitteeSwiper();
    initJurySwipers();
    initAwardsSwipers();
    initFilmSelectionSwiper();
  }

  function safeInitAll(){ window.__ensureSwiper().then(() => requestAnimationFrame(initAll)); }

  // DOM listo
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', safeInitAll);
  } else {
    safeInitAll();
  }

  // Refuerzos
  window.addEventListener('load', safeInitAll);
  setTimeout(safeInitAll, 500);
  setTimeout(safeInitAll, 1500);

  // Observer para contenido dinámico
  let moTimer = null;
  const mo = new MutationObserver(function(){
    clearTimeout(moTimer);
    moTimer = setTimeout(safeInitAll, 200);
  });
  mo.observe(document.body, { childList: true, subtree: true });

  // API manual
  window.addEventListener('farloop:refresh-swipers', safeInitAll);
})();
</script>

<?php get_footer();
