<?php
/**
 * Partial template for Artist Video single content
 * Usado dentro de single-artist-video.php y en related_pages_module()
 */

// ─────────────────────────────────────────────────────────────────────────────
// Resolver display mode (prioridad: global → perfil actual → full)
$__av_display_mode = isset($GLOBALS['__av_display_mode']) ? $GLOBALS['__av_display_mode'] : null;
$display_mode = 'full';

if ($__av_display_mode) {
    $display_mode = $__av_display_mode;
} elseif (function_exists('is_singular') && is_singular('profile')) {
    $maybe = function_exists('get_field') ? get_field('artist_video_display_mode', get_queried_object_id()) : '';
    if (!empty($maybe)) {
        $display_mode = $maybe;
    }
}

// ─────────────────────────────────────────────────────────────────────────────
// Campos
$vimeo_id  = get_field( 'vimeo_id' );
$trailer_id = get_field( 'trailer_id' );
$options   = get_field('video_options');
$cover     = get_field('cover_image');
$authors   = get_field('author');
$gallery   = get_field('gallery');
$year      = get_field('year');
$duration  = get_field('duration'); // en tu plantilla original venía como array
$duration  = is_array($duration) && isset($duration[0]) ? array_filter($duration[0]) : $duration;
$format_and_technical = get_field('format_and_technical');
$credits   = get_field('credits');
$lead_description = get_field('lead_description');
$full_description = get_field('full_description');
$link      = get_field('extra_content_link'); 
$link      = is_array($link) && isset($link[0]) ? $link[0] : $link;
$stills    = get_field('stills');

// Helper mínimo para formatear duración si viene como array
$duration_text = '';
if (is_array($duration)) {
    // Intenta algunas claves comunes
    $parts = array();
    foreach (['hours','minutes','seconds','text','value'] as $k) {
        if (!empty($duration[$k])) $parts[] = $duration[$k];
    }
    $duration_text = trim(implode(' ', $parts));
} elseif (!empty($duration)) {
    $duration_text = $duration;
}

// Helper para galería
$gallery_title = '';
$gallery_city  = '';
if (!empty($gallery)) {
    $gallery_title = isset($gallery->post_title) ? $gallery->post_title : get_the_title($gallery);
    $gallery_address = get_field('address', is_object($gallery) ? $gallery->ID : $gallery);
    if (is_array($gallery_address) && isset($gallery_address[0]['city'])) {
        $gallery_city = $gallery_address[0]['city'];
    }
}

?>

<?php if ($display_mode === 'video_module') : ?>

	<!-- === MODO 3: Solo módulo de vídeo + datos básicos === -->
	<div class="u_mb-4">
	<?php if ( is_array($options) && in_array('private', $options) && !is_user_logged_in() ) : ?>
		<figure class="cover-image">
		<?php
		if ( ! empty( $cover ) ) {
			$src     = $cover['url'];
			$caption = $cover['caption'];
		} else {
			$src     = get_template_directory_uri() . '/img/horizontal-placeholder.svg';
			$caption = 'placeholder';
		}
		?>
		<img src="<?php echo esc_url( $src ); ?>" alt="<?php echo esc_attr( $caption ); ?>">
		<?php if ( ! empty( $caption ) ) : ?>
			<figcaption class="cover-image__caption"><?php echo esc_html( $caption ); ?></figcaption>
		<?php endif; ?>
		</figure>
		<p class="u_mt-min1 u_mb-0 u_text-italic eta">&mdash;
		<a href="<?php echo esc_url( wp_login_url( get_permalink() ) ); ?>" class="u_bd-bottom-dotted">Log in</a>
		to watch the artist video if you have been given an access
		</p>

	<?php else : ?>

		<?php if ( ! empty( $vimeo_id ) ) : ?>

		<?php video_player_module( $vimeo_id ); ?>

		<?php else : ?>

		<?php
		// Intentar primer still
		$first_still = null;
		if ( ! empty( $stills ) && is_array( $stills ) ) {
			foreach ( $stills as $s ) {
			if ( ! empty( $s['url'] ) ) { $first_still = $s; break; }
			}
		}
		?>

		<?php if ( $first_still ) : ?>
			<figure class="cover-image cover-image--still">
			<img src="<?php echo esc_url( $first_still['url'] ); ?>"
				alt="<?php echo esc_attr( ! empty( $first_still['caption'] ) ? $first_still['caption'] : 'Still' ); ?>">
			<?php if ( ! empty( $first_still['caption'] ) ) : ?>
				<figcaption class="cover-image__caption"><?php echo esc_html( $first_still['caption'] ); ?></figcaption>
			<?php endif; ?>
			</figure>

		<?php elseif ( ! empty( $cover ) ) : ?>
			<figure class="cover-image">
			<img src="<?php echo esc_url( $cover['url'] ); ?>" alt="<?php echo esc_attr( $cover['caption'] ); ?>">
			<?php if ( ! empty( $cover['caption'] ) ) : ?>
				<figcaption class="cover-image__caption"><?php echo esc_html( $cover['caption'] ); ?></figcaption>
			<?php endif; ?>
			</figure>

		<?php else : ?>
			<figure class="cover-image">
			<img src="<?php echo esc_url( get_template_directory_uri() . '/img/horizontal-placeholder.svg' ); ?>" alt="placeholder">
			<figcaption class="cover-image__caption">placeholder</figcaption>
			</figure>
		<?php endif; ?>

		<?php endif; ?>

	<?php endif; ?>
	</div>

      <div data-sticky-sidebar-grid class="grid u_mh-min1p5">
        <div data-sticky-sidebar class="col--sm--seventh--seventh u_ph-1p5">
          <?php if ( is_array( $options ) && in_array( 'premiere', $options ) ) : ?>
            <div href="#" class="premiere-mark">Première</div>
          <?php endif; ?>
          <?php get_template_part( 'template-parts/infocard-artist-video' ); ?>
        </div>
      </div>

