<?php
/**
 * Single template for the `bw-product` post type (NYIBC product redesign v5).
 *
 * Filename note: WordPress maps `single-{post_type}.php` to its CPT, and this
 * site's product CPT slug is `bw-product` (registered in
 * bw-winners-global-site/includes/class-product-posts.php). The template
 * hierarchy will pick this file up automatically once the Kadence Element
 * that currently overrides it is disabled.
 */

namespace Kadence;

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

/* -----------------------------------------------------------------------------
 * Data helpers (scoped to this template).
 * --------------------------------------------------------------------------- */

if ( ! function_exists( __NAMESPACE__ . '\\apn_product_score_to_medal' ) ) {
	function apn_product_score_to_medal( $score ) {
		$score = (int) $score;

		// Per-site thresholds from bw-winners (Winners Settings → Display Score As),
		// with the historical hardcoded values as fallback when the option is missing.
		$opts       = get_option( 'bw_winners_options', [] );
		$thresholds = isset( $opts['displayScoreAs'] ) && is_array( $opts['displayScoreAs'] )
			? $opts['displayScoreAs']
			: [];

		$dg     = isset( $thresholds['doubleGold'] ) ? (int) $thresholds['doubleGold'] : 95;
		$gold   = isset( $thresholds['gold'] )       ? (int) $thresholds['gold']       : 90;
		$silver = isset( $thresholds['silver'] )     ? (int) $thresholds['silver']     : 85;
		$bronze = isset( $thresholds['bronze'] )     ? (int) $thresholds['bronze']     : 80;

		if ( $score >= $dg )     return [ 'Double Gold', 'double-gold' ];
		if ( $score >= $gold )   return [ 'Gold',        'gold'        ];
		if ( $score >= $silver ) return [ 'Silver',      'silver'      ];
		if ( $score >= $bronze ) return [ 'Bronze',      'bronze'      ];
		return [ '', '' ];
	}
}

if ( ! function_exists( __NAMESPACE__ . '\\apn_product_get_medal_image_url' ) ) {
	/**
	 * Returns the uploaded medal image URL for a tier slug
	 * (double-gold|gold|silver|bronze), or '' if none configured.
	 *
	 * Lookup order:
	 *   1. Current site `medalsByYear[$entry_year][$tier]` (year-specific override)
	 *   2. Current site `medals[$tier]` (default)
	 *   3. Main site `medalsByYear[$entry_year][$tier]`
	 *   4. Main site `medals[$tier]`
	 *
	 * The attachment lives in whichever site's media library it was uploaded to,
	 * so URL resolution wraps in switch_to_blog() when the source blog differs
	 * from the current one.
	 *
	 * @param string      $tier_slug   double-gold|gold|silver|bronze
	 * @param int|string  $entry_year  4-digit year, or empty for default-only lookup
	 */
	function apn_product_get_medal_image_url( $tier_slug, $entry_year = '' ) {
		$slug_to_key = [
			'double-gold' => 'doubleGold',
			'gold'        => 'gold',
			'silver'      => 'silver',
			'bronze'      => 'bronze',
		];
		if ( ! isset( $slug_to_key[ $tier_slug ] ) ) return '';
		$tier_key = $slug_to_key[ $tier_slug ];

		$year = '';
		if ( $entry_year !== '' && preg_match( '/^\d{4}$/', (string) $entry_year ) ) {
			$year = (string) $entry_year;
		}

		static $cache = [];
		$cache_key = $year . '|' . $tier_key;
		if ( array_key_exists( $cache_key, $cache ) ) {
			return $cache[ $cache_key ];
		}

		$pick_id = function ( $options ) use ( $year, $tier_key ) {
			if ( ! is_array( $options ) ) return 0;
			if ( $year && ! empty( $options['medalsByYear'][ $year ][ $tier_key ] ) ) {
				return (int) $options['medalsByYear'][ $year ][ $tier_key ];
			}
			if ( ! empty( $options['medals'][ $tier_key ] ) ) {
				return (int) $options['medals'][ $tier_key ];
			}
			return 0;
		};

		$attachment_id = 0;
		$source_blog   = 0;

		// 1. Current site
		$current_options = get_option( 'bw_winners_options', array() );
		$attachment_id   = $pick_id( $current_options );
		if ( $attachment_id ) {
			$source_blog = get_current_blog_id();
		}

		// 2. Main site fallback
		if ( ! $attachment_id && function_exists( 'get_blog_option' ) ) {
			$main_site_id = function_exists( 'get_main_site_id' ) ? get_main_site_id() : 1;
			if ( $main_site_id !== get_current_blog_id() ) {
				$main_options  = get_blog_option( $main_site_id, 'bw_winners_options', array() );
				$attachment_id = $pick_id( $main_options );
				if ( $attachment_id ) {
					$source_blog = $main_site_id;
				}
			}
		}

		$url = '';
		if ( $attachment_id ) {
			if ( $source_blog && $source_blog !== get_current_blog_id() ) {
				switch_to_blog( $source_blog );
				$url = wp_get_attachment_image_url( $attachment_id, 'medium' );
				restore_current_blog();
			} else {
				$url = wp_get_attachment_image_url( $attachment_id, 'medium' );
			}
		}
		$cache[ $cache_key ] = $url ?: '';
		return $cache[ $cache_key ];
	}
}

