<?php
// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound -- Template variables are scoped when required inside the block render callback.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

require_once dirname( __DIR__, 3 ) . '/includes/block-css-generator.php';

// ─── Tag & identity ───────────────────────────────────────────────────────────

$tag_name     = isset( $attributes['tagName'] ) ? tag_escape( $attributes['tagName'] ) : 'div'; // Box is a container, defaults to <div>.
$anchor       = isset( $attributes['anchor'] ) ? sanitize_title( $attributes['anchor'] ) : '';
$unique_class = isset( $attributes['uniqueClass'] ) ? sanitize_html_class( $attributes['uniqueClass'] ) : '';
if ( empty( $unique_class ) ) {
	$unique_class = sanitize_html_class( 'axb-' . wp_unique_id() );
}

// Additional CSS class(es) entered by the user in the editor.
$custom_class = isset( $attributes['className'] ) ? sanitize_text_field( $attributes['className'] ) : '';

// ─── Wrapper attributes ───────────────────────────────────────────────────────
// Built manually (not get_block_wrapper_attributes) so WordPress does not inject
// has-global-padding / is-layout-constrained / wp-block-* helper classes.

$extra_attrs = [ 'class' => trim( 'axcelersblocks-box ' . $unique_class . ( $custom_class ? ' ' . $custom_class : '' ) ) ];
if ( $anchor ) {
	$extra_attrs['id'] = $anchor;
}
if ( ! empty( $attributes['align'] ) ) {
	$align = sanitize_key( $attributes['align'] );
	if ( in_array( $align, [ 'wide', 'full', 'left', 'right', 'center' ], true ) ) {
		$extra_attrs['class'] .= ' align' . $align;
	}
}

$attr_pairs = [];
foreach ( $extra_attrs as $key => $value ) {
	if ( $value === '' || $value === null ) {
		continue;
	}
	$attr_pairs[] = sprintf( '%s="%s"', esc_attr( $key ), esc_attr( (string) $value ) );
}
$wrapper_attrs = implode( ' ', $attr_pairs );

// ─── CSS generation & collection ──────────────────────────────────────────────

$devices    = axcelersblocks_get_responsive_devices();
$styles_css = axcelersblocks_generate_block_styles( $unique_class, $devices, $attributes );
$hover_css  = axcelersblocks_generate_block_styles_hover( $unique_class, $devices, $attributes );
axcelersblocks_collect_block_styles( $unique_class, $block, array_merge( $styles_css, $hover_css ) );

// ─── Output (container prints its inner block content) ────────────────────────

printf(
	'<%1$s %2$s>%3$s</%1$s>',
	esc_attr( $tag_name ),
	$wrapper_attrs, // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Built from esc_attr()'d key/value pairs above.
	$content        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Inner block content is already rendered/sanitized by each inner block's own render callback.
);
// phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
