<?php
/**
 * ReadJutsu — server-side render for the readjutsu/reading-time block.
 *
 * Available variables (set by WP block framework):
 *   $attributes (array)    Block attributes.
 *   $content    (string)   Inner block content (empty — no inner blocks).
 *   $block      (WP_Block) Block instance, including $block->context.
 */

defined( 'ABSPATH' ) or exit;

// Resolve post ID: prefer block context (works inside Query Loop), fall back to current post.
$post_id = isset( $block->context['postId'] )
	? (int) $block->context['postId']
	: (int) get_the_ID();

if ( ! $post_id ) {
	return;
}

// When the plugin is globally disabled, show a hint in the editor only.
if ( ! get_option( 'readjutsu_activate' ) ) {
	if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
		echo '<p style="color:#999;font-size:13px;font-style:italic;margin:0">'
			. esc_html__( 'Enable ReadJutsu in Settings → ReadJutsu to preview.', 'readjutsu' )
			. '</p>';
	}
	return;
}

if ( ! class_exists( '\ReadJutsu\Frontend' ) ) {
	require_once READJUTSU_PLUGIN_PATH . 'includes/class-readjutsu-frontend.php';
}

$readjutsu_frontend = new \ReadJutsu\Frontend();

// Base stylesheet: enqueued on the front end here, and loaded into the editor
// canvas automatically via the block's "style" handle (block.json). The dynamic
// custom-property overrides ride on the wrapper's style="" attribute so the
// editor preview is styled without echoing a <style> tag (REST drops enqueued
// inline styles), and the front end stays consistent.
if ( ! ( defined( 'REST_REQUEST' ) && REST_REQUEST ) && ! wp_style_is( 'readjutsu-public', 'enqueued' ) ) {
	wp_enqueue_style( 'readjutsu-public' );
}

printf(
	'<div %1$s style="%2$s">%3$s</div>',
	get_block_wrapper_attributes(), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- escaped by WordPress core.
	esc_attr( $readjutsu_frontend->build_inline_vars() ),
	$readjutsu_frontend->render_badge( $post_id ) // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- render_badge() escapes all dynamic parts.
);
