<?php
/**
 * Widget Name: Side Menu
 * Description: A persistent vertical dashboard sidebar navigation. Features a
 *              brand / logo header, a collapse ( icons-only ) toggle, menu items
 *              with icons and badges, and expandable accordion sub-menus with a
 *              connector line. Supports automatic active-item detection from the
 *              current URL, auto-expanding the active group and remembering the
 *              collapsed state. Ships five distinct styles and loads only the
 *              selected style CSS on the frontend.
 *
 * @package    captain-widgets-kit
 * @subpackage captain-widgets-kit/includes
 * @since      1.6.0
 */

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

use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Repeater;
use Elementor\Group_Control_Typography;
use Elementor\Icons_Manager;

/**
 * Class Captwiki_Side_Menu
 *
 * @since 1.6.0
 */
class Captwiki_Side_Menu extends Widget_Base {

	/**
	 * Get widget name.
	 *
	 * @since 1.6.0
	 * @return string
	 */
	public function get_name(): string {
		return 'captwiki-side-menu';
	}

	/**
	 * Get widget title.
	 *
	 * @since 1.6.0
	 * @return string
	 */
	public function get_title(): string {
		return esc_html__( 'Side Menu', 'captain-widgets-kit' );
	}

	/**
	 * Get widget icon.
	 *
	 * @since 1.6.0
	 * @return string
	 */
	public function get_icon(): string {
		return 'eicon-menu-bar captwiki-el-logo';
	}

	/**
	 * Get widget categories.
	 *
	 * @since 1.6.0
	 * @return array
	 */
	public function get_categories(): array {
		return array( 'captwiki-essential' );
	}

	/**
	 * Get widget keywords.
	 *
	 * @since 1.6.0
	 * @return array
	 */
	public function get_keywords(): array {
		return array( 'side', 'menu', 'sidebar', 'dashboard', 'vertical', 'navigation', 'nav', 'collapse', 'captain-widgets-kit' );
	}

	/**
	 * Frontend script dependency.
	 *
	 * @since 1.6.0
	 * @return array
	 */
	public function get_script_depends(): array {
		return array( 'captwiki-side-menu' );
	}

	/**
	 * Common stylesheet dependency.
	 *
	 * @since 1.6.0
	 * @return array
	 */
	public function get_style_depends(): array {
		return array( 'captwiki_side_menu' );
	}

	/**
	 * Disable Elementor's default inner wrapper.
	 *
	 * @since 1.6.0
	 * @return bool
	 */
	public function has_widget_inner_wrapper(): bool {
		return ! \Elementor\Plugin::$instance->experiments->is_feature_active( 'e_optimized_markup' );
	}

	/**
	 * Selectable visual styles.
	 *
	 * @since 1.6.0
	 * @return array
	 */
	private function captwiki_style_options(): array {
		return array(
			'style-1' => esc_html__( 'Style 1 – Clean Light', 'captain-widgets-kit' ),
			'style-2' => esc_html__( 'Style 2 – Dark Pro', 'captain-widgets-kit' ),
			'style-3' => esc_html__( 'Style 3 – Floating Cards', 'captain-widgets-kit' ),
			'style-4' => esc_html__( 'Style 4 – Minimal Bar', 'captain-widgets-kit' ),
			'style-5' => esc_html__( 'Style 5 – Gradient Active', 'captain-widgets-kit' ),
		);
	}

	/**
	 * Register widget controls.
	 *
	 * @since 1.6.0
	 * @return void
	 */
	protected function register_controls(): void {
		$this->register_header_controls();
		$this->register_menu_controls();
		$this->register_settings_controls();

		$this->register_general_style_controls();
		$this->register_header_style_controls();
		$this->register_items_style_controls();
		$this->register_subitems_style_controls();
	}

