<?php
/**
 * Tooto Popover：触发器为按钮（文本+图标），弹出内容为 WordPress 菜单。
 */

namespace Tooto_Elementor\Widgets;

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

use Elementor\Controls_Manager;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Typography;
use Elementor\Icons_Manager;
use Elementor\Widget_Base;

class Popover extends Widget_Base {

	public function get_name(): string {
		return 'tooto-popover';
	}

	public function get_title(): string {
		return __( 'Tooto Popover', 'tooto-elementor' );
	}

	public function get_icon(): string {
		return 'eicon-tooltip';
	}

	public function get_categories(): array {
		return [ 'tooto' ];
	}

	public function get_keywords(): array {
		return [ 'popover', 'tooltip', 'dropdown', 'menu', 'navigation', 'tooto' ];
	}

	public function get_style_depends(): array {
		return [ 'tooto-elementor' ];
	}

	public function get_script_depends(): array {
		return [ 'tooto-elementor' ];
	}

	protected function register_controls(): void {
		// ========== 触发器设置 ==========
		$this->start_controls_section(
			'section_trigger',
			[
				'label' => __( '触发器', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'trigger_text',
			[
				'label'       => __( '文本', 'tooto-elementor' ),
				'type'        => Controls_Manager::TEXT,
				'default'     => __( '菜单', 'tooto-elementor' ),
				'placeholder' => __( '输入触发器文本', 'tooto-elementor' ),
				'label_block' => true,
				'dynamic'     => [ 'active' => true ],
			]
		);

		$this->add_control(
			'trigger_icon',
			[
				'label'            => __( '图标', 'tooto-elementor' ),
				'type'             => Controls_Manager::ICONS,
				'fa4compatibility' => 'icon',
				'skin'             => 'inline',
				'label_block'      => false,
				'default'          => [
					'value'   => 'fas fa-chevron-down',
					'library' => 'fa-solid',
				],
			]
		);

		$this->add_control(
			'icon_position',
			[
				'label'     => __( '图标位置', 'tooto-elementor' ),
				'type'      => Controls_Manager::SELECT,
				'options'   => [
					'before' => __( '文本前', 'tooto-elementor' ),
					'after'  => __( '文本后', 'tooto-elementor' ),
				],
				'default'   => 'after',
				'condition' => [
					'trigger_icon[value]!' => '',
				],
			]
		);

		$this->add_responsive_control(
			'icon_spacing',
			[
				'label'      => __( '图标间距', 'tooto-elementor' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => [ 'px', 'em' ],
				'range'      => [
					'px' => [ 'min' => 0, 'max' => 50 ],
					'em' => [ 'min' => 0, 'max' => 3, 'step' => 0.1 ],
				],
				'default'    => [ 'size' => 6, 'unit' => 'px' ],
				'selectors'  => [
					'{{WRAPPER}} .tooto-popover__trigger-btn' => 'gap: {{SIZE}}{{UNIT}};',
				],
				'condition'  => [
					'trigger_icon[value]!' => '',
				],
			]
		);

		$this->end_controls_section();

		// ========== 弹出内容（菜单） ==========
		$this->start_controls_section(
			'section_content',
			[
				'label' => __( '弹出内容', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'menu_id',
			[
				'label'       => __( '选择菜单', 'tooto-elementor' ),
				'type'        => Controls_Manager::SELECT,
				'options'     => $this->get_available_menus(),
				'default'     => '',
				'description' => __( '选择一个 WordPress 导航菜单。', 'tooto-elementor' ),
			]
		);

		$this->end_controls_section();

		// ========== 弹出行为设置 ==========
		$this->start_controls_section(
			'section_behavior',
			[
				'label' => __( '弹出行为', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'trigger_type',
			[
				'label'   => __( '触发方式', 'tooto-elementor' ),
				'type'    => Controls_Manager::SELECT,
				'options' => [
					'click' => __( '点击', 'tooto-elementor' ),
					'hover' => __( '悬停', 'tooto-elementor' ),
				],
				'default' => 'click',
			]
		);

		$this->add_control(
			'placement',
			[
				'label'   => __( '弹出位置', 'tooto-elementor' ),
				'type'    => Controls_Manager::SELECT,
				'options' => [
					'auto'   => __( '自动', 'tooto-elementor' ),
					'top'    => __( '上', 'tooto-elementor' ),
					'bottom' => __( '下', 'tooto-elementor' ),
					'left'   => __( '左', 'tooto-elementor' ),
					'right'  => __( '右', 'tooto-elementor' ),
				],
				'default' => 'bottom',
			]
		);

		$this->add_control(
			'alignment',
			[
				'label'       => __( '对齐', 'tooto-elementor' ),
				'type'        => Controls_Manager::SELECT,
				'options'     => [
					'start'  => __( '左对齐', 'tooto-elementor' ),
					'center' => __( '居中', 'tooto-elementor' ),
					'end'    => __( '右对齐', 'tooto-elementor' ),
				],
				'default'     => 'end',
				'description' => __( '上/下弹出时控制水平对齐；左/右弹出时控制垂直对齐。', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'offset',
			[
				'label'   => __( '偏移（px）', 'tooto-elementor' ),
				'type'    => Controls_Manager::NUMBER,
				'default' => 4,
				'min'     => 0,
				'max'     => 100,
			]
		);

		$this->add_control(
			'hover_open_delay',
			[
				'label'     => __( '悬停打开延迟（ms）', 'tooto-elementor' ),
				'type'      => Controls_Manager::NUMBER,
				'default'   => 80,
				'min'       => 0,
				'max'       => 1000,
				'condition' => [
					'trigger_type' => 'hover',
				],
			]
		);

		$this->add_control(
			'hover_close_delay',
			[
				'label'     => __( '悬停关闭延迟（ms）', 'tooto-elementor' ),
				'type'      => Controls_Manager::NUMBER,
				'default'   => 120,
				'min'       => 0,
				'max'       => 2000,
				'condition' => [
					'trigger_type' => 'hover',
				],
			]
		);

		$this->add_control(
			'append_to_body',
			[
				'label'        => __( '附加到 Body（防止父容器裁切）', 'tooto-elementor' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			]
		);

		$this->add_control(
			'close_on_outside',
			[
				'label'        => __( '点击外部关闭', 'tooto-elementor' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
				'condition'    => [
					'trigger_type' => 'click',
				],
			]
		);

		$this->add_control(
			'close_on_esc',
			[
				'label'        => __( 'ESC 关闭', 'tooto-elementor' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => 'yes',
			]
		);

		$this->add_control(
			'show_arrow',
			[
				'label'        => __( '显示箭头', 'tooto-elementor' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => '',
			]
		);

		$this->end_controls_section();

		// ========== 触发器样式 ==========
		$this->start_controls_section(
			'section_style_trigger',
			[
				'label' => __( '触发器样式', 'tooto-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'trigger_typo',
				'selector' => '{{WRAPPER}} .tooto-popover__trigger-btn',
			]
		);

		$this->add_responsive_control(
			'trigger_padding',
			[
				'label'      => __( '内边距', 'tooto-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', 'em', 'rem' ],
				'selectors'  => [
					'{{WRAPPER}} .tooto-popover__trigger-btn' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				],
			]
		);

		$this->add_responsive_control(
			'trigger_icon_size',
			[
				'label'      => __( '图标大小', 'tooto-elementor' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => [ 'px', 'em' ],
				'range'      => [
					'px' => [ 'min' => 8, 'max' => 80 ],
					'em' => [ 'min' => 0.5, 'max' => 5, 'step' => 0.1 ],
				],
				'selectors'  => [
					'{{WRAPPER}} .tooto-popover__trigger-icon'     => 'font-size: {{SIZE}}{{UNIT}};',
					'{{WRAPPER}} .tooto-popover__trigger-icon svg' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
				],
			]
		);

		// Normal / Hover 状态
		$this->start_controls_tabs( 'trigger_state_tabs' );

		$this->start_controls_tab(
			'trigger_normal',
			[ 'label' => __( '正常', 'tooto-elementor' ) ]
		);

		$this->add_control(
			'trigger_color',
			[
				'label'     => __( '文本颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .tooto-popover__trigger-btn' => 'color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'trigger_bg',
			[
				'label'     => __( '背景颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .tooto-popover__trigger-btn' => 'background-color: {{VALUE}};',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Border::get_type(),
			[
				'name'     => 'trigger_border',
				'selector' => '{{WRAPPER}} .tooto-popover__trigger-btn',
			]
		);

		$this->end_controls_tab();

		$this->start_controls_tab(
			'trigger_hover',
			[ 'label' => __( '悬停', 'tooto-elementor' ) ]
		);

		$this->add_control(
			'trigger_color_hover',
			[
				'label'     => __( '文本颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .tooto-popover__trigger-btn:hover' => 'color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'trigger_bg_hover',
			[
				'label'     => __( '背景颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .tooto-popover__trigger-btn:hover' => 'background-color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'trigger_border_color_hover',
			[
				'label'     => __( '边框颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .tooto-popover__trigger-btn:hover' => 'border-color: {{VALUE}};',
				],
			]
		);

		$this->end_controls_tab();

		$this->end_controls_tabs();

		$this->add_control(
			'trigger_border_radius',
			[
				'label'      => __( '圆角', 'tooto-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', '%' ],
				'separator'  => 'before',
				'selectors'  => [
					'{{WRAPPER}} .tooto-popover__trigger-btn' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				],
			]
		);

		$this->end_controls_section();

		// ========== 弹出层样式 ==========
		$this->start_controls_section(
			'section_style_panel',
			[
				'label' => __( '弹出层样式', 'tooto-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_responsive_control(
			'panel_width',
			[
				'label'      => __( '宽度', 'tooto-elementor' ),
				'type'       => Controls_Manager::SLIDER,
				'size_units' => [ 'px', '%', 'vw' ],
				'range'      => [
					'px' => [ 'min' => 80, 'max' => 600 ],
					'%'  => [ 'min' => 10, 'max' => 100 ],
					'vw' => [ 'min' => 10, 'max' => 100 ],
				],
				'selectors'  => [
					'{{WRAPPER}} .tooto-popover__panel' => 'width: {{SIZE}}{{UNIT}};',
				],
			]
		);

		$this->add_responsive_control(
			'panel_padding',
			[
				'label'      => __( '内边距', 'tooto-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', 'em', 'rem' ],
				'selectors'  => [
					'{{WRAPPER}} .tooto-popover__panel-inner' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				],
			]
		);

		$this->add_control(
			'panel_bg',
			[
				'label'     => __( '背景色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#ffffff',
				'selectors' => [
					'{{WRAPPER}} .tooto-popover__panel'         => 'background: {{VALUE}};',
					'{{WRAPPER}} .tooto-popover__arrow::before' => 'background: {{VALUE}};',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Border::get_type(),
			[
				'name'     => 'panel_border',
				'selector' => '{{WRAPPER}} .tooto-popover__panel',
			]
		);

		$this->add_control(
			'panel_border_radius',
			[
				'label'      => __( '圆角', 'tooto-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', '%' ],
				'selectors'  => [
					'{{WRAPPER}} .tooto-popover__panel' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				],
			]
		);

		$this->add_group_control(
			Group_Control_Box_Shadow::get_type(),
			[
				'name'     => 'panel_shadow',
				'selector' => '{{WRAPPER}} .tooto-popover__panel',
			]
		);

		$this->add_control(
			'panel_z_index',
			[
				'label'     => __( '层级（z-index）', 'tooto-elementor' ),
				'type'      => Controls_Manager::NUMBER,
				'default'   => 9999,
				'min'       => 1,
				'selectors' => [
					'{{WRAPPER}} .tooto-popover__panel' => 'z-index: {{VALUE}};',
				],
			]
		);

		$this->end_controls_section();

		// ========== 菜单项样式 ==========
		$this->start_controls_section(
			'section_style_menu',
			[
				'label' => __( '菜单项样式', 'tooto-elementor' ),
				'tab'   => Controls_Manager::TAB_STYLE,
			]
		);

		$this->add_group_control(
			Group_Control_Typography::get_type(),
			[
				'name'     => 'menu_typo',
				'selector' => '{{WRAPPER}} .tooto-popover__menu a',
			]
		);

		$this->add_responsive_control(
			'menu_item_padding',
			[
				'label'      => __( '菜单项内边距', 'tooto-elementor' ),
				'type'       => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', 'em' ],
				'default'    => [
					'top'    => 10,
					'right'  => 16,
					'bottom' => 10,
					'left'   => 16,
					'unit'   => 'px',
				],
				'selectors'  => [
					'{{WRAPPER}} .tooto-popover__menu a' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				],
			]
		);

		// Normal / Hover 状态
		$this->start_controls_tabs( 'menu_state_tabs' );

		$this->start_controls_tab(
			'menu_normal',
			[ 'label' => __( '正常', 'tooto-elementor' ) ]
		);

		$this->add_control(
			'menu_color',
			[
				'label'     => __( '文本颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .tooto-popover__menu a' => 'color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'menu_bg',
			[
				'label'     => __( '背景颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .tooto-popover__menu a' => 'background-color: {{VALUE}};',
				],
			]
		);

		$this->end_controls_tab();

		$this->start_controls_tab(
			'menu_hover',
			[ 'label' => __( '悬停', 'tooto-elementor' ) ]
		);

		$this->add_control(
			'menu_color_hover',
			[
				'label'     => __( '文本颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .tooto-popover__menu a:hover' => 'color: {{VALUE}};',
				],
			]
		);

		$this->add_control(
			'menu_bg_hover',
			[
				'label'     => __( '背景颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'selectors' => [
					'{{WRAPPER}} .tooto-popover__menu a:hover' => 'background-color: {{VALUE}};',
				],
			]
		);

		$this->end_controls_tab();

		$this->end_controls_tabs();

		$this->add_control(
			'menu_divider',
			[
				'label'        => __( '显示分隔线', 'tooto-elementor' ),
				'type'         => Controls_Manager::SWITCHER,
				'return_value' => 'yes',
				'default'      => '',
				'separator'    => 'before',
			]
		);

		$this->add_control(
			'menu_divider_color',
			[
				'label'     => __( '分隔线颜色', 'tooto-elementor' ),
				'type'      => Controls_Manager::COLOR,
				'default'   => '#eee',
				'selectors' => [
					'{{WRAPPER}} .tooto-popover__menu li + li' => 'border-top: 1px solid {{VALUE}};',
				],
				'condition' => [
					'menu_divider' => 'yes',
				],
			]
		);

		$this->end_controls_section();
	}

	protected function render(): void {
		$settings = $this->get_settings_for_display();

		$text          = $settings['trigger_text'] ?? '';
		$icon          = $settings['trigger_icon'] ?? [];
		$icon_position = $settings['icon_position'] ?? 'after';
		$menu_id       = $settings['menu_id'] ?? '';

		$trigger_type   = $settings['trigger_type'] ?? 'click';
		$placement      = $settings['placement'] ?? 'bottom';
		$alignment      = $settings['alignment'] ?? 'end';
		$offset         = (int) ( $settings['offset'] ?? 4 );
		$append_to_body = ( 'yes' === ( $settings['append_to_body'] ?? 'yes' ) ) ? 'true' : 'false';
		$close_on_out   = ( 'yes' === ( $settings['close_on_outside'] ?? 'yes' ) ) ? 'true' : 'false';
		$close_on_esc   = ( 'yes' === ( $settings['close_on_esc'] ?? 'yes' ) ) ? 'true' : 'false';
		$hover_open     = (int) ( $settings['hover_open_delay'] ?? 80 );
		$hover_close    = (int) ( $settings['hover_close_delay'] ?? 120 );
		$show_arrow     = ( 'yes' === ( $settings['show_arrow'] ?? '' ) );

		$has_icon = ! empty( $icon['value'] );
		$has_text = ! empty( $text );

		echo '<div class="tooto-popover" data-tooto-popover';
		echo ' data-trigger="' . esc_attr( $trigger_type ) . '"';
		echo ' data-placement="' . esc_attr( $placement ) . '"';
		echo ' data-align="' . esc_attr( $alignment ) . '"';
		echo ' data-offset="' . esc_attr( (string) $offset ) . '"';
		echo ' data-append-to-body="' . esc_attr( $append_to_body ) . '"';
		echo ' data-close-on-outside="' . esc_attr( $close_on_out ) . '"';
		echo ' data-close-on-esc="' . esc_attr( $close_on_esc ) . '"';
		echo ' data-hover-open-delay="' . esc_attr( (string) $hover_open ) . '"';
		echo ' data-hover-close-delay="' . esc_attr( (string) $hover_close ) . '"';
		echo '>';

		// ===== 触发器 =====
		echo '<div class="tooto-popover__trigger" data-tooto-popover-trigger>';
		echo '<button type="button" class="tooto-popover__trigger-btn">';

		if ( $has_icon && 'before' === $icon_position ) {
			echo '<span class="tooto-popover__trigger-icon">';
			Icons_Manager::render_icon( $icon, [ 'aria-hidden' => 'true' ] );
			echo '</span>';
		}

		if ( $has_text ) {
			echo '<span class="tooto-popover__trigger-text">' . esc_html( $text ) . '</span>';
		}

		if ( $has_icon && 'after' === $icon_position ) {
			echo '<span class="tooto-popover__trigger-icon">';
			Icons_Manager::render_icon( $icon, [ 'aria-hidden' => 'true' ] );
			echo '</span>';
		}

		// 如果既没有图标也没有文本，显示默认文本
		if ( ! $has_icon && ! $has_text ) {
			echo '<span class="tooto-popover__trigger-text">' . esc_html__( '菜单', 'tooto-elementor' ) . '</span>';
		}

		echo '</button>';
		echo '</div>';

		// ===== 弹出层 =====
		echo '<div class="tooto-popover__panel" data-tooto-popover-panel aria-hidden="true">';

		if ( $show_arrow ) {
			echo '<div class="tooto-popover__arrow" data-tooto-popover-arrow aria-hidden="true"></div>';
		}

		echo '<div class="tooto-popover__panel-inner">';

		if ( $menu_id ) {
			wp_nav_menu(
				[
					'menu'            => $menu_id,
					'container'       => 'nav',
					'container_class' => 'tooto-popover__menu',
					'menu_class'      => 'tooto-popover__menu-list',
					'depth'           => 1,
					'fallback_cb'     => false,
				]
			);
		} else {
			echo '<div class="tooto-popover__empty">' . esc_html__( '请选择一个菜单。', 'tooto-elementor' ) . '</div>';
		}

		echo '</div></div></div>';
	}

	/**
	 * 获取可用的 WordPress 菜单列表
	 */
	private function get_available_menus(): array {
		$menus   = wp_get_nav_menus();
		$options = [ '' => __( '— 选择菜单 —', 'tooto-elementor' ) ];

		foreach ( $menus as $menu ) {
			$options[ $menu->term_id ] = $menu->name;
		}

		return $options;
	}
}
