<?php
if ( ! defined( 'ABSPATH' ) ) { exit; }

/**
 * Frontend rendering - shortcode outputs an <iframe> pointing to a standalone
 * viewer page. The viewer page loads the flipbook in complete CSS/JS isolation,
 * eliminating all style conflicts with the host WordPress theme.
 */
class TNC_Flipbook_3D_Frontend {

    public static function init() {
        add_shortcode( 'tnc-flipbook-3d-embed', array( __CLASS__, 'render_shortcode' ) );
        add_shortcode( 'tnc-flipbook-3d-link', array( __CLASS__, 'render_link_shortcode' ) );
        add_shortcode( 'tnc-flipbook-3d-image-link', array( __CLASS__, 'render_image_link_shortcode' ) );

        // Intercept ?tncfb3d_viewer=ID requests early and serve the standalone viewer
        add_action( 'template_redirect', array( __CLASS__, 'maybe_serve_viewer' ) );

        // Register the query var so WordPress doesn't strip it
        add_filter( 'query_vars', array( __CLASS__, 'register_query_vars' ) );

        // Enqueue lightweight frontend script for link/image-link block popup handling
        add_action( 'wp_enqueue_scripts', array( __CLASS__, 'enqueue_frontend_script' ) );
    }

    /**
     * Enqueue the lightweight popup/link handler on pages that have flipbook blocks.
     */
    public static function enqueue_frontend_script() {
        // Register the script; it will be enqueued by blocks that need it
        wp_register_script(
            'tncfb3d-frontend',
            TNC_FLIPBOOK_3D_URL . 'assets/frontend/tnc-flipbook-wp-init.js',
            array(),
            TNC_FLIPBOOK_3D_VERSION,
            true
        );

        // Register companion styles for link/image-link blocks
        wp_register_style(
            'tncfb3d-frontend',
            TNC_FLIPBOOK_3D_URL . 'assets/frontend/tnc-flipbook-frontend.css',
            array(),
            TNC_FLIPBOOK_3D_VERSION
        );
    }

    // ── Query var registration ───────────────────────────────────────────────

    public static function register_query_vars( $vars ) {
        $vars[] = 'tncfb3d_viewer';
        return $vars;
    }

    // ── Shortcode ─────────────────────────────────────────────────────────────

    /**
     * [flipbook id="123" width="100%" height="600px" title="My Book" class="my-class"]
     */
    public static function render_shortcode( $atts ) {
        $atts = shortcode_atts( array(
            'id'                       => 0,
            'width'                    => '',
            'height'                   => '',
            'title'                    => '',
            'class'                    => '',
            'page'                     => '',
            'fullscreen_link'          => 'false',
            'fullscreen_link_text'     => '',
            'fullscreen_link_position' => 'above',
            'fullscreen_link_align'    => 'left',
            'fullscreen_link_mode'     => 'popup',
            'fullscreen_popup_width'   => '90vw',
            'fullscreen_popup_height'  => '90vh',
            'fullscreen_popup_theme'   => 'dark',
            'fullscreen_transparent'   => 'false',
            'fullscreen_nofollow'      => 'false',
        ), $atts, 'tnc-flipbook-3d-embed' );

        $post_id = absint( $atts['id'] );
        if ( ! $post_id ) {
            return '';
        }

        return TNC_Flipbook_3D_Blocks::render_embed_block( array(
            'flipbookId'             => $post_id,
            'width'                  => $atts['width'],
            'height'                 => $atts['height'],
            'iframeTitle'            => $atts['title'],
            'className'              => $atts['class'],
            'page'                   => $atts['page'],
            'fullscreenLink'         => filter_var( $atts['fullscreen_link'], FILTER_VALIDATE_BOOLEAN ),
            'fullscreenLinkText'     => $atts['fullscreen_link_text'] ?: __( 'View FlipBook', 'tnc-flipbook-3d-lite' ),
            'fullscreenLinkPosition' => $atts['fullscreen_link_position'],
            'fullscreenLinkAlign'    => $atts['fullscreen_link_align'],
            'fullscreenLinkMode'     => $atts['fullscreen_link_mode'],
            'fullscreenPopupWidth'   => $atts['fullscreen_popup_width'],
            'fullscreenPopupHeight'  => $atts['fullscreen_popup_height'],
            'fullscreenPopupTheme'   => $atts['fullscreen_popup_theme'],
            'fullscreenTransparent'  => filter_var( $atts['fullscreen_transparent'], FILTER_VALIDATE_BOOLEAN ),
            'fullscreenNofollow'     => filter_var( $atts['fullscreen_nofollow'], FILTER_VALIDATE_BOOLEAN ),
        ) );
    }

