<?php
// /relevanssi-live-ajax-search/search-results-query.php
if ( ! defined( 'ABSPATH' ) ) exit;

// En modo wp_query el plugin pasa $relevanssi_query (WP_Query)
$q     = isset( $relevanssi_query ) && $relevanssi_query instanceof WP_Query ? $relevanssi_query : null;
$posts = $q && $q->have_posts() ? $q->posts : array();
?>
<div class="archive-grid search-grid search-query">
  <?php if ( ! empty( $posts ) ) : foreach ( $posts as $post ) :
    setup_postdata( $post );
    $pid   = get_the_ID();
    $title = get_the_title( $pid );
    $url   = get_permalink( $pid );
    $ptype = get_post_type( $pid );

    // ✅ Imagen principal según tipo
    $thumb = '';
    if ( $ptype === 'activity' || $ptype === 'venue' ) {
        $img = get_field( 'featured_image', $pid );
        if ( is_array( $img ) ) {
            $thumb = $img['sizes']['large']
                ?? $img['sizes']['medium_large']
                ?? $img['url']
                ?? '';
        }
    }

    // fallback al post_thumbnail
    if ( ! $thumb ) {
      $thumb = get_the_post_thumbnail_url( $pid, 'large' );
    }

    // placeholder final
    if ( ! $thumb ) {
      $thumb = get_template_directory_uri() . '/img/horizontal-placeholder.svg';
    }

    $pt_obj = get_post_type_object( $ptype );
    $label  = $pt_obj && ! empty( $pt_obj->labels->singular_name ) ? $pt_obj->labels->singular_name : '';
  ?>
    <div class="archive-item">
      <a class="archive-new-thumb" href="<?php echo esc_url( $url ); ?>">
        <div class="archive-thumb__image-container search">
          <img src="<?php echo esc_url( $thumb ); ?>" alt="<?php echo esc_attr( $title ); ?>">
        </div>
        <div class="archive-thumb__text">
          <?php if ( $label ) : ?>
            <div class="archive-thumb__label"><?php echo esc_html( $label ); ?></div>
          <?php endif; ?>
          <h3 class="archive-thumb__title"><?php echo esc_html( $title ); ?></h3>
        </div>
      </a>
    </div>
  <?php endforeach; wp_reset_postdata(); else : ?>
    <p class="eta u_mt-2"><?php esc_html_e( 'No results found.', 'far_loop' ); ?></p>
  <?php endif; ?>
</div>