<?php
/**
 * Icon Box Grid widget render layer.
 *
 * Shortcode: [rsmspark_icon_box_grid]
 *
 * @package Rsmspark_Content_Widgets
 */

defined( 'ABSPATH' ) || exit;

/**
 * Rsmspark_Content_Widgets_Widget_Icon_Box_Grid
 *
 * Refactored in compat branch - Phase 2
 */
class Rsmspark_Content_Widgets_Widget_Icon_Box_Grid {

	const REGISTRY_ID = 'icon_box_grid';

	/**
	 * @return void
	 */
	public static function register() {
		Rsmspark_Content_Widgets_Shortcodes::add(
			Rsmspark_Content_Widgets_Registry::shortcode_tag( self::REGISTRY_ID ),
			array( __CLASS__, 'shortcode' ),
			self::REGISTRY_ID
		);

		Rsmspark_Content_Widgets_Blocks::add(
			'icon-box-grid',
			array(
				'api_version'     => 3,
				'title'           => __( 'RSM Icon Box Grid', 'rsm-content-widgets' ),
				'description'     => __( 'Grid of icon, title, and description cards.', 'rsm-content-widgets' ),
				'category'        => Rsmspark_Content_Widgets_Blocks::BLOCK_CATEGORY,
				'icon'            => 'grid-view',
				'keywords'        => array( 'icon', 'grid', 'features', 'rsm' ),
				'supports'        => array( 'html' => false ),
				'attributes'      => self::block_attributes(),
				'render_callback' => array( __CLASS__, 'render_block' ),
			)
		);
	}

	/**
	 * @return array<string, array<string, mixed>>
	 */
	public static function block_attributes() {
		return array(
			'title'   => array( 'type' => 'string', 'default' => '' ),
			'columns' => array( 'type' => 'string', 'default' => '3' ),
			'items'   => array( 'type' => 'array', 'default' => self::default_items() ),
		);
	}

	/**
	 * @return array<int, array<string, string>>
	 */
	public static function default_items() {
		return array(
			array(
				'icon'        => 'dashicons dashicons-yes-alt',
				'title'       => __( 'Easy to use', 'rsm-content-widgets' ),
				'description' => __( 'Drop widgets into any layout.', 'rsm-content-widgets' ),
			),
			array(
				'icon'        => 'dashicons dashicons-admin-customizer',
				'title'       => __( 'Customizable', 'rsm-content-widgets' ),
				'description' => __( 'Tune colors and spacing from settings.', 'rsm-content-widgets' ),
			),
			array(
				'icon'        => 'dashicons dashicons-performance',
				'title'       => __( 'Lightweight', 'rsm-content-widgets' ),
				'description' => __( 'Assets load only when widgets are on the page.', 'rsm-content-widgets' ),
			),
		);
	}

	/**
	 * @param array<string, mixed> $atts Shortcode attributes.
	 * @param string               $content Inner content.
	 * @return string
	 */
	public static function shortcode( $atts, $content = '' ) {
		unset( $content );
		return self::render( self::normalize_atts( is_array( $atts ) ? $atts : array() ) );
	}

	/**
	 * @param array<string, mixed> $attributes Block attributes.
	 * @return string
	 */
	public static function render_block( $attributes, $content = '', $block = null ) {
		unset( $content );
		$attributes = self::merge_block_attributes( $attributes, $block );
		return self::render( self::prepare_template_vars( self::normalize_atts( $attributes ) ) );
	}

	/**
	 * Merge attributes from WP_Block (parsed block JSON is authoritative).
	 *
	 * @param mixed         $attributes Render callback attributes.
	 * @param WP_Block|null $block      Block instance.
	 * @return array<string, mixed>
	 */
	public static function merge_block_attributes( $attributes, $block = null ) {
		$merged = is_array( $attributes ) ? $attributes : array();

		if ( $block instanceof WP_Block ) {
			if ( ! empty( $block->parsed_block['attrs'] ) && is_array( $block->parsed_block['attrs'] ) ) {
				$merged = array_merge( $merged, $block->parsed_block['attrs'] );
			}
			if ( ! empty( $block->attributes ) && is_array( $block->attributes ) ) {
				$merged = array_merge( $merged, $block->attributes );
			}
		}

		return $merged;
	}

