<?php

if ( ! defined( 'ABSPATH' ) ) { exit; }

class AIEO_Menu_Block {

	const BLOCK_NAME = 'aieo/menu';

	public function __construct() {
		add_action( 'init', array( $this, 'register_block' ) );
		
		
		add_action( 'enqueue_block_editor_assets', array( $this, 'enqueue_block_editor_assets' ) );
	}

	public function enqueue_block_editor_assets() {
		$handle = 'aieo-menu-editor';
		if ( wp_script_is( $handle, 'registered' ) ) {
			wp_enqueue_script( $handle );
		}
	}

	public function register_block() {
		if ( ! function_exists( 'register_block_type' ) ) { return; }

		$handle = 'aieo-menu-editor';
		$rel    = 'assets/js/aieo-menu-editor.js';
		$path   = AIEO_DIR . $rel;
		$url    = plugins_url( $rel, AIEO_FILE );
		$ver    = file_exists( $path ) ? filemtime( $path ) : ( defined( 'AIEO_VERSION' ) ? AIEO_VERSION : false );

		if ( file_exists( $path ) ) {
			wp_register_script(
				$handle,
				$url,
				array( 'wp-blocks', 'wp-block-editor', 'wp-components', 'wp-element', 'wp-i18n' ),
				$ver,
				true
			);
			
			
			$menus = array();
			foreach ( wp_get_nav_menus() as $m ) {
				$menus[] = array(
					'value' => (string) $m->term_id,
					'label' => sprintf( '%s (#%d, %d)', $m->name, $m->term_id, $m->count ),
				);
			}
			wp_localize_script( $handle, 'aieoMenuConfig', array( 'menus' => $menus ) );
		}

		register_block_type( self::BLOCK_NAME, array(
			'api_version'     => 3,
			'title'           => __( 'AIEO Menu', 'ai-eshop-optimizer' ),
			'category'        => 'theme',
			'icon'            => 'menu',
			'description'     => __( 'Render a WordPress menu — inline strip (header) or accordion (footer).', 'ai-eshop-optimizer' ),
			'keywords'        => array( 'menu', 'nav', 'navigation', 'header', 'footer', 'aieo' ),
			'attributes'      => array(
				'menuId'             => array( 'type' => 'number',  'default' => 0 ),
				'mode'               => array( 'type' => 'string',  'default' => 'inline' ),
				'showCatalogTrigger' => array( 'type' => 'boolean', 'default' => true ),
			),
			'supports'        => array(
				'align'   => array( 'wide', 'full' ),
				'spacing' => array( 'margin' => true, 'padding' => true ),
			),
			'editor_script'   => $handle,
			'render_callback' => array( $this, 'render_block' ),
		) );
	}

	public function render_block( $attrs = array() ) {
		$menu_id      = isset( $attrs['menuId'] ) ? (int) $attrs['menuId'] : 0;
		$mode         = isset( $attrs['mode'] ) ? sanitize_key( (string) $attrs['mode'] ) : 'inline';
		$show_trigger = isset( $attrs['showCatalogTrigger'] ) ? (bool) $attrs['showCatalogTrigger'] : true;

		if ( ! $menu_id || ! wp_get_nav_menu_object( $menu_id ) ) {
			return is_admin()
				? '<div class="aieo-menu aieo-menu--empty">' . esc_html__( 'No menu selected — pick one in the block sidebar.', 'ai-eshop-optimizer' ) . '</div>'
				: '';
		}

		return ( 'accordion' === $mode )
			? $this->render_accordion( $menu_id )
			: $this->render_inline( $menu_id, $show_trigger );
	}

	
	private function render_inline( $menu_id, $show_trigger ) {
		$menu_html = wp_nav_menu( array(
			'menu'        => $menu_id,
			'container'   => false,
			'items_wrap'  => '<ul class="aieo-menu__list ff-simple-menu">%3$s</ul>',
			'depth'       => 1,
			'echo'        => false,
			'fallback_cb' => false,
		) );
		if ( ! $menu_html ) { return ''; }

		$trigger = '';
		if ( $show_trigger ) {
			
			
			
			$trigger = '<button type="button" class="aieo-menu__catalog ff-fast-finder-trigger" data-aieo-navigator-trigger '
				. 'aria-label="' . esc_attr__( 'Κατάλογος', 'ai-eshop-optimizer' ) . '" title="' . esc_attr__( 'Κατάλογος', 'ai-eshop-optimizer' ) . '">'
				. '<svg class="ff-fast-finder-icon" width="1em" height="1em" viewBox="0 0 24 24" fill="currentColor" stroke="none" aria-hidden="true">'
				. '<rect x="3" y="4" width="3" height="3"/><rect x="9" y="4.5" width="12" height="2"/>'
				. '<rect x="3" y="10.5" width="3" height="3"/><rect x="9" y="11" width="10" height="2"/>'
				. '<rect x="3" y="17" width="3" height="3"/><rect x="9" y="17.5" width="7" height="2"/>'
				. '</svg><span class="ff-fast-finder-label">' . esc_html__( 'ΚΑΤΑΛΟΓΟΣ', 'ai-eshop-optimizer' ) . '</span>'
				. '</button>';
		}

		return '<nav class="aieo-menu aieo-menu--inline ff-menu-strip" aria-label="' . esc_attr__( 'Κύριο μενού', 'ai-eshop-optimizer' ) . '">'
			. $trigger . $menu_html . '</nav>';
	}

	
	private function render_accordion( $menu_id ) {
		$items = wp_get_nav_menu_items( $menu_id );
		if ( ! $items ) { return ''; }

		$by_parent = array();
		foreach ( $items as $it ) {
			$by_parent[ (int) $it->menu_item_parent ][] = $it;
		}
		$top = isset( $by_parent[0] ) ? $by_parent[0] : array();
		if ( ! $top ) { return ''; }

		$out = '<div class="aieo-menu aieo-menu--accordion ff-footer__sections">';
		foreach ( $top as $parent ) {
			$children = isset( $by_parent[ (int) $parent->ID ] ) ? $by_parent[ (int) $parent->ID ] : array();
			$out .= '<details class="wp-block-details aieo-menu__section ff-footer__section">';
			$out .= '<summary>' . esc_html( $parent->title ) . '</summary>';
			if ( $children ) {
				$out .= '<ul class="aieo-menu__list ff-footer__list">';
				foreach ( $children as $c ) {
					$target = $c->target ? ' target="' . esc_attr( $c->target ) . '"' : '';
					$out   .= '<li><a href="' . esc_url( $c->url ) . '"' . $target . '>' . esc_html( $c->title ) . '</a></li>';
				}
				$out .= '</ul>';
			}
			$out .= '</details>';
		}
		$out .= '</div>';
		return $out;
	}
}

new AIEO_Menu_Block();