    /**
     * [flipbook_link id="123" text="Read Now" mode="popup" style="button" popup_width="90vw" popup_height="90vh" nofollow="false"]
     */
    public static function render_link_shortcode( $atts ) {
        $atts = shortcode_atts( array(
            'id'           => 0,
            'text'         => __( 'View TNC FlipBook 3D', 'tnc-flipbook-3d-lite' ),
            'mode'         => 'popup',
            'style'        => 'text',
            'popup_width'  => '90vw',
            'popup_height' => '90vh',
            'nofollow'     => 'false',
            'class'        => '',
            'page'         => '',
            'transparent'  => 'false',
            'popup_theme'  => 'dark',
        ), $atts, 'tnc-flipbook-3d-link' );

        $post_id = absint( $atts['id'] );
        if ( ! $post_id ) {
            return '';
        }

        return TNC_Flipbook_3D_Blocks::render_link_block( array(
            'flipbookId'  => $post_id,
            'linkText'    => $atts['text'],
            'mode'        => $atts['mode'],
            'linkStyle'   => $atts['style'],
            'popupWidth'  => $atts['popup_width'],
            'popupHeight' => $atts['popup_height'],
            'nofollow'    => filter_var( $atts['nofollow'], FILTER_VALIDATE_BOOLEAN ),
            'className'   => $atts['class'],
            'page'        => $atts['page'],
            'transparent' => filter_var( $atts['transparent'], FILTER_VALIDATE_BOOLEAN ),
            'popupTheme'  => $atts['popup_theme'],
        ) );
    }

    /**
     * [flipbook_image_link id="123" cover="true" image="" mode="popup" popup_width="90vw" popup_height="90vh" width="" nofollow="false" class=""]
     *
     * cover="true"  → auto-resolve from Featured Image or first image source
     * image="URL"   → use an explicit image URL (overrides cover)
     */
    public static function render_image_link_shortcode( $atts ) {
        $atts = shortcode_atts( array(
            'id'           => 0,
            'cover'        => 'true',
            'image'        => '',
            'alt'          => '',
            'mode'         => 'popup',
            'popup_width'  => '90vw',
            'popup_height' => '90vh',
            'width'        => '',
            'nofollow'     => 'false',
            'class'        => '',
            'page'         => '',
            'transparent'  => 'false',
            'popup_theme'  => 'dark',
        ), $atts, 'tnc-flipbook-3d-image-link' );

        $post_id = absint( $atts['id'] );
        if ( ! $post_id ) {
            return '';
        }

        $post = get_post( $post_id );
        if ( ! $post || TNC_FLIPBOOK_3D_CPT !== $post->post_type ) {
            return '';
        }

        // Resolve the image URL
        $image_url = '';
        if ( ! empty( $atts['image'] ) ) {
            $image_url = $atts['image'];
        } elseif ( filter_var( $atts['cover'], FILTER_VALIDATE_BOOLEAN ) ) {
            $image_url = self::get_cover_url( $post_id );
        }

        $alt = ! empty( $atts['alt'] ) ? $atts['alt'] : get_the_title( $post_id );

        // If we have an image, delegate to the image-link block renderer
        if ( $image_url ) {
            return TNC_Flipbook_3D_Blocks::render_image_link_block( array(
                'flipbookId'  => $post_id,
                'imageUrl'    => $image_url,
                'imageAlt'    => $alt,
                'imageWidth'  => $atts['width'],
                'mode'        => $atts['mode'],
                'popupWidth'  => $atts['popup_width'],
                'popupHeight' => $atts['popup_height'],
                'nofollow'    => filter_var( $atts['nofollow'], FILTER_VALIDATE_BOOLEAN ),
                'className'   => $atts['class'],
                'transparent' => filter_var( $atts['transparent'], FILTER_VALIDATE_BOOLEAN ),
                'popupTheme'  => $atts['popup_theme'],
            ) );
        }

        // No image available - render a styled placeholder card
        return self::render_cover_placeholder( $post_id, $alt, $atts );
    }

