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

/**
 * Gutenberg block registration.
 *
 * All three blocks are zero-build (vanilla ES5/ES6 using window.wp globals).
 * All blocks use server-side rendering so proxy tokens stay fresh and
 * markup changes never cause block validation errors.
 */
class TNC_Flipbook_3D_Blocks {

    public static function init() {
        add_action( 'init',                   array( __CLASS__, 'register_blocks' ) );
        add_action( 'block_categories_all',   array( __CLASS__, 'register_category' ), 10, 2 );
        add_action( 'enqueue_block_editor_assets', array( __CLASS__, 'enqueue_editor_assets' ) );
    }

    // ── Block category ────────────────────────────────────────────────────────

    public static function register_category( $categories ) {
        array_unshift( $categories, array(
            'slug'  => 'tncfb3d',
            'title' => __( 'TNC FlipBook 3D', 'tnc-flipbook-3d-lite' ),
            'icon'  => null,
        ) );
        return $categories;
    }

    // ── Block registration ────────────────────────────────────────────────────

    public static function register_blocks() {
        // Register the script handle at init so block.json can reference it
        wp_register_script(
            'tncfb3d-blocks',
            TNC_FLIPBOOK_3D_URL . 'blocks/blocks-bundle.js',
            array( 'wp-blocks', 'wp-element', 'wp-components', 'wp-block-editor', 'wp-data', 'wp-i18n' ),
            TNC_FLIPBOOK_3D_VERSION,
            true
        );

        // Embed block
        register_block_type( TNC_FLIPBOOK_3D_DIR . 'blocks/flipbook-embed/block.json', array(
            'editor_script'   => 'tncfb3d-blocks',
            'render_callback' => array( __CLASS__, 'render_embed_block' ),
        ) );

        // Link block
        register_block_type( TNC_FLIPBOOK_3D_DIR . 'blocks/flipbook-link/block.json', array(
            'editor_script'   => 'tncfb3d-blocks',
            'render_callback' => array( __CLASS__, 'render_link_block' ),
        ) );

        // Image-link block
        register_block_type( TNC_FLIPBOOK_3D_DIR . 'blocks/flipbook-image-link/block.json', array(
            'editor_script'   => 'tncfb3d-blocks',
            'render_callback' => array( __CLASS__, 'render_image_link_block' ),
        ) );
    }

    // ── Server-side render: Embed ──────────────────────────────────────────────

    public static function render_embed_block( $attributes ) {
        $post_id = absint( $attributes['flipbookId'] ?? 0 );
        if ( ! $post_id ) {
            return '';
        }
        $embed = TNC_Flipbook_3D_Frontend::render( $post_id, array(
            'width'        => $attributes['width']  ?? '',
            'height'       => $attributes['height'] ?? '',
            'class'        => $attributes['className'] ?? '',
            'iframe_title' => $attributes['iframeTitle'] ?? '',
            'page'         => $attributes['page'] ?? '',
        ) );

        $html = $embed;

        if ( ! empty( $attributes['fullscreenLink'] ) ) {
            $position = ( ( $attributes['fullscreenLinkPosition'] ?? 'above' ) === 'below' ) ? 'below' : 'above';
            $align    = sanitize_key( $attributes['fullscreenLinkAlign'] ?? 'left' );
            if ( ! in_array( $align, array( 'left', 'center', 'right' ), true ) ) {
                $align = 'left';
            }

            $link = self::render_link_block( array(
                'flipbookId'  => $post_id,
                'linkText'    => $attributes['fullscreenLinkText'] ?? __( 'View FlipBook', 'tnc-flipbook-3d-lite' ),
                'mode'        => $attributes['fullscreenLinkMode'] ?? 'popup',
                'linkStyle'   => 'text',
                'popupWidth'  => $attributes['fullscreenPopupWidth']  ?? '90vw',
                'popupHeight' => $attributes['fullscreenPopupHeight'] ?? '90vh',
                'popupTheme'  => $attributes['fullscreenPopupTheme']  ?? 'dark',
                'transparent' => ! empty( $attributes['fullscreenTransparent'] ),
                'nofollow'    => ! empty( $attributes['fullscreenNofollow'] ),
                'page'        => $attributes['page'] ?? '',
            ) );

            $wrap_class  = 'tncfb-embed-with-fs tncfb-embed-fs-' . $position;
            $wrap_class .= ' tncfb-embed-fs-align-' . $align;

            $top    = ( 'above' === $position ) ? $link : '';
            $bottom = ( 'below' === $position ) ? $link : '';
            $html   = '<div class="' . esc_attr( $wrap_class ) . '">' . $top . $embed . $bottom . '</div>';
        }

        /**
         * @hook tncfb3d_embed_block_output
         * @param string $html       Rendered embed block HTML.
         * @param array  $attributes Block attributes.
         * @param int    $post_id    Flipbook post ID.
         * @return string
         */
        return apply_filters( 'tncfb3d_embed_block_output', $html, $attributes, $post_id );
    }

