<?php
/**
 * Template name: City Screen
 *
 * @package far_loop
 */

get_header();

$fields = array_fill_keys( array(
  'featured_image',
  'description',
  'venues',
), null );

foreach ( $fields as $field => $value ) {
  $fields[ $field ] = get_field( $field );
}

$page_id = get_queried_object_id();
?>

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

    <?php
    /**
     * ===============================
     * Past Editions (city-screen-YYYY)
     * ===============================
     * - Busca páginas cuyo slug termine en city-screen-YYYY
     * - Muestra hasta 7 años y el resto tras “…” (revelan al hacer hover/click)
     */

    global $post;
    $is_city_screen = false;
    $view_year      = null;

    if ( $post && ! empty( $post->post_name ) ) {
      if ( preg_match( '/city-screen-(\d{4})$/', $post->post_name, $m ) ) {
        $is_city_screen = true;
        $view_year      = (int) $m[1];
      }
    }

    if ( $is_city_screen ) :

      $now_year       = (int) date('Y');
      $min_year       = 2001;
      $max_links_show = 7;

      // Buscar todas las páginas y filtrar por slug con regex
      $pages = get_posts( array(
        'post_type'      => 'page',
        'post_status'    => 'publish',
        'posts_per_page' => -1,
        'fields'         => 'ids',
        'orderby'        => 'post_name',
        'order'          => 'DESC',
      ) );

      $found_years = array();
      foreach ( $pages as $pid ) {
        $p = get_post( $pid );
        if ( $p && preg_match( '/city-screen-(\d{4})$/', $p->post_name, $m ) ) {
          $yr = (int) $m[1];
          if ( $yr >= $min_year && $yr <= $now_year ) {
            $found_years[] = $yr;
          }
        }
      }

      // Asegurar que el año actual aparece aunque no exista página
      if ( ! in_array( $now_year, $found_years, true ) ) {
        $found_years[] = $now_year;
      }

      // Normalizar y ordenar desc
      $found_years = array_values( array_unique( $found_years ) );
      rsort( $found_years, SORT_NUMERIC );

      if ( ! empty( $found_years ) ) :
        $display_years = array_slice( $found_years, 0, $max_links_show );
        $extra_years   = array_slice( $found_years, $max_links_show );
        ?>
        <div class="nav-past-editions u_mb-3">
          <ul class="same-page-nav past-editions" id="past-editions-menu">
            <span class="past-editions-title"><?php _e( 'Past Editions', 'far_loop' );?></span>

            <?php foreach ( $display_years as $i => $y ) :
              $active_class = ( (int) $view_year === (int) $y ) ? ' is-active' : '';
              // Construimos URL siempre como /city-screen-YYYY/ (funciona aunque la real sea hija; el rewrite la resolverá si existe)
              $url = home_url( '/city-screen-' . $y . '/' );
            ?>
              <li class="same-page-nav__item">
                <a class="<?php echo esc_attr( trim( $active_class ) ); ?>" href="<?php echo esc_url( $url ); ?>">
                  <?php echo esc_html( $y ); ?>
                </a><?php
                  // Separador "/" si no es el último del grupo o si habrá “...”
                  if ( $i < count($display_years) - 1 || $extra_years ) echo '/';
                ?>
              </li>
            <?php endforeach; ?>

            <?php if ( $extra_years ) : ?>
              <li class="same-page-nav__item past-editions-more">
                <a href="#" tabindex="-1" aria-expanded="false">…</a>
              </li>
              <?php foreach ( $extra_years as $i => $y ) :
                $url = home_url( '/city-screen-' . $y . '/' );
              ?>
                <li class="same-page-nav__item extra-year" hidden>
                  <a href="<?php echo esc_url( $url ); ?>"><?php echo esc_html( $y ); ?></a><?php
                    if ( $i < count($extra_years) - 1 ) echo '/';
                  ?>
                </li>
              <?php endforeach; ?>
            <?php endif; ?>
          </ul>
        </div>
        <?php
      endif;
    endif;
    ?>

    <!-- Mapa (va después del nav de past editions) -->
    <div class="places-map-horizontal">
      <?php get_template_part( 'page-templates/locations/content' ); ?>
    </div>

    <!-- Cabecera descriptiva -->
    <div class="grid u_mh-min1p5 u_mt-4">
      <div data-sticky-sidebar class="col--sm--three--seventh col--tb--three--seventh col--md--two--fifth u_ph-1p5">
        <h1 class="page-title__apex-title">City Screen</h1>
      </div>
      <div class="col--sm--four--seventh col--tb--four--seventh col--md--three--fifth u_ph-1p5">
        <div class="wysiwyg">
          <p><?php echo esc_html( $fields['description'] );?></p>
        </div>
      </div>
    </div>

    <!-- Venues (ordenados alfabéticamente) -->
    <div class="u_mt-3">
      <div class="grid">
        <?php
        $venues = $fields['venues'] ?? array();
        $names  = array();

        if ( ! empty( $venues ) ) {
          foreach ( $venues as $k => $venue ) {
            $names[$k] = remove_accents( $venue['name'] ?? '' );
          }
          $names_lower = array_map( 'strtolower', $names );
          array_multisort( $names_lower, SORT_ASC, $names, $venues );
        }
        ?>

        <?php if ( ! empty( $venues ) ) : ?>
          <div class="wrapper-city-screen-venues">
            <?php
            // Pasamos el array a un parcial que ya lo muestre con el layout/slide deseado
            set_query_var( 'venues_list', $venues );
            get_template_part( 'template-parts/city-screen-venue' );
            ?>
          </div>
        <?php endif; ?>

      </div>
    </div>

  </div>
</div>

<!-- JS: comportamiento “…” mostrar/ocultar años extra -->
<script>
document.addEventListener('DOMContentLoaded', function () {
  var nav   = document.querySelector('.nav-past-editions');
  if (!nav) return;

  var menu  = nav.querySelector('#past-editions-menu');
  var more  = menu ? menu.querySelector('.past-editions-more') : null;
  var extras= menu ? menu.querySelectorAll('.extra-year') : [];

  if (!menu || !more || !extras.length) return;

  var hideTimer = null;

  function reveal() {
    if (menu.classList.contains('revealed')) return;
    menu.classList.add('revealed');
    var a = more.querySelector('a');
    if (a) a.setAttribute('aria-expanded', 'true');
    extras.forEach(function(li){ li.hidden = false; });
  }

  function hide() {
    if (!menu.classList.contains('revealed')) return;
    menu.classList.remove('revealed');
    var a = more.querySelector('a');
    if (a) a.setAttribute('aria-expanded', 'false');
    extras.forEach(function(li){ li.hidden = true; });
  }

  // Mostrar (click/hover/touch)
  more.addEventListener('click', function (e) { e.preventDefault(); reveal(); });
  more.addEventListener('mouseenter', reveal);
  more.addEventListener('touchstart', function (e) { e.preventDefault(); reveal(); }, { passive: false });

  // Ocultar tras salir 3 segundos
  nav.addEventListener('mouseleave', function () {
    clearTimeout(hideTimer);
    hideTimer = setTimeout(hide, 3000);
  });

  // Cancelar ocultado si vuelve el ratón
  nav.addEventListener('mouseenter', function () {
    clearTimeout(hideTimer);
  });
});
</script>

<?php get_footer();