    /**
     * Render a styled placeholder card when no cover image is available.
     */
    private static function render_cover_placeholder( $post_id, $title, $atts ) {
        $mode    = sanitize_text_field( $atts['mode'] );
        $popup_w = sanitize_text_field( $atts['popup_width'] );
        $popup_h = sanitize_text_field( $atts['popup_height'] );
        $class   = ! empty( $atts['class'] ) ? ' ' . sanitize_html_class( $atts['class'] ) : '';
        $width   = ! empty( $atts['width'] ) ? 'width:' . esc_attr( $atts['width'] ) . ';' : '';

        $viewer_url = add_query_arg( 'tncfb3d_viewer', $post_id, home_url( '/' ) );
        if ( ! empty( $atts['page'] ) ) {
            $viewer_url = add_query_arg( 'page', absint( $atts['page'] ), $viewer_url );
        }
        $href       = ( 'same_tab' === $mode ) ? esc_url( $viewer_url ) : '#';

        $html  = '<a class="tncfb-flipbook-image-link tncfb-cover-placeholder' . $class . '"';
        $html .= ' href="' . $href . '"';
        $html .= ' data-tncfb-id="' . absint( $post_id ) . '"';
        $html .= ' data-tncfb-mode="' . esc_attr( $mode ) . '"';
        $html .= ' data-tncfb-viewer-url="' . esc_url( $viewer_url ) . '"';
        if ( 'popup' === $mode ) {
            $html .= ' data-tncfb-popup-width="' . esc_attr( $popup_w ) . '"';
            $html .= ' data-tncfb-popup-height="' . esc_attr( $popup_h ) . '"';
        }
        $html .= ' style="' . $width . '">';
        $html .= '<span class="tncfb-cover-placeholder-icon">';
        $html .= '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" width="48" height="48">';
        $html .= '<path d="M4 19.5A2.5 2.5 0 0 1 6.5 17H20"/>';
        $html .= '<path d="M6.5 2H20v20H6.5A2.5 2.5 0 0 1 4 19.5v-15A2.5 2.5 0 0 1 6.5 2z"/>';
        $html .= '</svg>';
        $html .= '</span>';
        $html .= '<span class="tncfb-cover-placeholder-title">' . esc_html( $title ) . '</span>';
        $html .= '<span class="tncfb-cover-placeholder-cta">' . esc_html__( 'Click to read', 'tnc-flipbook-3d-lite' ) . '</span>';
        $html .= '</a>';

        wp_enqueue_script( 'tncfb3d-frontend' );
        wp_enqueue_style( 'tncfb3d-frontend' );

        return $html;
    }

    /**
     * Get the cover image URL for a flipbook.
     * Delegates to the public API function tnc_flipbook_3d_get_cover_url().
     */
    public static function get_cover_url( $post_id ) {
        return tnc_flipbook_3d_get_cover_url( $post_id, 'large' );
    }