<?php else : ?>

  <!-- === MODO 1 y 2 comparten la mayor parte. MODO 1 = FULL, MODO 2 = FULL SIN STILLS === -->

  <!-- ⚠️ NO TOCO NADA DE TU BLOQUE "FULL" ORIGINAL (solo lo envuelvo) -->
  	<div class="page-title u_mb-3 u_mb-md-4"></div>

	<div class="u_mb-5">
	<?php if ( is_array( $options ) && in_array( 'private', $options ) && ! is_user_logged_in() ) : ?>
		<figure class="cover-image">
		<?php
		if ( ! empty( $cover ) ) {
			$src     = $cover['url'];
			$caption = $cover['caption'];
		} else {
			$src     = get_template_directory_uri() . '/img/horizontal-placeholder.svg';
			$caption = 'placeholder';
		}
		?>
		<img src="<?php echo esc_url( $src ); ?>" alt="<?php echo esc_attr( $caption ); ?>">
		<figcaption class="cover-image__caption"><?php echo esc_html( $caption ); ?></figcaption>
		</figure>
		<p class="u_mt-min1 u_mb-0 u_text-italic eta">&mdash;
		<a href="<?php echo esc_url( wp_login_url( get_permalink() ) ); ?>" class="u_bd-bottom-dotted">Log in</a>
		to watch the artist video if you have been given an access
		</p>

	<?php else : ?>

		<?php
		if ( ! empty( $vimeo_id ) ) {
		// Hay video
		video_player_module( $vimeo_id );

		} else {
		// No hay video: intentar primer still
		$first_still = null;

		if ( ! empty( $stills ) && is_array( $stills ) ) {
			foreach ( $stills as $s ) {
			if ( ! empty( $s['url'] ) ) { $first_still = $s; break; }
			}
		}

		if ( $first_still ) : ?>
			<figure class="cover-image cover-image--still">
			<img src="<?php echo esc_url( $first_still['url'] ); ?>"
				alt="<?php echo esc_attr( ! empty( $first_still['caption'] ) ? $first_still['caption'] : 'Still' ); ?>">
			<?php if ( ! empty( $first_still['caption'] ) ) : ?>
				<figcaption class="cover-image__caption"><?php echo esc_html( $first_still['caption'] ); ?></figcaption>
			<?php endif; ?>
			</figure>
		<?php
		// Fallback final: cover o placeholder
		elseif ( ! empty( $cover ) ) :
			$src     = $cover['url'];
			$caption = $cover['caption']; ?>
			<figure class="cover-image">
			<img src="<?php echo esc_url( $src ); ?>" alt="<?php echo esc_attr( $caption ); ?>">
			<?php if ( ! empty( $caption ) ) : ?>
				<figcaption class="cover-image__caption"><?php echo esc_html( $caption ); ?></figcaption>
			<?php endif; ?>
			</figure>
		<?php else : ?>
			<figure class="cover-image">
			<img src="<?php echo esc_url( get_template_directory_uri() . '/img/horizontal-placeholder.svg' ); ?>" alt="placeholder">
			<figcaption class="cover-image__caption">placeholder</figcaption>
			</figure>
		<?php endif;
		}
		?>

	<?php endif; ?>
	</div>

  <div data-sticky-sidebar-grid class="grid u_mh-min1p5">
    <div data-sticky-sidebar class="col--sm--three--seventh col--md--two--fifth u_ph-1p5">
      <?php if ( is_array( $options ) && in_array( 'premiere', $options ) ) : ?>
        <div href="#" class="premiere-mark">Première</div>
      <?php endif; ?>
      <?php get_template_part( 'template-parts/infocard-artist-video' ); ?>
    </div>
    <div class="col--sm--four--seventh col--md--three--fifth u_ph-1p5">

     
	  	<?php if ( function_exists('award_list_module') ) award_list_module(); ?>
 
		<?php if ( !empty( $lead_description ) ) : ?>
      		<p class="lead-description u_mb-2 h1 ddd"><?php echo $lead_description; ?></p>
		<?php endif; ?>
		


      <div class="wysiwyg">
        <?php echo $full_description; ?>
      </div>

      <?php if ( !empty( $trailer_id ) ) : ?>
        <h3 class="section-heading delta u_mt-5"><span class="u_text-underline">Trailer</span></h3>
        <?php video_player_module( $trailer_id ); ?>
      <?php endif; ?>

      <?php if ( !empty( $link['url'] ) ) : ?>
        <div class="u_mt-4">
          <a href="<?php echo $link['url']; ?>" class="u_bd-bottom-dotted">
            <?php echo empty( $link['link_text'] ) ? remove_http( $link['url'] ) : $link['link_text']; ?>
          </a>
        </div>
      <?php endif; ?>
    </div>
  </div>

  <?php if ($display_mode !== 'full_no_imgs') : ?>
    <div class="stills-wrapper-part">
      <?php if ( !empty($stills) ) : ?>
        <h3 class="section-heading delta"><span class="u_text-underline">Stills</span></h3>

			<div class="archive-grid">
				<?php foreach ( $stills as $still ) : ?>
					<div class="archive-item">
						<div class="archive-new-thumb">
							<div class="archive-thumb__image-container still-image" data-pswp-image="data-pswp-image">
								<img src="<?php echo esc_url($still['url']); ?>" alt="Still">
							</div>
						</div>
					</div>
				<?php endforeach; ?>
			</div>


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

  <!-- pswp (photoswipe) module-->
  <div class="pswp">
    <div class="pswp__bg"></div>
    <div class="pswp__scroll-wrap">
      <div class="pswp__container">
        <div class="pswp__item"></div>
        <div class="pswp__item"></div>
        <div class="pswp__item"></div>
      </div>
      <div class="pswp__ui pswp__ui--hidden">
        <div class="pswp__top-bar">
          <div class="pswp__counter"></div>
          <div class="pswp__button pswp__button--close"></div>
          <div class="pswp__button pswp__button--fs"></div>
          <div class="pswp__button pswp__button--zoom"></div>
          <div class="pswp__preloader">
            <div class="pswp__preloader__icn">
              <div class="pswp__preloader__cut">
                <div class="pswp__preloader__donut"></div>
              </div>
            </div>
          </div>
        </div>
        <button class="pswp__button pswp__button--arrow--left"></button>
        <button class="pswp__button pswp__button--arrow--right"></button>
        <div class="pswp__caption">
          <div class="pswp__caption__center"></div>
        </div>
      </div>
    </div>
  </div>

