<?php
/**
 * Advance Mega Sidebar – mobile/sidebar menu that reads menu data from Advance Mega Menu widget.
 *
 * @package Unlockafe_addons\Widgets
 */

namespace Unlockafe_addons\Widgets;

use Elementor\Controls_Manager;
use Elementor\Repeater;
use Elementor\Widget_Base;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Background;
use Elementor\Icons_Manager;
use Unlockafe_addons\Widgets\Advance_Mega_Menu;

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

class Advance_Mega_Sidebar extends Widget_Base {

	public function get_name() {
		return 'unlockafe-advance-mega-sidebar';
	}

	public function get_title() {
		return __( 'Advance Mega Sidebar', 'unlock-addons-for-elementor' );
	}

	public function get_icon() {
		return 'eicon-sidebar ulicon';
	}

	public function get_categories() {
		return [ 'unlockafe-addons' ];
	}

	public function get_keywords() {
		return [ 'mega menu', 'sidebar', 'mobile', 'offcanvas', 'navigation' ];
	}

	public function get_style_depends() {
		return [ 'unlockafe-global', 'unlockafe-advance-mega-sidebar' ];
	}

	public function get_script_depends() {
		return [ 'unlockafe-advance-mega-sidebar' ];
	}

	protected function register_controls() {
		$this->register_content_controls();
		$this->register_style_controls();
	}

	protected function register_content_controls() {
		$this->start_controls_section( 'section_data_source', [
			'label' => __( 'Menu Data Source', 'unlock-addons-for-elementor' ),
			'tab'   => Controls_Manager::TAB_CONTENT,
		] );
		$this->add_control( 'amm_widget_id', [
			'label'       => __( 'Advance Mega Menu Widget ID', 'unlock-addons-for-elementor' ),
			'type'        => Controls_Manager::TEXT,
			'placeholder' => 'abc1234',
			'description' => __( 'Use "Select Advance Mega Menu on this page" below to pick the menu, or enter the widget ID manually (click the Advance Mega Menu widget in the Navigator to see its ID).', 'unlock-addons-for-elementor' ),
		] );
		$this->add_control( 'amm_widget_id_picker', [
			'type'        => Controls_Manager::RAW_HTML,
			'raw'         => '<button type="button" class="button button-secondary unlockafe-ams-pick-amm" style="width:100%; margin-top:6px;">' . esc_html__( 'Select Advance Mega Menu on this page', 'unlock-addons-for-elementor' ) . '</button><p class="unlockafe-ams-pick-help elementor-descriptor" style="margin-top:8px; display:none;"></p>',
			'content_classes' => 'elementor-control-raw-html',
		] );
		$this->end_controls_section();

		$this->start_controls_section( 'section_toggle', [
			'label' => __( 'Toggle Button', 'unlock-addons-for-elementor' ),
			'tab'   => Controls_Manager::TAB_CONTENT,
		] );
		$this->add_control( 'toggle_icon', [
			'label'   => __( 'Icon', 'unlock-addons-for-elementor' ),
			'type'    => Controls_Manager::ICONS,
			'default' => [ 'value' => 'fas fa-bars', 'library' => 'fa-solid' ],
		] );
		$this->add_control( 'toggle_label', [
			'label'   => __( 'Button label (accessibility)', 'unlock-addons-for-elementor' ),
			'type'    => Controls_Manager::TEXT,
			'default' => __( 'Open menu', 'unlock-addons-for-elementor' ),
		] );
		$this->end_controls_section();

		$this->start_controls_section( 'section_sidebar_content', [
			'label' => __( 'Sidebar Content', 'unlock-addons-for-elementor' ),
			'tab'   => Controls_Manager::TAB_CONTENT,
		] );
		$this->add_control( 'show_close', [
			'label'        => __( 'Show close button', 'unlock-addons-for-elementor' ),
			'type'         => Controls_Manager::SWITCHER,
			'return_value' => 'yes',
			'default'      => 'yes',
		] );
		$this->add_control( 'logo_image', [
			'label' => __( 'Logo', 'unlock-addons-for-elementor' ),
			'type'  => Controls_Manager::MEDIA,
		] );
		$this->add_control( 'logo_link', [
			'label'         => __( 'Logo link', 'unlock-addons-for-elementor' ),
			'type'          => Controls_Manager::URL,
			'placeholder'   => home_url( '/' ),
			'show_external' => true,
		] );
		$this->add_control( 'brand_name', [
			'label'       => __( 'Brand name', 'unlock-addons-for-elementor' ),
			'type'        => Controls_Manager::TEXT,
			'placeholder' => get_bloginfo( 'name' ),
			'default'     => '',
		] );
		$this->add_control( 'description_text', [
			'label'   => __( 'Description / Tagline', 'unlock-addons-for-elementor' ),
			'type'    => Controls_Manager::TEXTAREA,
			'rows'    => 3,
			'default' => '',
		] );
		$contact_repeater = new Repeater();
		$contact_repeater->add_control( 'icon', [
			'label' => __( 'Icon', 'unlock-addons-for-elementor' ),
			'type'  => Controls_Manager::ICONS,
			'default' => [ 'value' => 'fas fa-phone', 'library' => 'fa-solid' ],
		] );
		$contact_repeater->add_control( 'label', [
			'label'   => __( 'Label', 'unlock-addons-for-elementor' ),
			'type'    => Controls_Manager::TEXT,
			'default' => __( 'Contact Us 24/7', 'unlock-addons-for-elementor' ),
		] );
		$contact_repeater->add_control( 'value', [
			'label'   => __( 'Value (phone, email, address)', 'unlock-addons-for-elementor' ),
			'type'    => Controls_Manager::TEXT,
			'default' => '',
		] );
		$contact_repeater->add_control( 'link', [
			'label'         => __( 'Link (optional)', 'unlock-addons-for-elementor' ),
			'type'          => Controls_Manager::URL,
			'show_external' => true,
		] );
		$this->add_control( 'contact_items', [
			'label'       => __( 'Contact blocks', 'unlock-addons-for-elementor' ),
			'type'        => Controls_Manager::REPEATER,
			'fields'      => $contact_repeater->get_controls(),
			'default'     => [
				[ 'label' => __( 'Contact Us 24/7', 'unlock-addons-for-elementor' ), 'value' => '+55 (9900) 666 22', 'icon' => [ 'value' => 'fas fa-phone', 'library' => 'fa-solid' ] ],
				[ 'label' => __( 'Contact Mail', 'unlock-addons-for-elementor' ), 'value' => 'info@demo.com', 'icon' => [ 'value' => 'fas fa-envelope', 'library' => 'fa-solid' ] ],
				[ 'label' => __( 'Contact Location', 'unlock-addons-for-elementor' ), 'value' => '18/2, Topkhana Road, Australia.', 'icon' => [ 'value' => 'fas fa-map-marker-alt', 'library' => 'fa-solid' ] ],
			],
			'title_field' => '{{{ label }}}',
		] );
		$this->add_control( 'footer_text', [
			'label'   => __( 'Footer / Copyright', 'unlock-addons-for-elementor' ),
			'type'    => Controls_Manager::TEXT,
			'default' => '© ' . gmdate( 'Y' ) . ' All rights reserved.',
		] );
		$this->add_control( 'sidebar_position', [
			'label'   => __( 'Sidebar position', 'unlock-addons-for-elementor' ),
			'type'    => Controls_Manager::SELECT,
			'options' => [
				'right' => __( 'From right', 'unlock-addons-for-elementor' ),
				'left'  => __( 'From left', 'unlock-addons-for-elementor' ),
			],
			'default' => 'right',
		] );
		$this->add_control( 'hide_on_desktop', [
			'label'        => __( 'Hide on desktop', 'unlock-addons-for-elementor' ),
			'type'         => Controls_Manager::SWITCHER,
			'description'  => __( 'When enabled, this sidebar menu will be hidden on desktop devices (desktop layout from theme/header will show instead).', 'unlock-addons-for-elementor' ),
			'return_value' => 'yes',
			'default'      => '',
		] );
		$this->add_control( 'hide_on_tablet', [
			'label'        => __( 'Hide on tablet', 'unlock-addons-for-elementor' ),
			'type'         => Controls_Manager::SWITCHER,
			'description'  => __( 'When enabled, this sidebar menu will be hidden on tablet. Useful if you only want it on mobile.', 'unlock-addons-for-elementor' ),
			'return_value' => 'yes',
			'default'      => '',
		] );
		$this->end_controls_section();
	}

