<?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-0">

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

        <!-- Item Video Chnnel -->
        <li class="same-page-nav__item">
          <a href="#video-channel" class="same-page-nav__link">
            <?php esc_html_e('Video Channel', 'far_loop'); ?>
          </a>
        </li>

         <!-- Item Pasr Editions -->
        <li class="same-page-nav__item">
          <a href="#past-editions" class="same-page-nav__link" >
            <?php esc_html_e('Past Editions', 'far_loop'); ?>
          </a>
        </li>
      </ul>
    </div>

    <!-- ===== Hero ===== -->


        <?php if ( has_post_thumbnail() ) : 
          $thumb_id = get_post_thumbnail_id();
          $thumb_caption = get_post($thumb_id)->post_excerpt;
          $thumb_img = wp_get_attachment_image( $thumb_id, 'full', false, [
            'alt' => get_the_title()
          ] );
        ?>
          <figure class="cover-image fair-main-image">
            <?php echo $thumb_img; ?>
            <?php if ( $thumb_caption ) : ?>
              <figcaption class="cover-image__caption"><?php echo esc_html( $thumb_caption ); ?></figcaption>
            <?php endif; ?>
          </figure>
        <?php endif; ?>




    <div class="grid  u_mh-min1p5">


			<div data-sticky-sidebar class="col--sm--one--half u_ph-1p5">
        <div class="info-card info-card-big">
          <dl class="info-card__list">
            <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>

            <?php $location = get_field('location_symposium'); ?>
            <?php 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 echo esc_html($location); ?></dd>
            <?php endif; ?>	

            <?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--one--half u_ph-1p5">
        <div class="wysiwyg">
          <?php the_field('description_symposium')?>
        </div>
      </div>
    </div>

    <!-- ===== Paneles ===== -->
    <?php if ( have_rows('panel_symposium') ) : ?>
      <?php while ( have_rows('panel_symposium') ) : the_row(); ?>
        <section id="panel-<?php echo get_row_index(); ?>" class="u_mv-4 symposium-section">

          <!-- Título “ancla” estático (no scrolea) -->
          <h3 class="section-heading delta section-sticky">
            <span class="u_text-underline"><?php the_sub_field('name'); ?><?php if ( get_sub_field('subtitle') ) : ?>—	<?php the_sub_field('subtitle'); ?><?php endif; ?></span>
          </h3>

            <?php 
            $image = get_sub_field('panel_image'); // debe devolver un array
            if ( $image ) : 
            ?>
              <figure class="cover-image fair-main-image">
                <img src="<?php echo esc_url($image['url']); ?>" alt="<?php echo esc_attr($image['alt'] ?: $image['title']); ?>">
                <?php if ( !empty($image['caption']) ) : ?>
                  <figcaption class="cover-image__caption"><?php echo esc_html($image['caption']); ?></figcaption>
                <?php endif; ?>
              </figure>
            <?php endif; ?>

          <div class="grid">
            <div data-sticky-sidebar class="col--sm--three--seventh col--md--two--fifth">
              <!-- (El título real se “rellena” con el item del menú cuando llega) -->
              <!-- info-card -->
              <div class="info-card">
                <dl class="info-card__list">
                  <?php if ( get_sub_field('dates') ) : ?>	
                  <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>
                  <?php endif; ?>	

                  <?php if ( get_sub_field('moderator') ) : ?>	
                  <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>
                  <?php endif; ?>	
                </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">
              <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>

              <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;

                    $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);
                    }

                    $src = '';
                    if ($portrait_id) {
                      $srcData = wp_get_attachment_image_src($portrait_id, 'full');
                      if ($srcData && !empty($srcData[0])) $src = $srcData[0];
                    }
                    if (!$src) $src = get_template_directory_uri() . '/img/square-placeholder.svg';

                    $name    = (string) get_field('name', $member_id);
                    $surname = (string) get_field('surname', $member_id);
                    $title   = trim($name . ' ' . $surname);
                    if ($title === '') $title = get_the_title($member_id);
                    $profile_url = get_permalink($member_id);
                  ?>
                    <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__title">
                            <a href="<?php echo esc_url($profile_url); ?>"><?php echo esc_html($title ?: __('Jury', 'far_loop')); ?></a>
                          </div>
                        </div>
                      </article>
                    </div>
                  <?php endforeach; ?>
                </div>
              </div><!-- /.swiper -->
            </div>
          <?php endif; ?>
        </section>
      <?php endwhile; ?>
    <?php endif; ?>

    <!-- ===== VIDEO CHANNEL (tal como lo tenías) ===== -->
    <div class="u_pt-2 u_pt-md-4" id="video-channel">

      <h3 class="section-heading delta section-sticky">
            <span class="u_text-underline"><?php _e( 'Video Channel', 'far_loop' ); ?></span>
      </h3>
    
      <?php
      if ( ! function_exists('farloop_resolve_image_url') ) {
        function farloop_resolve_image_url( $img, $size = 'large' ) {
          if (empty($img)) return '';
          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] : '';
            }
          }
          if (is_numeric($img)) {
            $src = wp_get_attachment_image_src((int)$img, $size);
            return $src && !empty($src[0]) ? $src[0] : '';
          }
          if (is_string($img) && filter_var($img, FILTER_VALIDATE_URL)) return $img;
          return '';
        }
      }

      $display_mode = get_field('video_channel_display'); // 'grid' | 'slide'
      if ( ! in_array($display_mode, array('grid','slide'), true) ) $display_mode = 'grid';

      $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();
          $cover    = get_field('cover_image', get_the_ID());
          $speakers = get_field('speakers', get_the_ID(), false);
          $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;

      if ( ! empty($items) ) :
        if ( $display_mode === '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">
                    <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 :
          $count = count($items);
          $root_id = 'video-channel-' . uniqid();
        ?>
          <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__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>
        <?php endif;
      endif; ?>
    </div><!-- /#video-channel -->








    <?php
			/**
			 * Past Editions – Slider (sustituye al menú antiguo)
			 */
			if ( is_page() ) {
			global $post;

			// Detecta edición actual desde el slug tipo loop-festival-YYYY
			$current_year = null;
			if ( $post && ! empty( $post->post_name ) && preg_match( '/^loop-symposium-(\d{4})$/', $post->post_name, $m ) ) {
				$current_year = (int) $m[1];
			}

			$min_year  = 2010;
			$now_year  = (int) date('Y');
			$base_slug = 'loop-symposium-';

			// Reúne páginas de ediciones (excluye la edición actual)
			$editions = array(); // cada item: ['year'=>YYYY, 'page'=>WP_Post, 'thumb'=>url, 'url'=>url]

			for ( $y = $now_year; $y >= $min_year; $y-- ) {
				$slug = $base_slug . $y;

				// Con WPML: si hay traducción, busca en idioma actual
				$page = get_page_by_path( $slug, OBJECT, 'page' );
				if ( ! $page instanceof WP_Post && function_exists('icl_object_id') ) {
				// Intento 2: obtener ID de la edición en idioma default y traducir
				$default_page = get_page_by_path( $slug, OBJECT, 'page' );
				if ( $default_page instanceof WP_Post ) {
					$tr_id = icl_object_id( $default_page->ID, 'page', true );
					if ( $tr_id ) $page = get_post( $tr_id );
				}
				}

				if ( $page instanceof WP_Post ) {
				if ( $current_year && (int)$y === (int)$current_year ) {
					// Si NO quieres mostrar la edición actual en “past”, sáltala:
					continue;
				}

				// Thumbnail (featured image) o placeholder
				$thumb = get_the_post_thumbnail_url( $page->ID, 'large' );
				if ( ! $thumb ) {
					$thumb = get_template_directory_uri() . '/img/horizontal-placeholder.svg';
				}

				$url = get_permalink( $page->ID );

				$editions[] = array(
					'year'  => (int)$y,
					'page'  => $page,
					'thumb' => $thumb,
					'url'   => $url,
				);
				}
			}

			// Si hay ediciones, imprime la sección en slide
			if ( ! empty( $editions ) ) :
			?>
      <div class="u_pt-2 u_pt-md-4" id="past-editions">
        <h3 class="section-heading delta section-sticky">
          <span class="u_text-underline"><?php esc_html_e('Past Editions', 'far_loop'); ?></span>
        </h3>

        <div class="past-editions-swiper-outer u_mt-2" data-past-root>
          <div class="swiper-nav">
            <button class="swiper-btn prev past-editions-swiper__prev" type="button" aria-label="<?php esc_attr_e('Previous','far_loop'); ?>">&larr;</button>
            <button class="swiper-btn next past-editions-swiper__next" type="button" aria-label="<?php esc_attr_e('Next','far_loop'); ?>">&rarr;</button>
          </div>

          <div class="swiper past-editions-swiper"
              data-swiper-past-editions
              data-editions-count="<?php echo esc_attr( count($editions) ); ?>"
              style="opacity:0;transition:opacity .2s">
            <div class="swiper-wrapper">
              <?php foreach ( $editions as $ed ) : ?>
                <div class="swiper-slide">
                  <div class="archive-item">
                    <a class="archive-new-thumb" href="<?php echo esc_url( $ed['url'] ); ?>">
                      <div class="archive-thumb__image-container award">
                        <img src="<?php echo esc_url( $ed['thumb'] ); ?>" alt="<?php echo esc_attr( get_the_title( $ed['page']->ID ) ); ?>">
                      </div>
                      <div class="archive-thumb__text">
                        <h3 class="archive-thumb__title"><?php echo esc_html( get_the_title( $ed['page']->ID ) ); ?></h3>
                        <div class="archive-thumb__year"><?php echo esc_html( $ed['year'] ); ?></div>
                      </div>
                    </a>
                  </div>
                </div>
              <?php endforeach; ?>
            </div>
          </div><!-- /.swiper -->
        </div><!-- /.outer -->
      </div>
			<?php
			endif; // !empty(editions)
			}
			?>





  </div><!-- /.l_container -->
</div><!-- page wrap -->



<!-- ===== JS: Sticky titles + Swipers ===== -->
<script>
// Loader único 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;
  };
})();



