<?php
/**
 * Search results (infinite scroll)
 */
get_header();

$query_string = get_search_query();

/**
 * Imagen de cada resultado (según post type) con fallback.
 */
function far_loop_get_search_thumb_url( $post_id ) {
    $thumb = get_the_post_thumbnail_url( $post_id, 'large' );
    if ( $thumb ) return $thumb;

    $pt = get_post_type( $post_id );

    if ( 'artist-video' === $pt ) {
        $cover = get_field( 'cover_image', $post_id );
        if ( is_array($cover) ) {
            if ( !empty($cover['sizes']['large']) ) return $cover['sizes']['large'];
            if ( !empty($cover['url']) ) return $cover['url'];
        }
        $stills = get_field( 'stills', $post_id );
        if ( is_array($stills) && !empty($stills) ) {
            $first = $stills[0];
            if ( !empty($first['sizes']['large']) ) return $first['sizes']['large'];
            if ( !empty($first['url']) ) return $first['url'];
        }
    }

    if ( 'activity' === $pt ) {
        $fi = get_field( 'featured_image', $post_id );
        if ( is_array($fi) ) {
            if ( !empty($fi['sizes']['large']) ) return $fi['sizes']['large'];
            if ( !empty($fi['url']) ) return $fi['url'];
        }
    }

    if ( 'profile' === $pt ) {
        $att_id = get_field( 'portrait', $post_id, false );
        if ( ! $att_id ) $att_id = get_field( 'portait', $post_id, false );
        if ( $att_id ) {
            $u = wp_get_attachment_image_url( (int)$att_id, 'large' );
            if ( $u ) return $u;
        }
    }

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

<div class="u_pt-3 u_pt-md-6">
  <div class="l_container">
    <header class="u_mb-3">
      <h1 class="page-title__alpha-title">
        <?php printf( esc_html__( 'Search results for “%s”', 'far_loop' ), esc_html( $query_string ) ); ?>
      </h1>
    </header>

    <?php if ( have_posts() ) : ?>
      <div class="archive-grid">
        <?php while ( have_posts() ) : the_post(); ?>
          <?php
            $thumb        = far_loop_get_search_thumb_url( get_the_ID() );
            $ptype        = get_post_type_object( get_post_type() );
            $ptype_label  = $ptype ? $ptype->labels->singular_name : get_post_type();
          ?>
          <div class="archive-item">
            <a class="archive-new-thumb" href="<?php the_permalink(); ?>">
              <div class="archive-thumb__image-container search-result">
                <img src="<?php echo esc_url( $thumb ); ?>" alt="<?php the_title_attribute(); ?>">
              </div>
              <div class="archive-thumb__text">
                <div class="archive-thumb__label"><?php echo esc_html( $ptype_label ); ?></div>
                <h3 class="archive-thumb__title"><?php the_title(); ?></h3>
                <div class="archive-thumb__year">
                  <?php
                  if ( function_exists( 'relevanssi_the_excerpt' ) ) {
                    relevanssi_the_excerpt();
                  } else {
                    echo wp_kses_post( wp_trim_words( get_the_excerpt(), 28, '…' ) );
                  }
                  ?>
                </div>
              </div>
            </a>
          </div>
        <?php endwhile; ?>
      </div>

      <?php
      // URL de la siguiente página (si existe)
      global $wp_query;
      $next_url = get_next_posts_page_link( $wp_query->max_num_pages );
      ?>
      <div id="search-load-more-trigger"
           data-next-url="<?php echo esc_url( $next_url ?: '' ); ?>"
           style="height:1px;"></div>

    <?php else : ?>

      <p class="eta u_mt-3">
        <?php esc_html_e( 'No results found. Try different keywords.', 'far_loop' ); ?>
      </p>

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

<script>
document.addEventListener('DOMContentLoaded', function () {
  const grid    = document.querySelector('.archive-grid');
  const trigger = document.getElementById('search-load-more-trigger');
  if (!grid || !trigger) return;

  let nextUrl   = trigger.dataset.nextUrl || '';
  let loading   = false;

  // Distancia (px) desde el fondo a la que empezamos a pedir más.
  const PREFETCH_DISTANCE = 2800; // súbelo si quieres aún antes
  const MAX_CHAIN_LOADS   = 3;    // nº de páginas seguidas por ciclo

  function distanceToBottom() {
    const docH = Math.max(
      document.body.scrollHeight, document.documentElement.scrollHeight,
      document.body.offsetHeight,  document.documentElement.offsetHeight,
      document.body.clientHeight,  document.documentElement.clientHeight
    );
    return docH - (window.scrollY + window.innerHeight);
  }

  async function fetchNextPage() {
    if (!nextUrl || loading) return false;
    loading = true;

    try {
      const res  = await fetch(nextUrl, { credentials: 'same-origin' });
      const html = await res.text();
      const doc  = new DOMParser().parseFromString(html, 'text/html');

      // Extrae nuevos items
      const newItems = doc.querySelectorAll('.archive-grid .archive-item');
      if (newItems.length) {
        newItems.forEach(el => grid.appendChild(el));
      }

      // Siguiente URL
      const nextEl = doc.getElementById('search-load-more-trigger');
      nextUrl = nextEl ? (nextEl.dataset.nextUrl || '') : '';

      return newItems.length > 0;
    } catch (e) {
      console.error(e);
      nextUrl = ''; // evita loops si falla
      return false;
    } finally {
      loading = false;
    }
  }

  // Carga si estamos dentro del umbral; puede encadenar varias páginas.
  async function maybeLoadMore() {
    if (!nextUrl) return;

    // Si ya estamos suficientemente cerca del fondo, pedimos más
    if (distanceToBottom() <= PREFETCH_DISTANCE) {
      let loads = 0;
      while (loads < MAX_CHAIN_LOADS && nextUrl && distanceToBottom() <= PREFETCH_DISTANCE) {
        const ok = await fetchNextPage();
        if (!ok) break;
        loads++;
      }
    }
  }

  // Observer con rootMargin muy grande (backup)
  const obs = new IntersectionObserver(async (entries) => {
    if (!entries[0].isIntersecting) return;
    await maybeLoadMore();
  }, { rootMargin: '3000px' }); // dispara mucho antes
  obs.observe(trigger);

  // También chequeamos por scroll/resize (ráfaga controlada)
  let ticking = false;
  function onScrollResize() {
    if (ticking) return;
    ticking = true;
    requestAnimationFrame(async () => {
      await maybeLoadMore();
      ticking = false;
    });
  }
  window.addEventListener('scroll', onScrollResize, { passive: true });
  window.addEventListener('resize', onScrollResize);

  // Primer “prime” por si la primera tanda es corta
  maybeLoadMore();
});
</script>

<?php get_footer();