<?php
declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

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

final class SidebarWidget extends WidgetBase {
	public function get_type(): string { return 'sidebar'; }
	public function get_title(): string { return 'Barra lateral'; }
	public function get_icon(): string { return 'sidebar'; }
	public function get_defaults(): array {
		return array( 'sidebar' => 'sidebar-1' );
	}
	public function sanitize_settings( array $settings ): array {
		return array( 'sidebar' => sanitize_key( (string) ( $settings['sidebar'] ?? 'sidebar-1' ) ) );
	}
	public function render( Node $node, array $context = array() ): string {
		$id = (string) ( $node->settings['sidebar'] ?? 'sidebar-1' );
		if ( ! empty( $context['editor'] ) ) {
			return '<div class="ab-sidebar ab-sidebar--editor">Sidebar: <code>' . esc_html( $id ) . '</code></div>';
		}
		if ( ! is_active_sidebar( $id ) ) {
			// Try common fallbacks.
			foreach ( array( $id, 'sidebar-1', 'primary', 'main-sidebar' ) as $try ) {
				if ( is_active_sidebar( $try ) ) {
					$id = $try;
					break;
				}
			}
		}
		if ( ! is_active_sidebar( $id ) ) {
			return '';
		}
		ob_start();
		echo '<div class="ab-sidebar">';
		dynamic_sidebar( $id );
		echo '</div>';
		return (string) ob_get_clean();
	}
}