// Swipers (committee, video-channel, past-editions)
(function(){
  function pvDesktopByCount(count){ return (count <= 4) ? Math.max(count,1) : 4.3; }

  function initCommittee(){
    document.querySelectorAll('.committee-swiper[data-swiper-committee]').forEach(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 sw = new Swiper(el, {
        slidesPerView: pvDesktopByCount(count),
        spaceBetween: 15,
        watchOverflow: true,
        observer: true, observeParents: true,
        preloadImages: false, lazy: { loadOnTransitionStart: true },
        navigation: { nextEl, prevEl },
        breakpoints: {
          0:    { slidesPerView: 1.2, spaceBetween: 15 },
          640:  { slidesPerView: 2.2, spaceBetween: 15 },
          768: { slidesPerView: pvDesktopByCount(count), spaceBetween: 15 },
          1400: { slidesPerView: pvDesktopByCount(count), spaceBetween: 15 },
          1800: { slidesPerView: pvDesktopByCount(count), spaceBetween: 24 }
        },
        on: {
          init(){ el.style.opacity = '1'; },
          resize(){ this.update(); }
        }
      });
      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 });
      });
      document.fonts && document.fonts.ready && document.fonts.ready.then(()=>sw.update());
      window.addEventListener('load', ()=>sw.update());
      setTimeout(()=>sw.update(), 400);
    });
  }

  function initVideoChannel(){
    document.querySelectorAll('[data-swiper-video-channel]').forEach(el=>{
      if (el.__inited) return; el.__inited = true;
      const root = el.closest('[data-video-channel-root]');
      const nextEl = root?.querySelector('.video-channel-swiper__next');
      const prevEl = root?.querySelector('.video-channel-swiper__prev');
      const count = parseInt(el.getAttribute('data-items-count'),10) || el.querySelectorAll('.swiper-slide').length || 0;
      const pvDesk = pvDesktopByCount(count);
      const sw = new Swiper(el, {
        slidesPerView: 1.2, spaceBetween: 15,
        observer:true, observeParents:true,
        preloadImages:false, lazy:{ loadOnTransitionStart:true },
        navigation: { nextEl, prevEl },
        breakpoints: {
          640: { slidesPerView: 1.2, spaceBetween: 15 },
          768: { slidesPerView: 2.2, spaceBetween: 15 },
          1400:{ slidesPerView: pvDesk, spaceBetween: 15 },
          1800: { slidesPerView: pvDesk, spaceBetween: 32 }
        },
        on:{ init(){ el.style.opacity='1'; }, resize(){ this.update(); } }
      });
      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 });
      });
    });
  }

