<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Local template-scope variables, not true globals.
// phpcs:disable WordPress.Security.NonceVerification.Recommended -- Public read-only viewer URL parameters; no state changes.
// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- JSON and pre-escaped values output; documented at each echo site.
// phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- Standalone viewer template renders outside theme context.
/**
 * Single flipbook CPT template.
 *
 * Serves the standalone flipbook viewer at the post's permalink URL
 * (e.g. /flipbook/my-book/). Completely bypasses the active theme so
 * the flipbook renders in full CSS/JS isolation — identical to the
 * ?tncfb3d_viewer=ID viewer used by shortcodes and blocks.
 *
 * @package TNC_Flipbook
 */

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

$post_id = get_the_ID();
$post    = get_post( $post_id );

if ( ! $post || TNC_FLIPBOOK_3D_CPT !== $post->post_type ) {
    wp_die( esc_html__( 'FlipBook not found.', 'tnc-flipbook-3d-lite' ), esc_html__( 'FlipBook Viewer', 'tnc-flipbook-3d-lite' ), array( 'response' => 404 ) );
}

// Published flipbooks are public; drafts/private require edit capability
if ( 'publish' !== $post->post_status && ! current_user_can( 'edit_post', $post_id ) ) {
    wp_die( esc_html__( 'This FlipBook is not available.', 'tnc-flipbook-3d-lite' ), esc_html__( 'FlipBook Viewer', 'tnc-flipbook-3d-lite' ), array( 'response' => 403 ) );
}

// Build config
$payload = TNC_Flipbook_3D_Config_Builder::build( $post_id );
$json    = wp_json_encode( $payload, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE );

$base               = TNC_FLIPBOOK_3D_URL;
$ver                = TNC_FLIPBOOK_3D_VERSION;
$css_url            = esc_url( $base . 'assets/flipbook/tnc-flipbook.css?ver=' . $ver );
$three_url          = esc_url( $base . 'assets/lib/three.module.js' );
$buffer_utils_url   = esc_url( $base . 'assets/lib/BufferGeometryUtils.js' );
$gltf_loader_url    = esc_url( $base . 'assets/lib/GLTFLoader.js' );
$orbit_controls_url = esc_url( $base . 'assets/lib/OrbitControls.js' );
$pdf_lib_url        = esc_url( $base . 'assets/lib/pdf.mjs' );
$pdf_worker_url     = esc_url( $base . 'assets/lib/pdf.worker.mjs' );
$translations_url   = esc_url( $base . 'assets/translations/translations.js' );
$flipbook_js_url    = esc_url( $base . 'assets/flipbook/tnc-flipbook.js?ver=' . $ver );
$lib_base_url       = esc_url( $base . 'assets/lib/' );

// Output standalone HTML — no WordPress theme, no parent styles
header( 'Content-Type: text/html; charset=utf-8' );
header( 'X-Frame-Options: SAMEORIGIN' );
$is_transparent = ! empty( $_GET['transparent'] );