	/**
	 * @param array<string, mixed> $atts Raw attributes.
	 * @return array<string, mixed>
	 */
	public static function normalize_atts( array $atts ) {
		$defaults = array(
			'title'   => '',
			'columns' => '3',
			'items'   => self::default_items(),
		);
		$parsed = Rsmspark_Content_Widgets_Render::parse_atts( $atts, $defaults, 'rsmspark_icon_box_grid' );
		$items  = self::coerce_items( $parsed['items'] );

		$columns = (string) $parsed['columns'];
		if ( ! in_array( $columns, array( '2', '3', '4' ), true ) ) {
			$columns = '3';
		}

		return array(
			'title'   => sanitize_text_field( (string) $parsed['title'] ),
			'columns' => $columns,
			'items'   => $items,
		);
	}

	/**
	 * @param mixed $items Raw items from shortcode or block.
	 * @return array<int, array<string, string>>
	 */
	public static function coerce_items( $items ) {
		if ( is_string( $items ) && '' !== $items ) {
			$items = Rsmspark_Content_Widgets_Render::parse_json_attr( $items, self::default_items() );
		}
		if ( ! is_array( $items ) ) {
			$items = self::default_items();
		}

		$clean = self::sanitize_items( $items );
		if ( empty( $clean ) ) {
			$clean = self::sanitize_items( self::default_items() );
		}

		return $clean;
	}

	/**
	 * @param array<string, mixed> $content SiteOrigin content section.
	 * @return array<string, mixed>
	 */
	public static function prepare_from_instance( array $content ) {
		return self::normalize_atts( $content );
	}

	/**
	 * @param array<string, mixed> $instance SiteOrigin widget instance.
	 * @return array<string, mixed>
	 */
	public static function prepare_from_siteorigin_instance( array $instance ) {
		return self::prepare_from_instance(
			Rsmspark_Content_Widgets_Render::section_instance( $instance, 'content' )
		);
	}

	/**
	 * @param array<string, mixed> $attrs Block attributes.
	 * @return array<string, mixed>
	 */
	public static function instance_from_atts( array $attrs ) {
		$normalized = self::normalize_atts( $attrs );

		return array(
			'content' => array(
				'title'   => $normalized['title'],
				'columns' => $normalized['columns'],
				'items'   => $normalized['items'],
			),
		);
	}

	/**
	 * @param array<string, mixed> $instance SiteOrigin or import instance.
	 * @return array<string, mixed>
	 */
	public static function sanitize_instance( array $instance ) {
		unset( $instance['import_export'], $instance['panels_info'] );

		if ( isset( $instance['content'] ) ) {
			return self::instance_from_atts( self::prepare_from_siteorigin_instance( $instance ) );
		}

		return self::instance_from_atts( $instance );
	}

	/**
	 * @param array<int, mixed> $items Raw items.
	 * @return array<int, array<string, string>>
	 */
	public static function sanitize_items( array $items ) {
		$clean = array();
		foreach ( $items as $item ) {
			if ( ! is_array( $item ) ) {
				continue;
			}
			if ( empty( $item['title'] ) && empty( $item['description'] ) ) {
				continue;
			}
			$clean[] = array(
				'icon'        => sanitize_text_field( (string) ( $item['icon'] ?? 'dashicons dashicons-yes-alt' ) ),
				'title'       => sanitize_text_field( (string) ( $item['title'] ?? '' ) ),
				'description' => sanitize_textarea_field( (string) ( $item['description'] ?? '' ) ),
			);
		}
		return $clean;
	}

	/**
	 * @param array<string, mixed> $args Normalized args.
	 * @return array<string, mixed>
	 */
	public static function prepare_template_vars( array $args ) {
		return array(
			'title'      => $args['title'] ?? '',
			'columns'    => $args['columns'] ?? '3',
			'items'      => $args['items'] ?? array(),
			'style_vars' => Rsmspark_Content_Widgets_Render::inline_style_vars(),
		);
	}

	/**
	 * @param array<string, mixed> $args Template variables.
	 * @return string
	 */
	public static function render( array $args ) {
		$vars = isset( $args['style_vars'] ) ? $args : self::prepare_template_vars( $args );
		if ( empty( $vars['items'] ) ) {
			return '';
		}

		return Rsmspark_Content_Widgets_Render::render_template( self::REGISTRY_ID, 'icon-box-grid.php', $vars );
	}
}

function rsmspark_cw_render_icon_box_grid( array $args ) {
	return Rsmspark_Content_Widgets_Widget_Icon_Box_Grid::render( $args );
}
