<?php
/**
 * "Flipa Flipbook" Gutenberg block — a dynamic block (no build step) that lets
 * the user pick a flipbook by id and renders it via the shared Flipa_Render.
 */
if ( ! defined( 'ABSPATH' ) ) { exit; }

class Flipa_Block {

	public static function init() {
		add_action( 'init', array( __CLASS__, 'register' ) );
	}

	public static function register() {
		if ( ! function_exists( 'register_block_type' ) ) { return; } // pre-Gutenberg WP

		wp_register_script(
			'flipa-block',
			FLIPA_URL . 'blocks/flipa-block/index.js',
			array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-data', 'wp-i18n', 'wp-server-side-render' ),
			(string) @filemtime( FLIPA_DIR . 'blocks/flipa-block/index.js' ), // mtime → bust cache on every change
			true
		);
		wp_set_script_translations( 'flipa-block', 'flipa-pdf-flipbook' );
		wp_localize_script( 'flipa-block', 'FlipaBlock', array(
			'icon' => FLIPA_URL . 'assets/mark-color.png?v=' . filemtime( FLIPA_DIR . 'assets/mark-color.png' ),
		) );

		register_block_type( 'flipa/flipbook', array(
			'api_version'     => 3,
			'editor_script'   => 'flipa-block',
			'attributes'      => array(
				'id'        => array( 'type' => 'number', 'default' => 0 ),
				'width'     => array( 'type' => 'string', 'default' => '' ),
				'height'    => array( 'type' => 'string', 'default' => '' ),
				'bookAlign' => array( 'type' => 'string', 'default' => '' ),
				'mode'      => array( 'type' => 'string', 'default' => '' ),
				'text'      => array( 'type' => 'string', 'default' => '' ),
				'render'    => array( 'type' => 'string', 'default' => '' ),
			),
			'render_callback' => array( __CLASS__, 'render' ),
		) );
	}

	/** Server render — reuses the shortcode/iframe renderer. */
	public static function render( $attr ) {
		$id = isset( $attr['id'] ) ? absint( $attr['id'] ) : 0;
		if ( ! $id ) {
			return current_user_can( 'edit_posts' )
				? '<div style="padding:10px 14px;border:1px dashed #c00;color:#c00;border-radius:6px;font:14px sans-serif">' . esc_html__( 'Flipa: choose a flipbook in the block settings.', 'flipa-pdf-flipbook' ) . '</div>'
				: '';
		}
		return Flipa_Render::render_book( $id, array(
			'width'  => isset( $attr['width'] )     ? $attr['width']     : '',
			'height' => isset( $attr['height'] )    ? $attr['height']    : '',
			'align'  => isset( $attr['bookAlign'] ) ? $attr['bookAlign'] : '',
			'mode'   => isset( $attr['mode'] )      ? $attr['mode']      : '',
			'text'   => isset( $attr['text'] )      ? $attr['text']      : '',
			'render' => isset( $attr['render'] )    ? $attr['render']    : '',
		) );
	}
}