	protected function register_style_controls() {
		$this->start_controls_section( 'section_style_panel', [
			'label' => __( 'Sidebar panel', 'unlock-addons-for-elementor' ),
			'tab'   => Controls_Manager::TAB_STYLE,
		] );
		$this->add_group_control( Group_Control_Background::get_type(), [
			'name'     => 'panel_background',
			'types'    => [ 'classic', 'gradient' ],
			'selector' => '{{WRAPPER}} .unlockafe-ams-panel',
			'default'  => 'classic',
			'fields_options' => [
				'background' => [ 'default' => 'classic' ],
				'color'      => [ 'default' => '#000000' ],
			],
		] );
		$this->add_control( 'panel_width', [
			'label'      => __( 'Panel width (desktop)', 'unlock-addons-for-elementor' ),
			'type'       => Controls_Manager::SLIDER,
			'size_units' => [ 'px', '%' ],
			'range'      => [ 'px' => [ 'min' => 320, 'max' => 1200 ], '%' => [ 'min' => 30, 'max' => 100 ] ],
			'default'    => [ 'unit' => '%', 'size' => 70 ],
			'selectors'  => [ '{{WRAPPER}} .unlockafe-ams-panel' => 'width: {{SIZE}}{{UNIT}}; max-width: 100%;' ],
		] );
		$this->add_control( 'panel_text_color', [
			'label'     => __( 'Text color', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::COLOR,
			'default'   => '#ffffff',
			'selectors' => [
				'{{WRAPPER}} .unlockafe-ams-panel' => 'color: {{VALUE}};',
				'{{WRAPPER}} .unlockafe-ams-nav__link' => 'color: {{VALUE}};',
				'{{WRAPPER}} .unlockafe-ams-desc' => 'color: {{VALUE}};',
				'{{WRAPPER}} .unlockafe-ams-footer' => 'color: {{VALUE}};',
				'{{WRAPPER}} .unlockafe-ams-contact-item' => 'color: {{VALUE}};',
			],
		] );
		$this->end_controls_section();

		$this->start_controls_section( 'section_style_toggle', [
			'label' => __( 'Toggle button', 'unlock-addons-for-elementor' ),
			'tab'   => Controls_Manager::TAB_STYLE,
		] );
		$this->add_control( 'toggle_color', [
			'label'     => __( 'Icon color', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::COLOR,
			'selectors' => [ '{{WRAPPER}} .unlockafe-ams-toggle' => 'color: {{VALUE}};' ],
		] );
		$this->add_control( 'toggle_size', [
			'label'      => __( 'Icon size', 'unlock-addons-for-elementor' ),
			'type'       => Controls_Manager::SLIDER,
			'size_units' => [ 'px' ],
			'range'      => [ 'px' => [ 'min' => 16, 'max' => 48 ] ],
			'default'    => [ 'size' => 24 ],
			'selectors'  => [ '{{WRAPPER}} .unlockafe-ams-toggle' => 'font-size: {{SIZE}}{{UNIT}};' ],
		] );
		$this->end_controls_section();

		$this->start_controls_section( 'section_style_close', [
			'label' => __( 'Close button', 'unlock-addons-for-elementor' ),
			'tab'   => Controls_Manager::TAB_STYLE,
		] );
		$this->add_control( 'close_bg_color', [
			'label'     => __( 'Background', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::COLOR,
			'default'   => '#ffffff',
			'selectors' => [ '{{WRAPPER}} .unlockafe-ams-close' => 'background-color: {{VALUE}};' ],
		] );
		$this->add_control( 'close_icon_color', [
			'label'     => __( 'Icon color', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::COLOR,
			'default'   => '#000000',
			'selectors' => [ '{{WRAPPER}} .unlockafe-ams-close' => 'color: {{VALUE}};' ],
		] );
		$this->add_control( 'close_size', [
			'label'      => __( 'Size', 'unlock-addons-for-elementor' ),
			'type'       => Controls_Manager::SLIDER,
			'size_units' => [ 'px' ],
			'range'      => [ 'px' => [ 'min' => 32, 'max' => 80 ] ],
			'default'    => [ 'size' => 48 ],
			'selectors'  => [ '{{WRAPPER}} .unlockafe-ams-close' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}}; font-size: calc({{SIZE}}{{UNIT}} * 0.5);' ],
		] );
		$this->end_controls_section();

		$this->start_controls_section( 'section_style_menu', [
			'label' => __( 'Menu items', 'unlock-addons-for-elementor' ),
			'tab'   => Controls_Manager::TAB_STYLE,
		] );
		$this->add_group_control( Group_Control_Typography::get_type(), [
			'name'     => 'menu_typography',
			'selector' => '{{WRAPPER}} .unlockafe-ams-nav__link',
		] );
		$this->add_control( 'menu_item_spacing', [
			'label'      => __( 'Item spacing', 'unlock-addons-for-elementor' ),
			'type'       => Controls_Manager::SLIDER,
			'size_units' => [ 'px' ],
			'range'      => [ 'px' => [ 'min' => 0, 'max' => 40 ] ],
			'default'    => [ 'size' => 12 ],
			'selectors'  => [ '{{WRAPPER}} .unlockafe-ams-nav__item' => 'margin-bottom: {{SIZE}}{{UNIT}};' ],
		] );
		$this->end_controls_section();

		$this->start_controls_section( 'section_style_brand', [
			'label' => __( 'Logo & description', 'unlock-addons-for-elementor' ),
			'tab'   => Controls_Manager::TAB_STYLE,
		] );
		$this->add_control( 'logo_max_height', [
			'label'      => __( 'Logo height', 'unlock-addons-for-elementor' ),
			'type'       => Controls_Manager::SLIDER,
			'size_units' => [ 'px' ],
			'range'      => [ 'px' => [ 'min' => 16, 'max' => 120 ] ],
			'selectors'  => [ '{{WRAPPER}} .unlockafe-ams-logo__img' => 'max-height: {{SIZE}}{{UNIT}};' ],
		] );
		$this->add_group_control( Group_Control_Typography::get_type(), [
			'name'     => 'brand_name_typography',
			'label'    => __( 'Brand name typography', 'unlock-addons-for-elementor' ),
			'selector' => '{{WRAPPER}} .unlockafe-ams-brand-name',
		] );
		$this->add_control( 'brand_name_color', [
			'label'     => __( 'Brand name color', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::COLOR,
			'selectors' => [ '{{WRAPPER}} .unlockafe-ams-brand-name' => 'color: {{VALUE}};' ],
		] );
		$this->add_group_control( Group_Control_Typography::get_type(), [
			'name'     => 'description_typography',
			'label'    => __( 'Description typography', 'unlock-addons-for-elementor' ),
			'selector' => '{{WRAPPER}} .unlockafe-ams-desc',
		] );
		$this->add_control( 'description_color', [
			'label'     => __( 'Description color', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::COLOR,
			'selectors' => [ '{{WRAPPER}} .unlockafe-ams-desc' => 'color: {{VALUE}};' ],
		] );
		$this->end_controls_section();

		$this->start_controls_section( 'section_style_contact', [
			'label' => __( 'Contact info', 'unlock-addons-for-elementor' ),
			'tab'   => Controls_Manager::TAB_STYLE,
		] );
		$this->add_group_control( Group_Control_Typography::get_type(), [
			'name'     => 'contact_label_typography',
			'label'    => __( 'Label typography', 'unlock-addons-for-elementor' ),
			'selector' => '{{WRAPPER}} .unlockafe-ams-contact-item__label',
		] );
		$this->add_group_control( Group_Control_Typography::get_type(), [
			'name'     => 'contact_value_typography',
			'label'    => __( 'Value typography', 'unlock-addons-for-elementor' ),
			'selector' => '{{WRAPPER}} .unlockafe-ams-contact-item__value',
		] );
		$this->add_control( 'contact_label_color', [
			'label'     => __( 'Label color', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::COLOR,
			'selectors' => [ '{{WRAPPER}} .unlockafe-ams-contact-item__label' => 'color: {{VALUE}};' ],
		] );
		$this->add_control( 'contact_value_color', [
			'label'     => __( 'Value color', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::COLOR,
			'selectors' => [ '{{WRAPPER}} .unlockafe-ams-contact-item__value' => 'color: {{VALUE}};' ],
		] );
		$this->add_control( 'contact_icon_color', [
			'label'     => __( 'Icon color', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::COLOR,
			'selectors' => [ '{{WRAPPER}} .unlockafe-ams-contact-item__icon' => 'color: {{VALUE}};' ],
		] );
		$this->add_control( 'contact_icon_bg', [
			'label'     => __( 'Icon background', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::COLOR,
			'selectors' => [ '{{WRAPPER}} .unlockafe-ams-contact-item__icon' => 'background-color: {{VALUE}};' ],
		] );
		$this->add_control( 'contact_icon_border', [
			'label'     => __( 'Icon border color', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::COLOR,
			'selectors' => [ '{{WRAPPER}} .unlockafe-ams-contact-item__icon' => 'border-color: {{VALUE}};' ],
		] );
		$this->add_control( 'contact_icon_size', [
			'label'      => __( 'Icon size', 'unlock-addons-for-elementor' ),
			'type'       => Controls_Manager::SLIDER,
			'size_units' => [ 'px' ],
			'range'      => [ 'px' => [ 'min' => 10, 'max' => 40 ] ],
			'selectors'  => [
				'{{WRAPPER}} .unlockafe-ams-contact-item__icon svg' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
			],
		] );
		$this->add_control( 'contact_row_gap', [
			'label'      => __( 'Item spacing', 'unlock-addons-for-elementor' ),
			'type'       => Controls_Manager::SLIDER,
			'size_units' => [ 'px' ],
			'range'      => [ 'px' => [ 'min' => 0, 'max' => 40 ] ],
			'selectors'  => [ '{{WRAPPER}} .unlockafe-ams-contact' => 'gap: {{SIZE}}{{UNIT}};' ],
		] );
		$this->end_controls_section();

		$this->start_controls_section( 'section_style_footer', [
			'label' => __( 'Footer / copyright', 'unlock-addons-for-elementor' ),
			'tab'   => Controls_Manager::TAB_STYLE,
		] );
		$this->add_group_control( Group_Control_Typography::get_type(), [
			'name'     => 'footer_typography',
			'selector' => '{{WRAPPER}} .unlockafe-ams-footer',
		] );
		$this->add_control( 'footer_color', [
			'label'     => __( 'Text color', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::COLOR,
			'selectors' => [ '{{WRAPPER}} .unlockafe-ams-footer' => 'color: {{VALUE}};' ],
		] );
		$this->add_control( 'footer_align', [
			'label'     => __( 'Alignment', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::CHOOSE,
			'options'   => [
				'left'   => [ 'title' => __( 'Left', 'unlock-addons-for-elementor' ), 'icon' => 'eicon-text-align-left' ],
				'center' => [ 'title' => __( 'Center', 'unlock-addons-for-elementor' ), 'icon' => 'eicon-text-align-center' ],
				'right'  => [ 'title' => __( 'Right', 'unlock-addons-for-elementor' ), 'icon' => 'eicon-text-align-right' ],
			],
			'default'   => '',
			'toggle'    => true,
			'selectors' => [ '{{WRAPPER}} .unlockafe-ams-footer' => 'text-align: {{VALUE}};' ],
		] );
		$this->end_controls_section();

		$this->start_controls_section( 'section_style_cards', [
			'label' => __( 'Submenu cards', 'unlock-addons-for-elementor' ),
			'tab'   => Controls_Manager::TAB_STYLE,
		] );
		$this->add_control( 'card_title_color', [
			'label'     => __( 'Title color', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::COLOR,
			'selectors' => [ '{{WRAPPER}} .unlockafe-ams-card__title' => 'color: {{VALUE}};' ],
		] );
		$this->add_control( 'card_subtitle_color', [
			'label'     => __( 'Subtitle color', 'unlock-addons-for-elementor' ),
			'type'      => Controls_Manager::COLOR,
			'selectors' => [ '{{WRAPPER}} .unlockafe-ams-card__subtitle' => 'color: {{VALUE}};' ],
		] );
		$this->end_controls_section();
	}

	/**
	 * Get menu data from linked Advance Mega Menu widget (repeater items or WP menu tree).
	 *
	 * @return array{ type: string, menus: array } Either ['type' => 'repeater', 'menus' => menu_items] or ['type' => 'wp_menu', 'menus' => tree].
	 */
	private function get_menu_data() {
		$settings = $this->get_settings_for_display();
		$widget_id = isset( $settings['amm_widget_id'] ) ? trim( (string) $settings['amm_widget_id'] ) : '';
		$post_id  = get_the_ID();
		// When used inside Elementor templates (header/footer/theme builder),
		// the current document is not the same as get_the_ID(). Prefer the
		// active Elementor document ID if available so we can read the
		// Advance Mega Menu widget from the same template.
		if ( class_exists( '\Elementor\Plugin' ) ) {
			try {
				$doc = \Elementor\Plugin::instance()->documents->get_current();
				if ( $doc && method_exists( $doc, 'get_main_id' ) ) {
					$doc_id = (int) $doc->get_main_id();
					if ( $doc_id > 0 ) {
						$post_id = $doc_id;
					}
				}
			} catch ( \Throwable $e ) {
				// Fallback silently to get_the_ID().
			}
		}
		if ( $post_id <= 0 ) {
			return [ 'type' => 'none', 'menus' => [] ];
		}
		$amm_settings = Advance_Mega_Menu::get_settings_by_widget_id( $post_id, $widget_id );
		if ( $amm_settings === null ) {
			return [ 'type' => 'none', 'menus' => [] ];
		}
		$menu_source = isset( $amm_settings['menu_source'] ) ? $amm_settings['menu_source'] : 'repeater';
		if ( $menu_source === 'repeater' ) {
			$menus = isset( $amm_settings['menu_items'] ) && is_array( $amm_settings['menu_items'] ) ? $amm_settings['menu_items'] : [];
			return [ 'type' => 'repeater', 'menus' => $menus ];
		}
		$wp_menu_id = isset( $amm_settings['wp_menu_id'] ) ? (int) $amm_settings['wp_menu_id'] : 0;
		if ( $wp_menu_id <= 0 ) {
			return [ 'type' => 'none', 'menus' => [] ];
		}
		$items = wp_get_nav_menu_items( $wp_menu_id );
		if ( ! $items || ! is_array( $items ) ) {
			return [ 'type' => 'wp_menu', 'menus' => [] ];
		}
		$top = array_filter( $items, function ( $item ) {
			return (int) $item->menu_item_parent === 0;
		} );
		$top = array_values( $top );
		$tree = [];
		foreach ( $top as $item ) {
			$children = array_filter( $items, function ( $i ) use ( $item ) {
				return (int) $i->menu_item_parent === (int) $item->ID;
			} );
			$tree[] = [
				'menu_label'     => $item->title,
				'menu_link'      => [ 'url' => $item->url, 'is_external' => ( $item->target === '_blank' ), 'nofollow' => false ],
				'menu_type'      => count( $children ) > 0 ? 'mega' : 'simple',
				'submenu_items'  => array_map( function ( $c ) {
					return [
						'title'       => $c->title,
						'description' => '',
						'link'        => [ 'url' => $c->url, 'is_external' => ( $c->target === '_blank' ), 'nofollow' => false ],
						'image'       => [],
					];
				}, array_values( $children ) ),
			];
		}
		return [ 'type' => 'wp_menu', 'menus' => $tree ];
	}

	private function placeholder_image_url( $title ) {
		return 'https://placehold.co/600x400/e2e8f0/64748b?text=' . rawurlencode( $title );
	}

	protected function render() {
		$settings = $this->get_settings_for_display();
		$sid      = 'unlockafe-ams-' . $this->get_id();
		$menu_data = $this->get_menu_data();
		$position = isset( $settings['sidebar_position'] ) && $settings['sidebar_position'] === 'left' ? 'left' : 'right';
		$wrapper_classes = [
			'unlockafe-ams',
			'unlockafe-ams--position-' . $position,
		];
		if ( ( $settings['hide_on_desktop'] ?? '' ) === 'yes' ) {
			$wrapper_classes[] = 'elementor-hidden-desktop';
		}
		if ( ( $settings['hide_on_tablet'] ?? '' ) === 'yes' ) {
			$wrapper_classes[] = 'elementor-hidden-tablet';
		}
		?>
		<div class="<?php echo esc_attr( implode( ' ', $wrapper_classes ) ); ?>" data-ams-id="<?php echo esc_attr( $sid ); ?>">
			<button type="button" class="unlockafe-ams-toggle" data-ams-trigger="<?php echo esc_attr( $sid ); ?>" aria-label="<?php echo esc_attr( $settings['toggle_label'] ?? __( 'Open menu', 'unlock-addons-for-elementor' ) ); ?>" aria-expanded="false" aria-controls="<?php echo esc_attr( $sid ); ?>-panel">
				<?php
				if ( ! empty( $settings['toggle_icon']['value'] ) ) {
					Icons_Manager::render_icon( $settings['toggle_icon'], [ 'aria-hidden' => 'true' ] );
				} else {
					echo '<span class="unlockafe-ams-toggle__bar"></span><span class="unlockafe-ams-toggle__bar"></span><span class="unlockafe-ams-toggle__bar"></span>';
				}
				?>
			</button>

			<div class="unlockafe-ams-backdrop" data-ams-close="<?php echo esc_attr( $sid ); ?>" aria-hidden="true"></div>

			<div id="<?php echo esc_attr( $sid ); ?>-panel" class="unlockafe-ams-panel" role="dialog" aria-label="<?php esc_attr_e( 'Menu', 'unlock-addons-for-elementor' ); ?>" aria-hidden="true">
				<?php if ( ( $settings['show_close'] ?? 'yes' ) === 'yes' ) : ?>
					<button type="button" class="unlockafe-ams-close" data-ams-close="<?php echo esc_attr( $sid ); ?>" aria-label="<?php esc_attr_e( 'Close menu', 'unlock-addons-for-elementor' ); ?>">
						<span aria-hidden="true">&times;</span>
					</button>
				<?php endif; ?>

				<div class="unlockafe-ams-panel__inner">
					<?php if ( ! empty( $settings['logo_image']['url'] ) || ( isset( $settings['brand_name'] ) && trim( $settings['brand_name'] ) !== '' ) ) : ?>
						<div class="unlockafe-ams-logo">
							<?php
							$logo_url = isset( $settings['logo_link']['url'] ) && $settings['logo_link']['url'] !== '' ? $settings['logo_link']['url'] : '';
							$logo_ext = ! empty( $settings['logo_link']['is_external'] );
							$logo_nof = ! empty( $settings['logo_link']['nofollow'] );
							if ( $logo_url !== '' ) {
								echo '<a href="' . esc_url( $logo_url ) . '" class="unlockafe-ams-logo__link"' . ( $logo_ext ? ' target="_blank" rel="noopener noreferrer"' : '' ) . ( $logo_nof ? ' rel="nofollow"' : '' ) . '>';
							}
							if ( ! empty( $settings['logo_image']['url'] ) ) {
								echo '<img src="' . esc_url( $settings['logo_image']['url'] ) . '" alt="' . esc_attr( get_bloginfo( 'name' ) ) . '" class="unlockafe-ams-logo__img" />';
							}
							if ( isset( $settings['brand_name'] ) && trim( $settings['brand_name'] ) !== '' ) {
								echo '<div class="unlockafe-ams-brand-name">' . esc_html( $settings['brand_name'] ) . '</div>';
							}
							if ( $logo_url !== '' ) {
								echo '</a>';
							}
							?>
						</div>
					<?php endif; ?>

					<?php if ( isset( $settings['description_text'] ) && trim( $settings['description_text'] ) !== '' ) : ?>
						<div class="unlockafe-ams-desc"><?php echo wp_kses_post( nl2br( $settings['description_text'] ) ); ?></div>
					<?php endif; ?>

					<?php if ( $menu_data['type'] === 'none' && empty( $menu_data['menus'] ) ) : ?>
						<p class="unlockafe-ams-empty"><?php esc_html_e( 'Select Advance Mega Menu widget ID in sidebar settings.', 'unlock-addons-for-elementor' ); ?></p>
					<?php else : ?>
						<nav class="unlockafe-ams-nav" aria-label="<?php esc_attr_e( 'Sidebar menu', 'unlock-addons-for-elementor' ); ?>">
							<ul class="unlockafe-ams-nav__list">
								<?php
								foreach ( $menu_data['menus'] as $index => $menu ) {
									$this->render_sidebar_menu_item( $menu, $index, $sid );
								}
								?>
							</ul>
						</nav>
					<?php endif; ?>

					<?php if ( ! empty( $settings['contact_items'] ) ) : ?>
						<div class="unlockafe-ams-contact">
							<?php foreach ( $settings['contact_items'] as $contact ) :
								$val = isset( $contact['value'] ) ? trim( $contact['value'] ) : '';
								$lab = isset( $contact['label'] ) ? $contact['label'] : '';
								$link = isset( $contact['link']['url'] ) ? $contact['link']['url'] : '';
								$link_ext = ! empty( $contact['link']['is_external'] );
								?>
								<div class="unlockafe-ams-contact-item">
									<?php if ( ! empty( $contact['icon']['value'] ) ) : ?>
										<span class="unlockafe-ams-contact-item__icon"><?php Icons_Manager::render_icon( $contact['icon'], [ 'aria-hidden' => 'true' ] ); ?></span>
									<?php endif; ?>
									<div class="unlockafe-ams-contact-item__text">
										<?php if ( $lab !== '' ) : ?><span class="unlockafe-ams-contact-item__label"><?php echo esc_html( $lab ); ?></span><?php endif; ?>
										<?php if ( $val !== '' ) : ?>
											<?php if ( $link !== '' ) : ?>
												<a href="<?php echo esc_url( $link ); ?>" class="unlockafe-ams-contact-item__value"<?php echo $link_ext ? ' target="_blank" rel="noopener noreferrer"' : ''; ?>><?php echo esc_html( $val ); ?></a>
											<?php else : ?>
												<span class="unlockafe-ams-contact-item__value"><?php echo esc_html( $val ); ?></span>
											<?php endif; ?>
										<?php endif; ?>
									</div>
								</div>
							<?php endforeach; ?>
						</div>
					<?php endif; ?>

					<?php if ( isset( $settings['footer_text'] ) && trim( $settings['footer_text'] ) !== '' ) : ?>
						<div class="unlockafe-ams-footer"><?php echo esc_html( $settings['footer_text'] ); ?></div>
					<?php endif; ?>
				</div>
			</div>
		</div>
		<?php
	}

	private function render_sidebar_menu_item( array $menu, int $index, string $sid ) {
		$label    = isset( $menu['menu_label'] ) ? $menu['menu_label'] : '';
		$link     = isset( $menu['menu_link']['url'] ) ? $menu['menu_link']['url'] : '#';
		$external = ! empty( $menu['menu_link']['is_external'] );
		$nofollow = ! empty( $menu['menu_link']['nofollow'] );
		$rel      = array_filter( [ $external ? 'noopener noreferrer' : '', $nofollow ? 'nofollow' : '' ] );
		$type     = isset( $menu['menu_type'] ) ? $menu['menu_type'] : 'simple';
		$layout   = isset( $menu['menu_layout'] ) ? $menu['menu_layout'] : 'blocks';
		$page_id  = 0;
		if ( $type === 'mega' && $layout === 'custom' ) {
			$page_id = isset( $menu['custom_layout_page_id'] ) ? (int) $menu['custom_layout_page_id'] : 0;
		}

		// Build submenu items based on menu type.
		$subitems = [];
		if ( $type === 'dropdown' ) {
			$dropdown_items = isset( $menu['dropdown_items'] ) && is_array( $menu['dropdown_items'] ) ? $menu['dropdown_items'] : [];
			$subitems       = array_map(
				function ( $item ) {
					$label = isset( $item['label'] ) ? $item['label'] : '';
					$link  = isset( $item['link'] ) && is_array( $item['link'] ) ? $item['link'] : [ 'url' => '#', 'is_external' => false, 'nofollow' => false ];
					return [
						'title'       => $label,
						'description' => '',
						'link'        => $link,
						'image'       => [],
						'category_id' => '',
					];
				},
				$dropdown_items
			);
		} else {
			$subitems = isset( $menu['submenu_items'] ) && is_array( $menu['submenu_items'] ) ? $menu['submenu_items'] : [];
		}

		if ( $type === 'mega' && $layout === 'custom' ) {
			// Custom Elementor page: show toggle if a page is selected.
			$has_sub = $page_id > 0;
		} else {
			$has_sub = ( $type === 'mega' || $type === 'dropdown' ) && count( $subitems ) > 0;
		}
		$item_id  = $sid . '-item-' . $index;
		?>
		<li class="unlockafe-ams-nav__item<?php echo $has_sub ? ' unlockafe-ams-nav__item--has-sub' : ''; ?>">
			<div class="unlockafe-ams-nav__row">
				<a href="<?php echo esc_url( $link ); ?>" class="unlockafe-ams-nav__link"<?php echo $external ? ' target="_blank"' : ''; ?><?php echo ! empty( $rel ) ? ' rel="' . esc_attr( implode( ' ', $rel ) ) . '"' : ''; ?>><?php echo esc_html( $label ); ?></a>
				<?php if ( $has_sub ) : ?>
					<button type="button" class="unlockafe-ams-nav__toggle" data-ams-expand="<?php echo esc_attr( $item_id ); ?>" aria-expanded="false" aria-controls="<?php echo esc_attr( $item_id ); ?>"><span aria-hidden="true">+</span></button>
				<?php endif; ?>
			</div>
			<?php if ( $has_sub ) : ?>
				<div id="<?php echo esc_attr( $item_id ); ?>" class="unlockafe-ams-sub unlockafe-ams-sub--<?php echo esc_attr( $type ); ?>" hidden>
					<?php if ( $type === 'mega' ) : ?>
						<?php
						if ( $layout === 'custom' ) {
							// Render selected Elementor page inside the sidebar panel.
							?>
							<div class="unlockafe-ams-sub__inner unlockafe-ams-sub__inner--custom">
								<?php
								if ( $page_id > 0 && class_exists( '\Elementor\Plugin' ) ) {
									$content = \Elementor\Plugin::instance()->frontend->get_builder_content_for_display( $page_id );
									echo $content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
								} else {
									?>
									<p class="unlockafe-ams-empty"><?php esc_html_e( 'Select an Elementor page in Mega Menu Settings → Layout → Custom.', 'unlock-addons-for-elementor' ); ?></p>
									<?php
								}
								?>
							</div>
							<?php
						} else {
							$categories = isset( $menu['categories'] ) && is_array( $menu['categories'] ) ? $menu['categories'] : [];
							?>
							<div class="unlockafe-ams-sub__inner">
								<?php if ( count( $categories ) > 0 ) : ?>
									<div class="unlockafe-ams-sub-tabs" role="tablist" aria-label="<?php esc_attr_e( 'Categories', 'unlock-addons-for-elementor' ); ?>">
										<?php
										$all_label = ( $layout === 'solutions' ) ? __( 'All Solutions', 'unlock-addons-for-elementor' ) : __( 'All Blocks', 'unlock-addons-for-elementor' );
										?>
										<button type="button" class="unlockafe-ams-sub-tab is-active" data-ams-cat=""><?php echo esc_html( $all_label ); ?></button>
										<?php foreach ( $categories as $cat ) :
											$cid = isset( $cat['category_id'] ) ? trim( (string) $cat['category_id'] ) : '';
											if ( $cid === '' || $cid === 'all' ) {
												continue;
											}
											$lab = isset( $cat['category_label'] ) ? $cat['category_label'] : $cid;
											?>
											<button type="button" class="unlockafe-ams-sub-tab" data-ams-cat="<?php echo esc_attr( $cid ); ?>"><?php echo esc_html( $lab ); ?></button>
										<?php endforeach; ?>
									</div>
								<?php endif; ?>
								<div class="unlockafe-ams-sub__grid">
									<?php foreach ( $subitems as $sub ) : ?>
										<?php $this->render_sidebar_submenu_card( $sub ); ?>
									<?php endforeach; ?>
								</div>
							</div>
							<?php
						}
						?>
					<?php elseif ( $type === 'dropdown' ) : ?>
						<ul class="unlockafe-ams-sub__list">
							<?php foreach ( $subitems as $sub ) : ?>
								<?php $this->render_sidebar_submenu_link( $sub ); ?>
							<?php endforeach; ?>
						</ul>
					<?php endif; ?>
				</div>
			<?php endif; ?>
		</li>
		<?php
	}

	private function render_sidebar_submenu_link( array $sub ) {
		$title = isset( $sub['title'] ) ? $sub['title'] : '';
		$desc  = isset( $sub['description'] ) ? $sub['description'] : '';
		$link  = isset( $sub['link']['url'] ) ? $sub['link']['url'] : '#';
		$ext   = ! empty( $sub['link']['is_external'] );
		$nof   = ! empty( $sub['link']['nofollow'] );
		$rel   = array_filter( [ $ext ? 'noopener noreferrer' : '', $nof ? 'nofollow' : '' ] );
		?>
		<li class="unlockafe-ams-sub__item">
			<a href="<?php echo esc_url( $link ); ?>" class="unlockafe-ams-sub__link"<?php echo $ext ? ' target="_blank"' : ''; ?><?php echo ! empty( $rel ) ? ' rel="' . esc_attr( implode( ' ', $rel ) ) . '"' : ''; ?>>
				<span class="unlockafe-ams-sub__link-label"><?php echo esc_html( $title ); ?></span>
				<?php if ( $desc !== '' ) : ?>
					<span class="unlockafe-ams-sub__link-desc"><?php echo esc_html( $desc ); ?></span>
				<?php endif; ?>
			</a>
		</li>
		<?php
	}

	private function render_sidebar_submenu_card( array $sub ) {
		$title = isset( $sub['title'] ) ? $sub['title'] : '';
		$desc  = isset( $sub['description'] ) ? $sub['description'] : '';
		$link  = isset( $sub['link']['url'] ) ? $sub['link']['url'] : '#';
		$ext   = ! empty( $sub['link']['is_external'] );
		$nof   = ! empty( $sub['link']['nofollow'] );
		$rel   = array_filter( [ $ext ? 'noopener noreferrer' : '', $nof ? 'nofollow' : '' ] );
		$img   = isset( $sub['image']['url'] ) ? $sub['image']['url'] : '';
		if ( $img === '' && $title !== '' ) {
			$img = $this->placeholder_image_url( $title );
		}
		$cat_id = isset( $sub['category_id'] ) ? trim( (string) $sub['category_id'] ) : '';
		$cat_label = $cat_id;
		?>
		<div class="unlockafe-ams-card"<?php echo $cat_id !== '' ? ' data-category="' . esc_attr( $cat_id ) . '"' : ''; ?>>
			<a href="<?php echo esc_url( $link ); ?>" class="unlockafe-ams-card__link"<?php echo $ext ? ' target="_blank"' : ''; ?><?php echo ! empty( $rel ) ? ' rel="' . esc_attr( implode( ' ', $rel ) ) . '"' : ''; ?>>
				<?php if ( $img !== '' ) : ?>
					<div class="unlockafe-ams-card__img" style="background-image:url(<?php echo esc_url( $img ); ?>);"></div>
				<?php else : ?>
					<div class="unlockafe-ams-card__img unlockafe-ams-card__img--placeholder"></div>
				<?php endif; ?>
				<div class="unlockafe-ams-card__content">
					<h4 class="unlockafe-ams-card__title"><?php echo esc_html( $title ); ?></h4>
					<?php if ( $desc !== '' ) : ?>
						<p class="unlockafe-ams-card__subtitle"><?php echo esc_html( $desc ); ?></p>
					<?php elseif ( $cat_label !== '' ) : ?>
						<p class="unlockafe-ams-card__subtitle"><?php echo esc_html( $cat_label ); ?></p>
					<?php endif; ?>
				</div>
			</a>
		</div>
		<?php
	}
}