if ( ! function_exists( __NAMESPACE__ . '\\apn_product_get_cta_labels' ) ) {
	/**
	 * Resolves the per-site product-page CTA labels (Buy button + Website button).
	 *
	 * Reads bw_winners_options.productCta on the current site:
	 *   - type = '' | brewery | winery | distillery | cidery | producer  → preset labels
	 *   - type = 'custom'                                                → buy/learn fields
	 * The preset table must stay in sync with ctaPresets in
	 * bw-winners/src/admin-pages/csv-import/SettingsPage.jsx.
	 *
	 * @return array{buy:string,learn:string}
	 */
	function apn_product_get_cta_labels() {
		static $cache = null;
		if ( $cache !== null ) return $cache;

		$presets = array(
			'brewery'    => array( 'buy' => 'View at Brewery',  'learn' => 'Brewery Website' ),
			'winery'     => array( 'buy' => 'Visit Winery',     'learn' => 'Winery Website' ),
			'distillery' => array( 'buy' => 'Visit Distillery', 'learn' => 'Distillery Website' ),
			'cidery'     => array( 'buy' => 'Visit Cidery',     'learn' => 'Cidery Website' ),
			'producer'   => array( 'buy' => 'Visit Producer',   'learn' => 'Producer Website' ),
		);

		$options = get_option( 'bw_winners_options', array() );
		$cta     = isset( $options['productCta'] ) && is_array( $options['productCta'] ) ? $options['productCta'] : array();
		$type    = isset( $cta['type'] ) ? (string) $cta['type'] : '';

		if ( $type === 'custom' ) {
			$labels = array(
				'buy'   => ! empty( $cta['buy'] )   ? (string) $cta['buy']   : $presets['brewery']['buy'],
				'learn' => ! empty( $cta['learn'] ) ? (string) $cta['learn'] : $presets['brewery']['learn'],
			);
		} else {
			$labels = $presets[ $type ] ?? $presets['brewery'];
		}

		$cache = apply_filters( 'apn_product_cta_labels', $labels, $type );
		return $cache;
	}
}

if ( ! function_exists( __NAMESPACE__ . '\\apn_product_get_brand' ) ) {
	function apn_product_get_brand( $product_post_id ) {
		global $wpdb;
		$prefix = $wpdb->prefix;
		// `bw-product` row IDs match the WP post ID (see class-product-posts.php).
		$row = $wpdb->get_row( $wpdb->prepare(
			"SELECT p.brand_id, p.type, p.price, p.country, b.name AS brand_name, b.url AS brand_url
			 FROM {$prefix}bw_winners_products p
			 LEFT JOIN {$prefix}bw_winners_brands b ON b.id = p.brand_id
			 WHERE p.id = %d",
			$product_post_id
		), ARRAY_A );
		return $row ?: [];
	}
}

if ( ! function_exists( __NAMESPACE__ . '\\apn_product_get_entries' ) ) {
	function apn_product_get_entries( $product_post_id ) {
		global $wpdb;
		$prefix = $wpdb->prefix;
		return $wpdb->get_results( $wpdb->prepare(
			"SELECT id, year, score
			 FROM {$prefix}bw_winners_entries
			 WHERE product_id = %d
			 ORDER BY year DESC, score DESC",
			$product_post_id
		), ARRAY_A );
	}
}

/* -----------------------------------------------------------------------------
 * Render.
 * --------------------------------------------------------------------------- */

get_header();

