<?php

/*
 * Template name: Symposium
 *
 * @package far_loop
 *
 */

get_header();
?>

<div class="u_pt-3 u_pt-md-6">
  <div id="symposium-overview" class="l_container u_mv-5">



    <div class="grid u_mh-min1 u_mb-3 u_mb-md-0">
      <!-- same-page-nav module-->
      <ul class="same-page-nav">
        <?php if( have_rows('panel_symposium') ): ?>
          <?php while( have_rows('panel_symposium') ): the_row(); ?>
            <li class="same-page-nav__item">
              <a href="#" data-soft-scroll="#panel-<?php echo get_row_index(); ?>" class="same-page-nav__link">
                <?php the_sub_field('name'); ?>
              </a>
            </li>
          <?php endwhile; ?>
        <?php endif; ?>
      </ul>
    </div>

    <div class="grid">

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

      <div data-sticky-sidebar class="col--sm--three--seventh col--md--two--fifth ">
        <!-- info-card module-->
        <div class="info-card info-card-big">
          <!-- 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_symposium')?></dd>

            <!-- info-card list item-->
            <?php
            $location = get_field('location_symposium');
            if ( $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 the_field('location_symposium')?></dd>
            <?php endif; ?>	

            <!-- Download PDF -->				
            <?php if ( get_field('pdf_section') ) : ?>
              <span class="info-card_download-container">
                <dt class="info-card__key"><span class="info-card__key-text"><?php the_field('name_pdf_section'); ?></span></dt>
                <dd class="info-card__value"><a download href="<?php the_field('download_pdf_symposium'); ?>">Download</a></dd>
              </span>
            <?php endif; ?>
          </dl>
        </div>


      </div>

      <div class="col--sm--four--seventh col--md--three--fifth">
        <!-- wysiwyg module-->
        <div class="wysiwyg">
          <?php the_field('description_symposium')?>
        </div>
      </div>
    </div>

    <?php if( have_rows('panel_symposium') ): ?>
      <?php while( have_rows('panel_symposium') ): the_row(); ?>
        <div id="panel-<?php echo get_row_index(); ?>" class="u_mv-2 awards-section">


          <figure class="cover-image fair-main-image">
              <img src="<?php the_sub_field('panel_image'); ?>">
          </figure>


          <div class="grid">
            <div data-sticky-sidebar class="col--sm--three--seventh col--md--two--fifth">
              <h3 class="section-heading delta"><span class="u_text-underline"><?php the_sub_field('name'); ?></span></h3>

              <!-- 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_sub_field('dates'); ?></dd>

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

                </dl>
              </div>


            </div>
            <div class="col--sm--four--seventh col--md--three--fifth">
              <div class="wysiwyg"><?php the_sub_field('description'); ?></div>
            </div>
          </div>

          <?php
          $participants = get_sub_field('participants');
          if ( ! empty($participants) && is_array($participants) ) :
            $count = count($participants);
          ?>
            <div class="committee-swiper-outer"><!-- contenedor para scope de botones -->
              <!-- Botones de navegación (scoped a este bloque) -->
              <div class="swiper-nav">
                <button class="swiper-btn committee-swiper__prev" aria-label="<?php esc_attr_e('Previous','far_loop'); ?>">&larr;</button>
                <button class="swiper-btn committee-swiper__next" aria-label="<?php esc_attr_e('Next','far_loop'); ?>">&rarr;</button>
              </div>

              <!-- Swiper container con los mismos atributos que Committee -->
              <div class="swiper committee-swiper"
                   data-swiper-committee
                   data-members-count="<?php echo esc_attr($count); ?>"
                   style="opacity:0; transition:opacity .2s;">
                <div class="swiper-wrapper">
                  <?php foreach ( $participants as $member_post ) :
                    $member_id   = is_object($member_post) ? $member_post->ID : (int) $member_post;

                    // Retrato (key → id crudo 'portrait' → typo 'portait')
                    $portrait    = get_field('field_56c86aeb593d5', $member_id);
                    $portrait_id = 0;
                    if ( is_array($portrait) && !empty($portrait['ID']) ) {
                      $portrait_id = (int) $portrait['ID'];
                    } else {
                      $portrait_id = (int) get_field('portrait', $member_id, false);
                      if ( ! $portrait_id ) {
                        $portrait_id = (int) get_field('portait', $member_id, false);
                      }
                    }

                    // Render imagen (squared > square > medium > full) o placeholder
                    $img_html = '';
                    if ( $portrait_id ) {
                      foreach ( ['squared','square','medium','full'] as $size ) {
                        $img_html = wp_get_attachment_image( $portrait_id, $size, false, [
                          'alt' => get_the_title($member_id),
                        ]);
                        if ( $img_html ) break;
                      }
                    }
                    if ( ! $img_html ) {
                      $ph = get_template_directory_uri() . '/img/square-placeholder.svg';
                      $img_html = '<img src="' . esc_url($ph) . '" alt="' . esc_attr(get_the_title($member_id)) . '">';
                    }

                    // Campos de texto
                    $name    = (string) get_field('name', $member_id);
                    $surname = (string) get_field('surname', $member_id);
                    $about   = (string) get_field('biography', $member_id);
                    $about_excerpt = wp_trim_words( wp_strip_all_tags( $about ), 20, '…' );
                    $profile_url   = get_permalink( $member_id );
                  ?>


                  <?php
                  // Título visible de la tarjeta
                  $title = trim( (string) $name . ' ' . (string) $surname );
                  if ($title === '') {
                    $title = get_the_title($member_id);
                  }

                  // Construir la URL de imagen ($src) a partir del retrato
                  $src = '';
                  if (!empty($portrait_id)) {
                    // intenta en este orden: squared, square, medium, full
                    $sizesTry = ['squared','square','medium','full'];
                    foreach ($sizesTry as $sz) {
                      $img = wp_get_attachment_image_src((int)$portrait_id, 'full');
                      if ($img && !empty($img[0])) { $src = $img[0]; break; }
                    }
                  }
                  if ($src === '') {
                    $src = get_template_directory_uri() . '/img/square-placeholder.svg';
                  }
                  ?>

                  <div class="swiper-slide archive-grid">
                    <article class="committee-card">
                      <a class="committee-card__thumb archive-new-thumb portrait" href="<?php echo esc_url($profile_url); ?>">
                      
                          <img src="<?php echo esc_url($src); ?>" alt="<?php echo esc_attr($title ?: 'Jury'); ?>">
                      
                      </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 (!empty($about_excerpt)) : ?>
                          <div class="archive-thumb__year"><?php echo esc_html($about_excerpt); ?></div>
                        <?php endif; ?>
                        -->
                      </div>
                    </article>
                  </div>
                  <?php endforeach; ?>
                </div><!-- /.swiper-wrapper -->
              </div><!-- /.swiper -->
            </div><!-- /.committee-swiper-outer -->
          <?php endif; ?>
        </div>
      <?php endwhile; ?>
    <?php endif; ?>


       <!-- VIDEO Channel -->	
      <div class="u_pt-2 u_pt-md-2" id="video-channel">

                  <h3 class="section-heading delta">
                    <span class="u_text-underline"><?php _e( 'Video Channel', 'far_loop' ); ?></span>
                  </h3>
      



<?php
// === helper: resolver URL de imagen desde ACF image (id|array|null) ===
if ( ! function_exists('farloop_resolve_image_url') ) {
  function farloop_resolve_image_url( $img, $size = 'large' ) {
    if (empty($img)) return '';
    // Si viene como array de ACF (return_format=array)
    if (is_array($img)) {
      if (!empty($img['sizes'][$size])) return $img['sizes'][$size];
      if (!empty($img['url'])) return $img['url'];
      if (!empty($img['ID'])) {
        $src = wp_get_attachment_image_src((int)$img['ID'], $size);
        return $src && !empty($src[0]) ? $src[0] : '';
      }
    }
    // Si viene como ID
    if (is_numeric($img)) {
      $src = wp_get_attachment_image_src((int)$img, $size);
      return $src && !empty($src[0]) ? $src[0] : '';
    }
    // Si ya es URL
    if (is_string($img) && filter_var($img, FILTER_VALIDATE_URL)) return $img;
    return '';
  }
}

// Lee el modo de visualización (ACF select en la página actual)
$display_mode = get_field('video_channel_display'); // 'grid' | 'slide'
if ( ! in_array($display_mode, array('grid','slide'), true) ) {
  $display_mode = 'grid';
}

// Query de video-conference
$q = new WP_Query(array(
  'post_type'           => 'video-conference',
  'orderby'             => 'date',
  'order'               => 'DESC',
  'posts_per_page'      => -1,
  'no_found_rows'       => true,
  'ignore_sticky_posts' => true,
  'suppress_filters'    => false,
));

$items = array();

if ( $q->have_posts() ) :
  while ( $q->have_posts() ) : $q->the_post();

    // ACF fields del post
    $cover    = get_field('cover_image', get_the_ID());
    $speakers = get_field('speakers', get_the_ID(), false); // IDs crudos

    $src = farloop_resolve_image_url($cover, 'large');
    if ( ! $src ) {
      $src = get_template_directory_uri() . '/img/horizontal-placeholder.svg';
    }

    $speakers_label = '';
    if ( ! empty($speakers) && function_exists('get_authors_string') ) {
      $speakers_label = get_authors_string( (array)$speakers );
    }

    $items[] = array(
      'url'      => get_permalink(),
      'title'    => get_the_title(),
      'img'      => $src,
      'speakers' => $speakers_label,
    );

  endwhile;
  wp_reset_postdata();
endif;

// Nada que mostrar
if ( empty($items) ) return;

// Render según modo
if ( $display_mode === 'grid' ) : ?>

  <!-- ========== GRID ========== -->
  <div class="archive-grid">
    <?php foreach ( $items as $it ) : ?>
      <div class="archive-item">
        <a href="<?php echo esc_url($it['url']); ?>" class="archive-new-thumb">
          <div class="archive-thumb__image-container video-conference">
            <img src="<?php echo esc_url($it['img']); ?>" alt="<?php echo esc_attr($it['title']); ?>">
          </div>
          <div class="archive-thumb__text">
            <!-- <div class="archive-thumb__label"><?php esc_html_e('Video conference', 'far_loop'); ?></div> -->
            <h3 class="archive-thumb__title"><?php echo esc_html($it['title']); ?></h3>
            <?php if ( !empty($it['speakers']) ) : ?>
              <div class="archive-thumb__year"><?php echo esc_html($it['speakers']); ?></div>
            <?php endif; ?>
          </div>
        </a>
      </div>
    <?php endforeach; ?>
  </div>

<?php else :
  // slide
  $count = count($items);
  $root_id = 'video-channel-' . uniqid();
?>

  <!-- ========== SLIDE ========== -->
  <div class="video-channel-swiper-outer" data-video-channel-root="<?php echo esc_attr($root_id); ?>">
    <div class="swiper video-channel-swiper"
         id="<?php echo esc_attr($root_id); ?>-swiper"
         data-swiper-video-channel
         data-items-count="<?php echo esc_attr($count); ?>"
         style="opacity:0; transition:opacity .2s;">
      
      <div class="video-channel-swiper__controls">
        <button class="video-channel-swiper__prev" id="<?php echo esc_attr($root_id); ?>-prev" type="button" aria-label="<?php esc_attr_e('Previous', 'far_loop'); ?>">&larr;</button>
        <button class="video-channel-swiper__next" id="<?php echo esc_attr($root_id); ?>-next" type="button" aria-label="<?php esc_attr_e('Next', 'far_loop'); ?>">&rarr;</button>
      </div>

      <div class="swiper-wrapper">
        <?php foreach ( $items as $it ) : ?>
          <div class="swiper-slide archive-grid">
            <article class="committee-card">
              <a class="videochannel-card__thumb archive-new-thumb" href="<?php echo esc_url($it['url']); ?>">
                <div class="archive-thumb__image-container video-conference">
                  <img src="<?php echo esc_url($it['img']); ?>" alt="<?php echo esc_attr($it['title']); ?>">
                </div>
              </a>
              <div class="archive-thumb__text">
                <!-- <div class="archive-thumb__label"><?php esc_html_e('Video conference', 'far_loop'); ?></div> -->
                <div class="archive-thumb__title">
                  <a href="<?php echo esc_url($it['url']); ?>"><?php echo esc_html($it['title']); ?></a>
                </div>
                <?php if ( !empty($it['speakers']) ) : ?>
                  <div class="archive-thumb__year"><?php echo esc_html($it['speakers']); ?></div>
                <?php endif; ?>
              </div>
            </article>
          </div>
        <?php endforeach; ?>
      </div>
    </div>
  </div>

  <!-- loader único + init del slider -->
  <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;
      };
    })();

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

    function initVideoChannelSwipers(){
      document.querySelectorAll('[data-swiper-video-channel]').forEach(function(el){
        if (el.__inited) return;
        el.__inited = true;

        const outer = el.closest('[data-video-channel-root]') || document;
        const rootId = outer ? outer.getAttribute('data-video-channel-root') : null;

        const nextEl = rootId ? ('#'+rootId+'-next') : null;
        const prevEl = rootId ? ('#'+rootId+'-prev') : null;

        const count  = parseInt(el.getAttribute('data-items-count'), 10) || el.querySelectorAll('.swiper-slide').length || 0;
        const pvDesk = slidesPerViewDesktop(count);

        const sw = new Swiper(el, {
          slidesPerView: 1.1,
          spaceBetween: 32,
          watchSlidesProgress: true,
          observer: true,
          observeParents: true,
          preloadImages: false,
          lazy: { loadOnTransitionStart: true },
          navigation: { nextEl: nextEl, prevEl: prevEl },
          breakpoints: {
            640:  { slidesPerView: 1.6, spaceBetween: 16 },
            768:  { slidesPerView: 2.2, spaceBetween: 20 },
            1024: { slidesPerView: pvDesk, spaceBetween: 32 }
          },
          on: {
            init(){
              el.style.opacity = '1';
              const needScroll = (count > pvDesk);
              const next = nextEl ? document.querySelector(nextEl) : null;
              const prev = prevEl ? document.querySelector(prevEl) : null;
              if (next && prev) {
                next.style.display = needScroll ? '' : 'none';
                prev.style.display = needScroll ? '' : 'none';
              }
            },
            resize(){ sw.update(); }
          }
        });

        // Refrescos suaves
        const imgs = el.querySelectorAll('img');
        imgs.forEach(function(img){
          const once = ()=> sw.update();
          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(()=>sw.update()); }
        window.addEventListener('load', ()=>sw.update());
        setTimeout(()=>sw.update(), 400);
        setTimeout(()=>sw.update(), 1200);
      });
    }

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

<?php endif; ?>





      </div>






  </div>
</div>

<!-- ========== SCRIPT: loader único + init multi-instancia (Committee-like) ========== -->
<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;
    };
  })();

  function pvDesktopByCount(count){
    // ≤4 → 4, >4 → 4.3
    return (count <= 4) ? Math.max(count, 1) : 4.3;
  }

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

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

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

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

      const sw = new Swiper(el, {
        slidesPerView: slidesViewDesktop,
        spaceBetween: 24,
        watchOverflow: true,
        observer: true,
        observeParents: true,
        preloadImages: false,
        lazy: { loadOnTransitionStart: true },
        navigation: { nextEl, prevEl },
        breakpoints: {
          0:    { slidesPerView: (count <= 1 ? 1 : 1.2), spaceBetween: 16 },
          480:  { slidesPerView: (count <= 2 ? Math.min(count,2) : 1.6), spaceBetween: 16 },
          640:  { slidesPerView: (count <= 3 ? Math.min(count,3) : 2.2), spaceBetween: 18 },
          768:  { slidesPerView: (count <= 4 ? Math.max(count,1) : 3.2), spaceBetween: 24 },
          1024: { slidesPerView: slidesViewDesktop, spaceBetween: 32 }
        },
        on: {
          init(){
            el.style.opacity = '1'; // revelar al iniciar
            const needScroll = (count > slidesViewDesktop);
            if (nextEl && prevEl) {
              nextEl.style.display = needScroll ? '' : 'none';
              prevEl.style.display = needScroll ? '' : 'none';
            }
          },
          resize(){
            sw.update();
          }
        }
      });

      // Refrescos robustos
      const imgs = el.querySelectorAll('img');
      imgs.forEach(img=>{
        const once = ()=>{ sw.update(); };
        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(()=>{ sw.update(); });
      }
      window.addEventListener('load', ()=>{ sw.update(); });
      setTimeout(()=>{ sw.update(); }, 400);
      setTimeout(()=>{ sw.update(); }, 1200);
    });
  }

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

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
  } else {
    boot();
  }

  // Si el repeater se inyecta dinámicamente (AJAX, tabs), reintenta
  let moTimer = null;
  const mo = new MutationObserver(function(){
    clearTimeout(moTimer);
    moTimer = setTimeout(initCommitteeSwipers, 200);
  });
  mo.observe(document.body, { childList:true, subtree:true });
})();
</script>

<?php get_footer();