<?php
/*
 * Template Name: Video Channel
 *
 * @package far_loop
 */

get_header();

// Layout elegido en la página (acf button group)
$layout = get_field('video_channel_layout'); // 'grid' | 'slide'
if ( ! in_array($layout, array('grid','slide'), true) ) {
  $layout = 'grid';
}

// Obtener TODOS los video-conference
$videos = get_posts(array(
  'post_type'      => 'video-conference',
  'posts_per_page' => -1,
  'orderby'        => 'date',
  'order'          => 'DESC',
  'suppress_filters' => false,
));

// Agrupar por edición (año)
$groups = array(); // [label] => array(posts)
foreach ( $videos as $post ) {
  $terms = get_the_terms($post->ID, 'edition');
  if ( !empty($terms) && !is_wp_error($terms) ) {
    foreach ( $terms as $t ) {
      // Intento extraer año (4 dígitos) del name
      $label = $t->name;
      if ( preg_match('/\b(\d{4})\b/', $label, $m) ) {
        $label = $m[1];
      }
      $groups[$label][] = $post;
    }
  } else {
    $groups['Other Editions'][] = $post;
  }
}

// Ordenar secciones: años desc; “No edition” al final
uksort($groups, function($a,$b){
  $na = preg_match('/^\d{4}$/', $a) ? (int)$a : -INF;
  $nb = preg_match('/^\d{4}$/', $b) ? (int)$b : -INF;
  if ($na === -INF && $nb === -INF) return strcasecmp($a,$b);
  if ($na === -INF) return 1;  // a (no año) va después
  if ($nb === -INF) return -1; // b (no año) va después
  return $nb <=> $na; // desc
});