while ( have_posts() ) :
	the_post();

	$post_id    = get_the_ID();
	$brand      = apn_product_get_brand( $post_id );
	$entries    = apn_product_get_entries( $post_id );

	$brand_name = $brand['brand_name'] ?? '';
	$type_text  = $brand['type']       ?? ''; // e.g. "Ale Beer Styles - North American Origin"
	$price_text = $brand['price']      ?? ''; // e.g. "$11 - $15"

	// Postmeta-driven fields.
	$abv             = trim( (string) get_post_meta( $post_id, 'alcohol_by_volume', true ) );
	$tasting_notes   = (string) get_post_meta( $post_id, 'tasting_notes', true );
	$retail_price    = (string) get_post_meta( $post_id, 'retail_price', true );
	$brand_link      = (string) get_post_meta( $post_id, 'brand_link', true );
	$product_link    = (string) get_post_meta( $post_id, 'product_link', true );
	$purchase_link   = (string) get_post_meta( $post_id, 'purchase_link', true );
	$product_image   = (int)    get_post_meta( $post_id, 'product_image', true );
	$brand_logo      = (int)    get_post_meta( $post_id, 'brand_logo', true );

	// Fallbacks: use thumbnail if no `product_image` meta is set.
	if ( ! $product_image ) {
		$product_image = (int) get_post_thumbnail_id( $post_id );
	}

	// Product category taxonomy → "American IPA" style label.
	$category_terms = get_the_terms( $post_id, 'product-category' );
	$category_name  = ( $category_terms && ! is_wp_error( $category_terms ) )
		? $category_terms[0]->name
		: '';

	// Headline award (most recent / highest-scoring entry).
	$top_entry = $entries[0] ?? null;
	list( $top_medal, $top_medal_slug ) = $top_entry
		? apn_product_score_to_medal( $top_entry['score'] )
		: [ '', '' ];
	$top_medal_img_url = $top_medal_slug
		? apn_product_get_medal_image_url( $top_medal_slug, $top_entry['year'] ?? '' )
		: '';

	// Build URLs once.
	$product_image_url = $product_image ? wp_get_attachment_image_url( $product_image, 'large' )  : '';
	$brand_logo_url    = $brand_logo    ? wp_get_attachment_image_url( $brand_logo, 'full' )      : '';

	// Buy/learn-more buttons. Only render when a URL is set.
	$buy_url    = $purchase_link ?: $product_link;
	$learn_url  = $brand_link ?: '';
	$cta_labels = apn_product_get_cta_labels();
	?>

	<link rel="preconnect" href="https://fonts.googleapis.com">
	<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
	<link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;600;700;800&family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">

	<style>
	/* Scoped under .apnpt5-product-page so child-theme + Kadence styles don't collide.
	   Brand-driven colors are aliased onto the Kadence global palette so changing
	   the theme palette (Customizer → Colors) re-skins this template. Medal-foil
	   colors stay literal since they're medal artwork, not brand. */
	.apnpt5-product-page {
		--apnpt5-gold:           var(--global-palette1);
		--apnpt5-gold-light:     var(--global-palette2);
		--apnpt5-gold-dark:      var(--global-palette10);
		--apnpt5-dark:           var(--global-palette3);
		--apnpt5-dark-soft:      var(--global-palette4);
		--apnpt5-dark-deeper:    var(--global-palette3);
		--apnpt5-medal-gold:     #f7e259;
		--apnpt5-medal-core:     #eda140;
		--apnpt5-cream:          var(--global-palette7);
		--apnpt5-cream-dark:     var(--global-palette8);
		--apnpt5-text-primary:   var(--global-palette3);
		--apnpt5-text-secondary: var(--global-palette4);
		--apnpt5-text-light:     var(--global-palette5);
		--apnpt5-border:         var(--global-palette8);

		--apnpt5-grad-gold:      linear-gradient(135deg, var(--apnpt5-gold-light) 0%, var(--apnpt5-gold) 55%, var(--apnpt5-gold-dark) 100%);
		--apnpt5-grad-gold-soft: linear-gradient(135deg, color-mix(in srgb, var(--apnpt5-gold) 14%, transparent), color-mix(in srgb, var(--apnpt5-gold-light) 4%, transparent));
		--apnpt5-grad-dark:      linear-gradient(180deg, var(--apnpt5-dark-soft) 0%, var(--apnpt5-dark) 60%, var(--apnpt5-dark-deeper) 100%);
		--apnpt5-grad-title:     linear-gradient(135deg, var(--apnpt5-dark) 0%, var(--apnpt5-dark-soft) 50%, var(--apnpt5-gold) 100%);
		--apnpt5-grad-cream:     linear-gradient(180deg, var(--apnpt5-cream) 0%, var(--apnpt5-cream-dark) 100%);

		font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
		color: var(--apnpt5-text-primary);
		background: #fff;
		line-height: 1.6;
		position: relative;
	}
	.apnpt5-product-page::before {
		content: '';
		position: absolute; inset: 0;
		background: radial-gradient(ellipse 900px 600px at 25% 0%, color-mix(in srgb, var(--apnpt5-medal-gold) 12%, transparent) 0%, color-mix(in srgb, var(--apnpt5-gold) 6%, transparent) 25%, transparent 65%);
		pointer-events: none;
		z-index: 0;
	}
	.apnpt5-product-page > * { position: relative; z-index: 1; }

	/* Reset — defend against parent-theme bleed-through ------------------- */
	.apnpt5-product-page,
	.apnpt5-product-page * {
		box-sizing: border-box;
	}
	.apnpt5-product-page table,
	.apnpt5-product-page thead,
	.apnpt5-product-page tbody,
	.apnpt5-product-page tr,
	.apnpt5-product-page th,
	.apnpt5-product-page td,
	.apnpt5-product-page dl,
	.apnpt5-product-page dt,
	.apnpt5-product-page dd,
	.apnpt5-product-page button,
	.apnpt5-product-page h1,
	.apnpt5-product-page h2,
	.apnpt5-product-page h3,
	.apnpt5-product-page p {
		margin: 0;
		padding: 0;
		background: transparent;
		border: 0;
		border-radius: 0;
		box-shadow: none;
		text-transform: none;
		font: inherit;
		color: inherit;
	}
	.apnpt5-product-page button {
		appearance: none;
		-webkit-appearance: none;
		cursor: pointer;
	}
	.apnpt5-product-page table {
		border-collapse: collapse;
		border-spacing: 0;
		width: 100%;
	}
	.apnpt5-product-page img,
	.apnpt5-product-page svg { max-width: 100%; }

	/* Hero ------------------------------------------------------------------ */
	.apnpt5-product-hero {
		max-width: 1280px;
		margin: 0 auto;
		padding: 40px 40px 60px;
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 80px;
		align-items: start;
		position: relative;
	}
	.apnpt5-product-hero::before {
		content: '';
		position: absolute;
		top: 30px; bottom: 60px; left: 50%;
		width: 1px;
		background: linear-gradient(180deg, transparent 0%, var(--apnpt5-border) 15%, var(--apnpt5-gold) 50%, var(--apnpt5-border) 85%, transparent 100%);
		opacity: 0.7;
		pointer-events: none;
	}
	.apnpt5-product-image-section { position: sticky; top: 40px; }
	.apnpt5-product-image-wrapper {
		padding: 40px;
		display: flex; align-items: center; justify-content: center;
		min-height: 400px;
		position: relative;
		overflow: visible;
	}
	.apnpt5-product-medal-overlay {
		position: absolute;
		right: 12px;
		bottom: -56px;
		width: 180px;
		height: 180px;
		z-index: 5;
		pointer-events: none;
		filter: drop-shadow(0 14px 30px color-mix(in srgb, var(--apnpt5-gold-dark) 42%, transparent));
		transform: rotate(-6deg);
	}
	.apnpt5-product-medal-overlay img,
	.apnpt5-product-medal-overlay svg {
		width: 100%;
		height: 100%;
		object-fit: contain;
		display: block;
	}
	.apnpt5-product-image-wrapper::before {
		content: '';
		position: absolute;
		top: 50%; left: 50%;
		transform: translate(-50%, -50%);
		width: 90%; height: 75%;
		background: radial-gradient(ellipse at center, color-mix(in srgb, var(--apnpt5-gold) 14%, transparent) 0%, color-mix(in srgb, var(--apnpt5-medal-gold) 6%, transparent) 35%, transparent 70%);
		border-radius: 50%;
		pointer-events: none;
	}
	.apnpt5-product-photo {
		max-width: 100%;
		max-height: 500px;
		object-fit: contain;
		position: relative;
		z-index: 1;
	}
	.apnpt5-product-info { padding-top: 20px; }

	/* Brewery badge --------------------------------------------------------- */
	.apnpt5-brewery-badge {
		display: flex; align-items: center; gap: 18px;
		margin-bottom: 24px;
		padding: 0 4px 20px;
		border-image: linear-gradient(90deg, transparent, var(--apnpt5-border) 20%, var(--apnpt5-gold) 50%, var(--apnpt5-border) 80%, transparent) 1;
		border-width: 0 0 1px 0;
		border-style: solid;
	}
	.apnpt5-brewery-badge .apnpt5-badge-logo {
		width: auto;
		height: 72px;
		max-width: 160px;
		object-fit: contain;
		background: transparent;
		flex-shrink: 0;
		display: block;
	}
	.apnpt5-brewery-badge .apnpt5-badge-text { display: flex; flex-direction: column; gap: 2px; }
	.apnpt5-brewery-badge .apnpt5-badge-label {
		font-size: 10px; font-weight: 600;
		color: var(--apnpt5-text-light);
		text-transform: uppercase; letter-spacing: 1.8px; line-height: 1.2;
	}
	.apnpt5-brewery-badge .apnpt5-badge-name {
		font-family: 'Playfair Display', serif;
		font-size: 19px; font-weight: 700;
		color: var(--apnpt5-text-primary);
		line-height: 1.2; letter-spacing: -0.2px;
	}

	/* Award banner ---------------------------------------------------------- */
	.apnpt5-award-banner {
		display: flex; align-items: center; gap: 20px;
		background: linear-gradient(135deg, #fff8e7 0%, #fde8b5 50%, #f6cd6a 100%);
		border: 1px solid #f0d48a;
		border-radius: 18px;
		padding: 20px 24px;
		margin-top: 80px; /* room for medal overlay hovering at top-right */
		position: relative;
		overflow: hidden;
		box-shadow: 0 8px 24px color-mix(in srgb, var(--apnpt5-gold) 14%, transparent), inset 0 1px 0 rgba(255,255,255,0.55);
	}
	.apnpt5-award-banner::before {
		content: '';
		position: absolute; inset: 0;
		background: linear-gradient(120deg, transparent 30%, rgba(255,255,255,0.45) 50%, transparent 70%);
		pointer-events: none;
	}
	.apnpt5-award-banner::after {
		content: '';
		position: absolute; right: -60px; top: -60px;
		width: 220px; height: 220px;
		background: radial-gradient(circle, color-mix(in srgb, var(--apnpt5-medal-gold) 55%, transparent) 0%, transparent 65%);
		border-radius: 50%;
		pointer-events: none;
	}
	.apnpt5-award-text {
		display: flex; flex-direction: column; gap: 4px;
		position: relative; z-index: 1;
		flex: 1; min-width: 0;
	}
	.apnpt5-award-tier-eyebrow {
		font-size: 10.5px; font-weight: 700;
		text-transform: uppercase;
		letter-spacing: 2.2px;
		color: var(--apnpt5-text-light);
	}
	.apnpt5-award-tier {
		font-family: 'Playfair Display', serif;
		font-size: 24px; font-weight: 800;
		color: var(--apnpt5-gold-dark);
		line-height: 1.1;
		letter-spacing: -0.3px;
	}
	.apnpt5-award-meta {
		font-size: 13px; font-weight: 500;
		color: var(--apnpt5-text-secondary);
		letter-spacing: 0.3px;
	}
	.apnpt5-award-score {
		margin-left: auto;
		display: flex; flex-direction: column; align-items: center;
		padding-left: 20px;
		border-left: 1px solid color-mix(in srgb, var(--apnpt5-gold-dark) 25%, transparent);
		position: relative; z-index: 1;
		flex-shrink: 0;
	}
	.apnpt5-award-score-value {
		font-family: 'Playfair Display', serif;
		font-size: 36px; font-weight: 800;
		background: var(--apnpt5-grad-gold);
		-webkit-background-clip: text; background-clip: text;
		-webkit-text-fill-color: transparent;
		line-height: 1;
	}
	.apnpt5-award-score-label {
		font-size: 10px; font-weight: 600;
		color: var(--apnpt5-text-secondary);
		text-transform: uppercase; letter-spacing: 1.5px;
		margin-top: 4px;
	}

	/* Title block ----------------------------------------------------------- */
	.apnpt5-product-title {
		font-family: 'Playfair Display', serif;
		font-size: 52px; font-weight: 800;
		line-height: 1.05;
		margin-bottom: 8px;
		letter-spacing: -0.5px;
		background: var(--apnpt5-grad-title);
		-webkit-background-clip: text; background-clip: text;
		-webkit-text-fill-color: transparent;
		color: transparent;
	}
	.apnpt5-product-subtitle {
		font-size: 18px; font-weight: 500;
		color: var(--apnpt5-gold);
		margin-bottom: 20px;
		letter-spacing: 0.5px;
	}

	.apnpt5-meta-row {
		display: flex; align-items: center; flex-wrap: wrap;
		gap: 10px;
		margin-bottom: 32px;
	}
	.apnpt5-abv-badge {
		display: inline-flex; align-items: baseline; gap: 6px;
		background: var(--apnpt5-grad-dark);
		border-radius: 8px;
		padding: 8px 14px;
		box-shadow: 0 2px 10px color-mix(in srgb, var(--apnpt5-dark) 15%, transparent), inset 0 1px 0 rgba(255,255,255,0.06);
	}
	.apnpt5-abv-value { font-size: 16px; font-weight: 700; color: #fff; line-height: 1; }
	.apnpt5-abv-label {
		font-size: 10px; font-weight: 600; color: #fff;
		text-transform: uppercase; letter-spacing: 1px; opacity: 0.75;
	}
	.apnpt5-meta-tag {
		display: inline-flex; align-items: center; gap: 6px;
		background: var(--apnpt5-grad-gold-soft);
		color: var(--apnpt5-gold-dark);
		font-size: 12px; font-weight: 600;
		padding: 7px 14px;
		border-radius: 8px;
		letter-spacing: 0.3px;
		border: 1px solid color-mix(in srgb, var(--apnpt5-gold) 15%, transparent);
	}
	.apnpt5-meta-tag svg { width: 12px; height: 12px; fill: var(--apnpt5-gold-dark); }
	.apnpt5-meta-tag.apnpt5-price {
		background: linear-gradient(135deg, var(--apnpt5-cream), var(--apnpt5-cream-dark));
		color: var(--apnpt5-text-primary);
		border-color: var(--apnpt5-border);
	}

	.apnpt5-divider {
		width: 100%; height: 1px;
		background: linear-gradient(90deg, transparent, var(--apnpt5-border) 20%, var(--apnpt5-border) 80%, transparent);
		margin: 32px 0;
	}
	.apnpt5-section-label {
		font-size: 11px; font-weight: 700;
		text-transform: uppercase; letter-spacing: 2px;
		color: var(--apnpt5-text-light);
		margin-bottom: 14px;
	}
	.apnpt5-product-description {
		font-size: 16px; line-height: 1.8;
		color: var(--apnpt5-text-secondary);
	}

	/* Buttons --------------------------------------------------------------- */
	.apnpt5-cta-group { display: flex; gap: 12px; margin-top: 36px; flex-wrap: wrap; }
	.apnpt5-btn-primary, .apnpt5-btn-secondary {
		display: inline-flex; align-items: center; gap: 8px;
		font-family: 'Inter', sans-serif;
		font-size: 14px; font-weight: 600;
		padding: 14px 28px;
		border-radius: 12px;
		cursor: pointer;
		letter-spacing: 0.3px;
		transition: all 0.25s ease;
		text-decoration: none;
		border: 1.5px solid transparent;
		position: relative;
		overflow: hidden;
	}
	.apnpt5-btn-primary {
		background: var(--apnpt5-grad-gold);
		color: #fff;
		box-shadow: 0 4px 14px color-mix(in srgb, var(--apnpt5-gold) 30%, transparent), inset 0 1px 0 rgba(255,255,255,0.2);
	}
	.apnpt5-btn-primary::after {
		content: '';
		position: absolute; inset: 0;
		background: linear-gradient(120deg, transparent 30%, rgba(255,255,255,0.25) 50%, transparent 70%);
		transform: translateX(-100%);
		transition: transform 0.6s ease;
	}
	.apnpt5-btn-primary:hover {
		transform: translateY(-2px);
		box-shadow: 0 8px 24px color-mix(in srgb, var(--apnpt5-gold) 45%, transparent), inset 0 1px 0 rgba(255,255,255,0.25);
		color: #fff;
	}
	.apnpt5-btn-primary:hover::after { transform: translateX(100%); }
	.apnpt5-btn-secondary {
		background: #fff;
		color: var(--apnpt5-text-primary);
		border-color: var(--apnpt5-border);
	}
	.apnpt5-btn-secondary:hover {
		border-color: var(--apnpt5-gold);
		color: var(--apnpt5-gold-dark);
		transform: translateY(-2px);
		background: linear-gradient(135deg, #fff, var(--apnpt5-cream));
	}
	.apnpt5-btn-primary svg, .apnpt5-btn-secondary svg { width: 16px; height: 16px; fill: currentColor; position: relative; z-index: 1; }
	.apnpt5-btn-share {
		display: inline-flex; align-items: center; justify-content: center;
		width: 48px; height: 48px;
		background: #fff;
		border: 1.5px solid var(--apnpt5-border);
		border-radius: 12px;
		cursor: pointer;
		transition: all 0.25s ease;
	}
	.apnpt5-btn-share:hover {
		border-color: var(--apnpt5-gold);
		background: linear-gradient(135deg, #fff, var(--apnpt5-cream));
	}
	.apnpt5-btn-share svg {
		width: 18px !important;
		height: 18px !important;
		fill: var(--apnpt5-text-secondary);
		display: block;
		flex-shrink: 0;
	}
	.apnpt5-btn-share:hover svg { fill: var(--apnpt5-gold-dark); }

	/* Awards section -------------------------------------------------------- */
	.apnpt5-product-details-section {
		background: #fff!important;
		border-top: 1px solid var(--apnpt5-border);
		border-bottom: 1px solid var(--apnpt5-border);
		padding: 60px 40px 200px;
		position: relative;
	}
	.apnpt5-details-container { max-width: 1280px; margin: 0 auto; position: relative; }
	.apnpt5-section-header { display: flex; align-items: center; gap: 12px; margin-bottom: 28px; }
	.apnpt5-section-title {
		font-family: 'Playfair Display', serif;
		font-size: 28px; font-weight: 700;
		color: var(--apnpt5-text-primary);
		position: relative;
		padding-bottom: 10px;
	}
	.apnpt5-section-title::after {
		content: '';
		position: absolute; left: 0; bottom: 0;
		width: 56px; height: 3px;
		background: var(--apnpt5-grad-gold);
		border-radius: 2px;
	}

	.apnpt5-details-table-wrap {
		border-radius: 14px;
		border: 1px solid var(--apnpt5-border);
		background: #fff;
		box-shadow: 0 2px 8px color-mix(in srgb, var(--apnpt5-dark) 4%, transparent);
		overflow: hidden;
	}
	.apnpt5-details-table {
		width: 100%;
		table-layout: fixed;
		border-collapse: collapse;
		background: #fff;
	}
	.apnpt5-details-table thead th {
		background: var(--apnpt5-dark);
		color: var(--apnpt5-cream);
		font-size: 10.5px; font-weight: 700;
		text-transform: uppercase; letter-spacing: 1.2px;
		padding: 14px 16px;
		text-align: left;
		word-break: break-word;
	}
	.apnpt5-details-table tbody td {
		padding: 16px;
		font-size: 13px; font-weight: 500;
		color: var(--apnpt5-text-primary);
		border-top: 1px solid var(--apnpt5-border);
		vertical-align: middle;
		word-break: break-word;
	}
	.apnpt5-details-table .apnpt5-highlight {
		font-weight: 700;
		background: var(--apnpt5-grad-gold);
		-webkit-background-clip: text; background-clip: text;
		-webkit-text-fill-color: transparent;
	}
	.apnpt5-award-cell { text-align: center; }
	.apnpt5-award-medal { width: 44px; height: 44px; vertical-align: middle; }
	.apnpt5-details-cards { display: none; }

	.apnpt5-no-awards {
		font-size: 14px;
		color: var(--apnpt5-text-secondary);
		font-style: italic;
		padding: 28px;
		text-align: center;
		background: #fff;
		border: 1px dashed var(--apnpt5-border);
		border-radius: 12px;
	}

	/* Responsive ------------------------------------------------------------ */
	@media (max-width: 1024px) {
		.apnpt5-product-hero {
			grid-template-columns: 1fr;
			gap: 40px;
			padding: 24px 24px 40px;
		}
		.apnpt5-product-hero::before { display: none; }
		.apnpt5-product-image-section { position: static; max-width: 500px; margin: 0 auto; }
		.apnpt5-product-title { font-size: 40px; }
		.apnpt5-product-details-section { padding: 48px 24px 200px; }
	}
	@media (max-width: 640px) {
		.apnpt5-product-hero { padding: 24px 20px 40px; }
		.apnpt5-product-image-wrapper { padding: 24px; min-height: 300px; }
		.apnpt5-product-title { font-size: 32px; }
		.apnpt5-product-subtitle { font-size: 16px; }
		.apnpt5-product-medal-overlay {
			width: 130px; height: 130px;
			right: 8px;
			bottom: -42px;
		}
		.apnpt5-award-banner {
			flex-direction: column;
			text-align: center;
			gap: 14px;
			padding: 22px 20px;
			margin-top: 64px;
		}
		.apnpt5-award-text { align-items: center; gap: 4px; }
		.apnpt5-award-tier { font-size: 22px; }
		.apnpt5-award-score {
			margin-left: 0; padding-left: 0; border-left: 0;
			border-top: 1px solid color-mix(in srgb, var(--apnpt5-gold-dark) 25%, transparent);
			padding-top: 12px;
			flex-direction: row; gap: 10px; align-items: baseline;
			width: 100%; justify-content: center;
		}
		.apnpt5-award-score-value { font-size: 32px; }
		.apnpt5-award-score-label { margin-top: 0; }
		.apnpt5-cta-group { flex-direction: column; align-items: stretch; }
		.apnpt5-btn-primary, .apnpt5-btn-secondary { justify-content: center; }
		.apnpt5-btn-share { width: 100%; height: 48px; }
		.apnpt5-brewery-badge .apnpt5-badge-logo { height: 60px; max-width: 140px; }
		.apnpt5-brewery-badge .apnpt5-badge-name { font-size: 17px; }
		.apnpt5-product-details-section { padding: 40px 20px 200px; }
		.apnpt5-details-table-wrap { display: none; }
		.apnpt5-details-cards { display: grid; gap: 12px; }
		.apnpt5-details-card {
			background: #fff;
			border: 1px solid var(--apnpt5-border);
			border-radius: 12px;
			padding: 4px 18px;
			display: grid;
			grid-template-columns: 42% 58%;
			box-shadow: 0 4px 14px color-mix(in srgb, var(--apnpt5-dark) 4%, transparent);
		}
		.apnpt5-details-card dt,
		.apnpt5-details-card dd {
			padding: 12px 0;
			border-bottom: 1px solid var(--apnpt5-border);
			min-height: 0;
		}
		.apnpt5-details-card dt {
			font-size: 11px; font-weight: 700;
			text-transform: uppercase; letter-spacing: 1px;
			color: var(--apnpt5-text-light);
			align-self: center;
			padding-right: 14px;
		}
		.apnpt5-details-card dd {
			font-size: 14px; font-weight: 500;
			color: var(--apnpt5-text-primary);
			word-break: break-word;
		}
		.apnpt5-details-card dt:nth-last-of-type(1),
		.apnpt5-details-card dd:nth-last-of-type(1) {
			border-bottom: none;
		}
	}
	</style>

	<div class="apnpt5-product-page">

		<section class="apnpt5-product-hero">

			<div class="apnpt5-product-image-section">
				<div class="apnpt5-product-image-wrapper">
					<?php if ( $product_image_url ) : ?>
						<img class="apnpt5-product-photo"
						     src="<?php echo esc_url( $product_image_url ); ?>"
						     alt="<?php echo esc_attr( get_the_title() . ( $brand_name ? ' by ' . $brand_name : '' ) ); ?>" />
					<?php else : ?>
						<svg class="apnpt5-product-photo" viewBox="0 0 300 500" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
							<rect fill="#e5e0d8" width="300" height="500" rx="16"/>
							<text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" fill="#8a8a8a" font-family="sans-serif" font-size="18">Product Image</text>
						</svg>
					<?php endif; ?>

					<?php if ( $top_entry && $top_medal ) : ?>
						<div class="apnpt5-product-medal-overlay" aria-hidden="true">
							<?php if ( $top_medal_img_url ) : ?>
								<img src="<?php echo esc_url( $top_medal_img_url ); ?>"
								     alt="<?php echo esc_attr( $top_medal . ' Medal' ); ?>" />
							<?php else : ?>
								<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">
									<circle cx="50" cy="50" r="38" fill="#eda140"></circle>
									<circle cx="50" cy="50" r="44" fill="none" stroke="#f7e259" stroke-width="12"></circle>
									<text x="50" y="53" text-anchor="middle" dominant-baseline="middle" fill="#f7e259" style="font: 700 40px sans-serif;"><?php echo (int) $top_entry['score']; ?></text>
								</svg>
							<?php endif; ?>
						</div>
					<?php endif; ?>
				</div>

				<?php if ( $top_entry && $top_medal ) : ?>
					<div class="apnpt5-award-banner" role="note" aria-label="Competition award">
						<div class="apnpt5-award-text">
							<span class="apnpt5-award-tier-eyebrow">Award Winner</span>
							<div class="apnpt5-award-tier"><?php echo esc_html( $top_medal ); ?> Medal</div>
							<div class="apnpt5-award-meta"><?php echo esc_html( get_bloginfo( 'name' ) ); ?> &middot; <?php echo (int) $top_entry['year']; ?></div>
						</div>
						<div class="apnpt5-award-score" aria-label="Score <?php echo (int) $top_entry['score']; ?> out of 100">
							<span class="apnpt5-award-score-value"><?php echo (int) $top_entry['score']; ?></span>
							<span class="apnpt5-award-score-label">/ 100</span>
						</div>
					</div>
				<?php endif; ?>
			</div>

			<div class="apnpt5-product-info">

				<?php if ( $brand_name ) : ?>
					<div class="apnpt5-brewery-badge">
						<?php if ( $brand_logo_url ) : ?>
							<img class="apnpt5-badge-logo" src="<?php echo esc_url( $brand_logo_url ); ?>" alt="<?php echo esc_attr( $brand_name ); ?>" />
						<?php endif; ?>
						<div class="apnpt5-badge-text">
							<span class="apnpt5-badge-label">Brewed by</span>
							<span class="apnpt5-badge-name"><?php echo esc_html( $brand_name ); ?></span>
						</div>
					</div>
				<?php endif; ?>

				<h1 class="apnpt5-product-title"><?php the_title(); ?></h1>

				<?php if ( $type_text ) : ?>
					<p class="apnpt5-product-subtitle"><?php echo esc_html( $type_text ); ?></p>
				<?php endif; ?>

				<?php if ( $abv !== '' || $category_name || $price_text || $retail_price ) : ?>
					<div class="apnpt5-meta-row">
						<?php if ( $abv !== '' ) : ?>
							<div class="apnpt5-abv-badge">
								<span class="apnpt5-abv-value"><?php echo esc_html( $abv ); ?>%</span>
								<span class="apnpt5-abv-label">ABV</span>
							</div>
						<?php endif; ?>

						<?php if ( $category_name ) : ?>
							<span class="apnpt5-meta-tag">
								<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 2l1.09 6.26L19 9.27l-4.18 4.07L16 20l-4-2.73L8 20l1.18-6.66L5 9.27l5.91-1.01L12 2z"/></svg>
								<?php echo esc_html( $category_name ); ?>
							</span>
						<?php endif; ?>

						<?php
						$price_label = $retail_price !== '' ? $retail_price : $price_text;
						if ( $price_label ) : ?>
							<span class="apnpt5-meta-tag apnpt5-price"><?php echo esc_html( $price_label ); ?></span>
						<?php endif; ?>
					</div>
				<?php endif; ?>

				<div class="apnpt5-divider"></div>

				<?php if ( $tasting_notes ) : ?>
					<div>
						<p class="apnpt5-section-label">About this product</p>
						<p class="apnpt5-product-description"><?php echo esc_html( $tasting_notes ); ?></p>
					</div>
				<?php endif; ?>

				<?php if ( $buy_url || $learn_url ) : ?>
					<div class="apnpt5-cta-group">
						<?php if ( $buy_url ) : ?>
							<a href="<?php echo esc_url( $buy_url ); ?>" target="_blank" rel="noopener" class="apnpt5-btn-primary">
								<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49A1.003 1.003 0 0 0 20 4H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z"/></svg>
								<?php echo esc_html( $purchase_link ? 'Buy Now' : $cta_labels['buy'] ); ?>
							</a>
						<?php endif; ?>
						<?php if ( $learn_url ) : ?>
							<a href="<?php echo esc_url( $learn_url ); ?>" target="_blank" rel="noopener" class="apnpt5-btn-secondary">
								<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2v1.93zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39z"/></svg>
								<?php echo esc_html( $cta_labels['learn'] ); ?>
							</a>
						<?php endif; ?>
						<button type="button" class="apnpt5-btn-share" aria-label="Share this product"
						        onclick="if(navigator.share){navigator.share({title:document.title,url:location.href}).catch(function(){});}else{navigator.clipboard&&navigator.clipboard.writeText(location.href);}">
							<svg width="18" height="18" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false"><path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92s2.92-1.31 2.92-2.92-1.31-2.92-2.92-2.92z"/></svg>
						</button>
					</div>
				<?php endif; ?>
			</div>
		</section>

		<section class="apnpt5-product-details-section">
			<div class="apnpt5-details-container">
				<div class="apnpt5-section-header">
					<h2 class="apnpt5-section-title">Awards</h2>
				</div>

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

					<div class="apnpt5-details-table-wrap">
						<table class="apnpt5-details-table">
							<thead>
								<tr>
									<th>Brand Name</th>
									<th>Product Type</th>
									<th>Product Name</th>
									<th>Product Competition</th>
									<th>Price Category</th>
									<th>Entry Year</th>
									<th>Award</th>
								</tr>
							</thead>
							<tbody>
								<?php foreach ( $entries as $entry ) :
									list( $medal_label, $medal_slug ) = apn_product_score_to_medal( $entry['score'] );
								?>
									<tr>
										<td><?php echo esc_html( $brand_name ); ?></td>
										<td><?php echo esc_html( $type_text ); ?></td>
										<td class="apnpt5-highlight"><?php the_title(); ?></td>
										<td><?php echo esc_html( $category_name ); ?></td>
										<td><?php echo esc_html( $price_text ); ?></td>
										<td><?php echo (int) $entry['year']; ?></td>
										<td class="apnpt5-award-cell">
											<?php if ( $medal_label ) : ?>
												<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" class="apnpt5-award-medal" aria-label="<?php echo esc_attr( $medal_label . ' Medal, Score ' . (int) $entry['score'] ); ?>">
													<circle cx="50" cy="50" r="38" fill="#eda140"></circle>
													<circle cx="50" cy="50" r="44" fill="none" stroke="#f7e259" stroke-width="12"></circle>
													<text x="50" y="53" text-anchor="middle" dominant-baseline="middle" fill="#f7e259" style="font: 700 40px sans-serif;"><?php echo (int) $entry['score']; ?></text>
												</svg>
											<?php else : ?>
												<span><?php echo (int) $entry['score']; ?> / 100</span>
											<?php endif; ?>
										</td>
									</tr>
								<?php endforeach; ?>
							</tbody>
						</table>
					</div>

					<div class="apnpt5-details-cards">
						<?php foreach ( $entries as $entry ) :
							list( $medal_label, $medal_slug ) = apn_product_score_to_medal( $entry['score'] );
						?>
							<dl class="apnpt5-details-card">
								<dt>Brand Name</dt><dd><?php echo esc_html( $brand_name ); ?></dd>
								<dt>Product Type</dt><dd><?php echo esc_html( $type_text ); ?></dd>
								<dt>Product Name</dt><dd><strong><?php the_title(); ?></strong></dd>
								<dt>Product Competition</dt><dd><?php echo esc_html( $category_name ); ?></dd>
								<dt>Price Category</dt><dd><?php echo esc_html( $price_text ); ?></dd>
								<dt>Entry Year</dt><dd><?php echo (int) $entry['year']; ?></dd>
								<dt>Award</dt>
								<dd>
									<?php if ( $medal_label ) : ?>
										<?php echo esc_html( $medal_label ); ?> Medal &middot; <?php echo (int) $entry['score']; ?> / 100
									<?php else : ?>
										<?php echo (int) $entry['score']; ?> / 100
									<?php endif; ?>
								</dd>
							</dl>
						<?php endforeach; ?>
					</div>

				<?php else : ?>
					<p class="apnpt5-no-awards">No awards recorded for this product yet.</p>
				<?php endif; ?>
			</div>
		</section>

	</div>

	<?php
endwhile;

get_footer();