function initPastEditions(){
  document.querySelectorAll('[data-swiper-past-editions]').forEach(el=>{
    if (el.__inited) return;
    el.__inited = true;

    const root   = el.closest('[data-past-root]') || document;
    const nextEl = root.querySelector('.past-editions-swiper__next') || root.querySelector('.swiper-btn.next');
    const prevEl = root.querySelector('.past-editions-swiper__prev') || root.querySelector('.swiper-btn.prev');

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

    // helper: leer slidesPerView efectivo (con breakpoints de Swiper)
    function effectiveSPV(sw){
      // En Swiper 9, params.slidesPerView ya refleja el breakpoint activo si es numérico
      const spv = sw.params && typeof sw.params.slidesPerView === 'number'
        ? sw.params.slidesPerView
        : 1;
      return spv || 1;
    }

    const sw = new Swiper(el, {
      slidesPerView: 1.1,
      spaceBetween: 15,
      watchOverflow: true,           // Swiper marca overflow=false si no hace falta deslizar
      observer: true,
      observeParents: true,
      preloadImages: false,
      lazy: { loadOnTransitionStart:true },
      centeredSlides: false,
      navigation: { nextEl, prevEl },
      breakpoints: {
        640:  { slidesPerView: 1.2, spaceBetween: 15 },
        768:  { slidesPerView: 4, spaceBetween: 15 },
        // ⬇️ En desktop SIEMPRE 4 columnas, aunque haya 1–3 items

        1400: { slidesPerView: 4, spaceBetween: 15 },
        1800: { slidesPerView: 4, spaceBetween: 32 }
      },
      on: {
        init(){
          el.style.opacity = '1';

          // En init y resize, mostrar/ocultar navegación y permitir/denegar drag
          const spv = effectiveSPV(this);
          const needNav = count > spv;
          if (nextEl) nextEl.style.display = needNav ? '' : 'none';
          if (prevEl) prevEl.style.display = needNav ? '' : 'none';
          this.allowTouchMove = needNav;
        },
        resize(){
          // En cada resize recalculamos con el spv efectivo
          const spv = effectiveSPV(this);
          const needNav = count > spv;
          if (nextEl) nextEl.style.display = needNav ? '' : 'none';
          if (prevEl) prevEl.style.display = needNav ? '' : 'none';
          this.allowTouchMove = needNav;
          this.update();
        }
      }
    });

    // Forzar update al cargar imágenes
    el.querySelectorAll('img').forEach(img=>{
      const once = ()=> sw.update();
      if (img.complete) once();
      img.addEventListener('load', once, { once:true });
      img.addEventListener('error', once, { once:true });
    });
  });
}

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