// Helpers para pintar tarjeta
function vc_card_html( $p ) {
  $pid   = (int)$p->ID;
  $url   = get_permalink($pid);

  // Imagen
  $cover = get_field('cover_image', $pid);
  if ( is_array($cover) && !empty($cover['url']) ) {
    $src = $cover['url'];
  } else {
    $src = get_template_directory_uri() . '/img/horizontal-placeholder.svg';
  }

  // Speakers (profiles)
  $speakers = get_field('speakers', $pid);
  $speakers_string = '';
  if ( $speakers ) {
    if ( function_exists('get_authors_string') ) {
      $speakers_string = get_authors_string($speakers);
    } else {
      $names = array();
      foreach ( (array)$speakers as $sp ) {
        $sp_id = is_object($sp) ? $sp->ID : (int)$sp;
        if ($sp_id) $names[] = get_the_title($sp_id);
      }
      $speakers_string = implode(', ', $names);
    }
  }

  // Título
  $title = get_the_title($pid);

  ob_start(); ?>
  <div class="archive-item">
    <a href="<?php echo esc_url($url); ?>" class="archive-new-thumb">
      <div class="archive-thumb__image-container video-conference">
        <img src="<?php echo esc_url($src); ?>" alt="<?php echo esc_attr($title); ?>">
      </div>
      <div class="archive-thumb__text">
        <div class="archive-thumb__title">
          <?php echo esc_html($title); ?>
        </div>
        <?php if ( !empty($speakers_string) ) : ?>
          <div class="archive-thumb__year"><?php echo esc_html($speakers_string); ?></div>
        <?php endif; ?>
      </div>
    </a>
  </div>
  <?php
  return ob_get_clean();
}

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

    <div class="cover-image fair-main-image">
      <?php 
      $page_id = get_queried_object_id();
      if ( has_post_thumbnail( $page_id ) ) {
          echo get_the_post_thumbnail( 
              $page_id, 
              'full', 
              [ 'alt' => esc_attr( get_the_title( $page_id ) ) ] 
          );
      }
      ?>
    </div>


    <div class="grid u_mh-min1p5">
      <div data-sticky-sidebar class="col--sm--three--seventh col--md--two--fifth u_ph-1p5">
        <div class="page-title u_mb-3 u_mb-md-4">
          <h1 class="page-title__apex-title u_mb-0p5"><?php esc_html_e('Video Channel', 'far_loop'); ?></h1>
        </div>
      </div>
      <div class="col--sm--four--seventh col--md--three--fifth u_ph-1p5">
        <div class="wysiwyg">
          <?php the_field('video_channel_intro',$page_id); ?>
        </div>
      </div>
    </div>




  <!-- 
    <div class="grid u_mh-min1 u_mb-3 u_mb-md-0">
      <div class="col--md--one--half u_ph-1">
        <h1 class="page-title__apex-title"><?php esc_html_e('Video Channel', 'far_loop'); ?></h1>
      </div>
      <div class="col--md--one--half u_ph-1">
        <ul class="same-page-nav">
          <li class="same-page-nav__item">
            <span class="icon icon--list"></span>
            <a href="#" data-show-modal="participantsList" class="same-page-nav__link"><?php _e( 'List of all participants', 'far_loop' );?></a>
          </li>
        </ul>
      </div>
    </div>
	-->

    <?php if ( empty($groups) ) : ?>
      <p><?php esc_html_e('No videos found.', 'far_loop'); ?></p>
    <?php else: ?>

      <?php
      $swiper_sections = array(); // para JS

      foreach ( $groups as $label => $posts_in_year ) :
        if ( empty($posts_in_year) ) continue;

        // Título de sección
        $section_title = preg_match('/^\d{4}$/', $label) ? sprintf(__('Edition %s','far_loop'), $label) : $label;
      ?>
        <section class="video-channel-section u_mb-2">
          <h3 class="section-heading delta">
            <span class="u_text-underline"><?php echo esc_html($section_title); ?></span>
          </h3>

          <?php if ( $layout === 'grid' ) : ?>
            <div class="archive-grid">
              <?php
              foreach ( $posts_in_year as $p ) {
                echo vc_card_html($p);
              }
              ?>
            </div>

          <?php else: // slide ?>
            <?php
              $root_id   = 'vc-sec-' . md5($label . '-' . uniqid('', true));
              $swiper_id = $root_id . '-swiper';
              $prev_id   = $root_id . '-prev';
              $next_id   = $root_id . '-next';
              $count     = count($posts_in_year);
              $swiper_sections[] = array(
                'root_id'   => $root_id,
                'swiper_id' => $swiper_id,
                'prev_id'   => $prev_id,
                'next_id'   => $next_id,
                'count'     => $count,
              );
            ?>
            <div class="video-channel-swiper-outer" data-vc-swiper-root="<?php echo esc_attr($root_id); ?>">
              <div class="swiper video-channel-swiper"
                id="<?php echo esc_attr($swiper_id); ?>"
                data-items-count="<?php echo esc_attr($count); ?>"
                style="opacity:0; transition:opacity .2s;">

                <div class="video-channel-swiper__controls u_mt-1">
                  <button class="video-channel-swiper__prev" id="<?php echo esc_attr($prev_id); ?>" type="button" aria-label="<?php esc_attr_e('Previous', 'far_loop'); ?>">&larr;</button>
                  <button class="video-channel-swiper__next" id="<?php echo esc_attr($next_id); ?>" type="button" aria-label="<?php esc_attr_e('Next', 'far_loop'); ?>">&rarr;</button>
                </div>

                <div class="swiper-wrapper">
                  <?php foreach ( $posts_in_year as $p ) : ?>
                    <div class="swiper-slide">
                      <?php echo vc_card_html($p); ?>
                    </div>
                  <?php endforeach; ?>
                </div>
              </div>
            </div>
          <?php endif; ?>
        </section>
      <?php endforeach; ?>

    <?php endif; ?>
  </div>

  <?php
  // ======= Modal de participantes (mantenemos tu lógica) =======
  // recolectar speakers únicos
  $speakers_ids = array();
  foreach ( $videos as $post ) {
    $sp = get_field('speakers', $post->ID, false);
    if ($sp) $speakers_ids = array_merge($speakers_ids, (array)$sp);
  }
  $speakers_ids = array_unique(array_map('intval', $speakers_ids));
  $speakers = array();
  if ( $speakers_ids ) {
    $speakers = get_posts( array(
      'post_type'      => 'profile',
      'posts_per_page' => -1,
      'post__in'       => $speakers_ids,
      'orderby'        => 'title',
      'order'          => 'ASC',
      'tax_query'      => array(
        array(
          'taxonomy' => 'profile-type',
          'field'    => 'slug',
          'terms'    => 'speaker',
        ),
      ),
    ) );
  }
  ?>

  <div id="participantsList" class="modal">
    <div class="modal__window modal__window--small">
      <div class="modal__window__content">
        <?php if ( !empty($speakers) ) : ?>
          <ul>
            <?php foreach ( $speakers as $speaker ) : ?>
              <li><a href="<?php echo esc_url(get_permalink($speaker));?>" class="u_text-underline"><?php echo esc_html($speaker->post_title);?></a></li>
            <?php endforeach;?>
          </ul>
        <?php endif;?>
      </div>
      <a href="#" class="modal__window__close u_js-only">&times;</a>
    </div>
    <div class="modal__overlay"></div>
  </div>