    /**
     * Core render method - used by shortcode, blocks, and preview.
     * Outputs an <iframe> pointing to the standalone viewer.
     */
    public static function render( $post_id, $overrides = array() ) {
        $post = get_post( $post_id );
        if ( ! $post || TNC_FLIPBOOK_3D_CPT !== $post->post_type ) {
            return '';
        }

        /**
         * @hook tncfb3d_viewer_access
         * @param bool    $allowed Whether the current user can view this flipbook.
         * @param int     $post_id Flipbook post ID.
         * @param WP_Post $post    Flipbook post object.
         * @return bool
         */
        if ( ! apply_filters( 'tncfb3d_viewer_access', true, $post_id, $post ) ) {
            return '';
        }

        // Dimensions: shortcode attr > post meta > plugin default
        $p      = TNC_FLIPBOOK_3D_PREFIX;
        $width  = ! empty( $overrides['width'] )
            ? TNC_Flipbook_3D_Helpers::sanitize_dimension( $overrides['width'] )
            : TNC_Flipbook_3D_Helpers::sanitize_dimension( get_post_meta( $post_id, $p . 'width', true ) );
        $height = ! empty( $overrides['height'] )
            ? TNC_Flipbook_3D_Helpers::sanitize_dimension( $overrides['height'] )
            : TNC_Flipbook_3D_Helpers::sanitize_dimension( get_post_meta( $post_id, $p . 'height', true ) );

        if ( ! $width ) { $width = '100%'; }

        // Iframe title: override > post title
        $iframe_title = ! empty( $overrides['iframe_title'] )
            ? sanitize_text_field( $overrides['iframe_title'] )
            : get_the_title( $post_id );

        // Build viewer URL with optional overrides
        $url_params = array( 'tncfb3d_viewer' => $post_id );

        if ( ! empty( $overrides['page'] ) )     $url_params['page']     = absint( $overrides['page'] );
        if ( ! empty( $overrides['theme'] ) )    $url_params['theme']    = sanitize_key( $overrides['theme'] );
        if ( ! empty( $overrides['effect'] ) )   $url_params['effect']   = sanitize_key( $overrides['effect'] );
        if ( ! empty( $overrides['sound'] ) )    $url_params['sound']    = sanitize_text_field( $overrides['sound'] );
        if ( ! empty( $overrides['language'] ) ) $url_params['lang']     = sanitize_text_field( $overrides['language'] );
        if ( ! empty( $overrides['transparent'] ) && 'true' === $overrides['transparent'] ) {
            $url_params['transparent'] = '1';
        }

        $viewer_url = add_query_arg( $url_params, home_url( '/' ) );

        /**
         * @hook tncfb3d_viewer_url
         * @param string $viewer_url Fully-built viewer iframe URL.
         * @param int    $post_id    Flipbook post ID.
         * @return string
         */
        $viewer_url = apply_filters( 'tncfb3d_viewer_url', $viewer_url, $post_id );

        // CSS class
        $classes = 'tnc-flipbook-wrap';
        if ( ! empty( $overrides['class'] ) ) {
            $classes .= ' ' . sanitize_html_class( $overrides['class'] );
        }

        // Adaptive sizing: if no explicit height, use aspect-ratio so the
        // iframe shrinks on narrow screens instead of leaving empty space.
        // The iframe will also post its ideal aspect ratio once the PDF loads.
        $style = 'width:' . esc_attr( $width ) . ';';
        if ( $height ) {
            // Explicit height: use as max-height with aspect-ratio fallback
            $style .= 'max-height:' . esc_attr( $height ) . ';';
            $style .= 'aspect-ratio:16/10;';
        } else {
            // No height set: pure aspect-ratio, capped at 800px
            $style .= 'max-height:800px;';
            $style .= 'aspect-ratio:16/10;';
        }

        $uid = 'tncfb-' . absint( $post_id );

        $attrs = array(
            'src'             => esc_url( $viewer_url ),
            'style'           => 'width:100%;height:100%;border:none;display:block;',
            'allowfullscreen' => true,
            'loading'         => 'lazy',
            'title'           => $iframe_title,
        );

        /**
         * @hook tncfb3d_iframe_attributes
         * @param array $attrs   Associative array of iframe HTML attributes.
         * @param int   $post_id Flipbook post ID.
         * @return array
         */
        $attrs = apply_filters( 'tncfb3d_iframe_attributes', $attrs, $post_id );

        $html  = '<div class="' . esc_attr( $classes ) . '"';
        $html .= ' id="' . esc_attr( $uid ) . '"';
        $html .= ' style="' . esc_attr( $style ) . '">';
        $html .= '<iframe';
        foreach ( $attrs as $attr_name => $attr_value ) {
            if ( true === $attr_value ) {
                $html .= ' ' . esc_attr( $attr_name );
            } elseif ( false !== $attr_value && null !== $attr_value ) {
                $html .= ' ' . esc_attr( $attr_name ) . '="' . esc_attr( $attr_value ) . '"';
            }
        }
        $html .= '></iframe>';
        $html .= '</div>';

        // Resize listener: when the iframe posts its ideal aspect ratio, apply it.
        // Attached via the enqueued frontend handle (no inline <script> tag).
        wp_enqueue_script( 'tncfb3d-frontend' );
        $resize_js = 'window.addEventListener("message",function(e){'
            . 'if(e.data&&e.data.type==="tncfb-resize"&&e.data.id==' . absint( $post_id ) . '){'
            . 'var w=document.getElementById(' . wp_json_encode( $uid ) . ');'
            . 'if(w&&e.data.aspectRatio){w.style.aspectRatio=e.data.aspectRatio;}'
            . '}});';
        wp_add_inline_script( 'tncfb3d-frontend', $resize_js );

        return apply_filters( 'tncfb3d_shortcode_output', $html, $post_id, $overrides );
    }