<script>
(function(){

  const menu = document.querySelector('#symposium-sticky-nav');
  if (!menu || menu.offsetHeight === 0 || getComputedStyle(menu).display === 'none') return;

  // ✅ Siempre detectar correctamente el contenedor de scroll
  function getScrollElement() {
    return document.scrollingElement || document.documentElement || document.body;
  }

  function adminBarH() {
    return document.getElementById('wpadminbar')?.offsetHeight || 0;
  }

  function headerH() {
    const h = document.querySelector('.site-header, header, .main-header');
    const styles = h ? getComputedStyle(h) : null;
    return (h && styles.position === 'fixed' && styles.display !== 'none') ? h.offsetHeight : 0;
  }

  function setStickyVar() {
    const stickyTop = adminBarH() + headerH() + 16;
    document.documentElement.style.setProperty('--symposium-sticky-top', stickyTop + 'px');
  }

  setStickyVar();

  function menuTop() {
    const cs = getComputedStyle(menu);
    const pad = parseFloat(cs.paddingTop) || 0;
    const brd = parseFloat(cs.borderTopWidth) || 0;
    return menu.getBoundingClientRect().top + pad + brd;
  }

  const items    = Array.from(menu.querySelectorAll('.same-page-nav__item'));
  const links    = Array.from(menu.querySelectorAll('.same-page-nav__link'));
  const sections = [];
  const map      = new Map();

  links.forEach(link => {
    const sel = link.getAttribute('data-soft-scroll') || link.getAttribute('href');
    if (!sel || !sel.startsWith('#')) return;
    const sec = document.querySelector(sel);
    if (!sec) return;

    let title = sec.querySelector('.section-sticky');
    if (!title) {
      const children = Array.from(sec.children).filter(el => el.offsetHeight > 0);
      if (children.length > 0) title = children[0];
    }
    if (!title) return;

    sections.push(sec);
    map.set(sec, { link, li: link.closest('.same-page-nav__item'), title });
  });

  function liFullHeight(li){
    if (!li) return 0;
    const rect = li.getBoundingClientRect();
    const cs   = getComputedStyle(li);
    const mt   = parseFloat(cs.marginTop) || 0;
    const mb   = parseFloat(cs.marginBottom) || 0;
    return rect.height + mt + mb;
  }

  function hiddenStackBefore(index){
    let sum = 0;
    for (let i = 0; i < index; i++){
      const sec = sections[i];
      const { li } = map.get(sec);
      if (li && getComputedStyle(li).visibility === 'hidden') {
        sum += liFullHeight(li);
      }
    }
    return sum;
  }

  // ✅ Scroll robusto, usando siempre el contenedor correcto
  function scrollTitleToAnchor(title, index){
    const baseY   = menuTop();
    const adjust  = hiddenStackBefore(index);
    const anchor  = baseY - adjust;

    const scrollEl = getScrollElement();
    const currentScroll = scrollEl.scrollTop;
    const offset = title.getBoundingClientRect().top - anchor;

    scrollEl.scrollTo({
      top: currentScroll + offset,
      behavior: 'smooth'
    });
  }

  links.forEach(a => {
    a.addEventListener('click', e => {
      const sel = a.getAttribute('data-soft-scroll') || a.getAttribute('href');
      if (!sel || !sel.startsWith('#')) return;
      const sec = document.querySelector(sel);
      if (!sec) return;
      const { title } = map.get(sec) || {};
      if (!title) return;
      e.preventDefault();
      const idx = sections.indexOf(sec);
      scrollTitleToAnchor(title, idx);
    });
  });

  const H = 1;
  function evaluateAll(){
    const baseY = menuTop();
    let liveIndex = -1;

    for (let i = 0; i < sections.length; i++){
      const { title } = map.get(sections[i]);
      const tTop   = title.getBoundingClientRect().top;
      const anchor = baseY - hiddenStackBefore(i);

      if (tTop <= anchor + H) {
        liveIndex = i;
      }
    }

    sections.forEach((sec, i) => {
      const { li, title } = map.get(sec);
      if (!li || !title) return;

      if (i < liveIndex) {
        li.classList.add('is-hidden');
        title.classList.add('is-past');
        title.classList.remove('is-live');
      } else if (i === liveIndex) {
        li.classList.add('is-hidden');
        title.classList.add('is-live');
        title.classList.remove('is-past');
      } else {
        li.classList.remove('is-hidden');
        title.classList.remove('is-live');
        title.classList.remove('is-past');
      }
    });
  }

  let raf = null;
  window.addEventListener('scroll', () => {
    if (raf) cancelAnimationFrame(raf);
    raf = requestAnimationFrame(evaluateAll);
  }, { passive: true });

  window.addEventListener('resize', () => {
    setStickyVar();
    evaluateAll();
  });

  evaluateAll();
})();
</script>

<?php get_footer();