<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- Template/class file; variables are widget-scoped, not true globals.
/**
 * Single product shell: full page is the assigned Elementor library template (no default WC layout).
 *
 * Important: render the library template *before* the main loop runs `the_post()`. Elementor’s
 * get_builder_content_for_display() returns empty when the current post ID matches the template ID
 * (recursion guard), and priming the loop first can also break document switching.
 *
 * @package storzen
 */

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

get_header();

$id = class_exists( 'Storzen_WC_Elementor_Templates' )
	? Storzen_WC_Elementor_Templates::get_single_template_id()
	: 0;

$rendered = '';
if ( $id && class_exists( '\Elementor\Plugin' ) ) {
	// WC product widgets expect $product; do not call the_post() before this — Elementor skips output when get_the_ID() matches the library template ID (recursion guard).
	if ( function_exists( 'wc_setup_product_data' ) ) {
		$qo = get_queried_object();
		if ( $qo instanceof WP_Post && 'product' === $qo->post_type ) {
			wc_setup_product_data( $qo );
		}
	}
	// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor HTML output.
	$rendered = \Elementor\Plugin::instance()->frontend->get_builder_content_for_display( $id, true );
}

if ( is_string( $rendered ) && '' !== trim( $rendered ) ) {
	echo $rendered; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
} elseif ( function_exists( 'wc_get_template_part' ) && have_posts() ) {
	while ( have_posts() ) {
		the_post();
		wc_get_template_part( 'content', 'single-product' );
	}
}

rewind_posts();

get_footer();
