<?php
declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

use AuraBuilder\Document\Node;
use AuraBuilder\Widgets\WidgetBase;

final class ShortcodeWidget extends WidgetBase {
	public function get_type(): string { return 'shortcode'; }
	public function get_title(): string { return 'Shortcode'; }
	public function get_icon(): string { return 'shortcode'; }
	public function get_defaults(): array {
		return array( 'code' => '' );
	}
	public function sanitize_settings( array $settings ): array {
		// Keep brackets for shortcodes; strip dangerous tags only.
		$code = (string) ( $settings['code'] ?? '' );
		$code = wp_check_invalid_utf8( $code );
		// Limit length.
		if ( strlen( $code ) > 5000 ) {
			$code = substr( $code, 0, 5000 );
		}
		return array( 'code' => $code );
	}
	public function render( Node $node, array $context = array() ): string {
		$code = trim( (string) ( $node->settings['code'] ?? '' ) );
		if ( $code === '' ) {
			return ! empty( $context['editor'] ) ? '<div class="ab-shortcode ab-empty">Shortcode — ex: [gallery]</div>' : '';
		}
		if ( ! empty( $context['editor'] ) ) {
			return '<div class="ab-shortcode ab-shortcode--editor"><code>' . esc_html( $code ) . '</code></div>';
		}
		return '<div class="ab-shortcode">' . do_shortcode( $code ) . '</div>';
	}
}
