<?php
/**
 * File Path: templates/partials/section-kindle-preview.php
 *
 * My Book Showroom — Kindle Instant Preview Section (Story 13-7)
 *
 * PRO only. Renders a "Preview on Kindle" button that reveals an Amazon
 * Kindle Instant Preview iframe when clicked. Section absent when
 * mbs_kindle_preview_asin is empty or when mbs_is_pro() is false
 * (HTML comment only per SEC-02).
 *
 * The toggle behavior is handled by MBS.KindlePreview in mbs-front.js.
 * The Amazon external embed script is enqueued conditionally here via
 * wp_enqueue_script() — WordPress buffers this safely before wp_footer().
 *
 * @package MyBookShowroom
 * @since   1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- template-scope variables injected by mbs_get_template_part(); not global vars

if ( ! mbs_is_registered() ) {
	return;
}

if ( ! isset( $post_id ) ) {
	$post_id = get_the_ID();
}

// Extract ASIN from the first Amazon global buy link (Path B — no dedicated ASIN field).
// Matches /dp/ASIN and /gp/product/ASIN URL patterns.
$asin = '';
foreach ( MBS_Buy_Link_DAO::get_for_book( $post_id ) as $_bl ) {
	if ( 'amazon' === ( $_bl->retailer_key ?? '' ) ) {
		if ( preg_match( '#/(?:dp|gp/product)/([A-Z0-9]{10})#i', $_bl->url ?? '', $_m ) ) {
			$asin = strtoupper( $_m[1] );
			break;
		}
	}
}

// GP-UI-1: nothing to render when ASIN cannot be resolved from buy links.
if ( '' === $asin ) {
	return;
}

// SEC-02: PRO gate — no visible element on FREE tier.
if ( ! mbs_is_pro() ) {
	MBS_Pro_Gate::comment( 'Kindle Preview Button' );
	return;
}

// ASIN is validated as /^[A-Z0-9]{10}$/ on save; esc_attr() as defense-in-depth.
$asin_safe = esc_attr( $asin );
?>

<div class="mbs-section mbs-kindle-preview">
	<button
		type="button"
		class="mbs-kindle-preview__btn"
		aria-expanded="false"
		aria-controls="mbs-kindle-container-<?php echo $asin_safe; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- already esc_attr()'d above ?>"
	>
		<?php esc_html_e( 'Preview on Kindle', 'my-book-showroom' ); ?>
	</button>

	<div
		id="mbs-kindle-container-<?php echo $asin_safe; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- already esc_attr()'d above ?>"
		class="mbs-kindle-preview__container"
		hidden
	>
		<iframe
			src="https://read.amazon.com/kp/card?asin=<?php echo $asin_safe; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- already esc_attr()'d above ?>&amp;preview=inline&amp;linkCode=kpe"
			title="<?php esc_attr_e( 'Kindle Preview', 'my-book-showroom' ); ?>"
			sandbox="allow-scripts allow-same-origin allow-popups"
			loading="lazy"
			referrerpolicy="no-referrer-when-downgrade"
		></iframe>
	</div>
</div>
