<?php

namespace Calio\Widgets;

use Elementor\Controls_Manager;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Typography;
use Elementor\Repeater;
use WP_Query;

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

/**
 * Swiper cube slider for custom cards, posts, pages and WooCommerce products.
 */
class CubeSliderWidget extends BaseWidget
{
    public function get_name(): string
    {
        return 'calio-cube-slider';
    }

    public function get_title(): string
    {
        return esc_html__('Cube Slider', 'calio-addon');
    }

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

    public function get_keywords(): array
    {
        return ['calio', 'cube', 'slider', 'swiper', 'carousel', 'post', 'page', 'product'];
    }

    public function get_style_depends(): array
    {
        $depends = $this->resolve_widget_style_depends('calio-widget-cube-slider');
        $depends[] = 'swiper';

        return array_values(array_unique($depends));
    }

    public function get_script_depends(): array
    {
        return $this->resolve_widget_script_depends('calio-widget-cube-slider');
    }

    protected function register_controls(): void
    {
        $this->register_content_controls();
        $this->register_slider_controls();
        $this->register_motion_controls();
        $this->register_layout_style_controls();
        $this->register_card_style_controls();
        $this->register_text_style_controls();
        $this->register_button_style_controls();
        $this->register_navigation_style_controls();
    }

    private function register_content_controls(): void
    {
        $this->start_controls_section('content_section', [
            'label' => esc_html__('Content', 'calio-addon'),
        ]);

        $this->add_control('content_source', [
            'label' => esc_html__('Source', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'custom',
            'options' => [
                'custom' => esc_html__('Custom Content', 'calio-addon'),
                'post' => esc_html__('Blog Posts', 'calio-addon'),
                'page' => esc_html__('Pages', 'calio-addon'),
                'product' => esc_html__('WooCommerce Products', 'calio-addon'),
            ],
        ]);

        $repeater = new Repeater();
        $repeater->add_control('image', [
            'label' => esc_html__('Image', 'calio-addon'),
            'type' => Controls_Manager::MEDIA,
        ]);
        $repeater->add_control('eyebrow', [
            'label' => esc_html__('Eyebrow', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Featured', 'calio-addon'),
        ]);
        $repeater->add_control('title', [
            'label' => esc_html__('Title', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Cube Slider Item', 'calio-addon'),
            'label_block' => true,
        ]);
        $repeater->add_control('description', [
            'label' => esc_html__('Description', 'calio-addon'),
            'type' => Controls_Manager::TEXTAREA,
            'default' => esc_html__('Use this slide for campaigns, products, posts or visual storytelling.', 'calio-addon'),
        ]);
        $repeater->add_control('badge', [
            'label' => esc_html__('Badge', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('New', 'calio-addon'),
        ]);
        $repeater->add_control('button_text', [
            'label' => esc_html__('Button Text', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Explore', 'calio-addon'),
        ]);
        $repeater->add_control('link', [
            'label' => esc_html__('Link', 'calio-addon'),
            'type' => Controls_Manager::URL,
            'placeholder' => 'https://example.com',
        ]);

        $this->add_control('custom_items', [
            'label' => esc_html__('Slides', 'calio-addon'),
            'type' => Controls_Manager::REPEATER,
            'fields' => $repeater->get_controls(),
            'title_field' => '{{{ title }}}',
            'default' => $this->get_default_custom_items(),
            'condition' => ['content_source' => 'custom'],
        ]);

        $this->add_control('query_limit', [
            'label' => esc_html__('Items', 'calio-addon'),
            'type' => Controls_Manager::NUMBER,
            'default' => 6,
            'min' => 1,
            'max' => 20,
            'condition' => ['content_source!' => 'custom'],
        ]);
        $this->add_control('query_orderby', [
            'label' => esc_html__('Order By', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'date',
            'options' => [
                'date' => esc_html__('Date', 'calio-addon'),
                'title' => esc_html__('Title', 'calio-addon'),
                'menu_order' => esc_html__('Menu Order', 'calio-addon'),
                'rand' => esc_html__('Random', 'calio-addon'),
            ],
            'condition' => ['content_source!' => 'custom'],
        ]);
        $this->add_control('query_order', [
            'label' => esc_html__('Order', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'DESC',
            'options' => [
                'DESC' => 'DESC',
                'ASC' => 'ASC',
            ],
            'condition' => ['content_source!' => 'custom'],
        ]);
        $this->add_control('query_button_text', [
            'label' => esc_html__('Button Text', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('View Details', 'calio-addon'),
            'condition' => ['content_source!' => 'custom'],
        ]);
        $this->add_control('show_excerpt', [
            'label' => esc_html__('Show Excerpt', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
            'condition' => ['content_source!' => 'custom'],
        ]);
        $this->add_control('excerpt_length', [
            'label' => esc_html__('Excerpt Length', 'calio-addon'),
            'type' => Controls_Manager::NUMBER,
            'default' => 18,
            'min' => 5,
            'max' => 60,
            'condition' => [
                'content_source!' => 'custom',
                'show_excerpt' => 'yes',
            ],
        ]);

        $this->end_controls_section();
    }

    private function register_slider_controls(): void
    {
        $this->start_controls_section('slider_section', [
            'label' => esc_html__('Slider', 'calio-addon'),
        ]);

        $this->add_control('loop', [
            'label' => esc_html__('Loop', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);
        $this->add_control('grab_cursor', [
            'label' => esc_html__('Grab Cursor', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);
        $this->add_control('autoplay', [
            'label' => esc_html__('Autoplay', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => '',
        ]);
        $this->add_control('autoplay_speed', [
            'label' => esc_html__('Autoplay Speed', 'calio-addon'),
            'type' => Controls_Manager::NUMBER,
            'default' => 3600,
            'min' => 1200,
            'max' => 12000,
            'step' => 100,
            'condition' => ['autoplay' => 'yes'],
        ]);
        $this->add_control('transition_speed', [
            'label' => esc_html__('Transition Speed', 'calio-addon'),
            'type' => Controls_Manager::NUMBER,
            'default' => 850,
            'min' => 250,
            'max' => 2500,
            'step' => 50,
        ]);
        $this->add_control('pause_on_hover', [
            'label' => esc_html__('Pause On Hover', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
            'condition' => ['autoplay' => 'yes'],
        ]);
        $this->add_control('show_arrows', [
            'label' => esc_html__('Arrows', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);
        $this->add_control('prev_icon', [
            'label' => esc_html__('Previous Icon', 'calio-addon'),
            'type' => Controls_Manager::ICONS,
            'default' => [
                'value' => 'fas fa-chevron-left',
                'library' => 'fa-solid',
            ],
            'condition' => ['show_arrows' => 'yes'],
        ]);
        $this->add_control('next_icon', [
            'label' => esc_html__('Next Icon', 'calio-addon'),
            'type' => Controls_Manager::ICONS,
            'default' => [
                'value' => 'fas fa-chevron-right',
                'library' => 'fa-solid',
            ],
            'condition' => ['show_arrows' => 'yes'],
        ]);
        $this->add_control('show_pagination', [
            'label' => esc_html__('Pagination', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);

        $this->add_control('cube_shadow_heading', [
            'label' => esc_html__('Cube Effect', 'calio-addon'),
            'type' => Controls_Manager::HEADING,
            'separator' => 'before',
        ]);
        $this->add_control('cube_shadow', [
            'label' => esc_html__('Main Shadow', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);
        $this->add_control('cube_slide_shadows', [
            'label' => esc_html__('Slide Shadows', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);
        $this->add_control('cube_shadow_offset', [
            'label' => esc_html__('Shadow Offset', 'calio-addon'),
            'type' => Controls_Manager::NUMBER,
            'default' => 28,
            'min' => 0,
            'max' => 120,
        ]);
        $this->add_control('cube_shadow_scale', [
            'label' => esc_html__('Shadow Scale', 'calio-addon'),
            'type' => Controls_Manager::NUMBER,
            'default' => 0.82,
            'min' => 0,
            'max' => 1.5,
            'step' => 0.01,
        ]);

        $this->end_controls_section();
    }

    private function register_layout_style_controls(): void
    {
        $this->start_controls_section('style_layout', [
            'label' => esc_html__('Layout', 'calio-addon'),
            'tab' => Controls_Manager::TAB_STYLE,
        ]);

        $this->add_responsive_control('slider_height', [
            'label' => esc_html__('Height', 'calio-addon'),
            'type' => Controls_Manager::SLIDER,
            'size_units' => ['px', 'vh'],
            'range' => [
                'px' => ['min' => 260, 'max' => 900],
                'vh' => ['min' => 30, 'max' => 90],
            ],
            'default' => ['size' => 520, 'unit' => 'px'],
            'selectors' => [
                '{{WRAPPER}} .calio-cube-slider' => '--calio-cube-slider-height: {{SIZE}}{{UNIT}};',
            ],
        ]);
        $this->add_responsive_control('slider_max_width', [
            'label' => esc_html__('Max Width', 'calio-addon'),
            'type' => Controls_Manager::SLIDER,
            'size_units' => ['px', '%'],
            'range' => [
                'px' => ['min' => 280, 'max' => 1100],
                '%' => ['min' => 30, 'max' => 100],
            ],
            'default' => ['size' => 620, 'unit' => 'px'],
            'selectors' => [
                '{{WRAPPER}} .calio-cube-slider' => '--calio-cube-slider-width: {{SIZE}}{{UNIT}};',
            ],
        ]);
        $this->add_responsive_control('content_align', [
            'label' => esc_html__('Text Align', 'calio-addon'),
            'type' => Controls_Manager::CHOOSE,
            'options' => [
                'start' => ['title' => esc_html__('Left', 'calio-addon'), 'icon' => 'eicon-text-align-left'],
                'center' => ['title' => esc_html__('Center', 'calio-addon'), 'icon' => 'eicon-text-align-center'],
                'end' => ['title' => esc_html__('Right', 'calio-addon'), 'icon' => 'eicon-text-align-right'],
            ],
            'default' => 'start',
            'selectors' => [
                '{{WRAPPER}} .calio-cube-slider-content' => 'align-items: {{VALUE}}; text-align: {{VALUE}};',
            ],
        ]);
        $this->add_control('content_position', [
            'label' => esc_html__('Content Position', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'bottom',
            'options' => [
                'top' => esc_html__('Top', 'calio-addon'),
                'middle' => esc_html__('Middle', 'calio-addon'),
                'bottom' => esc_html__('Bottom', 'calio-addon'),
            ],
        ]);

        $this->end_controls_section();
    }

    private function register_motion_controls(): void
    {
        $this->start_controls_section('motion_section', [
            'label' => esc_html__('Effects', 'calio-addon'),
        ]);

        $this->add_control('motion_enabled', [
            'label' => esc_html__('Enable Item Effects', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => '',
        ]);
        $this->add_control('motion_effect', [
            'label' => esc_html__('Effect', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'fade-up',
            'options' => [
                'fade-up' => esc_html__('Fade Up', 'calio-addon'),
                'scale-in' => esc_html__('Scale In', 'calio-addon'),
                'slide-left' => esc_html__('Slide From Left', 'calio-addon'),
                'slide-right' => esc_html__('Slide From Right', 'calio-addon'),
                'blur-up' => esc_html__('Blur Up', 'calio-addon'),
            ],
            'condition' => ['motion_enabled' => 'yes'],
        ]);
        $this->add_control('motion_duration', [
            'label' => esc_html__('Duration (ms)', 'calio-addon'),
            'type' => Controls_Manager::NUMBER,
            'default' => 650,
            'min' => 100,
            'max' => 2500,
            'step' => 50,
            'condition' => ['motion_enabled' => 'yes'],
        ]);
        $this->add_control('motion_stagger', [
            'label' => esc_html__('Stagger (ms)', 'calio-addon'),
            'type' => Controls_Manager::NUMBER,
            'default' => 70,
            'min' => 0,
            'max' => 500,
            'step' => 10,
            'condition' => ['motion_enabled' => 'yes'],
        ]);
        $this->add_control('motion_delay', [
            'label' => esc_html__('Delay (ms)', 'calio-addon'),
            'type' => Controls_Manager::NUMBER,
            'default' => 80,
            'min' => 0,
            'max' => 1500,
            'step' => 10,
            'condition' => ['motion_enabled' => 'yes'],
        ]);
        $this->add_control('motion_ease', [
            'label' => esc_html__('Ease', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'power3.out',
            'options' => [
                'power2.out' => 'power2.out',
                'power3.out' => 'power3.out',
                'power4.out' => 'power4.out',
                'expo.out' => 'expo.out',
                'back.out(1.4)' => 'back.out(1.4)',
            ],
            'condition' => ['motion_enabled' => 'yes'],
        ]);

        $this->add_control('split_text_heading', [
            'label' => esc_html__('Split Text', 'calio-addon'),
            'type' => Controls_Manager::HEADING,
            'separator' => 'before',
        ]);
        $this->add_control('split_text_enabled', [
            'label' => esc_html__('Enable Split Text', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => '',
        ]);
        $this->add_control('split_text_targets', [
            'label' => esc_html__('Split Targets', 'calio-addon'),
            'type' => Controls_Manager::SELECT2,
            'multiple' => true,
            'default' => ['title'],
            'options' => [
                'badge' => esc_html__('Badge', 'calio-addon'),
                'eyebrow' => esc_html__('Eyebrow', 'calio-addon'),
                'title' => esc_html__('Title', 'calio-addon'),
                'description' => esc_html__('Description', 'calio-addon'),
                'button' => esc_html__('Button', 'calio-addon'),
            ],
            'condition' => [
                'split_text_enabled' => 'yes',
            ],
        ]);
        $this->add_control('split_text_type', [
            'label' => esc_html__('Split Type', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'words',
            'options' => [
                'chars' => esc_html__('Characters', 'calio-addon'),
                'words' => esc_html__('Words', 'calio-addon'),
                'lines' => esc_html__('Lines', 'calio-addon'),
                'words-chars' => esc_html__('Words + Characters', 'calio-addon'),
            ],
            'condition' => [
                'split_text_enabled' => 'yes',
            ],
        ]);
        $this->add_control('split_text_priority', [
            'label' => esc_html__('Split Priority', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'split-only',
            'options' => [
                'split-only' => esc_html__('Split Text Only', 'calio-addon'),
                'selected-targets' => esc_html__('Only Override Selected Targets', 'calio-addon'),
            ],
            'condition' => [
                'split_text_enabled' => 'yes',
            ],
        ]);
        $this->add_control('split_text_mask', [
            'label' => esc_html__('Mask Reveal', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => '',
            'condition' => [
                'split_text_enabled' => 'yes',
            ],
        ]);
        $this->add_control('split_text_effect', [
            'label' => esc_html__('Split Effect', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'rise',
            'options' => [
                'rise' => esc_html__('Premium Rise', 'calio-addon'),
                'blur' => esc_html__('Soft Blur', 'calio-addon'),
                'scale' => esc_html__('Scale Pop', 'calio-addon'),
                'rotate' => esc_html__('3D Rotate', 'calio-addon'),
            ],
            'condition' => [
                'split_text_enabled' => 'yes',
            ],
        ]);
        $this->add_control('split_text_duration', [
            'label' => esc_html__('Split Duration (ms)', 'calio-addon'),
            'type' => Controls_Manager::NUMBER,
            'default' => 620,
            'min' => 100,
            'max' => 2500,
            'step' => 20,
            'condition' => [
                'split_text_enabled' => 'yes',
            ],
        ]);
        $this->add_control('split_text_stagger', [
            'label' => esc_html__('Split Stagger (ms)', 'calio-addon'),
            'type' => Controls_Manager::NUMBER,
            'default' => 34,
            'min' => 0,
            'max' => 300,
            'step' => 2,
            'condition' => [
                'split_text_enabled' => 'yes',
            ],
        ]);

        $this->end_controls_section();
    }

    private function register_card_style_controls(): void
    {
        $this->start_controls_section('style_card', [
            'label' => esc_html__('Card', 'calio-addon'),
            'tab' => Controls_Manager::TAB_STYLE,
        ]);

        $this->add_dimensions_control('card_padding', esc_html__('Padding', 'calio-addon'), '{{WRAPPER}} .calio-cube-slider-content', 'padding');
        $this->add_dimensions_control('card_radius', esc_html__('Radius', 'calio-addon'), ['{{WRAPPER}} .calio-cube-slider-card', '{{WRAPPER}} .calio-cube-slider-media', '{{WRAPPER}} .calio-cube-slider-media img'], 'border-radius', ['size_units' => ['px', '%']]);
        $this->add_background_type_control('card_background', '{{WRAPPER}} .calio-cube-slider-card');
        $this->add_control('overlay_opacity', [
            'label' => esc_html__('Image Overlay Opacity', 'calio-addon'),
            'type' => Controls_Manager::SLIDER,
            'range' => ['px' => ['min' => 0, 'max' => 1, 'step' => 0.01]],
            'default' => ['size' => 0.45],
            'selectors' => [
                '{{WRAPPER}} .calio-cube-slider' => '--calio-cube-overlay-opacity: {{SIZE}};',
            ],
        ]);
        $this->add_control('overlay_color', [
            'label' => esc_html__('Image Overlay Color', 'calio-addon'),
            'type' => Controls_Manager::COLOR,
            'default' => '#101729',
            'selectors' => [
                '{{WRAPPER}} .calio-cube-slider' => '--calio-cube-overlay-color: {{VALUE}};',
            ],
        ]);
        $this->add_group_control(Group_Control_Border::get_type(), [
            'name' => 'card_border',
            'selector' => '{{WRAPPER}} .calio-cube-slider-card',
        ]);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), [
            'name' => 'card_shadow',
            'selector' => '{{WRAPPER}} .calio-cube-slider-card',
        ]);

        $this->end_controls_section();
    }

    private function register_text_style_controls(): void
    {
        $this->start_controls_section('style_text', [
            'label' => esc_html__('Text', 'calio-addon'),
            'tab' => Controls_Manager::TAB_STYLE,
        ]);

        $this->add_group_control(Group_Control_Typography::get_type(), [
            'name' => 'eyebrow_typography',
            'selector' => '{{WRAPPER}} .calio-cube-slider-eyebrow',
        ]);
        $this->add_text_paint_controls('cube_eyebrow_color', esc_html__('Eyebrow Color', 'calio-addon'), '{{WRAPPER}} .calio-cube-slider-eyebrow');
        $this->add_group_control(Group_Control_Typography::get_type(), [
            'name' => 'title_typography',
            'selector' => '{{WRAPPER}} .calio-cube-slider-title, {{WRAPPER}} .calio-cube-slider-title a',
        ]);
        $this->add_text_paint_controls('cube_title_color', esc_html__('Title Color', 'calio-addon'), ['{{WRAPPER}} .calio-cube-slider-title', '{{WRAPPER}} .calio-cube-slider-title a']);
        $this->add_group_control(Group_Control_Typography::get_type(), [
            'name' => 'description_typography',
            'selector' => '{{WRAPPER}} .calio-cube-slider-description',
        ]);
        $this->add_text_paint_controls('cube_description_color', esc_html__('Description Color', 'calio-addon'), '{{WRAPPER}} .calio-cube-slider-description');
        $this->add_group_control(Group_Control_Typography::get_type(), [
            'name' => 'badge_typography',
            'selector' => '{{WRAPPER}} .calio-cube-slider-badge',
        ]);
        $this->add_text_paint_controls('cube_badge_color', esc_html__('Badge Color', 'calio-addon'), '{{WRAPPER}} .calio-cube-slider-badge');
        $this->add_background_type_control('cube_badge_bg', '{{WRAPPER}} .calio-cube-slider-badge');

        $this->end_controls_section();
    }

    private function register_button_style_controls(): void
    {
        $this->start_controls_section('style_button', [
            'label' => esc_html__('Button', 'calio-addon'),
            'tab' => Controls_Manager::TAB_STYLE,
        ]);

        $this->add_group_control(Group_Control_Typography::get_type(), [
            'name' => 'button_typography',
            'selector' => '{{WRAPPER}} .calio-cube-slider-button',
        ]);
        $this->add_dimensions_control('button_padding', esc_html__('Padding', 'calio-addon'), '{{WRAPPER}} .calio-cube-slider-button', 'padding');
        $this->add_dimensions_control('button_radius', esc_html__('Radius', 'calio-addon'), '{{WRAPPER}} .calio-cube-slider-button', 'border-radius', ['size_units' => ['px', '%']]);

        $this->start_controls_tabs('button_tabs');
        $this->start_controls_tab('button_normal', ['label' => esc_html__('Normal', 'calio-addon')]);
        $this->add_text_paint_controls('button_text_normal', esc_html__('Text Color', 'calio-addon'), '{{WRAPPER}} .calio-cube-slider-button');
        $this->add_background_type_control('button_bg_normal', '{{WRAPPER}} .calio-cube-slider-button');
        $this->end_controls_tab();
        $this->start_controls_tab('button_hover', ['label' => esc_html__('Hover', 'calio-addon')]);
        $this->add_text_paint_controls('button_text_hover', esc_html__('Text Color', 'calio-addon'), '{{WRAPPER}} .calio-cube-slider-button:hover');
        $this->add_background_type_control('button_bg_hover', '{{WRAPPER}} .calio-cube-slider-button:hover');
        $this->end_controls_tab();
        $this->end_controls_tabs();

        $this->end_controls_section();
    }

    private function register_navigation_style_controls(): void
    {
        $this->start_controls_section('style_navigation', [
            'label' => esc_html__('Navigation', 'calio-addon'),
            'tab' => Controls_Manager::TAB_STYLE,
        ]);

        $this->add_control('navigation_position', [
            'label' => esc_html__('Position', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'side',
            'options' => [
                'side' => esc_html__('Side', 'calio-addon'),
                'top' => esc_html__('Top', 'calio-addon'),
                'bottom' => esc_html__('Bottom', 'calio-addon'),
            ],
        ]);
        $this->add_control('navigation_align', [
            'label' => esc_html__('Alignment', 'calio-addon'),
            'type' => Controls_Manager::CHOOSE,
            'options' => [
                'left' => ['title' => esc_html__('Left', 'calio-addon'), 'icon' => 'eicon-h-align-left'],
                'center' => ['title' => esc_html__('Center', 'calio-addon'), 'icon' => 'eicon-h-align-center'],
                'right' => ['title' => esc_html__('Right', 'calio-addon'), 'icon' => 'eicon-h-align-right'],
            ],
            'default' => 'center',
            'condition' => ['navigation_position!' => 'side'],
        ]);
        $this->add_control('navigation_offset', [
            'label' => esc_html__('Offset', 'calio-addon'),
            'type' => Controls_Manager::SLIDER,
            'size_units' => ['px'],
            'range' => ['px' => ['min' => -80, 'max' => 120]],
            'default' => ['size' => 20, 'unit' => 'px'],
            'selectors' => [
                '{{WRAPPER}} .calio-cube-slider' => '--calio-cube-nav-offset: {{SIZE}}{{UNIT}};',
            ],
        ]);
        $this->add_control('navigation_gap', [
            'label' => esc_html__('Gap', 'calio-addon'),
            'type' => Controls_Manager::SLIDER,
            'size_units' => ['px'],
            'range' => ['px' => ['min' => 0, 'max' => 48]],
            'default' => ['size' => 12, 'unit' => 'px'],
            'selectors' => [
                '{{WRAPPER}} .calio-cube-slider' => '--calio-cube-nav-gap: {{SIZE}}{{UNIT}};',
            ],
        ]);
        $this->add_control('arrow_size', [
            'label' => esc_html__('Button Size', 'calio-addon'),
            'type' => Controls_Manager::SLIDER,
            'range' => ['px' => ['min' => 32, 'max' => 96]],
            'default' => ['size' => 46],
            'selectors' => [
                '{{WRAPPER}} .calio-cube-slider' => '--calio-cube-arrow-size: {{SIZE}}{{UNIT}};',
            ],
        ]);
        $this->add_control('arrow_icon_size', [
            'label' => esc_html__('Icon Size', 'calio-addon'),
            'type' => Controls_Manager::SLIDER,
            'range' => ['px' => ['min' => 8, 'max' => 54]],
            'default' => ['size' => 18],
            'selectors' => [
                '{{WRAPPER}} .calio-cube-slider' => '--calio-cube-arrow-icon-size: {{SIZE}}{{UNIT}};',
            ],
        ]);
        $this->add_dimensions_control('arrow_padding', esc_html__('Padding', 'calio-addon'), '{{WRAPPER}} .calio-cube-slider-arrow', 'padding');
        $this->add_dimensions_control('arrow_radius', esc_html__('Radius', 'calio-addon'), '{{WRAPPER}} .calio-cube-slider-arrow', 'border-radius', ['size_units' => ['px', '%']]);

        $this->start_controls_tabs('arrow_state_tabs');
        $this->start_controls_tab('arrow_state_normal', ['label' => esc_html__('Normal', 'calio-addon')]);
        $this->add_text_paint_controls('nav_text', esc_html__('Icon Color', 'calio-addon'), '{{WRAPPER}} .calio-cube-slider-arrow');
        $this->add_background_type_control('nav_bg', '{{WRAPPER}} .calio-cube-slider-arrow');
        $this->end_controls_tab();
        $this->start_controls_tab('arrow_state_hover', ['label' => esc_html__('Hover', 'calio-addon')]);
        $this->add_text_paint_controls('nav_text_hover', esc_html__('Icon Color', 'calio-addon'), '{{WRAPPER}} .calio-cube-slider-arrow:hover');
        $this->add_background_type_control('nav_bg_hover', '{{WRAPPER}} .calio-cube-slider-arrow:hover');
        $this->end_controls_tab();
        $this->end_controls_tabs();

        $this->add_group_control(Group_Control_Border::get_type(), [
            'name' => 'arrow_border',
            'selector' => '{{WRAPPER}} .calio-cube-slider-arrow',
        ]);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), [
            'name' => 'arrow_shadow',
            'selector' => '{{WRAPPER}} .calio-cube-slider-arrow',
        ]);
        $this->add_control('dot_color', [
            'label' => esc_html__('Dot Color', 'calio-addon'),
            'type' => Controls_Manager::COLOR,
            'default' => '#d5def5',
            'selectors' => [
                '{{WRAPPER}} .calio-cube-slider' => '--calio-cube-dot-color: {{VALUE}};',
            ],
        ]);
        $this->add_control('dot_active_color', [
            'label' => esc_html__('Active Dot Color', 'calio-addon'),
            'type' => Controls_Manager::COLOR,
            'default' => '#2563ff',
            'selectors' => [
                '{{WRAPPER}} .calio-cube-slider' => '--calio-cube-dot-active-color: {{VALUE}};',
            ],
        ]);

        $this->end_controls_section();
    }

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

        if (empty($slides)) {
            echo '<div class="calio-cube-slider-empty">' . esc_html__('No slider items found.', 'calio-addon') . '</div>';
            return;
        }

        $slider_id = 'calio-cube-slider-' . $this->get_id();
        $classes = [
            'calio-cube-slider',
            'content-position-' . sanitize_html_class((string) ($settings['content_position'] ?? 'bottom')),
            'text-align-' . sanitize_html_class((string) ($settings['content_align'] ?? 'start')),
            'nav-position-' . sanitize_html_class((string) ($settings['navigation_position'] ?? 'side')),
            'nav-align-' . sanitize_html_class((string) ($settings['navigation_align'] ?? 'center')),
        ];
        if (($settings['motion_enabled'] ?? '') === 'yes') {
            $classes[] = 'motion-enabled';
        }
        if (($settings['split_text_enabled'] ?? '') === 'yes') {
            $classes[] = 'split-text-enabled';
        }

        $split_targets = $settings['split_text_targets'] ?? ['title'];
        if (!is_array($split_targets)) {
            $split_targets = array_filter(array_map('trim', explode(',', (string) $split_targets)));
        }
        $split_targets = implode(',', array_map('sanitize_key', $split_targets));

        echo '<div id="' . esc_attr($slider_id) . '" class="' . esc_attr(implode(' ', $classes)) . '"';
        echo ' data-loop="' . esc_attr((string) ($settings['loop'] ?? 'yes')) . '"';
        echo ' data-grab-cursor="' . esc_attr((string) ($settings['grab_cursor'] ?? 'yes')) . '"';
        echo ' data-autoplay="' . esc_attr((string) ($settings['autoplay'] ?? '')) . '"';
        echo ' data-autoplay-speed="' . esc_attr((string) ($settings['autoplay_speed'] ?? '3600')) . '"';
        echo ' data-speed="' . esc_attr((string) ($settings['transition_speed'] ?? '850')) . '"';
        echo ' data-pause-on-hover="' . esc_attr((string) ($settings['pause_on_hover'] ?? 'yes')) . '"';
        echo ' data-cube-shadow="' . esc_attr((string) ($settings['cube_shadow'] ?? 'yes')) . '"';
        echo ' data-cube-slide-shadows="' . esc_attr((string) ($settings['cube_slide_shadows'] ?? 'yes')) . '"';
        echo ' data-cube-shadow-offset="' . esc_attr((string) ($settings['cube_shadow_offset'] ?? '28')) . '"';
        echo ' data-cube-shadow-scale="' . esc_attr((string) ($settings['cube_shadow_scale'] ?? '0.82')) . '"';
        echo ' data-motion-enabled="' . esc_attr((string) ($settings['motion_enabled'] ?? '')) . '"';
        echo ' data-motion-effect="' . esc_attr((string) ($settings['motion_effect'] ?? 'fade-up')) . '"';
        echo ' data-motion-duration="' . esc_attr((string) ($settings['motion_duration'] ?? '650')) . '"';
        echo ' data-motion-stagger="' . esc_attr((string) ($settings['motion_stagger'] ?? '70')) . '"';
        echo ' data-motion-delay="' . esc_attr((string) ($settings['motion_delay'] ?? '80')) . '"';
        echo ' data-motion-ease="' . esc_attr((string) ($settings['motion_ease'] ?? 'power3.out')) . '"';
        echo ' data-split-enabled="' . esc_attr((string) ($settings['split_text_enabled'] ?? '')) . '"';
        echo ' data-split-targets="' . esc_attr($split_targets !== '' ? $split_targets : 'title') . '"';
        echo ' data-split-type="' . esc_attr((string) ($settings['split_text_type'] ?? 'words')) . '"';
        echo ' data-split-priority="' . esc_attr((string) ($settings['split_text_priority'] ?? 'split-only')) . '"';
        echo ' data-split-mask="' . esc_attr((string) ($settings['split_text_mask'] ?? '')) . '"';
        echo ' data-split-effect="' . esc_attr((string) ($settings['split_text_effect'] ?? 'rise')) . '"';
        echo ' data-split-duration="' . esc_attr((string) ($settings['split_text_duration'] ?? '620')) . '"';
        echo ' data-split-stagger="' . esc_attr((string) ($settings['split_text_stagger'] ?? '34')) . '"';
        echo '>';

        echo '<div class="swiper calio-cube-slider-swiper">';
        echo '<div class="swiper-wrapper">';
        foreach ($slides as $slide) {
            $this->render_slide($slide);
        }
        echo '</div>';
        echo '</div>';

        if (($settings['show_arrows'] ?? 'yes') === 'yes') {
            echo '<div class="calio-cube-slider-arrows">';
            echo '<button class="calio-cube-slider-arrow is-prev" type="button" aria-label="' . esc_attr__('Previous slide', 'calio-addon') . '">';
            $this->render_arrow_icon($settings['prev_icon'] ?? [], '&larr;');
            echo '</button>';
            echo '<button class="calio-cube-slider-arrow is-next" type="button" aria-label="' . esc_attr__('Next slide', 'calio-addon') . '">';
            $this->render_arrow_icon($settings['next_icon'] ?? [], '&rarr;');
            echo '</button>';
            echo '</div>';
        }

        if (($settings['show_pagination'] ?? 'yes') === 'yes') {
            echo '<div class="calio-cube-slider-pagination swiper-pagination"></div>';
        }

        echo '</div>';
    }

    /**
     * @param array<string, mixed> $settings
     * @return array<int, array<string, string>>
     */
    private function get_slides(array $settings): array
    {
        $source = (string) ($settings['content_source'] ?? 'custom');

        if ($source === 'custom') {
            return $this->get_custom_slides($settings);
        }

        if ($source === 'product' && !post_type_exists('product')) {
            return [];
        }

        return $this->get_query_slides($settings, $source);
    }

    /**
     * @param array<string, mixed> $settings
     * @return array<int, array<string, string>>
     */
    private function get_custom_slides(array $settings): array
    {
        $items = is_array($settings['custom_items'] ?? null) ? $settings['custom_items'] : [];
        $slides = [];

        foreach ($items as $item) {
            $image = '';
            if (!empty($item['image']['id'])) {
                $image = (string) wp_get_attachment_image_url((int) $item['image']['id'], 'large');
            } elseif (!empty($item['image']['url'])) {
                $image = (string) $item['image']['url'];
            }

            $rel = [];
            if (!empty($item['link']['is_external'])) {
                $rel[] = 'noopener';
                $rel[] = 'noreferrer';
            }
            if (!empty($item['link']['nofollow'])) {
                $rel[] = 'nofollow';
            }

            $slides[] = [
                'image' => $image,
                'eyebrow' => (string) ($item['eyebrow'] ?? ''),
                'title' => (string) ($item['title'] ?? ''),
                'description' => (string) ($item['description'] ?? ''),
                'badge' => (string) ($item['badge'] ?? ''),
                'button_text' => (string) ($item['button_text'] ?? ''),
                'url' => isset($item['link']['url']) ? (string) $item['link']['url'] : '',
                'target' => !empty($item['link']['is_external']) ? '_blank' : '',
                'rel' => implode(' ', array_unique($rel)),
            ];
        }

        return $slides;
    }

    /**
     * @param array<string, mixed> $settings
     * @return array<int, array<string, string>>
     */
    private function get_query_slides(array $settings, string $post_type): array
    {
        $query = new WP_Query([
            'post_type' => sanitize_key($post_type),
            'posts_per_page' => max(1, min(20, (int) ($settings['query_limit'] ?? 6))),
            'orderby' => sanitize_key((string) ($settings['query_orderby'] ?? 'date')),
            'order' => in_array((string) ($settings['query_order'] ?? 'DESC'), ['ASC', 'DESC'], true) ? (string) $settings['query_order'] : 'DESC',
            'post_status' => 'publish',
            'no_found_rows' => true,
        ]);

        $slides = [];
        $excerpt_length = max(5, min(60, (int) ($settings['excerpt_length'] ?? 18)));
        $button_text = trim((string) ($settings['query_button_text'] ?? esc_html__('View Details', 'calio-addon')));

        while ($query->have_posts()) {
            $query->the_post();
            $post_id = get_the_ID();
            $badge = get_post_type_object(get_post_type())?->labels->singular_name ?? '';

            if ($post_type === 'product' && function_exists('wc_get_product')) {
                $product = wc_get_product($post_id);
                if ($product) {
                    $badge = $this->get_product_price_label($product);
                }
            }

            $slides[] = [
                'image' => (string) get_the_post_thumbnail_url($post_id, 'large'),
                'eyebrow' => (string) get_the_date(),
                'title' => (string) get_the_title(),
                'description' => (($settings['show_excerpt'] ?? 'yes') === 'yes') ? wp_trim_words(wp_strip_all_tags(get_the_excerpt()), $excerpt_length) : '',
                'badge' => (string) $badge,
                'button_text' => $button_text,
                'url' => (string) get_permalink(),
                'target' => '',
                'rel' => '',
            ];
        }

        wp_reset_postdata();

        return $slides;
    }

    /**
     * Returns a single plain-text WooCommerce price instead of dumping full price HTML/ranges.
     *
     * @param object $product WooCommerce product instance.
     */
    private function get_product_price_label($product): string
    {
        if (!is_object($product) || !method_exists($product, 'get_price')) {
            return '';
        }

        $price = (string) $product->get_price();
        if ($price === '') {
            return '';
        }

        if (function_exists('wc_price')) {
            return html_entity_decode(wp_strip_all_tags(wc_price((float) $price)), ENT_QUOTES, get_bloginfo('charset'));
        }

        return $price;
    }

    /**
     * @param array<string, string> $slide
     */
    private function render_slide(array $slide): void
    {
        $url = trim($slide['url'] ?? '');
        $target = trim($slide['target'] ?? '');
        $rel = trim($slide['rel'] ?? '');

        echo '<div class="swiper-slide">';
        echo '<article class="calio-cube-slider-card">';

        if (!empty($slide['image'])) {
            echo '<div class="calio-cube-slider-media">';
            echo '<img src="' . esc_url($slide['image']) . '" alt="' . esc_attr($slide['title'] ?? '') . '" loading="lazy">';
            echo '</div>';
        } else {
            echo '<div class="calio-cube-slider-media is-placeholder" aria-hidden="true"></div>';
        }

        echo '<div class="calio-cube-slider-content">';
        if (!empty($slide['badge'])) {
            echo '<span class="calio-cube-slider-badge calio-cube-animate-item calio-cube-split-target-badge">' . esc_html($slide['badge']) . '</span>';
        }
        if (!empty($slide['eyebrow'])) {
            echo '<span class="calio-cube-slider-eyebrow calio-cube-animate-item calio-cube-split-target-eyebrow">' . esc_html($slide['eyebrow']) . '</span>';
        }
        if (!empty($slide['title'])) {
            echo '<h3 class="calio-cube-slider-title calio-cube-animate-item calio-cube-split-target-title">';
            if ($url !== '') {
                echo '<a href="' . esc_url($url) . '"';
                if ($target !== '') {
                    echo ' target="' . esc_attr($target) . '"';
                }
                if ($rel !== '') {
                    echo ' rel="' . esc_attr($rel) . '"';
                }
                echo '>' . esc_html($slide['title']) . '</a>';
            } else {
                echo esc_html($slide['title']);
            }
            echo '</h3>';
        }
        if (!empty($slide['description'])) {
            echo '<div class="calio-cube-slider-description calio-cube-animate-item calio-cube-split-target-description">' . esc_html($slide['description']) . '</div>';
        }
        if ($url !== '' && !empty($slide['button_text'])) {
            echo '<a class="calio-cube-slider-button calio-cube-animate-item calio-cube-split-target-button" href="' . esc_url($url) . '"';
            if ($target !== '') {
                echo ' target="' . esc_attr($target) . '"';
            }
            if ($rel !== '') {
                echo ' rel="' . esc_attr($rel) . '"';
            }
            echo '>' . esc_html($slide['button_text']) . '</a>';
        }
        echo '</div>';

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

    /**
     * @param mixed  $icon Elementor icon control value.
     * @param string $fallback Fallback text arrow.
     */
    private function render_arrow_icon($icon, string $fallback): void
    {
        if (is_array($icon) && !empty($icon['value'])) {
            echo wp_kses_post($this->get_icon_markup($icon));
            return;
        }

        echo '<span class="calio-cube-slider-arrow-fallback" aria-hidden="true">' . esc_html($fallback) . '</span>';
    }

    /**
     * @return array<int, array<string, string>>
     */
    private function get_default_custom_items(): array
    {
        return [
            [
                'eyebrow' => esc_html__('Design Story', 'calio-addon'),
                'title' => esc_html__('Editorial Cube Slider', 'calio-addon'),
                'description' => esc_html__('A focused cube slider for campaigns, posts and featured product moments.', 'calio-addon'),
                'badge' => esc_html__('Featured', 'calio-addon'),
                'button_text' => esc_html__('Explore', 'calio-addon'),
            ],
            [
                'eyebrow' => esc_html__('Product Drop', 'calio-addon'),
                'title' => esc_html__('Showcase One Hero Item', 'calio-addon'),
                'description' => esc_html__('Keep the widget clean: one cube, one content card, no extra hero wrapper.', 'calio-addon'),
                'badge' => esc_html__('New', 'calio-addon'),
                'button_text' => esc_html__('View', 'calio-addon'),
            ],
            [
                'eyebrow' => esc_html__('Content Feed', 'calio-addon'),
                'title' => esc_html__('Use Posts, Pages or Products', 'calio-addon'),
                'description' => esc_html__('Switch the source from custom content to WordPress or WooCommerce entries.', 'calio-addon'),
                'badge' => esc_html__('Flexible', 'calio-addon'),
                'button_text' => esc_html__('Read More', 'calio-addon'),
            ],
        ];
    }
}
