<?php
/**
 * Gutenberg block registration for BW Map Magnet.
 * Dynamic / server-rendered — delegates to BW_Map_Magnet_Shortcode::render().
 */

defined( 'ABSPATH' ) || exit;

class BW_Map_Magnet_Block {

	private static $instance = null;

	public static function instance() {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	public function boot() {
		add_action( 'init', [ $this, 'register_block' ] );
	}

	public function register_block() {
		$default_zoom = (int) BW_Map_Magnet_Settings::get( 'default_zoom' );

		register_block_type(
			'bw-map-magnet/map',
			[
				'api_version'     => 3,
				'title'           => __( 'BW Map Magnet', 'bw-map-magnet' ),
				'category'        => 'widgets',
				'icon'            => 'location-alt',
				'description'     => __( 'Interactive map with hover-to-zoom item list and category filter.', 'bw-map-magnet' ),
				'keywords'        => [ 'map', 'locations', 'attractions', 'resort' ],
				'supports'        => [ 'html' => false, 'align' => [ 'wide', 'full' ] ],
				'editor_script'   => 'bw-map-magnet-block',
				'attributes'      => [
					'category'  => [ 'type' => 'string', 'default' => '' ],
					'height'    => [ 'type' => 'number', 'default' => 600 ],
					'focusZoom' => [ 'type' => 'number', 'default' => $default_zoom ],
					'filter'    => [ 'type' => 'boolean', 'default' => true ],
				],
				'render_callback' => [ $this, 'render' ],
			]
		);

		wp_register_script(
			'bw-map-magnet-block',
			BW_MAP_MAGNET_URL . 'assets/js/bw-map-magnet-block.js',
			[ 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n', 'wp-server-side-render' ],
			BW_MAP_MAGNET_VERSION,
			true
		);

		wp_localize_script( 'bw-map-magnet-block', 'BwMapMagnetBlockData', [
			'categories'  => $this->category_options(),
			'defaultZoom' => $default_zoom,
		] );

		if ( function_exists( 'wp_set_script_translations' ) ) {
			wp_set_script_translations( 'bw-map-magnet-block', 'bw-map-magnet' );
		}
	}

	private function category_options() {
		$terms = get_terms( [
			'taxonomy'   => BW_MAP_MAGNET_TAX,
			'hide_empty' => false,
		] );
		$out = [ [ 'label' => __( 'All categories', 'bw-map-magnet' ), 'value' => '' ] ];
		if ( ! is_wp_error( $terms ) ) {
			foreach ( $terms as $term ) {
				$out[] = [ 'label' => $term->name, 'value' => $term->slug ];
			}
		}
		return $out;
	}

	public function render( $attributes ) {
		$default_zoom = (int) BW_Map_Magnet_Settings::get( 'default_zoom' );
		$atts = [
			'category'   => isset( $attributes['category'] ) ? (string) $attributes['category'] : '',
			'height'     => isset( $attributes['height'] ) ? (int) $attributes['height'] : 600,
			'focus_zoom' => isset( $attributes['focusZoom'] ) ? (float) $attributes['focusZoom'] : $default_zoom,
			'filter'     => ( ! isset( $attributes['filter'] ) || $attributes['filter'] ) ? 'true' : 'false',
		];
		return BW_Map_Magnet_Shortcode::instance()->render( $atts );
	}
}
