<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound, WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedFunctionFound
/**
 * Custom Reviews Listing Template
 *
 * @package Ugcify
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

if ( ! function_exists( 'ugcify_get_youtube_embed_url_from_url' ) ) {
	/**
	 * Build a safe YouTube embed URL from a YouTube page URL.
	 *
	 * @param string $url YouTube URL.
	 * @return string
	 */
	function ugcify_get_youtube_embed_url_from_url( $url ) {
		$url = esc_url_raw( (string) $url );
		if ( '' === $url ) {
			return '';
		}

		$parts = wp_parse_url( $url );
		if ( ! is_array( $parts ) ) {
			return '';
		}

		$host = isset( $parts['host'] ) ? strtolower( (string) $parts['host'] ) : '';
		$path = isset( $parts['path'] ) ? trim( (string) $parts['path'], '/' ) : '';
		$video_id = '';

		if ( false !== strpos( $host, 'youtu.be' ) ) {
			$video_id = $path;
		} else {
			if ( isset( $parts['query'] ) ) {
				parse_str( (string) $parts['query'], $query_vars );
				if ( ! empty( $query_vars['v'] ) ) {
					$video_id = (string) $query_vars['v'];
				}
			}

			if ( '' === $video_id && 0 === strpos( $path, 'shorts/' ) ) {
				$video_id = substr( $path, 7 );
			}

			if ( '' === $video_id && 0 === strpos( $path, 'embed/' ) ) {
				$video_id = substr( $path, 6 );
			}
		}

		$video_id = sanitize_text_field( (string) $video_id );
		$video_id = preg_replace( '/[^A-Za-z0-9_-]/', '', $video_id );
		if ( ! is_string( $video_id ) || '' === $video_id ) {
			return '';
		}

		return sprintf( 'https://www.youtube.com/embed/%s?rel=0&modestbranding=1', rawurlencode( $video_id ) );
	}
}

global $product;

