<?php
declare(strict_types=1);

namespace AuraBuilder\Widgets\Basic;

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

final class MapsWidget extends WidgetBase {
	public function get_type(): string { return 'google_maps'; }
	public function get_title(): string { return 'Google Maps'; }
	public function get_icon(): string { return 'maps'; }
	public function get_defaults(): array {
		return array(
			'address' => 'São Paulo, Brasil',
			'zoom'    => '14',
			'height'  => '320',
		);
	}
	public function sanitize_settings( array $settings ): array {
		return array(
			'address' => sanitize_text_field( (string) ( $settings['address'] ?? '' ) ),
			'zoom'    => (string) max( 1, min( 21, (int) ( $settings['zoom'] ?? 14 ) ) ),
			'height'  => (string) max( 120, min( 900, (int) ( $settings['height'] ?? 320 ) ) ),
		);
	}
	public function render( Node $node, array $context = array() ): string {
		$addr   = (string) ( $node->settings['address'] ?? '' );
		$zoom   = (int) ( $node->settings['zoom'] ?? 14 );
		$height = (int) ( $node->settings['height'] ?? 320 );
		if ( $addr === '' ) {
			return ! empty( $context['editor'] ) ? '<div class="ab-maps ab-empty">Google Maps — informe o endereço</div>' : '';
		}
		$q   = rawurlencode( $addr );
		$src = 'https://maps.google.com/maps?q=' . $q . '&z=' . $zoom . '&output=embed';
		return '<div class="ab-maps"><iframe src="' . esc_url( $src ) . '" height="' . esc_attr( (string) $height ) . '" loading="lazy" referrerpolicy="no-referrer-when-downgrade" title="Mapa"></iframe></div>';
	}
}
