<?php
/**
 * Tooto Image Carousel Widget
 */

namespace Tooto_Elementor\Widgets;

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

use Elementor\Controls_Manager;
use Elementor\Widget_Base;
use Elementor\Control_Media;

class Image_Carousel extends Widget_Base {
	public function get_name(): string {
		return 'tooto-image-carousel';
	}

	public function get_title(): string {
		return __( 'Tooto 图片轮播', 'tooto-elementor' );
	}

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

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

	public function get_keywords(): array {
		return [ 'carousel', 'image', 'slider', '轮播', '图片' ];
	}

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

	protected function register_controls(): void {
		// Content Section
		$this->start_controls_section(
			'section_content',
			[
				'label' => __( '图片内容', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'view_mode',
			[
				'label' => __( '显示模式', 'tooto-elementor' ),
				'type' => Controls_Manager::SELECT,
				'default' => 'simple',
				'options' => [
					'simple' => __( '简单图片', 'tooto-elementor' ),
					'brand_details' => __( '品牌详情', 'tooto-elementor' ),
				],
			]
		);

		$this->add_control(
			'carousel_images',
			[
				'label' => __( '选择图片', 'tooto-elementor' ),
				'type' => Controls_Manager::GALLERY,
				'default' => [],
				'condition' => [
					'view_mode' => 'simple',
				],
			]
		);

		$repeater = new \Elementor\Repeater();

		$repeater->add_control(
			'brand_logo',
			[
				'label' => __( '品牌 Logo', 'tooto-elementor' ),
				'type' => Controls_Manager::MEDIA,
				'default' => [
					'url' => \Elementor\Utils::get_placeholder_image_src(),
				],
			]
		);

		$repeater->add_control(
			'brand_title',
			[
				'label' => __( '品牌名称', 'tooto-elementor' ),
				'type' => Controls_Manager::TEXT,
				'default' => __( 'Brand Name', 'tooto-elementor' ),
				'label_block' => true,
			]
		);

		$repeater->add_control(
			'brand_subtitle',
			[
				'label' => __( '副标题/标签', 'tooto-elementor' ),
				'type' => Controls_Manager::TEXT,
				'default' => __( 'TAG', 'tooto-elementor' ),
			]
		);

		$repeater->add_control(
			'brand_description',
			[
				'label' => __( '描述', 'tooto-elementor' ),
				'type' => Controls_Manager::TEXTAREA,
				'default' => __( 'Description text here', 'tooto-elementor' ),
			]
		);

		$repeater->add_control(
			'brand_link',
			[
				'label' => __( '链接', 'tooto-elementor' ),
				'type' => Controls_Manager::URL,
				'placeholder' => __( 'https://your-link.com', 'tooto-elementor' ),
				'show_external' => true,
				'default' => [
					'url' => '',
					'is_external' => true,
					'nofollow' => true,
				],
			]
		);
		
		$repeater->add_control(
			'brand_link_text',
			[
				'label' => __( '链接文本', 'tooto-elementor' ),
				'type' => Controls_Manager::TEXT,
				'default' => __( 'See Their Products →', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'brands_list',
			[
				'label' => __( '品牌列表', 'tooto-elementor' ),
				'type' => Controls_Manager::REPEATER,
				'fields' => $repeater->get_controls(),
				'default' => [
					[
						'brand_title' => __( 'Brand #1', 'tooto-elementor' ),
					],
				],
				'title_field' => '{{{ brand_title }}}',
				'condition' => [
					'view_mode' => 'brand_details',
				],
			]
		);

		$this->end_controls_section();

		// Settings Section
		$this->start_controls_section(
			'section_settings',
			[
				'label' => __( '轮播设置', 'tooto-elementor' ),
			]
		);

		$this->add_control(
			'continuous_speed',
			[
				'label' => __( '播放速度', 'tooto-elementor' ),
				'description' => __( '数值越大速度越快', 'tooto-elementor' ),
				'type' => Controls_Manager::SLIDER,
				'range' => [
					'px' => [
						'min' => 0.1,
						'max' => 10,
						'step' => 0.1,
					],
				],
				'default' => [
					'size' => 1,
				],
			]
		);

		$this->add_control(
			'pause_on_hover',
			[
				'label' => __( '悬停暂停', 'tooto-elementor' ),
				'type' => Controls_Manager::SWITCHER,
				'default' => 'yes',
				'label_on' => __( '开启', 'tooto-elementor' ),
				'label_off' => __( '关闭', 'tooto-elementor' ),
			]
		);

		$this->end_controls_section();
		
		// Style Section
		$this->start_controls_section(
			'section_style',
			[
				'label' => __( '样式', 'tooto-elementor' ),
				'tab' => Controls_Manager::TAB_STYLE,
			]
		);
		
		$this->add_control(
			'image_border_radius',
			[
				'label' => __( '图片圆角', 'tooto-elementor' ),
				'type' => Controls_Manager::DIMENSIONS,
				'size_units' => [ 'px', '%' ],
				'selectors' => [
					'{{WRAPPER}} .tooto-image-carousel__image' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
				],
			]
		);

		$this->add_responsive_control(
			'slide_width',
			[
				'label' => __( '图片宽度', 'tooto-elementor' ),
				'type' => Controls_Manager::SLIDER,
				'size_units' => [ 'px', '%', 'vw' ],
				'range' => [
					'px' => [
						'min' => 0,
						'max' => 1000,
						'step' => 1,
					],
					'%' => [
						'min' => 0,
						'max' => 100,
					],
				],
				'default' => [
					'unit' => 'px',
					'size' => 165,
				],
				'selectors' => [
					'{{WRAPPER}} .splide__slide' => 'width: {{SIZE}}{{UNIT}};',
					'{{WRAPPER}} .tooto-image-carousel__image' => 'width: 100%;',
				],
			]
		);

		$this->add_responsive_control(
			'slide_gap',
			[
				'label' => __( '图片间隙', 'tooto-elementor' ),
				'type' => Controls_Manager::SLIDER,
				'size_units' => [ 'px', 'em', 'rem', '%' ],
				'range' => [
					'px' => [
						'min' => 0,
						'max' => 100,
						'step' => 1,
					],
				],
				'default' => [
					'unit' => 'px',
					'size' => 20,
				],
				'render_type' => 'template', // Pass to JS
			]
		);

		$this->add_control(
			'blend_mode',
			[
				'label' => __( '混合模式', 'tooto-elementor' ),
				'type' => Controls_Manager::SELECT,
				'default' => 'normal',
				'options' => [
					'normal' => __( '正常', 'tooto-elementor' ),
					'multiply' => __( '正片叠底 (Multiply)', 'tooto-elementor' ),
				],
			]
		);

		$this->end_controls_section();
	}

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

		// Determine view mode
		$view_mode = $settings['view_mode'] ?? 'simple';
		
		$slides = [];

		if ( 'brand_details' === $view_mode ) {
			if ( ! empty( $settings['brands_list'] ) ) {
				foreach ( $settings['brands_list'] as $item ) {
					if ( empty( $item['brand_logo']['url'] ) ) {
						continue;
					}
					$slides[] = [
						'type' => 'brand_details',
						'image_url' => $item['brand_logo']['url'],
						'image_alt' => Control_Media::get_image_alt( $item['brand_logo'] ),
						'title' => $item['brand_title'],
						'subtitle' => $item['brand_subtitle'],
						'description' => $item['brand_description'],
						'link_url' => $item['brand_link']['url'],
						'link_text' => $item['brand_link_text'],
						'is_external' => $item['brand_link']['is_external'] ? 'true' : 'false',
						'nofollow' => $item['brand_link']['nofollow'] ? 'true' : 'false',
					];
				}
			}
		} else {
			// Simple Mode
			if ( ! empty( $settings['carousel_images'] ) ) {
				foreach ( $settings['carousel_images'] as $image ) {
					$slides[] = [
						'type' => 'simple',
						'image_url' => $image['url'],
						'image_alt' => $image['alt'] ?? '',
					];
				}
			}
		}

		if ( empty( $slides ) ) {
			return;
		}

		$this->add_render_attribute( 'wrapper', 'class', 'tooto-image-carousel' );
		$this->add_render_attribute( 'wrapper', 'class', 'splide' );
		$this->add_render_attribute( 'wrapper', 'class', 'tooto-image-carousel--continuous' );
		
		if ( 'brand_details' === $view_mode ) {
			$this->add_render_attribute( 'wrapper', 'class', 'tooto-image-carousel--brand-details' );
		}

		if ( 'multiply' === $settings['blend_mode'] ) {
			$this->add_render_attribute( 'wrapper', 'class', 'tooto-image-carousel--blend-multiply' );
		}

		// Helper to get gap string
		$get_gap = function( $setting ) {
			if ( empty( $setting ) || ! isset( $setting['size'] ) ) {
				return '20px'; // default
			}
			return $setting['size'] . ( $setting['unit'] ?? 'px' );
		};

		$gap_desktop = $get_gap( $settings['slide_gap'] ?? null );
		$gap_tablet  = $get_gap( $settings['slide_gap_tablet'] ?? null );
		$gap_mobile  = $get_gap( $settings['slide_gap_mobile'] ?? null );

		// Base Splide Options for Continuous Mode
		$splide_options = [
			'type' => 'loop',
			'drag' => 'free',
			'autoWidth' => true,
			'pagination' => false,
			'arrows' => false,
			'gap' => $gap_desktop,
			'autoScroll' => [
				'speed' => $settings['continuous_speed']['size'] ?? 1,
				'pauseOnHover' => false, // Handled manually in JS to restrict to track only
				'useRequestAnimationFrame' => true,
			],
			'breakpoints' => [
				1024 => [
					'gap' => $gap_tablet,
				],
				767 => [
					'gap' => $gap_mobile,
				],
			],
		];
		
		// If brand details mode, we might want to ensure clicks work well
		if ( 'brand_details' === $view_mode ) {
			$splide_options['isNavigation'] = true; // Allows clicking slides to select
			$splide_options['focus'] = 'center'; // Center the selected slide
			$splide_options['updateOnMove'] = true;
		}

		$this->add_render_attribute( 'wrapper', 'data-splide', wp_json_encode( $splide_options ) );
		$this->add_render_attribute( 'wrapper', 'data-tooto-pause-on-hover', 'yes' === $settings['pause_on_hover'] ? 'yes' : 'no' );

		?>
		<div <?php $this->print_render_attribute_string( 'wrapper' ); ?>>
			<div class="splide__track">
				<ul class="splide__list">
					<?php foreach ( $slides as $index => $slide ) : ?>
						<li class="splide__slide tooto-image-carousel__slide" 
							<?php if ( 'brand_details' === $view_mode ) : ?>
								data-brand-title="<?php echo esc_attr( $slide['title'] ); ?>"
								data-brand-subtitle="<?php echo esc_attr( $slide['subtitle'] ); ?>"
								data-brand-description="<?php echo esc_attr( $slide['description'] ); ?>"
								data-brand-link-url="<?php echo esc_attr( $slide['link_url'] ); ?>"
								data-brand-link-text="<?php echo esc_attr( $slide['link_text'] ); ?>"
								data-brand-is-external="<?php echo esc_attr( $slide['is_external'] ); ?>"
								data-brand-nofollow="<?php echo esc_attr( $slide['nofollow'] ); ?>"
							<?php endif; ?>
						>
							<img src="<?php echo esc_url( $slide['image_url'] ); ?>" alt="<?php echo esc_attr( $slide['image_alt'] ); ?>" class="tooto-image-carousel__image">
						</li>
					<?php endforeach; ?>
				</ul>
			</div>
			
			<?php if ( 'brand_details' === $view_mode ) : ?>
				<div class="tooto-brand-details-container">
					<div class="tooto-brand-details-content">
						<h2 class="tooto-brand-title"></h2>
						<div class="tooto-brand-subtitle"></div>
						<div class="tooto-brand-description"></div>
						<a href="#" class="tooto-brand-link"></a>
					</div>
					<!-- Custom Pagination Dots -->
				<div class="tooto-brand-pagination">
					<?php foreach ( $slides as $index => $slide ) : ?><button type="button" class="tooto-brand-dot" aria-label="<?php echo esc_attr( sprintf( __( 'Go to slide %d', 'tooto-elementor' ), $index + 1 ) ); ?>"></button><?php endforeach; ?>
				</div>
				</div>
			<?php endif; ?>
		</div>
		<?php
	}

	/**
	 * Retrieve responsive setting value with fallback.
	 *
	 * @param string $key      The control key.
	 * @param array  $settings The settings array.
	 * @param string $device   The device (mobile, tablet).
	 * @return mixed The setting value.
	 */
	private function get_responsive_settings( string $key, array $settings, string $device = '' ) {
		// If no device specified, return desktop value
		if ( empty( $device ) ) {
			return $settings[ $key ] ?? null;
		}

		$device_key = $key . '_' . $device;

		// Check if specific device setting exists
		if ( isset( $settings[ $device_key ] ) && '' !== $settings[ $device_key ] ) {
			return $settings[ $device_key ];
		}

		// Fallback logic
		if ( 'mobile' === $device ) {
			// Fallback to tablet, then desktop
			$tablet_key = $key . '_tablet';
			if ( isset( $settings[ $tablet_key ] ) && '' !== $settings[ $tablet_key ] ) {
				return $settings[ $tablet_key ];
			}
		}

		// Fallback to desktop
		return $settings[ $key ] ?? null;
	}
}