// Support passing product_id directly (e.g. via include or shortcode)
if ( ! isset( $product_id ) ) {
	$product_id = ( $product instanceof \WC_Product ) ? $product->get_id() : 0;
}
$shortcode_tags = isset( $shortcode_tags ) && is_array( $shortcode_tags ) ? $shortcode_tags : array();
$shortcode_categories = isset( $shortcode_categories ) && is_array( $shortcode_categories ) ? $shortcode_categories : array();
$shortcode_type_filter = isset( $shortcode_type_filter ) ? sanitize_text_field( (string) $shortcode_type_filter ) : '';
$request_rating_filter = isset( $_GET['ugcify_rating'] ) ? absint( $_GET['ugcify_rating'] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$request_type_filter   = isset( $_GET['ugcify_type'] ) ? sanitize_text_field( wp_unslash( $_GET['ugcify_type'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$request_order_by      = isset( $_GET['ugcify_order_by'] ) ? sanitize_key( wp_unslash( $_GET['ugcify_order_by'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$request_order         = isset( $_GET['ugcify_order'] ) ? strtoupper( sanitize_key( wp_unslash( $_GET['ugcify_order'] ) ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
if ( '' !== $request_type_filter ) {
	$shortcode_type_filter = $request_type_filter;
}
$shortcode_tags_csv = implode( ',', $shortcode_tags );
$shortcode_categories_csv = implode( ',', $shortcode_categories );

// Get template customization settings if not already set.
if ( ! isset( $template_settings ) ) {
	$template_settings = array(
		'showHeaderTitle'         => true,
		'title'                   => 'Customers are saying',
		'emptyReviewText'         => 'No customer review yet.',
		'reviewsPerPage'          => '3',
		'reviewDateFormat'        => 'd M, Y',
		'showVerifiedCheck'       => true,
		'showInfluencerBadge'     => true,
		'reviewTextLength'        => 'large',
		'reviewerNameFormat'      => 'full',
	);
	$saved_settings = get_option( 'ugcify_template_customization', array() );
	if ( is_array( $saved_settings ) && ! empty( $saved_settings ) ) {
		$template_settings = array_merge( $template_settings, $saved_settings );
	}
}

$paged      = isset( $_GET['ugcify_paged'] ) ? max( 1, intval( $_GET['ugcify_paged'] ) ) : 1; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
$per_page   = ! empty( $template_settings['reviewsPerPage'] ) ? intval( $template_settings['reviewsPerPage'] ) : 3;

$widget_type                     = ! empty( $template_settings['widgetType'] ) ? strtolower( $template_settings['widgetType'] ) : 'grid';
$review_columns                  = ! empty( $template_settings['reviewColumn'] ) ? max( 1, min( 6, intval( $template_settings['reviewColumn'] ) ) ) : 3;
$review_gap                      = isset( $template_settings['gapSpacing'] ) ? max( 0, min( 60, intval( $template_settings['gapSpacing'] ) ) ) : 30;
$ugcify_default_order_by            = in_array( $request_order_by, array( 'created_at', 'rating' ), true ) ? $request_order_by : 'created_at';
$ugcify_default_order               = 'ASC' === $request_order ? 'ASC' : 'DESC';
$ugcify_prioritize_featured_reviews = true;
$ugcify_priority_exempt_type        = '' === $shortcode_type_filter;
$reels_section_style             = '';
$reels_inline_css                = '';
$ugcify_lazy_load_enabled           = ! isset( $template_settings['lazyLoadImages'] ) || ! empty( $template_settings['lazyLoadImages'] );
$ugcify_autoplay_video_enabled      = ! empty( $template_settings['autoplayVideo'] );
$ugcify_lightbox_enabled            = ! isset( $template_settings['enableLightbox'] ) || false !== filter_var( $template_settings['enableLightbox'], FILTER_VALIDATE_BOOLEAN );
$is_gallery_widget                  = 'gallery' === $widget_type;
$show_gallery_media_carousel_raw    = isset( $template_settings['showMediaCarousel'] ) ? filter_var( $template_settings['showMediaCarousel'], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE ) : true;
$show_gallery_media_carousel        = null === $show_gallery_media_carousel_raw ? true : $show_gallery_media_carousel_raw;
$show_gallery_reviews_section       = ! isset( $template_settings['showReviews'] ) || false !== filter_var( $template_settings['showReviews'], FILTER_VALIDATE_BOOLEAN );
$show_gallery_load_more             = ! isset( $template_settings['showLoadMoreButton'] ) || false !== filter_var( $template_settings['showLoadMoreButton'], FILTER_VALIDATE_BOOLEAN );
$show_gallery_header_title          = ! isset( $template_settings['showHeaderTitle'] ) || false !== filter_var( $template_settings['showHeaderTitle'], FILTER_VALIDATE_BOOLEAN );
$gallery_items_to_show              = isset( $template_settings['mediaCarouselItemsToShow'] ) ? intval( $template_settings['mediaCarouselItemsToShow'] ) : 10;
$gallery_items_to_show              = max( 1, min( 100, $gallery_items_to_show ) );
$gallery_load_more_text_color       = ! empty( $template_settings['loadMoreTextColor'] ) ? sanitize_hex_color( $template_settings['loadMoreTextColor'] ) : '#201CFE';
$gallery_load_more_bg_color         = ! empty( $template_settings['loadMoreBgColor'] ) ? sanitize_hex_color( $template_settings['loadMoreBgColor'] ) : '#FFFFFF';
$gallery_load_more_border_color     = ! empty( $template_settings['loadMoreBorderColor'] ) ? sanitize_hex_color( $template_settings['loadMoreBorderColor'] ) : '#201CFE';
$gallery_load_more_radius           = isset( $template_settings['loadMoreBorderRadius'] ) ? intval( $template_settings['loadMoreBorderRadius'] ) : 10;
$gallery_load_more_radius           = max( 0, min( 48, $gallery_load_more_radius ) );
$gallery_load_more_size_key         = ! empty( $template_settings['loadMoreTextSize'] ) ? sanitize_key( (string) $template_settings['loadMoreTextSize'] ) : 'medium';
$title_font_sizes                   = array(
	'small'  => '20px',
	'medium' => '24px',
	'large'  => '28px',
);
$gallery_font_size_map              = array(
	'small'  => '14px',
	'medium' => '16px',
	'large'  => '18px',
);
$gallery_load_more_text_size        = isset( $gallery_font_size_map[ $gallery_load_more_size_key ] ) ? $gallery_font_size_map[ $gallery_load_more_size_key ] : '16px';
$gallery_reviewer_name_size_key     = ! empty( $template_settings['reviewerNameFontSize'] ) ? sanitize_key( (string) $template_settings['reviewerNameFontSize'] ) : 'medium';
$gallery_reviewer_name_font_size    = isset( $gallery_font_size_map[ $gallery_reviewer_name_size_key ] ) ? $gallery_font_size_map[ $gallery_reviewer_name_size_key ] : '16px';
$gallery_title_size_key             = ! empty( $template_settings['titleFontSize'] ) ? sanitize_key( (string) $template_settings['titleFontSize'] ) : 'medium';
$gallery_title_font_size            = isset( $title_font_sizes[ $gallery_title_size_key ] ) ? $title_font_sizes[ $gallery_title_size_key ] : '24px';
$gallery_title_font_weight          = ! empty( $template_settings['titleFontWeight'] ) ? preg_replace( '/[^0-9]/', '', (string) $template_settings['titleFontWeight'] ) : '600';
$gallery_star_size_key              = ! empty( $template_settings['starRatingSize'] ) ? sanitize_key( (string) $template_settings['starRatingSize'] ) : 'medium';
$gallery_star_size_map              = array(
	'small'  => '14px',
	'medium' => '16px',
	'large'  => '18px',
);
$gallery_star_size                  = isset( $gallery_star_size_map[ $gallery_star_size_key ] ) ? $gallery_star_size_map[ $gallery_star_size_key ] : '16px';
$gallery_review_text_size_key       = ! empty( $template_settings['reviewTextSize'] ) ? sanitize_key( (string) $template_settings['reviewTextSize'] ) : 'medium';
$gallery_review_text_size           = isset( $gallery_font_size_map[ $gallery_review_text_size_key ] ) ? $gallery_font_size_map[ $gallery_review_text_size_key ] : '16px';

// Fetch reviews for this product or global.
$repository     = new \Ugcify\Database\ReviewRepository();
$review_filters = array(
	'product_id'          => $product_id,
	'status'              => 'approved',
	'tags'                => $shortcode_tags,
	'categories'          => $shortcode_categories,
	'type'                => $shortcode_type_filter,
	'per_page'            => $per_page,
	'page'                => $paged,
	'prioritize_pinned'   => true,
	'prioritize_featured' => true,
	'priority_exempt_type' => $ugcify_priority_exempt_type,
	'order_by'            => $ugcify_default_order_by,
	'order'               => $ugcify_default_order,
);
if ( $request_rating_filter >= 1 && $request_rating_filter <= 5 ) {
	$review_filters['rating'] = $request_rating_filter;
}
$avg_rating     = $repository->get_average_rating(
	$product_id,
	'approved',
	array(
		'tags'       => $shortcode_tags,
		'categories' => $shortcode_categories,
		'type'       => $shortcode_type_filter,
	)
);
$result         = $repository->get_paginated( array(
	'product_id'          => $review_filters['product_id'],
	'status'              => $review_filters['status'],
	'tags'                => $review_filters['tags'],
	'categories'          => $review_filters['categories'],
	'type'                => $review_filters['type'],
	'per_page'            => $review_filters['per_page'],
	'page'                => $review_filters['page'],
	'prioritize_pinned'   => $review_filters['prioritize_pinned'],
	'prioritize_featured' => $review_filters['prioritize_featured'],
	'priority_exempt_type' => $review_filters['priority_exempt_type'],
	'order_by'            => $review_filters['order_by'],
	'order'               => $review_filters['order'],
	'rating'              => isset( $review_filters['rating'] ) ? $review_filters['rating'] : '',
) );

$reviews       = $result['items'];
$total_reviews = $result['total'];
$total_pages   = $result['pages'];
$distribution  = $repository->get_rating_distribution(
	$product_id,
	'approved',
	array(
		'tags'       => $shortcode_tags,
		'categories' => $shortcode_categories,
		'type'       => $shortcode_type_filter,
	)
);
$rated_reviews_count = array_sum( $distribution );

$heading_level = apply_filters( 'ugcify_reviews_heading_level', 'h2' ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound
$heading_level = in_array( $heading_level, array( 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ), true ) ? $heading_level : 'h2';

$product_name_for_alt = ( $product instanceof \WC_Product ) ? $product->get_name() : '';
if ( '' === $product_name_for_alt && function_exists( 'wc_get_product' ) && $product_id ) {
	$product_for_alt = wc_get_product( $product_id );
	if ( $product_for_alt ) {
		$product_name_for_alt = $product_for_alt->get_name();
	}
}
$instance_id = isset( $instance_id ) ? sanitize_html_class( (string) $instance_id ) : '';
if ( '' === $instance_id ) {
	$instance_id = wp_unique_id( 'ugcify-reviews-' );
}
?>
<div class="ugcify-product-reviews-container ugcify-reviews-wrapper">
	<div class="ugcify-reviews-divider"></div>

	<section id="<?php echo esc_attr( $instance_id ); ?>" class="ugcify-reviews-section ugcify-custom-reviews-section<?php echo ! empty( $template_settings['tagStyle'] ) ? ' ugcify-tag-style-' . esc_attr( $template_settings['tagStyle'] ) : ''; ?>" aria-labelledby="ugcify-reviews-heading" data-ugcify-instance="<?php echo esc_attr( $instance_id ); ?>" data-per-page="<?php echo esc_attr( $per_page ); ?>" data-product-id="<?php echo esc_attr( $product_id ); ?>" data-tags="<?php echo esc_attr( $shortcode_tags_csv ); ?>" data-categories="<?php echo esc_attr( $shortcode_categories_csv ); ?>" data-rating="<?php echo esc_attr( $request_rating_filter ? $request_rating_filter : '' ); ?>" data-type="<?php echo esc_attr( $shortcode_type_filter ); ?>" data-status="approved" data-order-by="<?php echo esc_attr( $ugcify_default_order_by ); ?>" data-order="<?php echo esc_attr( $ugcify_default_order ); ?>" data-prioritize-pinned="1" data-prioritize-featured="<?php echo $ugcify_prioritize_featured_reviews ? '1' : '0'; ?>" data-priority-exempt-type="<?php echo $ugcify_priority_exempt_type ? '1' : '0'; ?>" data-widget-type="<?php echo esc_attr( $widget_type ); ?>" data-total-pages="<?php echo esc_attr( $total_pages ); ?>" data-total-items="<?php echo esc_attr( $total_reviews ); ?>" data-lazy-load="<?php echo $ugcify_lazy_load_enabled ? '1' : '0'; ?>" data-autoplay-video="<?php echo $ugcify_autoplay_video_enabled ? '1' : '0'; ?>" data-lightbox="<?php echo $ugcify_lightbox_enabled ? '1' : '0'; ?>" data-tag-style="<?php echo esc_attr( ! empty( $template_settings['tagStyle'] ) ? $template_settings['tagStyle'] : 'pulsing_dot' ); ?>" data-review-text-length="<?php echo esc_attr( ! empty( $template_settings['reviewTextLength'] ) ? $template_settings['reviewTextLength'] : 'large' ); ?>" data-show-verified-check="<?php echo ! empty( $template_settings['showVerifiedCheck'] ) ? '1' : '0'; ?>" data-show-influencer-badge="<?php echo ! empty( $template_settings['showInfluencerBadge'] ) ? '1' : '0'; ?>" data-reviewer-name-format="<?php echo esc_attr( ! empty( $template_settings['reviewerNameFormat'] ) ? $template_settings['reviewerNameFormat'] : 'full' ); ?>" data-review-date-format="<?php echo esc_attr( ! empty( $template_settings['reviewDateFormat'] ) ? $template_settings['reviewDateFormat'] : 'd M, Y' ); ?>" data-upvotes="<?php echo ! empty( $template_settings['enableUpvotes'] ) ? '1' : '0'; ?>" data-social-share="<?php echo ! empty( $template_settings['socialShareButtons'] ) ? '1' : '0'; ?>" data-customers-also-bought="<?php echo ! empty( $template_settings['customersAlsoBought'] ) ? '1' : '0'; ?>"<?php echo '' !== $reels_section_style ? ' style="' . esc_attr( $reels_section_style ) . '"' : ''; ?>>
			<?php if ( '' !== $reels_inline_css ) : ?>
			<style><?php echo esc_html( $reels_inline_css ); ?></style>
			<?php endif; ?>
			<!-- Header Section -->
			<?php if ( 'reels' !== $widget_type ) : ?>
			<div class="ugcify-reviews-header <?php echo $total_reviews === 0 ? 'is-empty' : ''; ?>">
				<div class="ugcify-header-left">
				<?php if ( $is_gallery_widget ? $show_gallery_header_title : ! empty( $template_settings['showHeaderTitle'] ) ) : ?>
					<<?php echo esc_html( $heading_level ); ?> id="ugcify-reviews-heading" class="ugcify-main-title">
						<?php echo esc_html( ! empty( $template_settings['title'] ) ? $template_settings['title'] : __( 'Customers are saying', 'ugcify' ) ); ?>
					</<?php echo esc_html( $heading_level ); ?>>
				<?php endif; ?>
					<?php if ( $rated_reviews_count > 0 ) : ?>
						<div class="ugcify-reviews-stats">
							<span class="ugcify-stats-label"><?php esc_html_e( 'Ratings:', 'ugcify' ); ?></span>
							<div class="ugcify-stars-summary">
								<span class="ugcify-avg-number"><?php echo number_format( $avg_rating, 1 ); ?></span>
								<?php 
								for ( $i = 1; $i <= 5; $i++ ) {
									$star_type = 'empty';
									if ( $i <= floor( $avg_rating ) ) {
										$star_type = 'full';
									} elseif ( $i <= ceil( $avg_rating ) && ( $avg_rating - floor( $avg_rating ) >= 0.5 ) ) {
										$star_type = 'half';
									}
									echo '<span class="ugcify-star-display ' . esc_attr( $star_type ) . '"></span>';
								}
								?>
							</div>
							<span class="ugcify-total-count"><?php
					/* translators: %d: number of reviews */
					printf( esc_html__( '%d reviews', 'ugcify' ), intval( $total_reviews ) );
					?></span>
							<span class="ugcify-stats-dropdown-icon" aria-hidden="true">
								<svg width="12" height="7" viewBox="0 0 12 7" fill="none" xmlns="http://www.w3.org/2000/svg">
									<path d="M1 1L6 6L11 1" stroke="#747481" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
								</svg>
							</span>
		
							<!-- Rating Stats Popup -->
							<div class="ugcify-rating-stats-popup">
								<div class="ugcify-stats-popup-content">
									<div class="ugcify-stats-popup-left">
										<div class="ugcify-stats-avg"><?php echo number_format( $avg_rating, 1 ); ?></div>
										<div class="ugcify-stats-stars">
											<?php 
											for ( $i = 1; $i <= 5; $i++ ) {
												$star_type = 'empty';
												if ( $i <= floor( $avg_rating ) ) {
													$star_type = 'full';
												} elseif ( $i <= ceil( $avg_rating ) && ( $avg_rating - floor( $avg_rating ) >= 0.5 ) ) {
													$star_type = 'half';
												}
												echo '<span class="ugcify-star-display ' . esc_attr( $star_type ) . '"></span>';
											}
											?>
										</div>
										<div class="ugcify-stats-total"><?php
								/* translators: %d: number of reviews */
								printf( esc_html__( '%d reviews', 'ugcify' ), intval( $total_reviews ) );
								?></div>
									</div>
									<div class="ugcify-stats-popup-right">
										<?php 
										for ( $i = 5; $i >= 1; $i-- ) : 
											$count = isset( $distribution[$i] ) ? $distribution[$i] : 0;
											$percentage = $rated_reviews_count > 0 ? ( $count / $rated_reviews_count ) * 100 : 0;
											?>
												<div class="ugcify-stats-row" data-rating="<?php echo esc_attr( $i ); ?>">
													<span class="ugcify-stats-star-num"><?php echo esc_html( $i ); ?></span>
													<div class="ugcify-stats-bar-wrapper">
														<div class="ugcify-stats-bar-fill" style="width: <?php echo esc_attr( $percentage ); ?>%;"></div>
													</div>
													<span class="ugcify-stats-count">(<?php echo intval( $count ); ?>)</span>
											</div>
										<?php endfor; ?>
									</div>
								</div>
							</div>
						</div>
					<?php endif; ?>
				</div>
				
				<div class="ugcify-header-right" style="<?php if( 0 === $total_reviews ) : ?>flex-direction: column;<?php endif; ?>">
					<?php if ( $product_id ) : ?>
					<?php
					// Get form visibility settings
					$form_settings = get_option( 'ugcify_review_form_settings', array(
						'formVisibility' => 'logged-in',
					) );
					$form_visibility = isset( $form_settings['formVisibility'] ) ? $form_settings['formVisibility'] : 'logged-in';
					$is_logged_in = is_user_logged_in();
					$can_show_button = false;
					$help_message = '';

				// Get WooCommerce My Account URL
				$myaccount_url = function_exists( 'wc_get_page_permalink' ) ? wc_get_page_permalink( 'myaccount' ) : wp_login_url( get_permalink() );

				// Check permission based on visibility setting
				if ( 'anyone' === $form_visibility ) {
					$can_show_button = true;
				} elseif ( 'logged-in' === $form_visibility ) {
					if ( $is_logged_in ) {
						$can_show_button = true;
					} else {
						$help_message = sprintf(
							/* translators: %s: My Account URL */
							__( 'Please <a href="%s">log in or register</a> to write a review.', 'ugcify' ),
							esc_url( $myaccount_url )
						);
					}
				} elseif ( 'verified-buyers' === $form_visibility ) {
					if ( ! $is_logged_in ) {
						$help_message = sprintf(
							/* translators: %s: My Account URL */
							__( 'Please <a href="%s">log in or register</a> to write a review.', 'ugcify' ),
							esc_url( $myaccount_url )
						);
					} else {
						// Check if user has purchased this product
						$is_verified = false;
						if ( function_exists( 'wc_customer_bought_product' ) ) {
							$current_user = wp_get_current_user();
							$is_verified = wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product_id );
						}

						if ( $is_verified ) {
							$can_show_button = true;
						} else {
							$help_message = __( 'Only customers who have purchased this product can write a review. Please purchase the product to submit your review.', 'ugcify' );
						}
					}
				}

			if ( $can_show_button ) : ?>
				<button class="ugcify-write-review-btn" onclick="document.querySelector('.ugcify-review-form-button').click();">
					<?php esc_html_e( 'Write a review', 'ugcify' ); ?>
				</button>
			<?php endif; ?>
		<?php endif; ?>
		<?php if ( $total_reviews > 0 ) : ?>
						<div class="ugcify-filter-wrapper">
							<button class="ugcify-filter-btn" title="<?php esc_attr_e( 'Sort and Filter', 'ugcify' ); ?>">
								<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
									<path d="M22 17.5H15" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
									<path d="M5 17.5H2" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
									<path d="M22 6.5H19" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
									<path d="M9 6.5H2" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
									<path d="M7 14.5H13C14.1 14.5 15 15 15 16.5V18.5C15 20 14.1 20.5 13 20.5H7C5.9 20.5 5 20 5 18.5V16.5C5 15 5.9 14.5 7 14.5Z" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
									<path d="M11 3.5H17C18.1 3.5 19 4 19 5.5V7.5C19 9 18.1 9.5 17 9.5H11C9.9 9.5 9 9 9 7.5V5.5C9 4 9.9 3.5 11 3.5Z" stroke="currentColor" stroke-width="1.5" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/>
								</svg>
							</button>
							<div class="ugcify-sort-dropdown">
								<div class="ugcify-sort-header"><?php esc_html_e( 'Sort By', 'ugcify' ); ?></div>
								<div class="ugcify-sort-options">
										<div class="ugcify-sort-item" data-sort="created_at" data-order="ASC">
										<span><?php esc_html_e( 'Oldest', 'ugcify' ); ?></span>
										<span class="ugcify-check-icon"><img src="<?php echo esc_url( UGCIFY_URL . 'assets/images/check-icon.svg' ); ?>" alt="" aria-hidden="true"></span>
									</div>
									<div class="ugcify-sort-item active" data-sort="created_at" data-order="DESC">
										<span><?php esc_html_e( 'Newest', 'ugcify' ); ?></span>
										<span class="ugcify-check-icon"><img src="<?php echo esc_url( UGCIFY_URL . 'assets/images/check-icon.svg' ); ?>" alt="" aria-hidden="true"></span>
									</div>

									<div class="ugcify-sort-divider"></div>
										<div class="ugcify-sort-item" data-sort="rating" data-order="DESC">
											<span><?php esc_html_e( 'High to low', 'ugcify' ); ?></span>
											<span class="ugcify-check-icon"><img src="<?php echo esc_url( UGCIFY_URL . 'assets/images/check-icon.svg' ); ?>" alt="" aria-hidden="true"></span>
										</div>
										<div class="ugcify-sort-item" data-sort="rating" data-order="ASC">
											<span><?php esc_html_e( 'Low to high', 'ugcify' ); ?></span>
											<span class="ugcify-check-icon"><img src="<?php echo esc_url( UGCIFY_URL . 'assets/images/check-icon.svg' ); ?>" alt="" aria-hidden="true"></span>
										</div>

										<div class="ugcify-sort-divider"></div>
											<div class="ugcify-filter-item" data-type="text">
											<span><?php esc_html_e( 'Text Only', 'ugcify' ); ?></span>
											<span class="ugcify-check-icon"><img src="<?php echo esc_url( UGCIFY_URL . 'assets/images/check-icon.svg' ); ?>" alt="" aria-hidden="true"></span>
										</div>
										<div class="ugcify-filter-item" data-type="image">
											<span><?php esc_html_e( 'Image Only', 'ugcify' ); ?></span>
											<span class="ugcify-check-icon"><img src="<?php echo esc_url( UGCIFY_URL . 'assets/images/check-icon.svg' ); ?>" alt="" aria-hidden="true"></span>
										</div>
										<div class="ugcify-filter-item" data-type="video">
											<span><?php esc_html_e( 'Video Only', 'ugcify' ); ?></span>
											<span class="ugcify-check-icon"><img src="<?php echo esc_url( UGCIFY_URL . 'assets/images/check-icon.svg' ); ?>" alt="" aria-hidden="true"></span>
										</div>
								</div>
							</div>
						</div>
					<?php endif; ?>
				</div>
				</div>
			<?php endif; // end if ( 'reels' !== $widget_type && ! $is_gallery_widget ) ?>

			<?php if ( $is_gallery_widget ) : ?>
				<style>
					.ugcify-gallery-media-section{margin:24px 0 32px;padding-bottom:32px;border-bottom:1px solid #e0e0e0}
					.ugcify-gallery-media-header{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-bottom:18px}
					.ugcify-gallery-media-title{margin:0;font-size:18px;line-height:1.25;font-weight:700;color:#0f172a}
					.ugcify-gallery-see-all{appearance:none;-webkit-appearance:none;display:inline-flex;align-items:center;gap:6px;border:0!important;padding:0!important;background:transparent!important;background-image:none!important;color:#2563eb;font-size:14px;font-weight:600;cursor:pointer;white-space:nowrap;box-shadow:none!important;text-shadow:none!important;line-height:1.2}
					.ugcify-gallery-see-all:before,.ugcify-gallery-see-all:after{content:none!important;display:none!important}
					.ugcify-gallery-see-all svg{display:block!important;width:10px!important;height:10px!important;flex:0 0 auto;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;color:inherit!important;fill:none!important;opacity:1!important;visibility:visible!important;pointer-events:none!important}
					.ugcify-gallery-see-all svg path{fill:none!important;stroke:currentColor!important}
					.ugcify-gallery-carousel-body{position:relative;display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:12px}
					.ugcify-gallery-carousel-btn{appearance:none;-webkit-appearance:none;width:46px;height:46px;min-width:46px;min-height:46px;border:1px solid #A7A7A7;border-radius:12px;background:#fff!important;background-image:none!important;color:#5D5D5D!important;display:flex;align-items:center;justify-content:center;cursor:pointer;flex:0 0 auto;box-shadow:0 1px 2px rgba(0,0,0,.04);padding:0!important;margin:0;line-height:1;text-shadow:none;overflow:visible}
					.ugcify-gallery-carousel-btn:before,.ugcify-gallery-carousel-btn:after{content:none!important;display:none!important}
					.ugcify-gallery-carousel-btn svg{display:block!important;width:12px!important;height:18px!important;flex:0 0 auto;pointer-events:none;color:inherit!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;fill:none!important;opacity:1!important;visibility:visible!important}
					.ugcify-gallery-carousel-btn svg path{fill:none!important;stroke:currentColor!important}
					.ugcify-gallery-carousel-btn[disabled]{opacity:.45;cursor:not-allowed}
					.ugcify-gallery-carousel-track{overflow:hidden;min-width:0}
					.ugcify-gallery-carousel-inner{--ugcify-gallery-tile-size:148px;--ugcify-gallery-tile-gap:12px;display:flex;gap:var(--ugcify-gallery-tile-gap);transition:transform .3s ease;will-change:transform}
					.ugcify-gallery-carousel-item{position:relative;flex:0 0 var(--ugcify-gallery-tile-size);width:var(--ugcify-gallery-tile-size);height:var(--ugcify-gallery-tile-size);border-radius:14px;overflow:hidden;background:#e9e9e9;cursor:pointer}
					.ugcify-gallery-carousel-item img,.ugcify-gallery-carousel-item video{width:100%;height:100%;object-fit:cover;display:block}
					.ugcify-gallery-carousel-play{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;pointer-events:none;background:transparent!important;border:0!important;box-shadow:none!important}
					.ugcify-gallery-carousel-play svg{display:block!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;opacity:1!important;visibility:visible!important}
					.ugcify-gallery-carousel-play svg circle{fill:rgba(255,255,255,.88)!important;stroke:none!important}
					.ugcify-gallery-carousel-play svg path{fill:#201CFE!important;stroke:none!important}
					.ugcify-attachment-lightbox{position:fixed;inset:0;z-index:99999;display:none;align-items:center;justify-content:center;background:rgba(0,0,0,.55);padding:16px}
					.ugcify-attachment-lightbox.is-open{display:flex}
					.ugcify-attachment-lightbox__dialog{position:relative;width:min(1320px,96vw);max-height:92vh;background:#fff;border-radius:10px;box-shadow:0 24px 80px rgba(15,23,42,.28);display:flex;flex-direction:column;overflow:hidden}
					.ugcify-attachment-lightbox__header{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:18px 22px;border-bottom:1px solid #edf2f7}
					.ugcify-attachment-lightbox__title{margin:0;font-size:20px;line-height:1.25;font-weight:700;color:#0f172a}
					.ugcify-attachment-lightbox__close{appearance:none;-webkit-appearance:none;width:36px;height:36px;min-width:36px;min-height:36px;border:0!important;border-radius:8px;background:transparent!important;background-image:none!important;color:#111827!important;display:flex;align-items:center;justify-content:center;cursor:pointer;padding:0!important;margin:0;line-height:1;box-shadow:none!important;text-shadow:none!important}
					.ugcify-attachment-lightbox__close:hover,.ugcify-attachment-lightbox__close:focus{background:#f3f4f6!important;background-image:none!important;color:#111827!important;border:0!important;box-shadow:none!important}
					.ugcify-attachment-lightbox__close:before,.ugcify-attachment-lightbox__close:after{content:none!important;display:none!important}
					.ugcify-attachment-lightbox__close svg{display:block!important;width:24px!important;height:24px!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;color:inherit!important;fill:none!important;opacity:1!important;visibility:visible!important;pointer-events:none!important}
					.ugcify-attachment-lightbox__close svg path{fill:none!important;stroke:currentColor!important}
					.ugcify-attachment-lightbox__body{padding:22px;overflow-y:auto}
					.ugcify-attachment-lightbox__grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(170px,1fr));gap:12px}
					.ugcify-attachment-lightbox__item{position:relative;aspect-ratio:1/1;border:0;border-radius:8px;overflow:hidden;background:#f1f5f9;padding:0;cursor:pointer}
					.ugcify-attachment-lightbox__item img,.ugcify-attachment-lightbox__item video{width:100%;height:100%;object-fit:cover;display:block}
					.ugcify-gallery-review-list{display:flex;flex-direction:column;gap:24px}
					.ugcify-gallery-review-card{padding:0 0 24px!important;border:0!important;border-bottom:1px solid #e5e7eb!important;border-radius:0!important;background:transparent!important;box-shadow:none!important;cursor:default!important;overflow:visible!important}
					.ugcify-gallery-review-card:last-child{padding-bottom:0!important;border-bottom:0!important}
						.ugcify-gallery-review-author{display:flex;align-items:center;gap:12px;margin-bottom:10px}
						.ugcify-gallery-review-author-main{min-width:0;display:flex;flex-direction:column;gap:2px}
					.ugcify-gallery-review-avatar{width:40px;height:40px;flex:0 0 40px;border-radius:999px;overflow:hidden;background:#e4e4e4}
					.ugcify-gallery-review-avatar img{width:100%;height:100%;object-fit:cover;display:block}
						.ugcify-gallery-review-name-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
							.ugcify-gallery-review-meta-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin:0 0 8px;min-height:18px}
							.ugcify-gallery-review-meta-divider{width:1px;height:14px;background:#d1d5db;display:inline-block;flex:0 0 1px}
							.ugcify-gallery-review-badges{display:flex;align-items:center;gap:8px;margin-left:0}
							.ugcify-gallery-review-share{display:flex;align-items:center;margin-left:auto}
							.ugcify-gallery-review-name{font-size:<?php echo esc_html( $gallery_reviewer_name_font_size ); ?>;line-height:1.25;font-weight:600;color:#111827}
							.ugcify-gallery-review-date.ugcify-card-date{font-size:13px;line-height:18px;color:#6b7280;margin:0!important}
					.ugcify-gallery-review-stars{margin:0 0 8px}
					.ugcify-main-title{font-size:<?php echo esc_html( $gallery_title_font_size ); ?>!important;font-weight:<?php echo esc_html( $gallery_title_font_weight ); ?>!important}
					.ugcify-gallery-review-stars .ugcify-star-display{width:<?php echo esc_html( $gallery_star_size ); ?>!important;height:<?php echo esc_html( $gallery_star_size ); ?>!important}
					.ugcify-gallery-review-text{font-size:<?php echo esc_html( $gallery_review_text_size ); ?>!important;line-height:1.55;color:#374151;max-width:820px}
					.ugcify-gallery-review-social-credit{margin-top:6px}
					.ugcify-gallery-review-social-credit .ugcify-social-credit{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:13px;line-height:1.35;color:#64748b}
					.ugcify-gallery-review-social-credit .ugcify-social-credit__link{color:#2563eb;font-weight:600;text-decoration:none}
					.ugcify-gallery-review-media{display:flex;gap:8px;margin-top:12px}
					.ugcify-gallery-review-media-item{appearance:none;-webkit-appearance:none;position:relative;width:72px;height:72px;aspect-ratio:1/1;border:0!important;outline:0;padding:0!important;margin:0;border-radius:8px;overflow:hidden;background:#ececec;display:block;cursor:pointer;line-height:0}
					.ugcify-gallery-review-media-item img,.ugcify-gallery-review-media-item video{width:100%;height:100%;object-fit:cover;display:block}
					.ugcify-gallery-review-media-more{position:absolute;inset:0;background:rgba(0,0,0,.55);color:#fff;font-size:20px;font-weight:700;display:flex;align-items:center;justify-content:center}
					.ugcify-gallery-review-card .ugcify-share-trigger{width:32px;height:32px;padding:0;justify-content:center;border-radius:8px}
					.ugcify-gallery-review-card .ugcify-share-trigger svg{width:14px;height:14px}
					.ugcify-gallery-review-card .ugcify-featured-badge{position:static;display:inline-flex;align-items:center;justify-content:center;font-size:0;line-height:0;background:transparent!important;border:0!important;box-shadow:none!important}
					.ugcify-gallery-review-card .ugcify-featured-badge:before,.ugcify-gallery-review-card .ugcify-featured-badge:after{content:none!important;display:none!important}
					.ugcify-gallery-review-card .ugcify-featured-badge svg{width:18px;height:18px;display:block!important;flex:0 0 auto;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;opacity:1!important;visibility:visible!important}
					.ugcify-gallery-review-card .ugcify-featured-badge svg rect{fill:#201CFE!important;stroke:none!important}
					.ugcify-gallery-review-card .ugcify-featured-badge svg path{fill:none!important;stroke:#fff!important}
					.ugcify-gallery-review-card .ugcify-pinned-badge{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important}
					.ugcify-gallery-review-card .ugcify-pinned-badge:before,.ugcify-gallery-review-card .ugcify-pinned-badge:after{content:none!important;display:none!important}
					.ugcify-gallery-review-card .ugcify-pinned-badge img{width:16px;height:16px;display:block!important;background:transparent!important;border:0!important;border-radius:0!important;box-shadow:none!important;filter:none!important;opacity:1!important;visibility:visible!important}
					.ugcify-gallery-review-card .ugcify-verified-badge,.ugcify-gallery-review-card .ugcify-influencer-badge{display:inline-flex;align-items:center;justify-content:center;width:18px;height:18px;line-height:0}
					.ugcify-gallery-review-card .ugcify-verified-badge svg,.ugcify-gallery-review-card .ugcify-influencer-badge svg{width:16px;height:16px;display:block}
					.ugcify-gallery-load-more-wrap{margin-top:28px;display:flex;justify-content:center}
					.ugcify-gallery-load-more-btn{position:relative;display:inline-flex;align-items:center;justify-content:center;gap:10px;min-width:180px;min-height:54px;padding:10px 28px;border:1px solid;border-radius:10px;background:#fff;cursor:pointer;font-weight:600;transition:opacity .18s ease,transform .18s ease}
					.ugcify-gallery-load-more-btn:disabled{cursor:not-allowed;opacity:.72}
					.ugcify-gallery-load-more-btn.is-loading .ugcify-gallery-load-more-label{opacity:.72}
					.ugcify-gallery-load-more-btn.is-loading::before{content:"";width:16px;height:16px;border:2px solid currentColor;border-right-color:transparent;border-radius:999px;animation:ugcify-gallery-load-more-spin .75s linear infinite}
					@keyframes ugcify-gallery-load-more-spin{to{transform:rotate(360deg)}}
					.ugcify-reviews-section[data-widget-type="gallery"] > .ugcify-pagination-wrapper{display:none!important}
					@media (max-width: 1024px){.ugcify-gallery-carousel-inner{--ugcify-gallery-tile-size:124px;--ugcify-gallery-tile-gap:10px}}
					@media (max-width: 640px){.ugcify-gallery-media-header{align-items:flex-start;flex-direction:column}.ugcify-gallery-carousel-body{grid-template-columns:1fr}.ugcify-gallery-carousel-btn{display:none}.ugcify-gallery-carousel-track{overflow-x:auto;scroll-snap-type:x mandatory}.ugcify-gallery-carousel-inner{--ugcify-gallery-tile-size:96px;--ugcify-gallery-tile-gap:8px;transform:none!important}.ugcify-gallery-carousel-item{scroll-snap-align:start}.ugcify-attachment-lightbox{padding:8px}.ugcify-attachment-lightbox__dialog{width:100%;max-height:94vh}.ugcify-attachment-lightbox__body{padding:14px}.ugcify-attachment-lightbox__grid{grid-template-columns:repeat(auto-fill,minmax(104px,1fr));gap:8px}.ugcify-gallery-review-media-item{width:64px;height:64px}}
				</style>
				<?php
				$gallery_media_items     = array();
				$gallery_all_media_items = array();
				if ( ! empty( $reviews ) && $show_gallery_media_carousel ) {
					$gallery_meta_handler = new \Ugcify\Review\ReviewMeta();
					$gallery_all_result = $repository->get_paginated( array(
						'product_id'          => $review_filters['product_id'],
						'status'              => $review_filters['status'],
						'tags'                => $review_filters['tags'],
						'categories'          => $review_filters['categories'],
						'type'                => $review_filters['type'],
						'per_page'            => max( 1, (int) $total_reviews ),
						'page'                => 1,
						'prioritize_pinned'   => $review_filters['prioritize_pinned'],
						'prioritize_featured' => $review_filters['prioritize_featured'],
							'priority_exempt_type' => $review_filters['priority_exempt_type'],
							'order_by'            => $review_filters['order_by'],
							'order'               => $review_filters['order'],
							'rating'              => isset( $review_filters['rating'] ) ? $review_filters['rating'] : '',
						) );
					$gallery_attachment_reviews = ! empty( $gallery_all_result['items'] ) ? $gallery_all_result['items'] : $reviews;
					foreach ( $gallery_attachment_reviews as $gallery_review ) {
						if ( $product_id > 0 && (int) $gallery_review->product_id !== (int) $product_id ) {
							continue;
						}
						$gallery_meta   = $gallery_meta_handler->get_meta( $gallery_review->id );
						$gallery_images = isset( $gallery_meta['images'][0] ) ? maybe_unserialize( $gallery_meta['images'][0] ) : array();
						$gallery_videos = isset( $gallery_meta['videos'][0] ) ? maybe_unserialize( $gallery_meta['videos'][0] ) : array();
						if ( is_array( $gallery_images ) ) {
							foreach ( $gallery_images as $gallery_image ) {
								if ( '' !== (string) $gallery_image ) {
									$gallery_all_media_items[] = array(
										'type'      => 'image',
										'url'       => esc_url_raw( (string) $gallery_image ),
										'review_id' => (int) $gallery_review->id,
									);
								}
							}
						}
						if ( is_array( $gallery_videos ) ) {
							foreach ( $gallery_videos as $gallery_video ) {
								if ( '' !== (string) $gallery_video ) {
									$gallery_all_media_items[] = array(
										'type'      => 'video',
										'url'       => esc_url_raw( (string) $gallery_video ),
										'review_id' => (int) $gallery_review->id,
									);
								}
							}
						}
					}
					$gallery_media_items = array_slice( $gallery_all_media_items, 0, $gallery_items_to_show );
				}
				$gallery_track_overflow = count( $gallery_media_items ) > 1;
				$gallery_media_first_id = ! empty( $gallery_media_items[0]['review_id'] ) ? (int) $gallery_media_items[0]['review_id'] : 0;
				?>
				<?php if ( $show_gallery_media_carousel && ! empty( $gallery_media_items ) ) : ?>
				<div class="ugcify-gallery-media-section" data-ugcify-gallery-carousel>
					<div class="ugcify-gallery-media-header">
						<h3 class="ugcify-gallery-media-title"><?php esc_html_e( 'Reviews with images', 'ugcify' ); ?></h3>
						<button type="button" class="ugcify-gallery-see-all" data-review-id="<?php echo esc_attr( $gallery_media_first_id ); ?>">
							<?php esc_html_e( 'See all attachments', 'ugcify' ); ?>
							<svg width="10" height="10" viewBox="0 0 10 10" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M3 1L7 5L3 9" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/></svg>
						</button>
					</div>
					<div class="ugcify-gallery-carousel-body">
						<?php if ( $gallery_track_overflow ) : ?>
						<button type="button" class="ugcify-gallery-carousel-btn ugcify-gallery-carousel-btn--prev" data-gallery-nav="prev" aria-label="<?php esc_attr_e( 'Previous', 'ugcify' ); ?>">
							<svg width="12" height="18" viewBox="0 0 12 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.5 2L2.5 9L9.5 16" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
						</button>
						<?php endif; ?>
						<div class="ugcify-gallery-carousel-track">
							<div class="ugcify-gallery-carousel-inner">
								<?php foreach ( $gallery_media_items as $gallery_item ) : ?>
									<div class="ugcify-gallery-carousel-item" data-review-id="<?php echo esc_attr( (int) $gallery_item['review_id'] ); ?>">
										<?php if ( 'video' === $gallery_item['type'] ) : ?>
											<video src="<?php echo esc_url( $gallery_item['url'] ); ?>#t=1" preload="metadata" muted playsinline></video>
											<span class="ugcify-gallery-carousel-play" aria-hidden="true">
												<svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="11" cy="11" r="11" fill="rgba(255,255,255,.88)"/><path d="M9 7.5L15 11L9 14.5V7.5Z" fill="#201CFE"/></svg>
											</span>
										<?php else : ?>
											<img src="<?php echo esc_url( $gallery_item['url'] ); ?>" alt="">
										<?php endif; ?>
									</div>
								<?php endforeach; ?>
							</div>
						</div>
						<?php if ( $gallery_track_overflow ) : ?>
						<button type="button" class="ugcify-gallery-carousel-btn ugcify-gallery-carousel-btn--next" data-gallery-nav="next" aria-label="<?php esc_attr_e( 'Next', 'ugcify' ); ?>">
							<svg width="12" height="18" viewBox="0 0 12 18" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M2.5 16L9.5 9L2.5 2" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
						</button>
						<?php endif; ?>
					</div>
				</div>
				<?php endif; ?>
				<?php if ( ! empty( $gallery_all_media_items ) ) : ?>
				<div class="ugcify-attachment-lightbox" data-ugcify-attachment-lightbox aria-hidden="true">
					<div class="ugcify-attachment-lightbox__dialog" role="dialog" aria-modal="true" aria-label="<?php esc_attr_e( 'All attachments', 'ugcify' ); ?>">
						<div class="ugcify-attachment-lightbox__header">
							<h3 class="ugcify-attachment-lightbox__title"><?php esc_html_e( 'All attachments', 'ugcify' ); ?></h3>
							<button type="button" class="ugcify-attachment-lightbox__close" data-attachment-lightbox-close aria-label="<?php esc_attr_e( 'Close', 'ugcify' ); ?>">
								<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M18 6L6 18M6 6l12 12" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>
							</button>
						</div>
						<div class="ugcify-attachment-lightbox__body">
							<div class="ugcify-attachment-lightbox__grid">
								<?php foreach ( $gallery_all_media_items as $gallery_lightbox_item ) : ?>
									<button type="button" class="ugcify-attachment-lightbox__item" data-review-id="<?php echo esc_attr( (int) $gallery_lightbox_item['review_id'] ); ?>">
										<?php if ( 'video' === $gallery_lightbox_item['type'] ) : ?>
											<video src="<?php echo esc_url( $gallery_lightbox_item['url'] ); ?>#t=1" preload="metadata" muted playsinline></video>
											<span class="ugcify-gallery-carousel-play" aria-hidden="true">
												<svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="11" cy="11" r="11" fill="rgba(255,255,255,.88)"/><path d="M9 7.5L15 11L9 14.5V7.5Z" fill="#201CFE"/></svg>
											</span>
										<?php else : ?>
											<img src="<?php echo esc_url( $gallery_lightbox_item['url'] ); ?>" alt="">
										<?php endif; ?>
									</button>
								<?php endforeach; ?>
							</div>
						</div>
					</div>
				</div>
				<div class="ugcify-gallery-hidden-review-anchors" hidden>
					<?php
					$gallery_anchor_ids = array_unique( array_map( 'intval', wp_list_pluck( $gallery_all_media_items, 'review_id' ) ) );
					foreach ( $gallery_anchor_ids as $gallery_anchor_id ) :
						?>
						<span class="ugcify-review-card" data-review-id="<?php echo esc_attr( $gallery_anchor_id ); ?>"></span>
					<?php endforeach; ?>
				</div>
				<?php endif; ?>
				<script>
				(function() {
					const root = document.getElementById('<?php echo esc_js( $instance_id ); ?>');
					if (!root) return;
					let isGalleryFiltering = false;
					const initGalleryCarousel = function() {
						const carousel = root.querySelector('[data-ugcify-gallery-carousel]');
						if (!carousel || carousel.dataset.ugcifyGalleryReady === '1') return;
						carousel.dataset.ugcifyGalleryReady = '1';
						const track = carousel.querySelector('.ugcify-gallery-carousel-track');
						const inner = carousel.querySelector('.ugcify-gallery-carousel-inner');
						const prevBtn = carousel.querySelector('[data-gallery-nav="prev"]');
						const nextBtn = carousel.querySelector('[data-gallery-nav="next"]');
						const items = inner ? Array.from(inner.children) : [];
						let index = 0;
						let maxIndex = 0;
						const update = function() {
							if (!inner || !items.length) return;
							const styles = window.getComputedStyle(inner);
							const itemGap = parseFloat(styles.columnGap || styles.gap || '12') || 12;
							const itemWidth = items[0].getBoundingClientRect().width;
							const trackWidth = track ? track.getBoundingClientRect().width : 0;
							const visibleCount = trackWidth > 0 ? Math.max(1, Math.floor((trackWidth + itemGap) / (itemWidth + itemGap))) : 1;
							maxIndex = Math.max(0, items.length - visibleCount);
							index = Math.min(index, maxIndex);
							const hasOverflow = maxIndex > 0;
							if (prevBtn) prevBtn.style.display = hasOverflow ? 'flex' : 'none';
							if (nextBtn) nextBtn.style.display = hasOverflow ? 'flex' : 'none';
							if (window.matchMedia('(max-width: 640px)').matches) {
								inner.style.transform = '';
								return;
							}
							const offset = (itemWidth + itemGap) * index;
							inner.style.transform = 'translateX(-' + offset + 'px)';
							if (prevBtn) prevBtn.disabled = index <= 0;
							if (nextBtn) nextBtn.disabled = index >= maxIndex;
						};
						if (prevBtn) prevBtn.addEventListener('click', function() { index = Math.max(0, index - 1); update(); });
						if (nextBtn) nextBtn.addEventListener('click', function() { index = Math.min(maxIndex, index + 1); update(); });
						window.addEventListener('resize', update);
						update();
					};
					const replaceOrRemove = function(selector, nextRoot) {
						const current = root.querySelector(selector);
						const next = nextRoot.querySelector(selector);
						if (current && next) {
							current.replaceWith(document.importNode(next, true));
						} else if (current && !next) {
							current.remove();
						} else if (!current && next) {
							const grid = root.querySelector('#ugcify-reviews-grid');
							if (grid) {
								grid.insertAdjacentElement('beforebegin', document.importNode(next, true));
							}
						}
					};
					const applyGalleryFilterAjax = function(page) {
						if (isGalleryFiltering) return;
						const url = new URL(window.location.href);
						url.searchParams.set('ugcify_paged', String(page || 1));
						const rating = root.getAttribute('data-rating') || '';
						const type = root.getAttribute('data-type') || '';
						const orderBy = root.getAttribute('data-order-by') || '';
						const order = root.getAttribute('data-order') || '';
						if (rating) url.searchParams.set('ugcify_rating', rating); else url.searchParams.delete('ugcify_rating');
						if (type) url.searchParams.set('ugcify_type', type); else url.searchParams.delete('ugcify_type');
						if (orderBy) url.searchParams.set('ugcify_order_by', orderBy); else url.searchParams.delete('ugcify_order_by');
						if (order) url.searchParams.set('ugcify_order', order); else url.searchParams.delete('ugcify_order');
						isGalleryFiltering = true;
						root.style.opacity = '0.55';
						root.style.pointerEvents = 'none';
						fetch(url.toString(), {
							credentials: 'same-origin',
							headers: {
								'X-Requested-With': 'XMLHttpRequest'
							}
						})
							.then(function(response) {
								if (!response.ok) throw new Error('Unable to filter reviews.');
								return response.text();
							})
							.then(function(html) {
								const parser = new DOMParser();
								const doc = parser.parseFromString(html, 'text/html');
								const nextRoot = doc.getElementById(root.id) || doc.querySelector('.ugcify-reviews-section[data-widget-type="gallery"]');
								if (!nextRoot) throw new Error('Unable to find filtered reviews.');
								const currentHeaderLeft = root.querySelector('.ugcify-header-left');
								const nextHeaderLeft = nextRoot.querySelector('.ugcify-header-left');
								if (currentHeaderLeft && nextHeaderLeft) {
									currentHeaderLeft.replaceWith(document.importNode(nextHeaderLeft, true));
								}
								replaceOrRemove('.ugcify-gallery-media-section', nextRoot);
								replaceOrRemove('[data-ugcify-attachment-lightbox]', nextRoot);
								replaceOrRemove('.ugcify-gallery-hidden-review-anchors', nextRoot);
								replaceOrRemove('#ugcify-reviews-grid', nextRoot);
								replaceOrRemove('.ugcify-gallery-load-more-wrap', nextRoot);
								root.setAttribute('data-current-page', String(page || 1));
								root.setAttribute('data-total-pages', nextRoot.getAttribute('data-total-pages') || '1');
								root.setAttribute('data-total-items', nextRoot.getAttribute('data-total-items') || '0');
								if (window.history && window.history.replaceState) {
									window.history.replaceState(null, '', url.toString());
								}
								initGalleryCarousel();
							})
							.catch(function(error) {
								if (window.console && window.console.error) {
									window.console.error(error);
								}
							})
							.finally(function() {
								isGalleryFiltering = false;
								root.style.opacity = '';
								root.style.pointerEvents = '';
							});
					};
					root.addEventListener('click', function(event) {
						const sortItem = event.target.closest('.ugcify-sort-item');
						const filterItem = event.target.closest('.ugcify-filter-item');
						const statsRow = event.target.closest('.ugcify-rating-stats-popup .ugcify-stats-row');
						if (!sortItem && !filterItem && !statsRow) return;
						event.preventDefault();
						event.stopPropagation();
						event.stopImmediatePropagation();
						if (sortItem) {
							root.setAttribute('data-order-by', sortItem.getAttribute('data-sort') || 'created_at');
							root.setAttribute('data-order', sortItem.getAttribute('data-order') || 'DESC');
							root.querySelectorAll('.ugcify-sort-item.active').forEach(function(item) {
								item.classList.remove('active');
							});
							sortItem.classList.add('active');
							applyGalleryFilterAjax(1);
							return;
						}
						if (filterItem) {
							filterItem.classList.toggle('active');
							const dropdown = root.querySelector('.ugcify-sort-dropdown');
							const activeTypes = [];
							if (dropdown) {
								dropdown.querySelectorAll('.ugcify-filter-item.active[data-type]').forEach(function(item) {
									activeTypes.push(item.getAttribute('data-type'));
								});
							}
							root.setAttribute('data-type', activeTypes.join(','));
							applyGalleryFilterAjax(1);
							return;
						}
						if (statsRow) {
							const selectedRating = statsRow.getAttribute('data-rating') || '';
							const currentRating = root.getAttribute('data-rating') || '';
							root.setAttribute('data-rating', currentRating === selectedRating ? '' : selectedRating);
							applyGalleryFilterAjax(1);
						}
					}, true);
					const openGalleryReviewDetails = function(reviewId) {
						if (!reviewId) return;
						const card = root.querySelector('#ugcify-reviews-grid .ugcify-review-card[data-review-id="' + reviewId + '"]') || root.querySelector('.ugcify-review-card[data-review-id="' + reviewId + '"]');
						if (!card) return;
						const readMoreButton = card.querySelector('.ugcify-read-more');
						if (readMoreButton) {
							readMoreButton.click();
							return;
						}
						const syntheticReadMore = document.createElement('button');
						syntheticReadMore.type = 'button';
						syntheticReadMore.className = 'ugcify-read-more';
						syntheticReadMore.style.display = 'none';
						card.appendChild(syntheticReadMore);
						syntheticReadMore.click();
						syntheticReadMore.remove();
					};
					const closeAttachmentLightbox = function(lightbox) {
						if (!lightbox) return;
						lightbox.classList.remove('is-open');
						lightbox.setAttribute('aria-hidden', 'true');
						document.body.classList.remove('ugcify-modal-open');
					};
					initGalleryCarousel();
					root.addEventListener('click', function(event) {
						const carouselItem = event.target.closest('.ugcify-gallery-carousel-item');
						if (carouselItem && root.contains(carouselItem)) {
							event.preventDefault();
							openGalleryReviewDetails(carouselItem.getAttribute('data-review-id'));
							return;
						}
						const seeAllBtn = event.target.closest('.ugcify-gallery-see-all');
						if (seeAllBtn && root.contains(seeAllBtn)) {
							event.preventDefault();
							const lightbox = root.querySelector('[data-ugcify-attachment-lightbox]');
							if (!lightbox || root.dataset.ugcNoLightbox === '1') return;
							lightbox.classList.add('is-open');
							lightbox.setAttribute('aria-hidden', 'false');
							document.body.classList.add('ugcify-modal-open');
							return;
						}
						const lightbox = event.target.closest('[data-ugcify-attachment-lightbox]');
						if (!lightbox || !root.contains(lightbox)) return;
						if (event.target === lightbox || event.target.closest('[data-attachment-lightbox-close]')) {
							event.preventDefault();
							closeAttachmentLightbox(lightbox);
							return;
						}
						const attachmentItem = event.target.closest('.ugcify-attachment-lightbox__item');
						if (!attachmentItem) return;
						event.preventDefault();
						const reviewId = attachmentItem.getAttribute('data-review-id');
						if (!reviewId) return;
						closeAttachmentLightbox(lightbox);
						window.setTimeout(function() {
							openGalleryReviewDetails(reviewId);
						}, 0);
					});
					document.addEventListener('keydown', function(event) {
						if (event.key !== 'Escape') return;
						closeAttachmentLightbox(root.querySelector('[data-ugcify-attachment-lightbox].is-open'));
					});
					root.addEventListener('click', function(event) {
						const mediaButton = event.target.closest('.ugcify-gallery-review-media-item');
						if (!mediaButton || !root.contains(mediaButton)) return;
						event.preventDefault();
						event.stopPropagation();
						openGalleryReviewDetails(mediaButton.getAttribute('data-review-id'));
					});
					let isLoadingMore = false;
					root.addEventListener('click', function(event) {
						const loadMoreBtn = event.target.closest('.ugcify-gallery-load-more-btn');
						if (!loadMoreBtn || !root.contains(loadMoreBtn)) return;
						event.preventDefault();
						event.stopPropagation();
						const totalPages = parseInt(root.getAttribute('data-total-pages') || '<?php echo (int) $total_pages; ?>', 10) || 1;
						const reviewGrid = root.querySelector('#ugcify-reviews-grid');
						const currentPage = parseInt(loadMoreBtn.getAttribute('data-current-page') || '<?php echo (int) $paged; ?>', 10) || 1;
						if (isLoadingMore || currentPage >= totalPages || !reviewGrid) return;
						const nextPage = currentPage + 1;
						const url = new URL(window.location.href);
						url.searchParams.set('ugcify_paged', String(nextPage));
						isLoadingMore = true;
						loadMoreBtn.disabled = true;
						loadMoreBtn.classList.add('is-loading');
						loadMoreBtn.setAttribute('aria-busy', 'true');
						fetch(url.toString(), {
							credentials: 'same-origin',
							headers: {
								'X-Requested-With': 'XMLHttpRequest'
							}
						})
							.then(function(response) {
								if (!response.ok) {
									throw new Error('Unable to load reviews.');
								}
								return response.text();
							})
							.then(function(html) {
								const parser = new DOMParser();
								const doc = parser.parseFromString(html, 'text/html');
								const nextGrid = doc.querySelector('.ugcify-reviews-section[data-widget-type="gallery"] #ugcify-reviews-grid');
								if (!nextGrid || !nextGrid.children.length) {
									throw new Error('Unable to find reviews.');
								}
								Array.from(nextGrid.children).forEach(function(card) {
									reviewGrid.appendChild(document.importNode(card, true));
								});
								loadMoreBtn.setAttribute('data-current-page', String(nextPage));
								if (nextPage >= totalPages) {
									const wrap = loadMoreBtn.closest('.ugcify-gallery-load-more-wrap');
									if (wrap) {
										wrap.remove();
									}
								}
							})
							.finally(function() {
								isLoadingMore = false;
								if (document.body.contains(loadMoreBtn)) {
									loadMoreBtn.disabled = false;
									loadMoreBtn.classList.remove('is-loading');
									loadMoreBtn.removeAttribute('aria-busy');
								}
							});
					});
				})();
				</script>
			<?php endif; ?>

			<?php if ( 'reels' !== $widget_type && 0 === $total_reviews ) : ?>
					<div class="ugcify-empty-reviews-state">
						<svg xmlns="http://www.w3.org/2000/svg" width="45" height="44" viewBox="0 0 45 44" fill="none">
							<g opacity="0.3">
								<path d="M36.8297 27.4117C36.0597 28.1817 35.6197 29.7217 35.8617 30.7777L37.3797 37.4217C38.0177 40.1717 37.6217 42.2397 36.2577 43.2297C35.7077 43.6257 35.0477 43.8237 34.2776 43.8237C33.1556 43.8237 31.8356 43.4057 30.3836 42.5477L23.9375 38.7197C22.9255 38.1257 21.2534 38.1257 20.2414 38.7197L13.7953 42.5477C11.3533 43.9777 9.26323 44.2197 7.9212 43.2297C7.8332 43.1637 7.7452 43.0977 7.6792 43.0097L35.4437 15.2457C36.4557 14.2337 37.8857 13.7717 39.2937 14.0137L39.6237 14.0797C41.9558 14.4757 43.5178 15.5317 44.0238 17.0717C44.5078 18.6117 43.8478 20.3937 42.1758 22.0657L36.8297 27.4117Z" fill="black"/>
								<path d="M8.31699 30.8C8.55899 29.744 8.11899 28.182 7.34897 27.412L2.00288 22.066C0.330855 20.394 -0.329156 18.612 0.154853 17.072C0.660861 15.532 2.22289 14.476 4.55493 14.08L11.419 12.936C12.4091 12.76 13.6191 11.88 14.0811 10.978L17.8652 3.388C18.9652 1.21 20.4612 0 22.0892 0C23.7172 0 25.2133 1.21 26.3133 3.388L30.0974 10.978C30.3834 11.55 30.9774 12.1 31.6154 12.474L6.84297 37.246L8.31699 30.8Z" fill="black"/>
								<path d="M43.5814 0.506047C42.9214 -0.153952 41.8434 -0.153952 41.1833 0.506047L0.592665 41.118C-0.0673465 41.778 -0.0673465 42.856 0.592665 43.516C0.92267 43.824 1.34068 44 1.78068 44C2.22069 44 2.6387 43.824 2.9687 43.494L43.5814 2.88204C44.2634 2.22205 44.2634 1.16605 43.5814 0.506047Z" fill="black"/>
							</g>
						</svg>
						<p class="ugcify-no-reviews-text">
							<?php echo esc_html( ! empty( $template_settings['emptyReviewText'] ) ? $template_settings['emptyReviewText'] : __( 'No customer review yet.', 'ugcify' ) ); ?>
						</p>
						<?php if ( ! empty( $help_message ) ) : ?>
							<div class="ugcify-review-form-message" style="margin-top: 1rem; padding: 0.75rem 1rem; background: #f7f7f7; border-radius: 4px; font-size: 14px; color: #666; text-align: center;">
								<?php echo wp_kses_post( $help_message ); ?>
							</div>
						<?php endif; ?>
					</div>
				<?php endif; ?>

			<!-- Reviews Grid / Reels -->
			<?php if ( 'reels' === $widget_type ) : ?>
				<?php include UGCIFY_PATH . 'templates/list/reels-type.php'; ?>
				<?php include UGCIFY_PATH . 'templates/list/reels-modal.php'; ?>
			<?php elseif ( $is_gallery_widget && ! empty( $reviews ) ) : ?>
				<?php if ( $show_gallery_reviews_section ) : ?>
				<div id="ugcify-reviews-grid" class="ugcify-reviews-grid ugcify-gallery-review-list" role="list">
					<?php
					$gallery_review_meta_handler = new \Ugcify\Review\ReviewMeta();
					foreach ( $reviews as $review ) :
						$meta = $gallery_review_meta_handler->get_meta( $review->id );
						$creator_display = array(
							'contributor_type' => '',
							'wrapper_class'    => '',
							'label'            => array( 'enabled' => false ),
						);
						if ( class_exists( '\\Ugcify\\Influencer\\PublicReviewPresentation' ) ) {
							$creator_display = \Ugcify\Influencer\PublicReviewPresentation::build_review_display_data( $review, $meta );
						}
						$author_name = '';
						if ( ! empty( $review->guest_name ) ) {
							$author_name = trim( (string) $review->guest_name );
						} elseif ( ! empty( $review->user_id ) ) {
							$author_name = trim( (string) get_the_author_meta( 'display_name', (int) $review->user_id ) );
						}
						$formatted_author_name = $author_name;
						if ( ! empty( $template_settings['reviewerNameFormat'] ) && ! empty( $author_name ) ) {
							$format = $template_settings['reviewerNameFormat'];
							$name_parts = explode( ' ', trim( $author_name ), 2 );
							$first_name = isset( $name_parts[0] ) ? $name_parts[0] : '';
							$last_name = isset( $name_parts[1] ) ? $name_parts[1] : '';
							switch ( $format ) {
								case 'first_last_initial':
									$formatted_author_name = $first_name . ( ! empty( $last_name ) ? ' ' . substr( $last_name, 0, 1 ) . '.' : '' );
									break;
								case 'first_only':
									$formatted_author_name = $first_name;
									break;
								case 'initials':
									$formatted_author_name = substr( $first_name, 0, 1 ) . ( ! empty( $last_name ) ? substr( $last_name, 0, 1 ) : '' );
									break;
								default:
									$formatted_author_name = $author_name;
							}
						}
						$is_verified   = isset( $meta['verified_purchase'][0] ) && ( $meta['verified_purchase'][0] === '1' || true === $meta['verified_purchase'][0] );
						$is_influencer = ! empty( $creator_display['label']['enabled'] );
						$avatar_html   = get_avatar( (int) $review->user_id, 48, '', $formatted_author_name, array( 'class' => 'ugcify-gallery-avatar-img' ) );
						$images        = isset( $meta['images'][0] ) ? maybe_unserialize( $meta['images'][0] ) : array();
						$videos        = isset( $meta['videos'][0] ) ? maybe_unserialize( $meta['videos'][0] ) : array();
						$all_media     = array();
						if ( is_array( $images ) ) {
							foreach ( $images as $image_url ) {
								if ( '' !== (string) $image_url ) {
									$all_media[] = array( 'type' => 'image', 'url' => (string) $image_url );
								}
							}
						}
						if ( is_array( $videos ) ) {
							foreach ( $videos as $video_url ) {
								if ( '' !== (string) $video_url ) {
									$all_media[] = array( 'type' => 'video', 'url' => (string) $video_url );
								}
							}
						}
						$social_platform   = isset( $meta['_social_platform'][0] ) ? strtolower( sanitize_key( (string) $meta['_social_platform'][0] ) ) : strtolower( sanitize_key( (string) $review->type ) );
						$is_social_type    = in_array( $social_platform, array( 'instagram', 'youtube', 'tiktok' ), true );
						$social_handle     = isset( $meta['_social_handle'][0] ) ? (string) $meta['_social_handle'][0] : '';
						$social_source_url = isset( $meta['_social_source_url'][0] ) ? (string) $meta['_social_source_url'][0] : '';
						$social_media_url  = isset( $meta['_social_media_url'][0] ) ? (string) $meta['_social_media_url'][0] : '';
						$social_cover_url  = isset( $meta['_social_cover_url'][0] ) ? (string) $meta['_social_cover_url'][0] : '';
						if ( $is_social_type ) {
							$social_preview_url = '' !== $social_cover_url ? $social_cover_url : $social_media_url;
							if ( '' !== $social_preview_url ) {
								$social_preview_path = (string) wp_parse_url( $social_preview_url, PHP_URL_PATH );
								$social_preview_ext  = strtolower( pathinfo( $social_preview_path, PATHINFO_EXTENSION ) );
								$social_preview_type = in_array( $social_preview_ext, array( 'mp4', 'webm', 'ogg', 'mov', 'm4v' ), true ) ? 'video' : 'image';
								$existing_media_urls = array_map(
									static function ( $media_item ) {
										return isset( $media_item['url'] ) ? (string) $media_item['url'] : '';
									},
									$all_media
								);
								if ( ! in_array( $social_preview_url, $existing_media_urls, true ) ) {
									array_unshift(
										$all_media,
										array(
											'type' => $social_preview_type,
											'url'  => $social_preview_url,
										)
									);
								}
							}
						}
						$text_length = ! empty( $template_settings['reviewTextLength'] ) ? $template_settings['reviewTextLength'] : 'large';
						$length_limits = array(
							'small'  => 80,
							'medium' => 120,
							'large'  => 200,
							'full'   => PHP_INT_MAX,
						);
						$char_limit = isset( $length_limits[ $text_length ] ) ? $length_limits[ $text_length ] : 200;
						$content_plain = wp_strip_all_tags( $review->content );
						$content_length = function_exists( 'mb_strlen' ) ? mb_strlen( $content_plain ) : strlen( $content_plain );
						$content_long = $content_length > $char_limit;
						$preview_text = function_exists( 'mb_substr' ) ? mb_substr( $content_plain, 0, $char_limit ) : substr( $content_plain, 0, $char_limit );
						$date_format = ! empty( $template_settings['reviewDateFormat'] ) ? $template_settings['reviewDateFormat'] : 'd M, Y';
						?>
						<article class="ugcify-review-card ugcify-gallery-review-card" id="ugcify-review-<?php echo esc_attr( $instance_id ); ?>-<?php echo esc_attr( $review->id ); ?>" data-review-id="<?php echo esc_attr( $review->id ); ?>" data-contributor-type="<?php echo esc_attr( (string) ( $creator_display['contributor_type'] ?? '' ) ); ?>" role="listitem">
							<div class="ugcify-gallery-review-author">
								<div class="ugcify-gallery-review-avatar">
									<?php echo $avatar_html ? wp_kses_post( $avatar_html ) : '<img src="' . esc_url( get_avatar_url( 0 ) ) . '" alt="">'; ?>
								</div>
								<div class="ugcify-gallery-review-author-main">
									<div class="ugcify-gallery-review-name-row">
										<?php if ( '' !== $formatted_author_name ) : ?>
											<span class="ugcify-gallery-review-name ugcify-author-name"><?php echo esc_html( $formatted_author_name ); ?></span>
										<?php endif; ?>
										<?php if ( ! empty( $template_settings['showVerifiedCheck'] ) && $is_verified ) : ?>
											<span class="ugcify-verified-badge" title="<?php esc_attr_e( 'Verified Purchase', 'ugcify' ); ?>">
												<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="8" cy="8" r="8" fill="#27AE60"></circle><path d="M5 8L7 10L11 6" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></svg>
											</span>
										<?php endif; ?>
										<?php if ( $is_influencer && ! empty( $template_settings['showInfluencerBadge'] ) ) : ?>
											<span class="ugcify-influencer-badge" title="<?php esc_attr_e( 'Influencer', 'ugcify' ); ?>">
												<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="20" height="20" viewBox="0 0 256 256" xml:space="preserve"><g style="stroke:none;stroke-width:0;stroke-dasharray:none;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;fill:none;fill-rule:nonzero;opacity:1;" transform="translate(1.4065934065934016 1.4065934065934016) scale(2.81 2.81)"><path d="M 44.759 63.847 L 56.954 90 l 9.909 -9.079 l 13.325 -1.755 L 68.323 53.721 c -9.609 -0.082 -17.439 3.046 -23.082 10.126" style="stroke:none;stroke-width:1;stroke-dasharray:none;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;fill:rgb(237,99,98);fill-rule:nonzero;opacity:1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round"/><path d="M 45.241 63.847 L 33.046 90 l -9.909 -9.079 L 9.812 79.166 l 11.865 -25.445 C 33.52 52.826 41.539 56.026 45.241 63.847 z" style="stroke:none;stroke-width:1;stroke-dasharray:none;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;fill:rgb(233,84,84);fill-rule:nonzero;opacity:1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round"/><path d="M 45 63.847 c 17.631 0 31.923 -14.293 31.923 -31.923 S 62.631 0 45 0 C 34.483 21.782 33.645 43.104 45 63.847 z" style="stroke:none;stroke-width:1;stroke-dasharray:none;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;fill:rgb(255,204,91);fill-rule:nonzero;opacity:1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round"/><path d="M 45 63.847 c -17.631 0 -31.923 -14.293 -31.923 -31.923 S 27.369 0 45 0 v 63.814" style="stroke:none;stroke-width:1;stroke-dasharray:none;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;fill:rgb(253,188,75);fill-rule:nonzero;opacity:1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round"/><path d="M 38.778 54.411 c -0.092 0 -0.186 -0.013 -0.279 -0.039 C 26.122 50.786 18.967 37.8 22.552 25.422 c 0.153 -0.531 0.707 -0.836 1.239 -0.682 c 0.53 0.153 0.836 0.708 0.682 1.239 c -3.277 11.318 3.264 23.193 14.583 26.471 c 0.53 0.154 0.836 0.709 0.682 1.239 C 39.611 54.127 39.211 54.411 38.778 54.411 z" style="stroke:none;stroke-width:1;stroke-dasharray:none;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;fill:rgb(236,153,34);fill-rule:nonzero;opacity:1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round"/><path d="M 66.487 39.146 c -0.092 0 -0.186 -0.013 -0.278 -0.04 c -0.53 -0.154 -0.836 -0.708 -0.683 -1.239 c 1.589 -5.483 0.946 -11.256 -1.808 -16.256 c -2.755 -5 -7.291 -8.628 -12.774 -10.216 c -0.53 -0.153 -0.836 -0.708 -0.683 -1.239 c 0.154 -0.53 0.708 -0.835 1.239 -0.682 c 5.996 1.736 10.957 5.704 13.969 11.172 c 3.013 5.468 3.715 11.781 1.979 17.777 C 67.321 38.862 66.922 39.146 66.487 39.146 z" style="stroke:none;stroke-width:1;stroke-dasharray:none;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;fill:rgb(236,153,34);fill-rule:nonzero;opacity:1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round"/><path d="M 37.058 47.693 c -0.225 0 -0.449 -0.075 -0.633 -0.227 c -0.374 -0.306 -0.476 -0.836 -0.241 -1.259 l 6.723 -12.121 l -5.127 -2.93 c -0.283 -0.162 -0.47 -0.451 -0.5 -0.776 c -0.03 -0.325 0.1 -0.644 0.348 -0.854 l 14.177 -12.04 c 0.359 -0.304 0.878 -0.317 1.253 -0.034 c 0.374 0.285 0.499 0.791 0.302 1.217 l -5.036 10.86 l 5.096 2.766 c 0.289 0.157 0.482 0.447 0.517 0.775 c 0.034 0.328 -0.095 0.651 -0.346 0.865 L 37.706 47.455 C 37.52 47.613 37.289 47.693 37.058 47.693 z" style="stroke:none;stroke-width:1;stroke-dasharray:none;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;fill:rgb(236,153,34);fill-rule:nonzero;opacity:1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round"/></g></svg>
											</span>
										<?php endif; ?>
									</div>
										<div class="ugcify-gallery-review-meta-row">
											<div class="ugcify-gallery-review-date ugcify-card-date"><?php echo esc_html( date_i18n( $date_format, strtotime( $review->created_at ) ) ); ?></div>
											<?php if ( ! empty( $review->is_featured ) || ! empty( $review->is_pinned ) ) : ?>
												<span class="ugcify-gallery-review-meta-divider" aria-hidden="true"></span>
												<div class="ugcify-gallery-review-badges">
													<?php if ( ! empty( $review->is_featured ) ) : ?>
														<span class="ugcify-featured-badge" aria-label="<?php esc_attr_e( 'Featured review', 'ugcify' ); ?>" title="<?php esc_attr_e( 'Featured review', 'ugcify' ); ?>">
															<svg width="18" height="18" viewBox="0 0 28 28" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false">
																<rect width="28" height="28" rx="5" fill="#201CFE"/>
																<path d="M14.903 19.9393C14.682 20.0202 14.318 20.0202 14.097 19.9393C12.212 19.2719 8 16.4876 8 11.7685C8 9.68539 9.6185 8 11.614 8C12.797 8 13.8435 8.59326 14.5 9.51011C15.1565 8.59326 16.2095 8 17.386 8C19.3815 8 21 9.68539 21 11.7685C21 16.4876 16.788 19.2719 14.903 19.9393Z" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
															</svg>
														</span>
													<?php endif; ?>
													<?php if ( ! empty( $review->is_pinned ) ) : ?><span class="ugcify-pinned-badge" aria-label="<?php esc_attr_e( 'Pinned review', 'ugcify' ); ?>" title="<?php esc_attr_e( 'Pinned review', 'ugcify' ); ?>"><img src="<?php echo esc_url( UGCIFY_URL . 'assets/images/pinned-badge.svg' ); ?>" alt="" aria-hidden="true"></span><?php endif; ?>
												</div>
											<?php endif; ?>
										</div>
									</div>
									<?php if ( \Ugcify\Admin\API\RewardSettingsAPI::is_social_share_enabled() ) : ?>
										<div class="ugcify-gallery-review-share">
											<button
												type="button"
												class="ugcify-share-trigger"
												aria-label="<?php esc_attr_e( 'Share this review', 'ugcify' ); ?>"
												data-review-id="<?php echo esc_attr( $review->id ); ?>"
											>
												<svg width="15" height="15" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
													<circle cx="18" cy="5" r="3" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
													<circle cx="6" cy="12" r="3" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
													<circle cx="18" cy="19" r="3" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
													<line x1="8.59" y1="13.51" x2="15.42" y2="17.49" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
													<line x1="15.41" y1="6.51" x2="8.59" y2="10.49" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
												</svg>
											</button>
										</div>
									<?php endif; ?>
								</div>
							<?php if ( $is_social_type ) : ?>
								<div class="ugcify-gallery-review-social-credit">
									<?php
									$platform   = $social_platform;
									$handle     = $social_handle;
									$source_url = $social_source_url;
									include UGCIFY_PATH . 'templates/parts/social-credit.php';
									?>
								</div>
							<?php else : ?>
								<div class="ugcify-gallery-review-stars ugcify-card-rating">
									<?php
									for ( $i = 1; $i <= 5; $i++ ) {
										$star_type = 'empty';
										if ( $i <= floor( $review->rating ) ) {
											$star_type = 'full';
										} elseif ( $i <= ceil( $review->rating ) && ( $review->rating - floor( $review->rating ) >= 0.5 ) ) {
											$star_type = 'half';
										}
										echo '<span class="ugcify-star-display ' . esc_attr( $star_type ) . '"></span>';
									}
									?>
								</div>
							<?php endif; ?>
							<div class="ugcify-gallery-review-text ugcify-card-text<?php echo $content_long ? ' ugcify-card-text--collapsible' : ''; ?>">
								<?php
								if ( $content_long ) {
									echo esc_html( $preview_text ) . '...';
									echo '<button type="button" class="ugcify-read-more">' . esc_html__( 'Show more', 'ugcify' ) . '</button>';
								} else {
									echo wp_kses_post( $review->content );
								}
								?>
							</div>
							<?php if ( ! empty( $all_media ) ) : ?>
							<div class="ugcify-gallery-review-media">
								<?php
								$visible_media = array_slice( $all_media, 0, 3 );
								$remaining_media_count = count( $all_media ) - count( $visible_media );
								foreach ( $visible_media as $media_index => $media_item ) :
									$is_more_tile = $remaining_media_count > 0 && $media_index === ( count( $visible_media ) - 1 );
									?>
									<button type="button" class="ugcify-gallery-review-media-item" data-review-id="<?php echo esc_attr( $review->id ); ?>">
										<?php if ( 'video' === $media_item['type'] ) : ?>
											<video src="<?php echo esc_url( $media_item['url'] ); ?>#t=1" preload="metadata" muted playsinline></video>
											<span class="ugcify-gallery-carousel-play" aria-hidden="true">
												<svg width="22" height="22" viewBox="0 0 22 22" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="11" cy="11" r="11" fill="rgba(255,255,255,.88)"/><path d="M9 7.5L15 11L9 14.5V7.5Z" fill="#201CFE"/></svg>
											</span>
										<?php else : ?>
											<img src="<?php echo esc_url( $media_item['url'] ); ?>" alt="">
										<?php endif; ?>
										<?php if ( $is_more_tile ) : ?>
											<span class="ugcify-gallery-review-media-more">+<?php echo esc_html( $remaining_media_count ); ?></span>
										<?php endif; ?>
									</button>
								<?php endforeach; ?>
								</div>
									<?php endif; ?>
								</article>
						<?php endforeach; ?>
				</div>
				<?php if ( $show_gallery_load_more && $total_pages > 1 ) : ?>
				<div class="ugcify-gallery-load-more-wrap">
					<button type="button" class="ugcify-gallery-load-more-btn"
						data-current-page="<?php echo esc_attr( $paged ); ?>"
						style="color: <?php echo esc_attr( $gallery_load_more_text_color ? $gallery_load_more_text_color : '#201CFE' ); ?>; background-color: <?php echo esc_attr( $gallery_load_more_bg_color ? $gallery_load_more_bg_color : '#FFFFFF' ); ?>; border-color: <?php echo esc_attr( $gallery_load_more_border_color ? $gallery_load_more_border_color : '#201CFE' ); ?>; border-radius: <?php echo esc_attr( $gallery_load_more_radius ); ?>px; font-size: <?php echo esc_attr( $gallery_load_more_text_size ); ?>;">
						<span class="ugcify-gallery-load-more-label"><?php esc_html_e( 'Load more', 'ugcify' ); ?></span>
					</button>
				</div>
				<?php endif; ?>
				<?php endif; ?>
			<?php elseif ( ! empty( $reviews ) ) : ?>
		<?php
		$layout_class = '';
		if ( 'masonry' === $widget_type ) {
			$layout_class = 'ugcify-layout-masonry';
		} elseif ( 'list' === $widget_type ) {
			$layout_class = 'ugcify-layout-list';
		} elseif ( 'slider' === $widget_type ) {
			$layout_class = 'ugcify-layout-slider';
		}
		$card_inline_style = '';
		$grid_inline_style = '';
		$tablet_columns    = min( 2, $review_columns );
		if ( 'masonry' === $widget_type ) {
			$card_inline_style = sprintf( 'break-inside:avoid;page-break-inside:avoid;display:inline-block;width:100%%;margin:0 0 %1$dpx;', $review_gap );
		} elseif ( 'list' !== $widget_type ) {
			$grid_inline_style = 'display:grid;';
		}
		?>
		<style>
			#<?php echo esc_html( $instance_id ); ?> .ugcify-reviews-grid:not(.ugcify-layout-list):not(.ugcify-layout-masonry){grid-template-columns:repeat(<?php echo esc_html( $review_columns ); ?>,minmax(0,1fr));gap:<?php echo esc_html( $review_gap ); ?>px}
			#<?php echo esc_html( $instance_id ); ?> .ugcify-reviews-grid.ugcify-layout-masonry{display:block;column-count:<?php echo esc_html( $review_columns ); ?>;column-gap:<?php echo esc_html( $review_gap ); ?>px}
			@media (max-width:768px){#<?php echo esc_html( $instance_id ); ?> .ugcify-reviews-grid:not(.ugcify-layout-list):not(.ugcify-layout-masonry){grid-template-columns:repeat(<?php echo esc_html( $tablet_columns ); ?>,minmax(0,1fr))}#<?php echo esc_html( $instance_id ); ?> .ugcify-reviews-grid.ugcify-layout-masonry{column-count:<?php echo esc_html( $tablet_columns ); ?>}}
			@media (max-width:640px){#<?php echo esc_html( $instance_id ); ?> .ugcify-reviews-grid:not(.ugcify-layout-list):not(.ugcify-layout-masonry){grid-template-columns:1fr}#<?php echo esc_html( $instance_id ); ?> .ugcify-reviews-grid.ugcify-layout-masonry{column-count:1}}
			@container (max-width:640px){#<?php echo esc_html( $instance_id ); ?> .ugcify-reviews-grid:not(.ugcify-layout-list):not(.ugcify-layout-masonry){grid-template-columns:1fr!important}#<?php echo esc_html( $instance_id ); ?> .ugcify-reviews-grid.ugcify-layout-masonry{column-count:1!important}}
		</style>
		<?php if ( 'slider' === $widget_type ) : ?>
		<div class="ugcify-slider-viewport">
			<div class="ugcify-slider-clip">
		<?php endif; ?>
		<div id="ugcify-reviews-grid" class="ugcify-reviews-grid <?php echo esc_attr( $layout_class ); ?>" role="list"<?php echo '' !== $grid_inline_style ? ' style="' . esc_attr( $grid_inline_style ) . '"' : ''; ?>>
					<?php 
					$review_meta_handler = new \Ugcify\Review\ReviewMeta();
					foreach ( $reviews as $review ) : 
						$meta = $review_meta_handler->get_meta( $review->id );
						$creator_display = array(
							'contributor_type' => '',
							'wrapper_class'    => '',
							'label'            => array( 'enabled' => false ),
							'attribution'      => array(),
						);
						if ( class_exists( '\\Ugcify\\Influencer\\PublicReviewPresentation' ) ) {
							$creator_display = \Ugcify\Influencer\PublicReviewPresentation::build_review_display_data( $review, $meta );
						}
						$is_social_type = in_array( $review->type, array( 'instagram', 'youtube', 'tiktok' ), true );
						$author_name = '';
						if ( ! empty( $review->guest_name ) ) {
							$author_name = trim( (string) $review->guest_name );
						} elseif ( ! empty( $review->user_id ) ) {
							$author_name = trim( (string) get_the_author_meta( 'display_name', (int) $review->user_id ) );
						}
						// Check for images and videos
						$images = isset( $meta['images'][0] ) ? maybe_unserialize( $meta['images'][0] ) : array();
						$videos = isset( $meta['videos'][0] ) ? maybe_unserialize( $meta['videos'][0] ) : array();
						$social_media_url = isset( $meta['_social_media_url'][0] ) ? esc_url_raw( (string) $meta['_social_media_url'][0] ) : '';
						$social_source_url = isset( $meta['_social_source_url'][0] ) ? esc_url_raw( (string) $meta['_social_source_url'][0] ) : '';
						$youtube_embed_url = '';
						if ( 'youtube' === strtolower( (string) $review->type ) ) {
							$youtube_embed_url = ugcify_get_youtube_embed_url_from_url( $social_source_url );
							if ( '' === $youtube_embed_url && '' !== $social_media_url ) {
								$youtube_embed_url = ugcify_get_youtube_embed_url_from_url( $social_media_url );
							}
						}
						
						$main_image = ! empty( $images ) ? $images[0] : '';
						$main_video = ! empty( $videos ) ? $videos[0] : '';
						$show_youtube_embed = '' !== $youtube_embed_url;
						$is_social_video_url = false;
						if ( $is_social_type && '' !== $social_media_url && ! $show_youtube_embed ) {
							$social_media_path = (string) wp_parse_url( $social_media_url, PHP_URL_PATH );
							$social_media_host = strtolower( (string) wp_parse_url( $social_media_url, PHP_URL_HOST ) );
							$social_media_query = strtolower( (string) wp_parse_url( $social_media_url, PHP_URL_QUERY ) );
							$social_media_ext  = strtolower( pathinfo( $social_media_path, PATHINFO_EXTENSION ) );
							$is_social_video_url = in_array( $social_media_ext, array( 'mp4', 'webm', 'ogg', 'mov', 'm4v' ), true );
							if ( ! $is_social_video_url ) {
								$is_instagram_cdn = false !== strpos( $social_media_host, 'cdninstagram.com' ) || false !== strpos( $social_media_host, 'fbcdn.net' );
								$has_video_hint   = false !== strpos( $social_media_path, '/video' ) || false !== strpos( $social_media_query, 'video' );
								$is_social_video_url = $is_instagram_cdn && $has_video_hint;
							}

							if ( '' === $main_video && $is_social_video_url ) {
								$main_video = $social_media_url;
							} elseif ( '' === $main_image ) {
								$main_image = $social_media_url;
							}
						}
						$attachment_count = count( $images ) + count( $videos );
						if ( 0 === $attachment_count && ( '' !== $main_image || '' !== $main_video ) ) {
							$attachment_count = 1;
						}
						
						// Determine if we should show video thumbnail.
						$show_video = ! empty( $main_video ) && ! $show_youtube_embed;
						$content_plain = wp_strip_all_tags( $review->content );
						$content_long   = strlen( $content_plain ) > 120;
						$social_handle  = isset( $meta['_social_handle'][0] ) ? (string) $meta['_social_handle'][0] : '';
						$social_url     = isset( $meta['_social_source_url'][0] ) ? (string) $meta['_social_source_url'][0] : '';
						$author_name_for_alt = ! empty( $author_name ) ? $author_name : __( 'Anonymous', 'ugcify' );
						$rating_for_alt      = number_format_i18n( (float) $review->rating, 1 );
						/* translators: %1$s: product name, %2$s: reviewer's name, %3$s: rating out of 5 */
						/* translators: %1$s: reviewer's name, %2$s: rating out of 5 */
						$review_image_alt    = $product_name_for_alt
							? sprintf(
								/* translators: %1$s: product name, %2$s: reviewer's name, %3$s: rating out of 5 */
								__( 'Review image for %1$s by %2$s (%3$s/5)', 'ugcify' ),
								$product_name_for_alt,
								$author_name_for_alt,
								$rating_for_alt
							)
							: sprintf(
								/* translators: %1$s: reviewer's name, %2$s: rating out of 5 */
								__( 'Review image by %1$s (%2$s/5)', 'ugcify' ),
								$author_name_for_alt,
								$rating_for_alt
							);
						$creator_wrapper_class = ! empty( $creator_display['wrapper_class'] ) ? ' ' . sanitize_html_class( (string) $creator_display['wrapper_class'] ) : '';
						$creator_attribution  = isset( $creator_display['attribution'] ) && is_array( $creator_display['attribution'] ) ? $creator_display['attribution'] : array();
						?>
						<article class="ugcify-review-card<?php echo esc_attr( $creator_wrapper_class ); ?>" id="ugcify-review-<?php echo esc_attr( $instance_id ); ?>-<?php echo esc_attr( $review->id ); ?>" data-review-id="<?php echo esc_attr( $review->id ); ?>" data-contributor-type="<?php echo esc_attr( (string) ( $creator_display['contributor_type'] ?? '' ) ); ?>" role="listitem" style="<?php echo esc_attr( $card_inline_style ); ?>">
							<?php if ( $show_youtube_embed || $show_video || $main_image ) : ?>
								<div class="ugcify-card-media">
									<?php if ( $show_youtube_embed ) : ?>
										<iframe
											src="<?php echo esc_url( $youtube_embed_url ); ?>"
											title="<?php esc_attr_e( 'YouTube review video', 'ugcify' ); ?>"
											loading="lazy"
											allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
											allowfullscreen
											referrerpolicy="strict-origin-when-cross-origin"
											width="100%"
											height="260"
										></iframe>
									<?php elseif ( $show_video ) : ?>
										<video 
											src="<?php echo esc_url( $main_video ); ?>#t=1" 
											preload="metadata" 
											muted 
											playsinline 
											class="ugcify-video-thumbnail"
										onloadeddata="this.currentTime=1"
									></video>
								<?php elseif ( $main_image ) : ?>
									<img src="<?php echo esc_url( $main_image ); ?>" alt="<?php echo esc_attr( $review_image_alt ); ?>">
								<?php endif; ?>
									
									<?php if ( $show_video ) : ?>
										<div class="ugcify-play-overlay">
											<svg width="50" height="50" viewBox="0 0 50 50" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="25" cy="25" r="24" stroke="#fff" stroke-width="2"/><path d="M15 25.5v-4.386c0-5.445 3.91-7.675 8.693-4.952l3.86 2.193 3.86 2.192c4.783 2.723 4.783 7.183 0 9.906l-3.86 2.192-3.86 2.193C18.91 37.561 15 35.331 15 29.886z" stroke="#fff" stroke-width="2" stroke-miterlimit="10" stroke-linecap="round" stroke-linejoin="round"/></svg>
										</div>
									<?php endif; ?>
										<?php if ( $attachment_count > 1 || ! empty( $review->is_pinned ) ) : ?>
											<div class="ugcify-card-media-badges">
												<?php if ( $attachment_count > 1 ) : ?>
													<span class="ugcify-attachment-count"><?php echo intval( $attachment_count ); ?> attachments</span>
												<?php endif; ?>
												<?php if ( ! empty( $review->is_pinned ) ) : ?>
													<span class="ugcify-pinned-badge" aria-label="<?php esc_attr_e( 'Pinned review', 'ugcify' ); ?>" title="<?php esc_attr_e( 'Pinned review', 'ugcify' ); ?>">
														<img src="<?php echo esc_url( UGCIFY_URL . 'assets/images/pinned-badge.svg' ); ?>" alt="" aria-hidden="true">
													</span>
												<?php endif; ?>
											</div>
										<?php endif; ?>
										<?php if ( ! empty( $review->is_featured ) ) : ?>
											<span class="ugcify-featured-badge"><?php esc_html_e( 'Featured', 'ugcify' ); ?></span>
										<?php endif; ?>
									</div>
								<?php endif; ?>
							
								<div class="ugcify-card-content">
									<?php if ( ! $show_youtube_embed && ! $show_video && ! $main_image && ( ! empty( $review->is_pinned ) || ! empty( $review->is_featured ) ) ) : ?>
										<div class="ugcify-review-indicators">
											<?php if ( ! empty( $review->is_featured ) ) : ?>
												<span class="ugcify-featured-badge"><?php esc_html_e( 'Featured', 'ugcify' ); ?></span>
											<?php endif; ?>
											<?php if ( ! empty( $review->is_pinned ) ) : ?>
												<span class="ugcify-pinned-badge" aria-label="<?php esc_attr_e( 'Pinned review', 'ugcify' ); ?>" title="<?php esc_attr_e( 'Pinned review', 'ugcify' ); ?>">
													<img src="<?php echo esc_url( UGCIFY_URL . 'assets/images/pinned-badge.svg' ); ?>" alt="" aria-hidden="true">
												</span>
											<?php endif; ?>
										</div>
									<?php endif; ?>
									<div class="ugcify-card-author">
					<?php
					// Format author name based on settings.
					$formatted_author_name = $author_name;
					if ( ! empty( $template_settings['reviewerNameFormat'] ) && ! empty( $author_name ) ) {
						$format = $template_settings['reviewerNameFormat'];
						$name_parts = explode( ' ', trim( $author_name ), 2 );
						$first_name = isset( $name_parts[0] ) ? $name_parts[0] : '';
						$last_name = isset( $name_parts[1] ) ? $name_parts[1] : '';
						
						switch ( $format ) {
							case 'first_last_initial':
								$formatted_author_name = $first_name . ( ! empty( $last_name ) ? ' ' . substr( $last_name, 0, 1 ) . '.' : '' );
								break;
							case 'first_only':
								$formatted_author_name = $first_name;
								break;
							case 'initials':
								$formatted_author_name = substr( $first_name, 0, 1 ) . ( ! empty( $last_name ) ? substr( $last_name, 0, 1 ) : '' );
								break;
							default: // 'full'
								$formatted_author_name = $author_name;
								break;
						}
					}
					?>
					<?php if ( '' !== $formatted_author_name ) : ?>
						<span class="ugcify-author-name"><?php echo esc_html( $formatted_author_name ); ?></span>
					<?php endif; ?>
					<?php 
					$is_verified = isset( $meta['verified_purchase'][0] ) && ( $meta['verified_purchase'][0] === '1' || $meta['verified_purchase'][0] === true );
					$is_influencer = ! empty( $creator_display['label']['enabled'] );
					
					// Show Verified Badge (for verified purchases OR influencers)
					if ( ! empty( $template_settings['showVerifiedCheck'] ) && ( $is_verified || $is_influencer ) ) : ?>
						<span class="ugcify-verified-badge" title="<?php esc_attr_e( 'Verified Purchase', 'ugcify' ); ?>">
							<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
								<circle cx="8" cy="8" r="8" fill="#27AE60"></circle>
								<path d="M5 8L7 10L11 6" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path>
							</svg>
						</span>
					<?php endif; ?>
					<?php 
					// Show Influencer Badge
					if ( $is_influencer && ! empty( $template_settings['showInfluencerBadge'] ) ) : ?>
						<span class="ugcify-influencer-badge" title="<?php esc_attr_e( 'Influencer', 'ugcify' ); ?>">
							<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="20" height="20" viewBox="0 0 256 256" xml:space="preserve">
								<g style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: none; fill-rule: nonzero; opacity: 1;" transform="translate(1.4065934065934016 1.4065934065934016) scale(2.81 2.81)">
									<path d="M 44.759 63.847 L 56.954 90 l 9.909 -9.079 l 13.325 -1.755 L 68.323 53.721 c -9.609 -0.082 -17.439 3.046 -23.082 10.126" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(237,99,98); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round"/>
									<path d="M 45.241 63.847 L 33.046 90 l -9.909 -9.079 L 9.812 79.166 l 11.865 -25.445 C 33.52 52.826 41.539 56.026 45.241 63.847 z" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(233,84,84); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round"/>
									<path d="M 45 63.847 c 17.631 0 31.923 -14.293 31.923 -31.923 S 62.631 0 45 0 C 34.483 21.782 33.645 43.104 45 63.847 z" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(255,204,91); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round"/>
									<path d="M 45 63.847 c -17.631 0 -31.923 -14.293 -31.923 -31.923 S 27.369 0 45 0 v 63.814" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(253,188,75); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round"/>
									<path d="M 38.778 54.411 c -0.092 0 -0.186 -0.013 -0.279 -0.039 C 26.122 50.786 18.967 37.8 22.552 25.422 c 0.153 -0.531 0.707 -0.836 1.239 -0.682 c 0.53 0.153 0.836 0.708 0.682 1.239 c -3.277 11.318 3.264 23.193 14.583 26.471 c 0.53 0.154 0.836 0.709 0.682 1.239 C 39.611 54.127 39.211 54.411 38.778 54.411 z" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(236,153,34); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round"/>
									<path d="M 66.487 39.146 c -0.092 0 -0.186 -0.013 -0.278 -0.04 c -0.53 -0.154 -0.836 -0.708 -0.683 -1.239 c 1.589 -5.483 0.946 -11.256 -1.808 -16.256 c -2.755 -5 -7.291 -8.628 -12.774 -10.216 c -0.53 -0.153 -0.836 -0.708 -0.683 -1.239 c 0.154 -0.53 0.708 -0.835 1.239 -0.682 c 5.996 1.736 10.957 5.704 13.969 11.172 c 3.013 5.468 3.715 11.781 1.979 17.777 C 67.321 38.862 66.922 39.146 66.487 39.146 z" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(236,153,34); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round"/>
									<path d="M 37.058 47.693 c -0.225 0 -0.449 -0.075 -0.633 -0.227 c -0.374 -0.306 -0.476 -0.836 -0.241 -1.259 l 6.723 -12.121 l -5.127 -2.93 c -0.283 -0.162 -0.47 -0.451 -0.5 -0.776 c -0.03 -0.325 0.1 -0.644 0.348 -0.854 l 14.177 -12.04 c 0.359 -0.304 0.878 -0.317 1.253 -0.034 c 0.374 0.285 0.499 0.791 0.302 1.217 l -5.036 10.86 l 5.096 2.766 c 0.289 0.157 0.482 0.447 0.517 0.775 c 0.034 0.328 -0.095 0.651 -0.346 0.865 L 37.706 47.455 C 37.52 47.613 37.289 47.693 37.058 47.693 z" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(236,153,34); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round"/>
								</g>
							</svg>
						</span>
					<?php endif; ?>
				</div>
				<?php if ( $is_social_type ) : ?>
					<?php
					ob_start();
					$platform   = $review->type;
					$handle     = $social_handle;
					$source_url = $social_url;
					include UGCIFY_PATH . 'templates/parts/social-credit.php';
					$social_credit_html = ob_get_clean();

					if ( '' !== trim( $social_credit_html ) ) {
						$html = $social_credit_html;
						include UGCIFY_PATH . 'templates/social-ugcify-item.php';
					}
					?>
				<?php endif; ?>
				
				<div class="ugcify-card-date">
					<?php
					$date_format = ! empty( $template_settings['reviewDateFormat'] ) ? $template_settings['reviewDateFormat'] : 'd M, Y';
					echo esc_html( date_i18n( $date_format, strtotime( $review->created_at ) ) );
					?>
				</div>
				
				<?php if ( $is_social_type ) : ?>
					<div class="ugcify-card-rating ugcify-card-rating-social" aria-label="<?php esc_attr_e( 'Imported social post', 'ugcify' ); ?>">
						<?php
						printf(
							/* translators: %s: Social media platform name (e.g. Instagram, YouTube). */
							esc_html__( 'Imported from %s', 'ugcify' ),
							esc_html( ucfirst( (string) $review->type ) )
						);
						?>
					</div>
				<?php else : ?>
					<div class="ugcify-card-rating">
						<?php
						for ( $i = 1; $i <= 5; $i++ ) {
							$star_type = 'empty';
							if ( $i <= floor( $review->rating ) ) {
								$star_type = 'full';
							} elseif ( $i <= ceil( $review->rating ) && ( $review->rating - floor( $review->rating ) >= 0.5 ) ) {
								$star_type = 'half';
							}
							echo '<span class="ugcify-star-display ' . esc_attr( $star_type ) . '"></span>';
						}
						?>
					</div>
				<?php endif; ?>
				
				<?php
				$text_length = ! empty( $template_settings['reviewTextLength'] ) ? $template_settings['reviewTextLength'] : 'large';
				$length_limits = array(
					'small'  => 80,
					'medium' => 120,
					'large'  => 200,
					'full'   => PHP_INT_MAX,
				);
				$char_limit = isset( $length_limits[ $text_length ] ) ? $length_limits[ $text_length ] : 200;
				$content_length = function_exists( 'mb_strlen' ) ? mb_strlen( $content_plain ) : strlen( $content_plain );
				$content_long = $content_length > $char_limit;
				$preview_text = function_exists( 'mb_substr' ) ? mb_substr( $content_plain, 0, $char_limit ) : substr( $content_plain, 0, $char_limit );
				?>
				<div class="ugcify-card-text<?php echo $content_long ? ' ugcify-card-text--collapsible' : ''; ?>">
					<?php
					if ( $content_long ) {
						echo esc_html( $preview_text ) . '...';
						echo '<button type="button" class="ugcify-read-more">' . esc_html__( 'Read More', 'ugcify' ) . '</button>';
					} else {
						echo wp_kses_post( $review->content );
					}
					?>
				</div>
							</div>
							<?php if ( in_array( $widget_type, array( 'grid', 'slider', 'masonry' ), true ) && \Ugcify\Admin\API\RewardSettingsAPI::is_social_share_enabled() ) : ?>
							<div class="ugcify-card-footer">
								<button
									type="button"
									class="ugcify-share-trigger"
									aria-label="<?php esc_attr_e( 'Share this review', 'ugcify' ); ?>"
									data-review-id="<?php echo esc_attr( $review->id ); ?>"
								>
									<svg width="15" height="15" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
										<circle cx="18" cy="5" r="3" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
										<circle cx="6" cy="12" r="3" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
										<circle cx="18" cy="19" r="3" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
										<line x1="8.59" y1="13.51" x2="15.42" y2="17.49" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
										<line x1="15.41" y1="6.51" x2="8.59" y2="10.49" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>
									</svg>
									<span class="ugcify-share-trigger__label"><?php esc_html_e( 'Share', 'ugcify' ); ?></span>
								</button>
							</div>
							<?php endif; ?>
						</article>
					<?php endforeach; ?>
			</div>
		<?php if ( 'slider' === $widget_type ) : ?>
			</div>
		</div>
		<?php endif; ?>
			<?php endif; // end elseif ( ! empty( $reviews ) ) ?>

			<?php if ( 'reels' !== $widget_type && ! $is_gallery_widget ) : ?>
			<!-- AJAX Pagination Container -->
			<div id="ugcify-pagination-container" class="ugcify-pagination-wrapper<?php echo 'slider' === $widget_type ? ' ugcify-pagination-wrapper--slider' : ''; ?>">
				<?php if ( 'slider' === $widget_type ) : ?>
					<?php if ( $total_pages > 1 ) : ?>
					<div class="ugcify-slider-pagination">
						<div class="ugcify-slider-controls">
							<div class="ugcify-slider-dots">
								<?php for ( $i = 1; $i <= $total_pages; $i++ ) : ?>
									<button class="ugcify-slider-dot<?php echo 1 === $i ? ' is-active' : ''; ?>" data-page="<?php echo esc_attr( $i ); ?>" aria-label="<?php echo esc_attr( sprintf( __( 'Page %d', 'ugcify' ), $i ) ); ?>"></button>
								<?php endfor; ?>
							</div>
						</div>
					</div>
					<?php endif; ?>
				<?php elseif ( $total_pages > 1 ) : ?>
					<div class="ugcify-pagination-info">
						<?php
						/* translators: %d: Total number of reviews. */
						printf( esc_html__( '%d items', 'ugcify' ), intval( $total_reviews ) );
						?>
					</div>
					<div class="ugcify-pagination">
						<?php
						// First Page Link
						$first_class = ( $paged <= 1 ) ? 'disabled' : '';
						echo '<a class="page-numbers first ' . esc_attr( $first_class ) . '" href="' . esc_url( add_query_arg( 'ugcify_paged', 1 ) ) . '"><span>&laquo;</span></a>';

						// Previous Page Link
						$prev_class = ( $paged <= 1 ) ? 'disabled' : '';
						$prev_page  = max( 1, $paged - 1 );
						echo '<a class="page-numbers prev ' . esc_attr( $prev_class ) . '" href="' . esc_url( add_query_arg( 'ugcify_paged', $prev_page ) ) . '"><span>&lsaquo;</span></a>';

						// Page Status
						/* translators: 1: Current page number, 2: Total number of pages. */
						echo '<span class="page-status">' . sprintf( esc_html__( '%1$d of %2$d', 'ugcify' ), intval( $paged ), intval( $total_pages ) ) . '</span>';

						// Next Page Link
						$next_class = ( $paged >= $total_pages ) ? 'disabled' : '';
						$next_page  = min( $total_pages, $paged + 1 );
						echo '<a class="page-numbers next ' . esc_attr( $next_class ) . '" href="' . esc_url( add_query_arg( 'ugcify_paged', $next_page ) ) . '"><span>&rsaquo;</span></a>';

						// Last Page Link
						$last_class = ( $paged >= $total_pages ) ? 'disabled' : '';
						echo '<a class="page-numbers last ' . esc_attr( $last_class ) . '" href="' . esc_url( add_query_arg( 'ugcify_paged', $total_pages ) ) . '"><span>&raquo;</span></a>';
						?>
					</div>
				<?php endif; ?>
			</div>
			<?php endif; // end if ( 'reels' !== $widget_type && ! $is_gallery_widget ) ?>

			<?php if ( $product_id ) : ?>
				<div style="display:none;">
					<?php echo wp_kses_post( $form_renderer->render( array( 'product_id' => $product_id, 'type' => 'button' ) ) ); ?>
				</div>
			<?php endif; ?>
		
		<?php if ( 'reels' !== $widget_type ) : ?>
		<?php include plugin_dir_path( __FILE__ ) . 'list/review-details-modal.php'; ?>
		<?php endif; ?>
	</section>
	<div class="ugcify-reviews-divider"></div>
</div>