<?php endif; ?>


<script>
(function () {
  // Cargador único de la Vimeo Player API
  function ensureVimeoPlayer() {
    if (window.Vimeo && window.Vimeo.Player) return Promise.resolve();
    if (document.getElementById('vimeo-player-cdn')) {
      return new Promise(function (res) {
        const i = setInterval(function () {
          if (window.Vimeo && window.Vimeo.Player) { clearInterval(i); res(); }
        }, 30);
      });
    }
    return new Promise(function (resolve) {
      var s = document.createElement('script');
      s.id = 'vimeo-player-cdn';
      s.src = 'https://player.vimeo.com/api/player.js';
      s.onload = resolve;
      document.head.appendChild(s);
    });
  }

  // Inicializa la preview en un contenedor .video-player__video-container
  function initPreview(container) {
    if (!container || container.__previewInited) return;
    container.__previewInited = true;

    var videoId = container.getAttribute('data-video-id');
    var start   = parseFloat(container.getAttribute('data-preview-start')) || 9;
    var end     = parseFloat(container.getAttribute('data-preview-end'))   || 12;

    // Creamos un iframe independiente para la preview (background: sin controles)
    var iframe = document.createElement('iframe');
    iframe.setAttribute('allow', 'autoplay; fullscreen; picture-in-picture');
    iframe.setAttribute('title', 'Preview');
    iframe.style.width = '100%';
    iframe.style.height = '100%';
    iframe.style.position = 'absolute';
    iframe.style.inset = '0';
    iframe.style.zIndex = '1'; // por encima del poster si existiera
    iframe.style.pointerEvents = 'none'; // que no “robe” el click al botón Play

    // URL del player en modo background sin controles, mute y autoplay
    // Nota: 'background=1' implica ocultar controles y audio.
    var src = 'https://player.vimeo.com/video/' + encodeURIComponent(videoId) +
              '?background=1&autoplay=1&muted=1&autopause=0&pip=0&dnt=1#t=' + Math.max(0, start) + 's';
    iframe.src = src;

    // Capa para posicionar correctamente el preview dentro del container
    var wrap = document.createElement('div');
    wrap.className = 'video-preview-wrap';
    wrap.style.position = 'absolute';
    wrap.style.inset = '0';
    wrap.style.overflow = 'hidden';
    wrap.style.borderRadius = 'inherit';
    wrap.style.zIndex = '1';

    wrap.appendChild(iframe);
    container.style.position = 'relative';
    container.appendChild(wrap);

    // Instancia Player y configura el bucle de rango
    var player = new Vimeo.Player(iframe);
    container.__previewPlayer = player;
    container.__previewWrap   = wrap;

    // Forzamos rango [start, end) en bucle
    player.on('loaded', function () {
      player.setCurrentTime(start).catch(function(){});
      player.play().catch(function(){});
    });

    player.on('timeupdate', function (e) {
      var t = e && typeof e.seconds === 'number' ? e.seconds : 0;
      if (t < start - 0.1) {
        player.setCurrentTime(start).catch(function(){});
      } else if (t >= end) {
        player.setCurrentTime(start).catch(function(){});
      }
    });

    // Por si cambia el tamaño/visibilidad
    window.addEventListener('resize', function(){ player && player.pause().then(()=>player.play()); });
  }

  // “Promoción” a reproducción completa: quita la preview
  function removePreview(container) {
    if (!container) return;
    var player = container.__previewPlayer;
    var wrap   = container.__previewWrap;
    if (player) {
      player.unload().catch(function(){});
      container.__previewPlayer = null;
    }
    if (wrap && wrap.parentNode) wrap.parentNode.removeChild(wrap);
  }

  // Conectar con tus botones de Play
  // (cuando se pulse Play, quitamos la preview; tu player normal continúa)
  function wirePlayButtons(root) {
    root = root || document;
    root.querySelectorAll('.video-player').forEach(function (vp) {
      if (vp.__wired) return;
      vp.__wired = true;

      var container = vp.querySelector('.video-player__video-container');
      if (!container) return;

      // Botones posibles en tu markup
      var triggers = vp.querySelectorAll(
        '.video-player__playpause, .video-player__large-play-button'
      );

      triggers.forEach(function (btn) {
        btn.addEventListener('click', function () {
          removePreview(container);
          // Aquí no tocamos nada más: tu código existente crea/gestiona el player “real”.
        });
      });

      // También si el usuario hace click en el poster, etc., puedes enganchar otros triggers.
    });
  }

  function boot() {
    ensureVimeoPlayer().then(function () {
      // Inicializa preview en todos los contenedores que tengan data-video-id
      document.querySelectorAll('.video-player__video-container[data-video-id]').forEach(function (c) {
        initPreview(c);
      });
      wirePlayButtons(document);
    });
  }

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