// Resolve initial chrome bg + polarity to paint correct theme on first frame
$opts_colors  = $payload['options']['colors'] ?? array();
$url_theme    = isset( $_GET['theme'] ) ? sanitize_key( wp_unslash( $_GET['theme'] ) ) : '';
$eff_mode     = in_array( $url_theme, array( 'dark', 'light' ), true ) ? $url_theme : ( $opts_colors['colorMode'] ?? 'auto' );
$init_chrome  = TNC_Flipbook_3D_Helpers::resolve_initial_chrome( $opts_colors['chrome'] ?? 'slate', $eff_mode );
$body_classes = array();
if ( $is_transparent )                  { $body_classes[] = 'tncfb-transparent'; }
if ( 'light' === $init_chrome['mode'] ) { $body_classes[] = 'light-theme'; }
$body_class_attr = $body_classes ? ' class="' . esc_attr( implode( ' ', $body_classes ) ) . '"' : '';
?>
<!DOCTYPE html>
<html lang="<?php echo esc_attr( get_bloginfo( 'language' ) ); ?>"<?php echo $is_transparent ? ' class="tncfb-transparent"' : ''; ?>>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title><?php echo esc_html( TNC_Flipbook_3D_SEO::get_title( $post_id ) . ' — ' . get_bloginfo( 'name' ) ); ?></title>
<?php
$_tncfb_opts = get_option( TNC_FLIPBOOK_3D_OPTION, array() );
$_favicon_id = absint( $_tncfb_opts['favicon_id'] ?? 0 );
if ( $_favicon_id ) {
    $_fav_url = wp_get_attachment_url( $_favicon_id );
    if ( $_fav_url ) {
        echo '<link rel="icon" href="' . esc_url( $_fav_url ) . '" />' . "\n";
        echo '<link rel="apple-touch-icon" href="' . esc_url( $_fav_url ) . '" />' . "\n";
    }
} elseif ( function_exists( 'get_site_icon_url' ) && get_site_icon_url( 32 ) ) {
    echo '<link rel="icon" href="' . esc_url( get_site_icon_url( 32 ) ) . '" />' . "\n";
}
?>
<?php do_action( 'tncfb3d_viewer_head', $post_id, $payload ); ?>
<?php
// WordPress.org build: register + enqueue the viewer stylesheet, attach the
// page-init CSS via wp_add_inline_style, then print this handle inline (this is
// a self-contained viewer document, not a themed page with wp_head()).
wp_register_style( 'tncfb3d-viewer', $css_url, array(), TNC_FLIPBOOK_3D_VERSION );
wp_enqueue_style( 'tncfb3d-viewer' );
wp_add_inline_style( 'tncfb3d-viewer', 'html,body{margin:0;padding:0;width:100%;height:100%;overflow:hidden}#app{width:100%;height:100%}' );
wp_add_inline_style( 'tncfb3d-viewer', 'html,body{' . ( $is_transparent ? 'background:transparent' : 'background:' . esc_attr( $init_chrome['pageBg'] ) ) . '}' );
wp_print_styles( 'tncfb3d-viewer' );
?>
<?php // WordPress.org build: per-FlipBook custom CSS is a Pro-only feature, not shipped here. ?>
<script type="importmap">
{
    "imports": {
        "three": "<?php echo esc_url( $three_url ); ?>",
        "three/addons/": "<?php echo esc_url( $lib_base_url ); ?>",
        "../utils/BufferGeometryUtils.js": "<?php echo esc_url( $buffer_utils_url ); ?>"
    }
}
</script>
</head>
<body<?php echo $body_class_attr; ?>>
<?php do_action( 'tncfb3d_viewer_body_start', $post_id, $payload ); ?>
<?php do_action( 'tncfb3d_seo_body_content', $post_id ); ?>
<div id="app"></div>
<script type="module">
// Three.js is loaded lazily by the engine (only when 3D actually renders) via
// options.threePath, so it is intentionally NOT imported here.
import * as pdfjsLib from '<?php echo esc_url( $pdf_lib_url ); ?>';
import { initTranslations, availableLanguages, rtlLanguages } from '<?php echo esc_url( $translations_url ); ?>';

pdfjsLib.GlobalWorkerOptions.workerSrc = '<?php echo esc_url( $pdf_worker_url ); ?>';

const { default: TNCFlipbook } = await import('<?php echo esc_url( $flipbook_js_url ); ?>');

const payload = <?php echo $json; ?>;
const config  = payload.config  || {};
const options = payload.options || {};
<?php if ( $is_transparent ) : ?>
config.transparentBackground = true;
<?php endif; ?>
<?php
// Shortcode/URL parameter overrides
$url_overrides = array();
if ( ! empty( $_GET['page'] ) )     $url_overrides[] = 'config.startPage = ' . absint( wp_unslash( $_GET['page'] ?? 0 ) ) . ';';
if ( ! empty( $_GET['theme'] ) )    $url_overrides[] = 'options.colors = options.colors || {}; options.colors.defaultMode = ' . wp_json_encode( sanitize_key( wp_unslash( $_GET['theme'] ?? '' ) ) ) . ';';
if ( ! empty( $_GET['effect'] ) )   $url_overrides[] = 'config.flipEffect = ' . wp_json_encode( sanitize_key( wp_unslash( $_GET['effect'] ?? '' ) ) ) . ';';
if ( ! empty( $_GET['sound'] ) )    $url_overrides[] = 'config.flipSound = ' . wp_json_encode( sanitize_text_field( wp_unslash( $_GET['sound'] ?? '' ) ) ) . ';';
if ( ! empty( $_GET['lang'] ) )     $url_overrides[] = 'config.language = ' . wp_json_encode( sanitize_text_field( wp_unslash( $_GET['lang'] ?? '' ) ) ) . ';';
if ( ! empty( $_GET['locktheme'] ) ) $url_overrides[] = 'config.toolbar = config.toolbar || {}; config.toolbar.themeToggle = false;';
if ( ! empty( $url_overrides ) ) {
    echo implode( "\n", $url_overrides ) . "\n";
}
?>

config._postId = <?php echo absint( $post_id ); ?>;

options.dependencies = { pdfjsLib, initTranslations, availableLanguages, rtlLanguages };
options.threePath         = '<?php echo esc_url( $three_url ); ?>';
options.gltfLoaderPath    = '<?php echo esc_url( $gltf_loader_url ); ?>';
options.orbitControlsPath = '<?php echo esc_url( $orbit_controls_url ); ?>';

const fb = new TNCFlipbook('#app', config, options);
window.__tncfb3d = window.__tncfb3d || {};
window.__tncfb3d.instance = fb;
</script>
<?php do_action( 'tncfb3d_viewer_body_end', $post_id, $payload ); ?>
</body>
</html>
<?php
exit;