    // ── Standalone viewer page ─────────────────────────────────────────────────

    /**
     * Intercept ?tncfb3d_viewer=ID and serve a complete standalone HTML page
     * that loads the flipbook with full CSS/JS isolation.
     */
    // phpcs:disable WordPress.Security.NonceVerification.Recommended -- Public read-only viewer URL parameters; no state changes.
    // phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- $json/$addon_json are wp_json_encode output; CSS values pass through wp_strip_all_tags; URLs already esc_url'd.
    // phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet -- Standalone viewer page renders outside WP theme context; direct <link> required.
    public static function maybe_serve_viewer() {
        $post_id = absint( get_query_var( 'tncfb3d_viewer', 0 ) );
        if ( ! $post_id ) {
            return;
        }

        $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 );
        $addon_data = apply_filters( 'tncfb3d_viewer_addon_config', array(), $post_id );
        $json       = wp_json_encode( $payload, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_UNESCAPED_UNICODE );
        $addon_json = wp_json_encode( $addon_data, 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' );
        // Transparent mode is only meaningful inside a popup overlay — the
        // popup launcher is the only thing that pipes `popuptheme` along with
        // `transparent=1`. Direct/inline viewer loads should not go transparent
        // (no surround to blend with), so gate on both being present.
        $is_transparent = ! empty( $_GET['transparent'] ) && ! empty( $_GET['popuptheme'] );

        // 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( get_the_title( $post_id ) ); ?></title>
<?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. ?>
<?php
// Favicon
$_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 ); ?>
<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 ); ?>
<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
// URL parameter overrides (from shortcode attributes)
$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['autoplay'] ) ) $url_overrides[] = 'config.autoPlay = true;';
if ( ! empty( $_GET['locktheme'] ) ) $url_overrides[] = 'config.toolbar = config.toolbar || {}; config.toolbar.themeToggle = false;';
if ( ! empty( $url_overrides ) ) {
    echo implode( "\n", $url_overrides ) . "\n";
}
?>

// Pass post ID so the iframe can identify itself in postMessage
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.addonData = <?php echo $addon_json; ?>;
</script>
<?php do_action( 'tncfb3d_viewer_body_end', $post_id, $payload ); ?>
</body>
</html>
        <?php
        exit;
    }
    // phpcs:enable WordPress.Security.NonceVerification.Recommended
    // phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
    // phpcs:enable WordPress.WP.EnqueuedResources.NonEnqueuedStylesheet

}