	/**
	 * Content tab — header / brand.
	 *
	 * @since 1.6.0
	 * @return void
	 */
	private function register_header_controls(): void {

		$this->start_controls_section(
			'section_header',
			array(
				'label' => esc_html__( 'Header', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'widget_style',
			array(
				'label'   => esc_html__( 'Style', 'captain-widgets-kit' ),
				'type'    => Controls_Manager::SELECT,
				'default' => 'style-1',
				'options' => $this->captwiki_style_options(),
			)
		);

		$this->add_control(
			'show_header',
			array(
				'label'        => esc_html__( 'Show Header', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Show', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'Hide', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'brand_logo',
			array(
				'label'     => esc_html__( 'Logo', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::MEDIA,
				'dynamic'   => array( 'active' => true ),
				'condition' => array( 'show_header' => 'yes' ),
			)
		);

		$this->add_control(
			'brand_text',
			array(
				'label'       => esc_html__( 'Brand Text', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'Captain Widgets Kit', 'captain-widgets-kit' ),
				'label_block' => true,
				'dynamic'     => array( 'active' => true ),
				'condition'   => array( 'show_header' => 'yes' ),
			)
		);

		$this->add_control(
			'brand_link',
			array(
				'label'         => esc_html__( 'Brand Link', 'captain-widgets-kit' ),
				'type'          => Controls_Manager::URL,
				'placeholder'   => esc_html__( 'https://your-site.com', 'captain-widgets-kit' ),
				'show_external' => true,
				'default'       => array( 'url' => '#' ),
				'condition'     => array( 'show_header' => 'yes' ),
			)
		);

		$this->add_control(
			'show_toggle',
			array(
				'label'        => esc_html__( 'Collapse Toggle', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Show', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'Hide', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => 'yes',
				'condition'    => array( 'show_header' => 'yes' ),
				'description'  => esc_html__( 'Shows a button that shrinks the sidebar to icons only.', 'captain-widgets-kit' ),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Content tab — menu items.
	 *
	 * @since 1.6.0
	 * @return void
	 */
	private function register_menu_controls(): void {

		$this->start_controls_section(
			'section_menu',
			array(
				'label' => esc_html__( 'Menu', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$repeater = new Repeater();

		$repeater->add_control(
			'is_sub',
			array(
				'label'        => esc_html__( 'Sub-item', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'No', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => '',
				'description'  => esc_html__( 'Nest this under the item above it.', 'captain-widgets-kit' ),
			)
		);

		$repeater->add_control(
			'item_title',
			array(
				'label'       => esc_html__( 'Title', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => esc_html__( 'Menu Item', 'captain-widgets-kit' ),
				'label_block' => true,
				'dynamic'     => array( 'active' => true ),
			)
		);

		$repeater->add_control(
			'item_icon',
			array(
				'label'       => esc_html__( 'Icon', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::ICONS,
				'skin'        => 'inline',
				'label_block' => false,
			)
		);

		$repeater->add_control(
			'item_link',
			array(
				'label'         => esc_html__( 'Link', 'captain-widgets-kit' ),
				'type'          => Controls_Manager::URL,
				'placeholder'   => esc_html__( 'https://your-link.com', 'captain-widgets-kit' ),
				'show_external' => true,
				'default'       => array( 'url' => '#' ),
				'dynamic'       => array( 'active' => true ),
				'description'   => esc_html__( 'Parent items that have sub-items act as a toggle and ignore this link.', 'captain-widgets-kit' ),
			)
		);

		$repeater->add_control(
			'item_badge',
			array(
				'label'       => esc_html__( 'Badge', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => '',
				'placeholder' => esc_html__( 'e.g. 3', 'captain-widgets-kit' ),
				'condition'   => array( 'is_sub!' => 'yes' ),
			)
		);

		$repeater->add_control(
			'set_active',
			array(
				'label'        => esc_html__( 'Mark Active', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'No', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => '',
			)
		);

		$repeater->add_control(
			'default_open',
			array(
				'label'        => esc_html__( 'Open by Default', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'No', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => '',
				'condition'    => array( 'is_sub!' => 'yes' ),
				'description'  => esc_html__( 'Expand this group on load ( if it has sub-items ).', 'captain-widgets-kit' ),
			)
		);

		$this->add_control(
			'menu_items',
			array(
				'label'       => esc_html__( 'Items', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::REPEATER,
				'fields'      => $repeater->get_controls(),
				'default'     => array(
					array(
						'item_title' => esc_html__( 'Dashboard', 'captain-widgets-kit' ),
						'set_active'  => 'yes',
						'item_icon'  => array( 'value' => 'fas fa-table-cells-large', 'library' => 'fa-solid' ),
					),
					array(
						'item_title'   => esc_html__( 'Templates', 'captain-widgets-kit' ),
						'default_open' => 'yes',
						'item_icon'    => array( 'value' => 'fas fa-table-columns', 'library' => 'fa-solid' ),
					),
					array( 'is_sub' => 'yes', 'item_title' => esc_html__( 'Uploaded', 'captain-widgets-kit' ) ),
					array( 'is_sub' => 'yes', 'item_title' => esc_html__( 'Favourite', 'captain-widgets-kit' ) ),
					array( 'is_sub' => 'yes', 'item_title' => esc_html__( 'Download', 'captain-widgets-kit' ) ),
					array( 'is_sub' => 'yes', 'item_title' => esc_html__( 'Shared with Me', 'captain-widgets-kit' ) ),
					array( 'is_sub' => 'yes', 'item_title' => esc_html__( 'Create New Kit', 'captain-widgets-kit' ) ),
					array(
						'item_title' => esc_html__( 'Widgets', 'captain-widgets-kit' ),
						'item_icon'  => array( 'value' => 'fas fa-cubes', 'library' => 'fa-solid' ),
					),
					array( 'is_sub' => 'yes', 'item_title' => esc_html__( 'All Widgets', 'captain-widgets-kit' ) ),
					array( 'is_sub' => 'yes', 'item_title' => esc_html__( 'Add New', 'captain-widgets-kit' ) ),
					array(
						'item_title' => esc_html__( 'Designs', 'captain-widgets-kit' ),
						'item_icon'  => array( 'value' => 'fas fa-pen-ruler', 'library' => 'fa-solid' ),
					),
					array(
						'item_title' => esc_html__( 'Code Snippet', 'captain-widgets-kit' ),
						'item_icon'  => array( 'value' => 'fas fa-code', 'library' => 'fa-solid' ),
					),
					array(
						'item_title' => esc_html__( 'Workspace', 'captain-widgets-kit' ),
						'item_icon'  => array( 'value' => 'fas fa-folder-open', 'library' => 'fa-solid' ),
					),
					array(
						'item_title' => esc_html__( 'License', 'captain-widgets-kit' ),
						'item_icon'  => array( 'value' => 'fas fa-id-card', 'library' => 'fa-solid' ),
					),
					array(
						'item_title' => esc_html__( 'Admin', 'captain-widgets-kit' ),
						'item_icon'  => array( 'value' => 'fas fa-user-gear', 'library' => 'fa-solid' ),
					),
				),
				'title_field' => '<# if ( is_sub === "yes" ) { #>&nbsp;&nbsp;↳ {{{ item_title }}}<# } else { #>{{{ item_title }}}<# } #>',
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Content tab — behaviour settings.
	 *
	 * @since 1.6.0
	 * @return void
	 */
	private function register_settings_controls(): void {

		$this->start_controls_section(
			'section_settings',
			array(
				'label' => esc_html__( 'Settings', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_CONTENT,
			)
		);

		$this->add_control(
			'accordion',
			array(
				'label'        => esc_html__( 'Accordion ( one open )', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'No', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => 'yes',
				'description'  => esc_html__( 'Close other groups when one opens.', 'captain-widgets-kit' ),
			)
		);

		$this->add_control(
			'auto_expand_active',
			array(
				'label'        => esc_html__( 'Auto-Expand Active', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'No', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => 'yes',
			)
		);

		$this->add_control(
			'auto_active',
			array(
				'label'        => esc_html__( 'Detect Active by URL', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'No', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => 'yes',
				'description'  => esc_html__( 'Highlight the item whose link matches the current page.', 'captain-widgets-kit' ),
			)
		);

		$this->add_control(
			'default_collapsed',
			array(
				'label'        => esc_html__( 'Start Collapsed', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'No', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => '',
			)
		);

		$this->add_control(
			'remember_state',
			array(
				'label'        => esc_html__( 'Remember Collapsed State', 'captain-widgets-kit' ),
				'type'         => Controls_Manager::SWITCHER,
				'label_on'     => esc_html__( 'Yes', 'captain-widgets-kit' ),
				'label_off'    => esc_html__( 'No', 'captain-widgets-kit' ),
				'return_value' => 'yes',
				'default'      => 'yes',
				'description'  => esc_html__( 'Save the expand / collapse choice in the browser.', 'captain-widgets-kit' ),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Style tab — general.
	 *
	 * @since 1.6.0
	 * @return void
	 */
	private function register_general_style_controls(): void {

		$this->start_controls_section(
			'section_general_style',
			array(
				'label' => esc_html__( 'Sidebar', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_control(
			'accent_color',
			array(
				'label'       => esc_html__( 'Accent Color', 'captain-widgets-kit' ),
				'type'        => Controls_Manager::COLOR,
				'default'     => '',
				'selectors'   => array(
					'{{WRAPPER}} .captwiki-sidenav' => '--captwiki-sn-accent: {{VALUE}};',
				),
				'description' => esc_html__( 'Active item background and highlights.', 'captain-widgets-kit' ),
			)
		);

		$this->add_control(
			'accent_color_2',
			array(
				'label'     => esc_html__( 'Secondary Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav' => '--captwiki-sn-accent-2: {{VALUE}};',
				),
			)
		);

		$this->add_responsive_control(
			'sidebar_width',
			array(
				'label'      => esc_html__( 'Width', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px', '%' ),
				'range'      => array(
					'px' => array(
						'min' => 200,
						'max' => 420,
					),
					'%'  => array(
						'min' => 20,
						'max' => 100,
					),
				),
				'default'    => array(
					'unit' => 'px',
					'size' => 280,
				),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-sidenav' => '--captwiki-sn-width: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'collapsed_width',
			array(
				'label'      => esc_html__( 'Collapsed Width', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array(
					'px' => array(
						'min' => 56,
						'max' => 110,
					),
				),
				'default'    => array(
					'unit' => 'px',
					'size' => 76,
				),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-sidenav' => '--captwiki-sn-cwidth: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_control(
			'sidebar_bg',
			array(
				'label'     => esc_html__( 'Background', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav' => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->add_responsive_control(
			'sidebar_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px' ),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-sidenav' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'sidebar_padding',
			array(
				'label'      => esc_html__( 'Padding', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em' ),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-sidenav' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Style tab — header.
	 *
	 * @since 1.6.0
	 * @return void
	 */
	private function register_header_style_controls(): void {

		$this->start_controls_section(
			'section_header_style',
			array(
				'label'     => esc_html__( 'Header', 'captain-widgets-kit' ),
				'tab'       => Controls_Manager::TAB_STYLE,
				'condition' => array( 'show_header' => 'yes' ),
			)
		);

		$this->add_responsive_control(
			'logo_height',
			array(
				'label'      => esc_html__( 'Logo Height', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array(
					'px' => array(
						'min' => 16,
						'max' => 80,
					),
				),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-sidenav__logo' => 'height: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_control(
			'brand_color',
			array(
				'label'     => esc_html__( 'Brand Text Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav__brand-text' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'brand_typography',
				'selector' => '{{WRAPPER}} .captwiki-sidenav__brand-text',
			)
		);

		$this->add_control(
			'toggle_color',
			array(
				'label'     => esc_html__( 'Toggle Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav__toggle' => 'color: {{VALUE}}; border-color: {{VALUE}};',
				),
				'condition' => array( 'show_toggle' => 'yes' ),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Style tab — menu items ( top level ).
	 *
	 * @since 1.6.0
	 * @return void
	 */
	private function register_items_style_controls(): void {

		$this->start_controls_section(
			'section_items_style',
			array(
				'label' => esc_html__( 'Menu Items', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'item_typography',
				'selector' => '{{WRAPPER}} .captwiki-sidenav__label',
			)
		);

		$this->start_controls_tabs( 'item_state_tabs' );

		$this->start_controls_tab(
			'item_normal_tab',
			array( 'label' => esc_html__( 'Normal', 'captain-widgets-kit' ) )
		);

		$this->add_control(
			'item_color',
			array(
				'label'     => esc_html__( 'Text Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav__link'     => 'color: {{VALUE}};',
					'{{WRAPPER}} .captwiki-sidenav__link svg' => 'fill: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'item_icon_color',
			array(
				'label'     => esc_html__( 'Icon Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav__icon'     => 'color: {{VALUE}};',
					'{{WRAPPER}} .captwiki-sidenav__icon svg' => 'fill: {{VALUE}};',
				),
			)
		);

		$this->end_controls_tab();

		$this->start_controls_tab(
			'item_hover_tab',
			array( 'label' => esc_html__( 'Hover', 'captain-widgets-kit' ) )
		);

		$this->add_control(
			'item_color_hover',
			array(
				'label'     => esc_html__( 'Text Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav__link:hover'     => 'color: {{VALUE}};',
					'{{WRAPPER}} .captwiki-sidenav__link:hover svg' => 'fill: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'item_bg_hover',
			array(
				'label'     => esc_html__( 'Background', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav__link:hover' => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->end_controls_tab();

		$this->start_controls_tab(
			'item_active_tab',
			array( 'label' => esc_html__( 'Active', 'captain-widgets-kit' ) )
		);

		$this->add_control(
			'item_color_active',
			array(
				'label'     => esc_html__( 'Text Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav__item.is-active > .captwiki-sidenav__link'     => 'color: {{VALUE}};',
					'{{WRAPPER}} .captwiki-sidenav__item.is-active > .captwiki-sidenav__link svg' => 'fill: {{VALUE}};',
					'{{WRAPPER}} .captwiki-sidenav__item.is-active > .captwiki-sidenav__link .captwiki-sidenav__icon' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'item_bg_active',
			array(
				'label'     => esc_html__( 'Background', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav__item.is-active > .captwiki-sidenav__link' => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->end_controls_tab();
		$this->end_controls_tabs();

		$this->add_responsive_control(
			'item_gap',
			array(
				'label'      => esc_html__( 'Gap Between Items', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array(
					'px' => array(
						'min' => 0,
						'max' => 24,
					),
				),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-sidenav__menu' => 'gap: {{SIZE}}{{UNIT}};',
				),
				'separator'  => 'before',
			)
		);

		$this->add_responsive_control(
			'item_padding',
			array(
				'label'      => esc_html__( 'Padding', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => array( 'px', 'em' ),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-sidenav__link' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'item_radius',
			array(
				'label'      => esc_html__( 'Border Radius', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array(
					'px' => array(
						'min' => 0,
						'max' => 30,
					),
				),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-sidenav__link' => 'border-radius: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_responsive_control(
			'item_icon_size',
			array(
				'label'      => esc_html__( 'Icon Size', 'captain-widgets-kit' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => array( 'px' ),
				'range'      => array(
					'px' => array(
						'min' => 12,
						'max' => 36,
					),
				),
				'selectors'  => array(
					'{{WRAPPER}} .captwiki-sidenav__icon' => 'font-size: {{SIZE}}{{UNIT}};',
				),
			)
		);

		$this->add_control(
			'badge_color',
			array(
				'label'     => esc_html__( 'Badge Text Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav__badge' => 'color: {{VALUE}};',
				),
				'separator' => 'before',
			)
		);

		$this->add_control(
			'badge_bg',
			array(
				'label'     => esc_html__( 'Badge Background', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav__badge' => 'background-color: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Style tab — sub-items.
	 *
	 * @since 1.6.0
	 * @return void
	 */
	private function register_subitems_style_controls(): void {

		$this->start_controls_section(
			'section_subitems_style',
			array(
				'label' => esc_html__( 'Sub-items', 'captain-widgets-kit' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			)
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			array(
				'name'     => 'subitem_typography',
				'selector' => '{{WRAPPER}} .captwiki-sidenav__sublink',
			)
		);

		$this->add_control(
			'subitem_color',
			array(
				'label'     => esc_html__( 'Text Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav__sublink' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'subitem_color_hover',
			array(
				'label'     => esc_html__( 'Hover / Active Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav__sublink:hover'        => 'color: {{VALUE}};',
					'{{WRAPPER}} .captwiki-sidenav__subitem.is-active > .captwiki-sidenav__sublink' => 'color: {{VALUE}};',
				),
			)
		);

		$this->add_control(
			'connector_color',
			array(
				'label'     => esc_html__( 'Connector Line Color', 'captain-widgets-kit' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '',
				'selectors' => array(
					'{{WRAPPER}} .captwiki-sidenav__sub' => '--captwiki-sn-connector: {{VALUE}};',
				),
			)
		);

		$this->end_controls_section();
	}

	/**
	 * Capture an Elementor icon as an HTML string.
	 *
	 * @since 1.6.0
	 * @param array $icon Icon control value.
	 * @return string
	 */
	private function captwiki_get_icon_html( array $icon ): string {
		ob_start();
		Icons_Manager::render_icon( $icon, array( 'aria-hidden' => 'true' ) );
		return (string) ob_get_clean();
	}

	/**
	 * Whether a URL matches the current request.
	 *
	 * @since 1.6.0
	 * @param string $url Link URL.
	 * @return bool
	 */
	private function captwiki_is_current_url( string $url ): bool {
		if ( '' === $url || '#' === $url ) {
			return false;
		}

		$path = wp_parse_url( $url, PHP_URL_PATH );

		if ( empty( $path ) ) {
			return false;
		}

		$current = isset( $_SERVER['REQUEST_URI'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REQUEST_URI'] ) ) : '';
		$current = strtok( $current, '?' );

		return untrailingslashit( $path ) === untrailingslashit( (string) $current );
	}

	/**
	 * Build a two-level tree from the flat repeater.
	 *
	 * @since 1.6.0
	 * @param array $items Repeater items.
	 * @return array
	 */
	private function captwiki_build_tree( array $items ): array {
		$tree = array();

		foreach ( $items as $row ) {
			$row    = (array) $row;
			$is_sub = ! empty( $row['is_sub'] ) && 'yes' === $row['is_sub'];

			if ( $is_sub && ! empty( $tree ) ) {
				$last_key = array_key_last( $tree );
				$tree[ $last_key ]['__children'][] = $row;
			} else {
				$row['__children'] = array();
				$tree[]            = $row;
			}
		}

		return $tree;
	}

	/**
	 * Render the open / close arrow.
	 *
	 * @since 1.6.0
	 * @return void
	 */
	private function captwiki_render_arrow(): void {
		echo '<span class="captwiki-sidenav__arrow" aria-hidden="true"></span>';
	}

	/**
	 * Render a sub-item link.
	 *
	 * @since 1.6.0
	 * @param array $child   Child item.
	 * @param bool  $auto    Auto-active detection enabled.
	 * @return bool Whether this child is active.
	 */
	private function captwiki_render_subitem( array $child, bool $auto ): bool {
		$title = isset( $child['item_title'] ) ? trim( (string) $child['item_title'] ) : '';

		if ( '' === $title ) {
			return false;
		}

		$url    = ! empty( $child['item_link']['url'] ) ? $child['item_link']['url'] : '#';
		$active = ( ! empty( $child['set_active'] ) && 'yes' === $child['set_active'] ) || ( $auto && $this->captwiki_is_current_url( $url ) );
		$cls    = $active ? ' is-active' : '';
		$target = ! empty( $child['item_link']['is_external'] ) ? ' target="_blank"' : '';
		$rel    = ! empty( $child['item_link']['nofollow'] ) ? ' rel="nofollow"' : '';
		$aria   = $active ? ' aria-current="page"' : '';

		echo '<li class="captwiki-sidenav__subitem' . esc_attr( $cls ) . '">'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo '<a class="captwiki-sidenav__sublink" href="' . esc_url( $url ) . '"' . $target . $rel . $aria . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo '<span class="captwiki-sidenav__sublabel">' . esc_html( $title ) . '</span>';
		echo '</a>';
		echo '</li>';

		return $active;
	}

	/**
	 * Render widget output on the frontend.
	 *
	 * @since 1.6.0
	 * @return void
	 */
	protected function render(): void {
		$settings = $this->get_settings_for_display();

		if ( empty( $settings['menu_items'] ) || ! is_array( $settings['menu_items'] ) ) {
			return;
		}

		$allowed_styles = array_keys( $this->captwiki_style_options() );
		$style          = in_array( $settings['widget_style'], $allowed_styles, true ) ? $settings['widget_style'] : 'style-1';

		wp_enqueue_style(
			'captwiki-side-menu-' . $style,
			CAPTWIKI_URL . 'assets/css/widgets/side-menu/captwiki-side-menu-' . $style . '.css',
			array( 'captwiki_side_menu' ),
			CAPTWIKI_VERSION
		);

		$auto        = 'yes' === $settings['auto_active'];
		$auto_expand = 'yes' === $settings['auto_expand_active'];
		$accordion   = 'yes' === $settings['accordion'] ? 'yes' : 'no';
		$remember    = 'yes' === $settings['remember_state'] ? 'yes' : 'no';
		$collapsed   = 'yes' === $settings['default_collapsed'];

		$uid       = $this->get_id();
		$tree      = $this->captwiki_build_tree( $settings['menu_items'] );
		$collapsed_class = $collapsed ? ' is-collapsed' : '';

		printf(
			'<nav class="captwiki-sidenav captwiki-%1$s%2$s" data-accordion="%3$s" data-remember="%4$s" data-uid="%5$s" aria-label="%6$s">',
			esc_attr( $style ),
			esc_attr( $collapsed_class ),
			esc_attr( $accordion ),
			esc_attr( $remember ),
			esc_attr( $uid ),
			esc_attr__( 'Sidebar navigation', 'captain-widgets-kit' )
		);

		// Header.
		if ( 'yes' === $settings['show_header'] ) {
			$has_logo = ! empty( $settings['brand_logo']['url'] );
			$brand    = trim( (string) $settings['brand_text'] );

			echo '<div class="captwiki-sidenav__header">';

			$b_url    = ! empty( $settings['brand_link']['url'] ) ? $settings['brand_link']['url'] : '';
			$b_tag    = '' !== $b_url ? 'a' : 'span';
			$b_href   = '' !== $b_url ? ' href="' . esc_url( $b_url ) . '"' : '';
			$b_target = ! empty( $settings['brand_link']['is_external'] ) ? ' target="_blank"' : '';

			echo '<' . esc_attr( $b_tag ) . ' class="captwiki-sidenav__brand"' . $b_href . $b_target . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

			if ( $has_logo ) {
				printf(
					'<img class="captwiki-sidenav__logo" src="%1$s" alt="%2$s" />',
					esc_url( $settings['brand_logo']['url'] ),
					esc_attr( $brand )
				);
			}

			if ( '' !== $brand ) {
				echo '<span class="captwiki-sidenav__brand-text">' . esc_html( $brand ) . '</span>';
			}

			echo '</' . esc_attr( $b_tag ) . '>';

			if ( 'yes' === $settings['show_toggle'] ) {
				printf(
					'<button type="button" class="captwiki-sidenav__toggle" aria-expanded="%1$s" aria-label="%2$s"><svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="16" rx="2"></rect><line x1="9" y1="4" x2="9" y2="20"></line></svg></button>',
					$collapsed ? 'false' : 'true',
					esc_attr__( 'Toggle sidebar', 'captain-widgets-kit' )
				);
			}

			echo '</div>';
		}

		// Menu.
		echo '<ul class="captwiki-sidenav__menu">';

		$index = 0;

		foreach ( $tree as $node ) {
			++$index;

			$title = isset( $node['item_title'] ) ? trim( (string) $node['item_title'] ) : '';

			if ( '' === $title ) {
				continue;
			}

			$children     = ! empty( $node['__children'] ) ? $node['__children'] : array();
			$has_children = ! empty( $children );
			$url          = ! empty( $node['item_link']['url'] ) ? $node['item_link']['url'] : '#';
			$badge        = isset( $node['item_badge'] ) ? trim( (string) $node['item_badge'] ) : '';

			$self_active = ( ! empty( $node['set_active'] ) && 'yes' === $node['set_active'] ) || ( $auto && ! $has_children && $this->captwiki_is_current_url( $url ) );

			$sub_id     = 'captwiki-sidenav-sub-' . $uid . '-' . $index;
			$icon_html  = ! empty( $node['item_icon']['value'] ) ? $this->captwiki_get_icon_html( $node['item_icon'] ) : '';

			// Pre-scan children for active state ( to set classes before output ).
			$child_active = false;

			if ( $has_children && $auto ) {
				foreach ( $children as $c ) {
					$c     = (array) $c;
					$c_url = ! empty( $c['item_link']['url'] ) ? $c['item_link']['url'] : '#';

					if ( ( ! empty( $c['set_active'] ) && 'yes' === $c['set_active'] ) || $this->captwiki_is_current_url( $c_url ) ) {
						$child_active = true;
						break;
					}
				}
			} elseif ( $has_children ) {
				foreach ( $children as $c ) {
					$c = (array) $c;
					if ( ! empty( $c['set_active'] ) && 'yes' === $c['set_active'] ) {
						$child_active = true;
						break;
					}
				}
			}

			$is_open = $has_children && ( ( ! empty( $node['default_open'] ) && 'yes' === $node['default_open'] ) || ( $auto_expand && $child_active ) );

			$item_classes = 'captwiki-sidenav__item';
			$item_classes .= $has_children ? ' captwiki-sidenav__item--has-sub' : '';
			$item_classes .= $self_active ? ' is-active' : '';
			$item_classes .= $is_open ? ' is-open' : '';

			echo '<li class="' . esc_attr( $item_classes ) . '">'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

			if ( $has_children ) {
				printf(
					'<button type="button" class="captwiki-sidenav__link captwiki-sidenav__link--parent" aria-expanded="%1$s" aria-controls="%2$s">',
					$is_open ? 'true' : 'false',
					esc_attr( $sub_id )
				);
			} else {
				$target = ! empty( $node['item_link']['is_external'] ) ? ' target="_blank"' : '';
				$rel    = ! empty( $node['item_link']['nofollow'] ) ? ' rel="nofollow"' : '';
				$aria   = $self_active ? ' aria-current="page"' : '';

				echo '<a class="captwiki-sidenav__link" href="' . esc_url( $url ) . '"' . $target . $rel . $aria . '>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			}

			if ( '' !== $icon_html ) {
				echo '<span class="captwiki-sidenav__icon" aria-hidden="true">' . $icon_html . '</span>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
			} else {
				echo '<span class="captwiki-sidenav__icon captwiki-sidenav__icon--empty" aria-hidden="true"></span>';
			}

			echo '<span class="captwiki-sidenav__label">' . esc_html( $title ) . '</span>';

			if ( '' !== $badge ) {
				echo '<span class="captwiki-sidenav__badge">' . esc_html( $badge ) . '</span>';
			}

			if ( $has_children ) {
				$this->captwiki_render_arrow();
				echo '</button>';

				echo '<ul class="captwiki-sidenav__sub" id="' . esc_attr( $sub_id ) . '">';

				foreach ( $children as $child ) {
					$this->captwiki_render_subitem( (array) $child, $auto );
				}

				echo '</ul>';
			} else {
				echo '</a>';
			}

			echo '</li>';
		}

		echo '</ul>';
		echo '</nav>';
	}
}