</div>

<?php if ( $layout === 'slide' ) : ?>
  <script>
  (function(){
    // ===== Loader único de Swiper (idempotente) =====
    window.__ensureSwiper = window.__ensureSwiper || (function(){
      var 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')) {
            var 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')) {
            var 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 {
            var i = setInterval(function(){
              if (window.Swiper) { clearInterval(i); resolve(); }
            }, 30);
          }
        });
        return p;
      };
    })();

    function initVCSectionSwipers(){
      if (!window.Swiper) return;

      document.querySelectorAll('[data-vc-swiper-root]').forEach(function(root){
        if (root.__inited) return;
        root.__inited = true;

        var rootId   = root.getAttribute('data-vc-swiper-root');
        var el       = document.getElementById(rootId + '-swiper');
        if (!el) return;

        var nextEl   = document.getElementById(rootId + '-next');
        var prevEl   = document.getElementById(rootId + '-prev');

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

        // PV según total (desktop >=1366)
        var pvDesktop, pv1024;
        if (total <= 3) { pvDesktop = 3;   pv1024 = 3;   }
        else if (total === 4) { pvDesktop = 4; pv1024 = 3.2; }
        else { pvDesktop = 4.2; pv1024 = 3.2; }

        var navOptions = {};
        // Solo pasamos navigation si existen ambos botones
        if (nextEl && prevEl) {
          navOptions = { navigation: { nextEl: nextEl, prevEl: prevEl } };
        }

        var sw = new Swiper(el, Object.assign({
          slidesPerView: 1.2,
          spaceBetween: 16,
          watchSlidesProgress: true,
          observer: true,
          observeParents: true,
          preloadImages: false,
          lazy: { loadOnTransitionStart: true },
          breakpoints: {
            640:  { slidesPerView: 1.2, spaceBetween: 16 },
            768:  { slidesPerView: 2.2, spaceBetween: 20 },
            1024: { slidesPerView: pv1024, spaceBetween: 28 },
            1366: { slidesPerView: pvDesktop, spaceBetween: 32 }
          },
          on: {
            init: function(){
              el.style.opacity = '1';
              safeToggleNav(this, total, pvDesktop);
            },
            resize: function(){
              safeToggleNav(this, this.slides ? this.slides.length : total, pvDesktop);
            }
          }
        }, navOptions));

        // Refrescos
        var imgs = el.querySelectorAll('img');
        var refresh = function(){
          sw && sw.update && sw.update();
          safeToggleNav(sw, sw && sw.slides ? sw.slides.length : total, pvDesktop);
        };
        imgs.forEach(function(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, 500);
        setTimeout(refresh, 1500);
      });
    }

    function safeToggleNav(sw, count, pvDesktop){
      if (!sw) return;
      var need = count > (pvDesktop || 4.2);

      // Swiper v9: navigation puede existir o no
      var nextEl = sw.navigation && sw.navigation.nextEl ? sw.navigation.nextEl : null;
      var prevEl = sw.navigation && sw.navigation.prevEl ? sw.navigation.prevEl : null;

      if (nextEl && nextEl.style) nextEl.style.display = need ? '' : 'none';
      if (prevEl && prevEl.style) prevEl.style.display = need ? '' : 'none';
    }

    function boot(){
      window.__ensureSwiper().then(function(){ requestAnimationFrame(initVCSectionSwipers); });
    }

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

<?php get_footer();