    // ── Server-side render: Link ───────────────────────────────────────────────

    public static function render_link_block( $attributes ) {
        $post_id = absint( $attributes['flipbookId'] ?? 0 );
        if ( ! $post_id ) {
            return '';
        }

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

        $mode       = sanitize_text_field( $attributes['mode']      ?? 'popup' );
        $link_text  = wp_kses_post( $attributes['linkText']         ?? __( 'View FlipBook', 'tnc-flipbook-3d-lite' ) );
        $link_style = sanitize_text_field( $attributes['linkStyle'] ?? 'text' );
        $popup_w    = sanitize_text_field( $attributes['popupWidth']  ?? '90vw' );
        $popup_h    = sanitize_text_field( $attributes['popupHeight'] ?? '90vh' );
        $nofollow   = ! empty( $attributes['nofollow'] );
        $class_name = ! empty( $attributes['className'] ) ? sanitize_html_class( $attributes['className'] ) : '';

        $viewer_url = add_query_arg( 'tncfb3d_viewer', $post_id, home_url( '/' ) );
        if ( ! empty( $attributes['page'] ) ) {
            $viewer_url = add_query_arg( 'page', absint( $attributes['page'] ), $viewer_url );
        }
        // Transparent only meaningful inside the popup overlay; skip on
        // new_tab / same_tab so the URL stays clean.
        if ( ! empty( $attributes['transparent'] ) && 'popup' === $mode ) {
            $viewer_url = add_query_arg( 'transparent', '1', $viewer_url );
        }

        // CSS classes
        $classes = 'tncfb-flipbook-link';
        if ( 'button' === $link_style ) {
            $classes .= ' tncfb-flipbook-button';
        }
        if ( $class_name ) {
            $classes .= ' ' . $class_name;
        }

        // rel attribute
        $rel_parts = array();
        if ( $nofollow ) {
            $rel_parts[] = 'nofollow';
        }
        if ( 'new_tab' === $mode ) {
            $rel_parts[] = 'noopener';
        }
        $rel = implode( ' ', $rel_parts );

        // href: real URL for same_tab, # for popup/new_tab (JS handles those)
        $href   = ( 'same_tab' === $mode ) ? esc_url( $viewer_url ) : '#';
        $target = ( 'new_tab' === $mode ) ? '_blank' : '';

        // Build tag
        $html  = '<a class="' . esc_attr( $classes ) . '"';
        $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 ) . '"';
            $popup_theme = sanitize_key( $attributes['popupTheme'] ?? 'dark' );
            if ( 'light' === $popup_theme ) {
                $html .= ' data-tncfb-popup-theme="light"';
            }
        }
        if ( $rel ) {
            $html .= ' rel="' . esc_attr( $rel ) . '"';
        }
        if ( $target ) {
            $html .= ' target="' . esc_attr( $target ) . '"';
        }

        $html .= '>' . $link_text . '</a>';

        // Ensure frontend assets are enqueued
        wp_enqueue_script( 'tncfb3d-frontend' );
        wp_enqueue_style( 'tncfb3d-frontend' );

        /**
         * @hook tncfb3d_link_block_output
         * @param string $html       Rendered link block HTML.
         * @param array  $attributes Block attributes.
         * @param int    $post_id    Flipbook post ID.
         * @return string
         */
        return apply_filters( 'tncfb3d_link_block_output', $html, $attributes, $post_id );
    }

    // ── Server-side render: Image Link ────────────────────────────────────────

    public static function render_image_link_block( $attributes ) {
        $post_id = absint( $attributes['flipbookId'] ?? 0 );
        if ( ! $post_id ) {
            return '';
        }

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

        $image_url = esc_url( $attributes['imageUrl'] ?? '' );

        // Auto-resolve cover from Featured Image / PDF thumbnail / first image
        if ( ! $image_url ) {
            $image_url = esc_url( TNC_Flipbook_3D_Frontend::get_cover_url( $post_id ) );
        }

        if ( ! $image_url ) {
            return '';
        }

        $image_alt  = esc_attr( $attributes['imageAlt']   ?? '' );
        $image_w    = sanitize_text_field( $attributes['imageWidth'] ?? '' );
        $mode       = sanitize_text_field( $attributes['mode']       ?? 'popup' );
        $popup_w    = sanitize_text_field( $attributes['popupWidth']  ?? '90vw' );
        $popup_h    = sanitize_text_field( $attributes['popupHeight'] ?? '90vh' );
        $class_name = ! empty( $attributes['className'] ) ? sanitize_html_class( $attributes['className'] ) : '';

        $viewer_url = add_query_arg( 'tncfb3d_viewer', $post_id, home_url( '/' ) );
        if ( ! empty( $attributes['page'] ) ) {
            $viewer_url = add_query_arg( 'page', absint( $attributes['page'] ), $viewer_url );
        }
        // Transparent only meaningful inside the popup overlay; skip on
        // new_tab / same_tab so the URL stays clean.
        if ( ! empty( $attributes['transparent'] ) && 'popup' === $mode ) {
            $viewer_url = add_query_arg( 'transparent', '1', $viewer_url );
        }

        // CSS classes
        $classes = 'tncfb-flipbook-image-link';
        if ( $class_name ) {
            $classes .= ' ' . $class_name;
        }

        // href
        $href   = ( 'same_tab' === $mode ) ? esc_url( $viewer_url ) : '#';
        $target = ( 'new_tab' === $mode ) ? '_blank' : '';

        // Image style
        $img_style = 'display:block;height:auto;';
        if ( $image_w ) {
            $img_style .= 'width:' . esc_attr( $image_w ) . ';';
        } else {
            $img_style .= 'max-width:100%;';
        }

        // Build tag
        $html  = '<a class="' . esc_attr( $classes ) . '"';
        $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 ) . '"';
            $popup_theme = sanitize_key( $attributes['popupTheme'] ?? 'dark' );
            if ( 'light' === $popup_theme ) {
                $html .= ' data-tncfb-popup-theme="light"';
            }
        }
        if ( $target ) {
            $html .= ' target="' . esc_attr( $target ) . '"';
        }
        $rel_parts = array();
        if ( ! empty( $attributes['nofollow'] ) ) {
            $rel_parts[] = 'nofollow';
        }
        if ( 'new_tab' === $mode ) {
            $rel_parts[] = 'noopener';
        }
        if ( $rel_parts ) {
            $html .= ' rel="' . esc_attr( implode( ' ', $rel_parts ) ) . '"';
        }

        $html .= '>';
        $html .= '<img src="' . esc_url( $image_url ) . '" alt="' . esc_attr( $image_alt ) . '" style="' . esc_attr( $img_style ) . '">';
        $html .= '</a>';

        // Ensure frontend assets are enqueued
        wp_enqueue_script( 'tncfb3d-frontend' );
        wp_enqueue_style( 'tncfb3d-frontend' );

        /**
         * @hook tncfb3d_image_link_block_output
         * @param string $html       Rendered image-link block HTML.
         * @param array  $attributes Block attributes.
         * @param int    $post_id    Flipbook post ID.
         * @return string
         */
        return apply_filters( 'tncfb3d_image_link_block_output', $html, $attributes, $post_id );
    }

    // ── Editor assets ─────────────────────────────────────────────────────────

    public static function enqueue_editor_assets() {
        // Script already registered at init - just enqueue and localize here
        wp_enqueue_script( 'tncfb3d-blocks' );

        // Pass flipbook list to editor for the selector dropdown
        $flipbooks = get_posts( array(
            'post_type'      => TNC_FLIPBOOK_3D_CPT,
            'posts_per_page' => 200,
            'post_status'    => 'publish',
            'orderby'        => 'title',
            'order'          => 'ASC',
        ) );

        $list = array();
        foreach ( $flipbooks as $fb ) {
            $list[] = array( 'id' => $fb->ID, 'title' => $fb->post_title );
        }

        $data = array(
            'flipbooks'  => $list,
            'pluginUrl'  => TNC_FLIPBOOK_3D_URL,
            'homeUrl'    => home_url( '/' ),
            'strings'    => array(
                'selectFlipbook'  => __( '— Select a FlipBook —', 'tnc-flipbook-3d-lite' ),
                'noFlipbooks'     => __( 'No FlipBooks found. Create one first.', 'tnc-flipbook-3d-lite' ),
                'viewFlipbook'    => __( 'View FlipBook', 'tnc-flipbook-3d-lite' ),
                'popup'           => __( 'Popup',         'tnc-flipbook-3d-lite' ),
                'newTab'          => __( 'New Tab',       'tnc-flipbook-3d-lite' ),
                'sameTab'         => __( 'Same Tab',      'tnc-flipbook-3d-lite' ),
            ),
        );

        /**
         * @hook tncfb3d_block_editor_data
         * @param array $data Localized data passed to the block editor scripts.
         * @return array
         */
        $data = apply_filters( 'tncfb3d_block_editor_data', $data );

        wp_localize_script( 'tncfb3d-blocks', 'tncfb3dBlockData', $data );

        // Editor CSS for all blocks
        wp_enqueue_style(
            'tncfb3d-blocks-editor',
            TNC_FLIPBOOK_3D_URL . 'blocks/editor.css',
            array(),
            TNC_FLIPBOOK_3D_VERSION
        );
    }
}
