<?php

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Frontend;

use ThemeREX\AutoDealer\Admin\VehicleMediaMetaBox;

/**
 * Shared slide-building logic for the media slider.
 *
 * Used by both the Elementor widget and the default single template.
 *
 * @package ThemeREX\AutoDealer
 */
class MediaSliderRenderer {

	/**
	 * Build unified slides array from post meta.
	 *
	 * @param int $postId Post ID.
	 * @return array<int, array{type: string, src: string, thumb: string, embed?: string}>
	 */
	public static function buildSlides( int $postId ): array {
		$slides     = array();
		$seen       = array();
		$featuredId = (int) get_post_thumbnail_id( $postId );

		// Featured image first.
		if ( $featuredId > 0 ) {
			$url   = wp_get_attachment_image_url( $featuredId, 'large' );
			$thumb = wp_get_attachment_image_url( $featuredId, 'thumbnail' );
			if ( $url ) {
				$slides[]            = array(
					'type'  => 'image',
					'src'   => $url,
					'full'  => wp_get_attachment_image_url( $featuredId, 'full' ) ?: $url,
					'thumb' => $thumb ?: $url,
				);
				$seen[ $featuredId ] = true;
			}
		}

		// Gallery images.
		foreach ( VehicleMediaMetaBox::getGalleryIds( $postId ) as $id ) {
			if ( isset( $seen[ $id ] ) ) {
				continue;
			}
			$url   = wp_get_attachment_image_url( $id, 'large' );
			$thumb = wp_get_attachment_image_url( $id, 'thumbnail' );
			if ( $url ) {
				$slides[]    = array(
					'type'  => 'image',
					'src'   => $url,
					'full'  => wp_get_attachment_image_url( $id, 'full' ) ?: $url,
					'thumb' => $thumb ?: $url,
				);
				$seen[ $id ] = true;
			}
		}

		// Self-hosted videos.
		foreach ( VehicleMediaMetaBox::getSelfVideos( $postId ) as $id ) {
			$url = wp_get_attachment_url( $id );
			if ( ! $url ) {
				continue;
			}
			$thumb = '';
			// Video attachments include an 'image' key with poster info; image
			// attachments don't. WP stubs declare the image shape — defensive
			// access for the video shape.
			/** @var array<string, mixed> $meta */
			$meta = wp_get_attachment_metadata( $id );
			if ( is_array( $meta ) && isset( $meta['image'] ) && is_array( $meta['image'] ) && ! empty( $meta['image']['src'] ) ) {
				$thumb = (string) $meta['image']['src'];
			}
			if ( '' === $thumb ) {
				$poster_id = (int) get_post_thumbnail_id( $id );
				if ( $poster_id > 0 ) {
					$thumb = (string) wp_get_attachment_image_url( $poster_id, 'thumbnail' );
				}
			}
			$slides[] = array(
				'type'  => 'video-self',
				'src'   => $url,
				'thumb' => $thumb,
			);
		}

		// External videos.
		foreach ( VehicleMediaMetaBox::getExternalVideos( $postId ) as $url ) {
			$embed = self::parseExternalVideo( $url );
			if ( $embed ) {
				$slides[] = $embed;
			}
		}

		return $slides;
	}

	/**
	 * Parse an external video URL into slide data.
	 *
	 * @param string $url Video URL.
	 * @return array{type: string, src: string, thumb: string, embed: string}|null
	 */
	public static function parseExternalVideo( string $url ): ?array {
		// YouTube.
		if ( preg_match( '/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/', $url, $m ) ) {
			return array(
				'type'  => 'video-external',
				'src'   => $url,
				'thumb' => 'https://img.youtube.com/vi/' . $m[1] . '/hqdefault.jpg',
				'embed' => 'https://www.youtube.com/embed/' . $m[1] . '?enablejsapi=1',
			);
		}

		// Vimeo.
		if ( preg_match( '/vimeo\.com\/(?:video\/)?(\d+)/', $url, $m ) ) {
			return array(
				'type'  => 'video-external',
				'src'   => $url,
				'thumb' => '',
				'embed' => 'https://player.vimeo.com/video/' . $m[1],
			);
		}

		return null;
	}

	/**
	 * Convert aspect ratio string to padding-bottom percentage.
	 *
	 * @param string $ratio Aspect ratio (e.g. "16:9").
	 * @return string CSS padding value.
	 */
	public static function aspectToPadding( string $ratio ): string {
		$map = array(
			'16:9' => '56.25%',
			'4:3'  => '75%',
			'3:2'  => '66.67%',
			'1:1'  => '100%',
		);

		return $map[ $ratio ] ?? '56.25%';
	}
}
