<?php
namespace Softech_Addons_for_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\Repeater;
use Elementor\Utils;
use Elementor\Widget_Base;
use Elementor\Core\DynamicTags\Manager as Dynamic_Tags_Manager;

// ── NEW: load the Query Manager so we can call its static methods ──────────
if ( ! class_exists( '\\Softech_Addons_for_Elementor\\Includes\\Softech_Post_Query_Manager' ) ) {
    require_once SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . 'includes/class-post-query-manager.php';
}
use Softech_Addons_for_Elementor\Includes\Softech_Post_Query_Manager;
// ──────────────────────────────────────────────────────────────────────────

class sitsel_filterable_gallery extends Widget_Base
{
    private static $ajax_hooks_registered = false;
    private static $editor_hooks_registered = false;

    private function get_widget_asset_version($relative_path)
    {
        $base_version = SITS_ELEMENTOR_ADDONS_VERSION;
        $file_path    = SITS_ELEMENTOR_ADDONS_PLUGIN_PATH . ltrim($relative_path, '/\\');

        if (file_exists($file_path)) {
            return $base_version . '.' . (string) filemtime($file_path);
        }

        return $base_version;
    }

    public function __construct($data = [], $args = null)
    {
        parent::__construct($data, $args);
        $this->register_ajax_hooks();
        $this->register_editor_hooks();
    }

    public function get_name()
    {
        return 'sitsel_filterable_gallery';
    }

    public function get_title()
    {
        return __('SITS Filterable Gallery', 'softech-addons-for-elementor');
    }

    public function get_icon()
    {
        return 'eicon-gallery-grid';
    }

    public function get_categories()
    {
        return ['sits-category'];
    }

    public function get_keywords()
    {
        return ['gallery', 'filter', 'masonry', 'lightbox', 'ajax'];
    }

    private function register_ajax_hooks()
    {
        if (self::$ajax_hooks_registered) {
            return;
        }

        add_action('wp_ajax_sitsel_filterable_gallery_filter', [$this, 'handle_ajax_filter']);
        add_action('wp_ajax_nopriv_sitsel_filterable_gallery_filter', [$this, 'handle_ajax_filter']);
        self::$ajax_hooks_registered = true;
    }

    private function register_editor_hooks()
    {
        if (self::$editor_hooks_registered) {
            return;
        }

        add_action('elementor/editor/after_enqueue_scripts', [$this, 'enqueue_editor_script']);
        self::$editor_hooks_registered = true;
    }

    public function enqueue_editor_script()
    {
        $this->register_widget_assets();
        wp_enqueue_script('sitsel-filterable-gallery-editor-js');
    }

    private function register_widget_assets()
    {
        $url            = SITS_ELEMENTOR_ADDONS_PLUGIN_URL;
        $style_version  = $this->get_widget_asset_version('assets/css/sitsel-filterable-gallery.css');
        $script_version = $this->get_widget_asset_version('assets/js/sitsel-filterable-gallery.js');
        $editor_version = $this->get_widget_asset_version('assets/js/sitsel-filterable-gallery-editor.js');

        if (!wp_style_is('sitsel-filterable-gallery-css', 'registered')) {
            wp_register_style('sitsel-filterable-gallery-css', $url . 'assets/css/sitsel-filterable-gallery.css', [], $style_version);
        }

        if (!wp_script_is('sitsel-filterable-gallery-js', 'registered')) {
            wp_register_script('sitsel-filterable-gallery-js', $url . 'assets/js/sitsel-filterable-gallery.js', ['jquery'], $script_version, true);
        }

        if (!wp_script_is('sitsel-filterable-gallery-editor-js', 'registered')) {
            wp_register_script('sitsel-filterable-gallery-editor-js', $url . 'assets/js/sitsel-filterable-gallery-editor.js', ['jquery', 'sitsel-filterable-gallery-js'], $editor_version, true);
        }

        wp_localize_script('sitsel-filterable-gallery-js', 'sitselFilterableGallery', [
            'ajaxUrl' => esc_url_raw(admin_url('admin-ajax.php')),
            'nonce'   => wp_create_nonce('sitsel_filterable_gallery'),
            'labels'  => [
                'loading'     => esc_html__('Loading gallery items...', 'softech-addons-for-elementor'),
                'loadingMore' => esc_html__('Loading more items...', 'softech-addons-for-elementor'),
                'noItems'     => esc_html__('No gallery items found.', 'softech-addons-for-elementor'),
            ],
        ]);
    }

    public function get_style_depends()
    {
        $this->register_widget_assets();
        return ['sitsel-filterable-gallery-css'];
    }

    public function get_script_depends()
    {
        $this->register_widget_assets();
        $scripts = ['sitsel-filterable-gallery-js'];

        if ($this->is_editor_mode()) {
            $scripts[] = 'sitsel-filterable-gallery-editor-js';
        }

        return $scripts;
    }

    protected function _register_controls()
    {
        // ── GALLERY SECTION ────────────────────────────────────────────────
        $repeater = new Repeater();
        $repeater->add_control('images', ['label' => esc_html__('Multiple Images', 'softech-addons-for-elementor'), 'type' => Controls_Manager::GALLERY, 'description' => esc_html__('You can add multiple images for each gallery item', 'softech-addons-for-elementor')]);
        $repeater->add_control('title', ['label' => esc_html__('Title', 'softech-addons-for-elementor'), 'type' => Controls_Manager::TEXT, 'dynamic' => ['active' => true], 'default' => esc_html__('Gallery Item', 'softech-addons-for-elementor')]);
        $repeater->add_control('category', ['label' => esc_html__('Category', 'softech-addons-for-elementor'), 'type' => Controls_Manager::TEXT, 'default' => esc_html__('Category', 'softech-addons-for-elementor'), 'description' => esc_html__('Use comma-separated values to assign multiple categories.', 'softech-addons-for-elementor')]);
        $repeater->add_control('description', ['label' => esc_html__('Description', 'softech-addons-for-elementor'), 'type' => Controls_Manager::TEXTAREA, 'dynamic' => ['active' => true], 'rows' => 3]);
        $repeater->add_control('link', ['label' => esc_html__('Link', 'softech-addons-for-elementor'), 'type' => Controls_Manager::URL, 'dynamic' => ['active' => true], 'placeholder' => esc_html__('https://your-link.com', 'softech-addons-for-elementor'), 'description' => esc_html__('Used when On Image Click is set to Custom Link.', 'softech-addons-for-elementor')]);
        $repeater->add_control('link_target', ['label' => esc_html__('Link Target', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SELECT, 'default' => '_self', 'options' => ['_self' => esc_html__('Same Tab', 'softech-addons-for-elementor'), '_blank' => esc_html__('New Tab', 'softech-addons-for-elementor')], 'description' => esc_html__('Used when On Image Click is set to Custom Link.', 'softech-addons-for-elementor')]);

        $this->start_controls_section('section_gallery', ['label' => esc_html__('Gallery', 'softech-addons-for-elementor'), 'tab' => Controls_Manager::TAB_CONTENT]);

        // ── SOURCE control — 3 options now ───────────────────────────────
        $this->add_control('source', [
            'label'   => esc_html__('Source', 'softech-addons-for-elementor'),
            'type'    => Controls_Manager::SELECT,
            'default' => 'basic_gallery',
            'options' => [
                'basic_gallery' => esc_html__('Basic Gallery', 'softech-addons-for-elementor'),
                'static'        => esc_html__('Filter Gallery', 'softech-addons-for-elementor'),
                // ── NEW ───────────────────────────────────────────────────
                'dynamic'       => esc_html__('Dynamic Gallery', 'softech-addons-for-elementor'),
                // ─────────────────────────────────────────────────────────
            ],
        ]);

        // Basic Gallery images (unchanged — only shows for basic_gallery)
        $this->add_control('basic_gallery_images', ['label' => esc_html__('Images', 'softech-addons-for-elementor'), 'type' => Controls_Manager::GALLERY, 'condition' => ['source' => 'basic_gallery']]);

        // Category Gallery repeater items (unchanged — only shows for static)
        $this->add_control('gallery_items', [
            'label'       => esc_html__('Gallery Items', 'softech-addons-for-elementor'),
            'type'        => Controls_Manager::REPEATER,
            'fields'      => $repeater->get_controls(),
            'title_field' => '{{{ title || "Gallery Item" }}}',
            'default'     => [
                [
                    'title'    => esc_html__('Gallery Item', 'softech-addons-for-elementor'),
                    'category' => esc_html__('Category', 'softech-addons-for-elementor'),
                    'images'   => [],
                ],
            ],
            'condition' => ['source' => 'static'],  // unchanged
        ]);

        // ── Filter-bar controls: show for BOTH static and dynamic ─────────
        // (basic_gallery has no categories, so filter makes no sense there)
        $this->add_control('show_filter_bar', [
            'label'     => esc_html__('Show Filter Bar', 'softech-addons-for-elementor'),
            'type'      => Controls_Manager::SWITCHER,
            'default'   => 'yes',
            'condition' => ['source!' => 'basic_gallery'],   // was: ['source'=>'static']
        ]);
        $this->add_control('show_all_tab', [
            'label'     => esc_html__('Show All Tab', 'softech-addons-for-elementor'),
            'type'      => Controls_Manager::SWITCHER,
            'default'   => 'yes',
            'condition' => ['source!' => 'basic_gallery', 'show_filter_bar' => 'yes'],
        ]);
        $this->add_control('all_label', [
            'label'     => esc_html__('All Label', 'softech-addons-for-elementor'),
            'type'      => Controls_Manager::TEXT,
            'default'   => esc_html__('All', 'softech-addons-for-elementor'),
            'condition' => ['source!' => 'basic_gallery', 'show_filter_bar' => 'yes', 'show_all_tab' => 'yes'],
        ]);

        // ── NEW: taxonomy to use for Dynamic Gallery filter tabs ──────────
        $this->add_control('dynamic_filter_taxonomy', [
            'label'       => esc_html__('Filter Taxonomy', 'softech-addons-for-elementor'),
            'type'        => Controls_Manager::SELECT,
            'default'     => 'category',
            'description' => esc_html__('Taxonomy used to build the filter tabs for Dynamic Gallery.', 'softech-addons-for-elementor'),
            'options'     => $this->get_public_taxonomies_for_select(),
            'condition'   => ['source' => 'dynamic', 'show_filter_bar' => 'yes'],
        ]);
        $this->add_control('dynamic_gallery_item_heading', ['label' => esc_html__('Gallery Item', 'softech-addons-for-elementor'), 'type' => Controls_Manager::HEADING, 'separator' => 'before', 'condition' => ['source' => 'dynamic']]);
        $this->add_control('dynamic_item_image', ['label' => esc_html__('Image', 'softech-addons-for-elementor'), 'type' => Controls_Manager::MEDIA, 'dynamic' => ['active' => true], 'condition' => ['source' => 'dynamic']]);
        $this->add_control('dynamic_item_title', ['label' => esc_html__('Title', 'softech-addons-for-elementor'), 'type' => Controls_Manager::TEXT, 'dynamic' => ['active' => true], 'condition' => ['source' => 'dynamic'], 'placeholder' => esc_html__('Leave empty to use post title', 'softech-addons-for-elementor')]);
        $this->add_control('dynamic_item_description', ['label' => esc_html__('Description', 'softech-addons-for-elementor'), 'type' => Controls_Manager::TEXTAREA, 'dynamic' => ['active' => true], 'condition' => ['source' => 'dynamic'], 'placeholder' => esc_html__('Leave empty to use post excerpt', 'softech-addons-for-elementor')]);
        $this->add_control('dynamic_item_link', ['label' => esc_html__('Link', 'softech-addons-for-elementor'), 'type' => Controls_Manager::URL, 'dynamic' => ['active' => true], 'condition' => ['source' => 'dynamic'], 'placeholder' => esc_html__('Leave empty to use post permalink', 'softech-addons-for-elementor')]);
        // ─────────────────────────────────────────────────────────────────

        $this->add_responsive_control('columns', ['label' => esc_html__('Columns', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SELECT, 'default' => '3', 'options' => ['1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', '10' => '10'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-gallery-columns: {{VALUE}};']]);
        $this->end_controls_section();

        // ── NEW: Dynamic Query section — powered by Softech_Post_Query_Manager ──
        // This entire section is HIDDEN unless source = 'dynamic'.
        // It adds: Post Type, Selection (dynamic/manual), Categories, Tags,
        // Order By, Order, Offset, Meta Query, Items Per Page, No Items Text.
        Softech_Post_Query_Manager::register_controls( $this, [
            'source_control' => 'source',          // condition: source = 'dynamic'
            'section_id'     => 'section_dynamic_query',
            'section_label'  => esc_html__( 'Query', 'softech-addons-for-elementor' ),
            'mode'           => 'post_only',       // simple post-type dropdown
        ] );
        // ─────────────────────────────────────────────────────────────────

        // ── SETTINGS SECTION (unchanged) ───────────────────────────────────
        $this->start_controls_section('section_settings', ['label' => esc_html__('Settings', 'softech-addons-for-elementor'), 'tab' => Controls_Manager::TAB_CONTENT]);
        $this->add_control('layout', ['label' => esc_html__('Layout', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SELECT, 'default' => 'masonry', 'options' => ['grid' => esc_html__('Grid', 'softech-addons-for-elementor'), 'masonry' => esc_html__('Masonry', 'softech-addons-for-elementor')]]);
        $this->add_control('limited_items', [
            'label'       => esc_html__('SHOW ALL ITEMS', 'softech-addons-for-elementor'),
            'type'        => Controls_Manager::SWITCHER,
            'default'     => '',
            'description' => esc_html__('To show all items, please enable this option.', 'softech-addons-for-elementor'),
            'condition'   => ['source!' => 'dynamic'],
        ]);
        $this->add_control('images_per_page', ['label' => esc_html__('Items Per Page', 'softech-addons-for-elementor'), 'type' => Controls_Manager::NUMBER, 'default' => 10, 'min' => 1, 'condition' => ['limited_items!' => 'yes', 'source!' => 'dynamic']]);
        $this->add_control('pagination_type', ['label' => esc_html__('Pagination Type', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SELECT, 'default' => 'none', 'options' => ['none' => esc_html__('None', 'softech-addons-for-elementor'), 'load-more' => esc_html__('Load More', 'softech-addons-for-elementor'), 'numbers' => esc_html__('Number Pagination', 'softech-addons-for-elementor')], 'condition' => ['source!' => 'basic_gallery', 'limited_items!' => 'yes']]);
        $this->add_control('load_more_text', ['label' => esc_html__('Button Text', 'softech-addons-for-elementor'), 'type' => Controls_Manager::TEXT, 'default' => esc_html__('Load More', 'softech-addons-for-elementor'), 'condition' => ['source!' => 'basic_gallery', 'pagination_type' => 'load-more', 'limited_items!' => 'yes']]);
        $this->add_responsive_control('gap', ['label' => esc_html__('Gap', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px', 'em', 'rem', '%', 'vw', 'vh'], 'range' => ['px' => ['min' => 0, 'max' => 120], 'em' => ['min' => 0, 'max' => 20], 'rem' => ['min' => 0, 'max' => 20], '%' => ['min' => 0, 'max' => 100], 'vw' => ['min' => 0, 'max' => 100], 'vh' => ['min' => 0, 'max' => 100]], 'default' => ['size' => 15, 'unit' => 'px'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-gallery-gap: {{SIZE}}{{UNIT}};']]);
        $this->add_control('image_size', ['label' => esc_html__('Image Size', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SELECT, 'default' => 'large', 'options' => ['thumbnail' => esc_html__('Thumbnail', 'softech-addons-for-elementor'), 'medium' => esc_html__('Medium', 'softech-addons-for-elementor'), 'large' => esc_html__('Large', 'softech-addons-for-elementor'), 'full' => esc_html__('Full', 'softech-addons-for-elementor')]]);
        $this->add_control('show_title', ['label' => esc_html__('Show Title On Overlay', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SWITCHER, 'default' => 'yes', 'condition' => ['source!' => 'basic_gallery']]);
        $this->add_control('show_description', ['label' => esc_html__('Show Description On Overlay', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SWITCHER, 'default' => '', 'condition' => ['source!' => 'basic_gallery']]);
        $this->add_control('gallery_animation', ['label' => esc_html__('Animation', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SELECT, 'default' => 'fade', 'options' => ['fade' => esc_html__('Fade', 'softech-addons-for-elementor'), 'zoom-in' => esc_html__('Zoom In', 'softech-addons-for-elementor'), 'slide-up' => esc_html__('Slide Up', 'softech-addons-for-elementor'), 'slide-down' => esc_html__('Slide Down', 'softech-addons-for-elementor'), 'none' => esc_html__('None', 'softech-addons-for-elementor')]]);
        $this->add_control('gallery_animation_speed', ['label' => esc_html__('Animation Speed', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['ms'], 'range' => ['ms' => ['min' => 100, 'max' => 1000]], 'default' => ['size' => 400, 'unit' => 'ms']]);
        $this->end_controls_section();

        // ── LIGHTBOX SECTION (unchanged) ───────────────────────────────────
        $this->start_controls_section('section_lightbox', ['label' => esc_html__('Lightbox', 'softech-addons-for-elementor'), 'tab' => Controls_Manager::TAB_CONTENT]);
        $this->add_control('enable_lightbox', ['label' => esc_html__('Enable Lightbox', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SWITCHER, 'default' => 'yes']);
        $this->add_control('on_image_click', ['label' => esc_html__('On Image Click', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SELECT, 'default' => 'lightbox', 'options' => ['lightbox' => esc_html__('Lightbox', 'softech-addons-for-elementor'), 'custom-link' => esc_html__('Custom Link', 'softech-addons-for-elementor'), 'none' => esc_html__('None', 'softech-addons-for-elementor')], 'condition' => ['source!' => 'basic_gallery']]);
        $this->add_control('on_image_click_basic', ['label' => esc_html__('On Image Click', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SELECT, 'default' => 'lightbox', 'options' => ['lightbox' => esc_html__('Lightbox', 'softech-addons-for-elementor'), 'none' => esc_html__('None', 'softech-addons-for-elementor')], 'condition' => ['source' => 'basic_gallery']]);
        $this->add_control('lightbox_caption', ['label' => esc_html__('Lightbox Caption', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SELECT, 'default' => 'title', 'options' => ['title' => esc_html__('Title', 'softech-addons-for-elementor'), 'description' => esc_html__('Description', 'softech-addons-for-elementor'), 'both' => esc_html__('Title + Description', 'softech-addons-for-elementor'), 'none' => esc_html__('None', 'softech-addons-for-elementor')], 'condition' => ['source!' => 'basic_gallery', 'enable_lightbox' => 'yes', 'on_image_click' => 'lightbox']]);
        $this->add_control('lightbox_title_position', ['label' => esc_html__('Title Position', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SELECT, 'default' => 'above', 'options' => ['above' => esc_html__('Above Image', 'softech-addons-for-elementor'), 'below' => esc_html__('Below Image', 'softech-addons-for-elementor')], 'condition' => ['source!' => 'basic_gallery', 'enable_lightbox' => 'yes', 'on_image_click' => 'lightbox']]);
        $this->add_control('show_lightbox_navigation', ['label' => esc_html__('Show Lightbox Navigation', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SWITCHER, 'default' => 'yes', 'condition' => ['enable_lightbox' => 'yes']]);
        $this->add_control('show_lightbox_counter', ['label' => esc_html__('Show Lightbox Counter', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SWITCHER, 'default' => 'yes', 'condition' => ['enable_lightbox' => 'yes']]);
        $this->add_control('show_lightbox_thumbnails', ['label' => esc_html__('Show Lightbox Thumbnails', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SWITCHER, 'default' => '', 'condition' => ['enable_lightbox' => 'yes']]);
        $this->add_control('show_lightbox_post_link', ['label' => esc_html__('Show Post Link Button', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SWITCHER, 'default' => 'yes', 'condition' => ['source' => 'dynamic', 'enable_lightbox' => 'yes', 'on_image_click' => 'lightbox']]);
        $this->add_control('lightbox_post_link_label', ['label' => esc_html__('Post Link Label', 'softech-addons-for-elementor'), 'type' => Controls_Manager::TEXT, 'default' => esc_html__('Open Post', 'softech-addons-for-elementor'), 'condition' => ['source' => 'dynamic', 'enable_lightbox' => 'yes', 'on_image_click' => 'lightbox', 'show_lightbox_post_link' => 'yes']]);
        $this->add_control('lightbox_post_link_target', ['label' => esc_html__('Post Link Target', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SELECT, 'default' => '_self', 'options' => ['_self' => esc_html__('Same Tab', 'softech-addons-for-elementor'), '_blank' => esc_html__('New Tab', 'softech-addons-for-elementor')], 'condition' => ['source' => 'dynamic', 'enable_lightbox' => 'yes', 'on_image_click' => 'lightbox', 'show_lightbox_post_link' => 'yes']]);
        $this->add_control('close_on_backdrop_click', ['label' => esc_html__('Close on Backdrop Click', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SWITCHER, 'default' => 'yes', 'condition' => ['enable_lightbox' => 'yes']]);
        $this->end_controls_section();

        // ── STYLE: Filter Bar — now applies to both static + dynamic ─────
        $this->start_controls_section('section_filter_style', [
            'label'     => esc_html__('Filter Bar', 'softech-addons-for-elementor'),
            'tab'       => Controls_Manager::TAB_STYLE,
            'condition' => ['source!' => 'basic_gallery', 'show_filter_bar' => 'yes'],  // was: source=static
        ]);
        $this->add_responsive_control('filter_alignment', ['label' => esc_html__('Alignment', 'softech-addons-for-elementor'), 'type' => Controls_Manager::CHOOSE, 'default' => 'center', 'options' => ['flex-start' => ['title' => esc_html__('Left', 'softech-addons-for-elementor'), 'icon' => 'eicon-text-align-left'], 'center' => ['title' => esc_html__('Center', 'softech-addons-for-elementor'), 'icon' => 'eicon-text-align-center'], 'flex-end' => ['title' => esc_html__('Right', 'softech-addons-for-elementor'), 'icon' => 'eicon-text-align-right']], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-toolbar' => 'justify-content: {{VALUE}};']]);
        $this->add_responsive_control('filter_gap', ['label' => esc_html__('Gap Between Buttons', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px', 'em', 'rem', '%', 'vw', 'vh'], 'range' => ['px' => ['min' => 0, 'max' => 120], 'em' => ['min' => 0, 'max' => 20], 'rem' => ['min' => 0, 'max' => 20], '%' => ['min' => 0, 'max' => 100], 'vw' => ['min' => 0, 'max' => 100], 'vh' => ['min' => 0, 'max' => 100]], 'default' => ['size' => 10, 'unit' => 'px'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-filter-gap: {{SIZE}}{{UNIT}};']]);
        $this->start_controls_tabs('filter_button_tabs');

        $this->start_controls_tab('filter_button_normal_tab', ['label' => esc_html__('Normal', 'softech-addons-for-elementor')]);
        $this->add_control('filter_button_bg', ['label' => esc_html__('Button Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#f5f5f5', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-filter-button-bg: {{VALUE}};']]);
        $this->add_control('filter_button_color', ['label' => esc_html__('Button Text Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#333333', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-filter-button-color: {{VALUE}};']]);
        $this->add_responsive_control('filter_button_radius', ['label' => esc_html__('Border Radius', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', '%', 'em'], 'default' => ['top' => 4, 'right' => 4, 'bottom' => 4, 'left' => 4, 'unit' => 'px', 'isLinked' => true], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-filter' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_responsive_control('filter_button_padding', ['label' => esc_html__('Padding', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', 'em', 'rem', '%'], 'default' => ['top' => 8, 'right' => 20, 'bottom' => 8, 'left' => 20, 'unit' => 'px', 'isLinked' => false], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-filter' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'filter_button_typography', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-filter']);
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'filter_button_border', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-filter']);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'filter_button_shadow', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-filter']);
        $this->end_controls_tab();

        $this->start_controls_tab('filter_button_active_tab', ['label' => esc_html__('Active', 'softech-addons-for-elementor')]);
        $this->add_control('filter_button_active_bg', ['label' => esc_html__('Active Button Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#000000', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-filter-button-active-bg: {{VALUE}};']]);
        $this->add_control('filter_button_active_color', ['label' => esc_html__('Active Button Text Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-filter-button-active-color: {{VALUE}};']]);
        $this->add_responsive_control('filter_button_active_radius', ['label' => esc_html__('Border Radius', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', '%', 'em'], 'default' => ['top' => 4, 'right' => 4, 'bottom' => 4, 'left' => 4, 'unit' => 'px', 'isLinked' => true], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-filter.is-active' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_responsive_control('filter_button_active_padding', ['label' => esc_html__('Padding', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', 'em', 'rem', '%'], 'default' => ['top' => 8, 'right' => 20, 'bottom' => 8, 'left' => 20, 'unit' => 'px', 'isLinked' => false], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-filter.is-active' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'filter_button_active_typography', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-filter.is-active']);
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'filter_button_active_border', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-filter.is-active']);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'filter_button_active_shadow', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-filter.is-active']);
        $this->end_controls_tab();

        $this->start_controls_tab('filter_button_hover_tab', ['label' => esc_html__('Hover', 'softech-addons-for-elementor')]);
        $this->add_control('filter_button_hover_bg', ['label' => esc_html__('Hover Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#e5e7eb', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-filter:hover, {{WRAPPER}} .sitsel-filterable-gallery-filter:focus-visible' => 'background-color: {{VALUE}};']]);
        $this->add_control('filter_button_hover_color', ['label' => esc_html__('Hover Text Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#111827', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-filter:hover, {{WRAPPER}} .sitsel-filterable-gallery-filter:focus-visible' => 'color: {{VALUE}};']]);
        $this->add_responsive_control('filter_button_hover_radius', ['label' => esc_html__('Border Radius', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', '%', 'em'], 'default' => ['top' => 4, 'right' => 4, 'bottom' => 4, 'left' => 4, 'unit' => 'px', 'isLinked' => true], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-filter:hover, {{WRAPPER}} .sitsel-filterable-gallery-filter:focus-visible' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_responsive_control('filter_button_hover_padding', ['label' => esc_html__('Padding', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', 'em', 'rem', '%'], 'default' => ['top' => 8, 'right' => 20, 'bottom' => 8, 'left' => 20, 'unit' => 'px', 'isLinked' => false], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-filter:hover, {{WRAPPER}} .sitsel-filterable-gallery-filter:focus-visible' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'filter_button_hover_typography', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-filter:hover, {{WRAPPER}} .sitsel-filterable-gallery-filter:focus-visible']);
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'filter_button_hover_border', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-filter:hover, {{WRAPPER}} .sitsel-filterable-gallery-filter:focus-visible']);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'filter_button_hover_shadow', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-filter:hover, {{WRAPPER}} .sitsel-filterable-gallery-filter:focus-visible']);
        $this->end_controls_tab();

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

        // ── All remaining style sections are 100 % unchanged ──────────────
        $this->start_controls_section('section_gallery_item_style', ['label' => esc_html__('Gallery Item', 'softech-addons-for-elementor'), 'tab' => Controls_Manager::TAB_STYLE]);
        $this->add_responsive_control('item_border_radius', ['label' => esc_html__('Border Radius', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', '%', 'em'], 'default' => ['top' => 0, 'right' => 0, 'bottom' => 0, 'left' => 0, 'unit' => 'px', 'isLinked' => true], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-card, {{WRAPPER}} .sitsel-filterable-gallery-action, {{WRAPPER}} .sitsel-filterable-gallery-image, {{WRAPPER}} .sitsel-filterable-gallery-lightbox-image' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'item_shadow', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-card']);
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'item_border', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-card']);
        $this->add_control('overlay_color', ['label' => esc_html__('Overlay Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => 'rgba(0,0,0,0.5)', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-gallery-overlay: {{VALUE}};']]);
        $this->add_control('overlay_on', ['label' => esc_html__('Overlay On', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SELECT, 'default' => 'hover', 'options' => ['hover' => esc_html__('Hover', 'softech-addons-for-elementor'), 'always' => esc_html__('Always', 'softech-addons-for-elementor'), 'none' => esc_html__('None', 'softech-addons-for-elementor')]]);
        $this->end_controls_section();

        $this->start_controls_section('section_title_style', ['label' => esc_html__('Title', 'softech-addons-for-elementor'), 'tab' => Controls_Manager::TAB_STYLE, 'condition' => ['source!' => 'basic_gallery', 'show_title' => 'yes', 'overlay_on!' => 'none']]);
        $this->add_control('title_color', ['label' => esc_html__('Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-title' => 'color: {{VALUE}};']]);
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'title_typography', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-title']);
        $this->add_responsive_control('title_alignment', ['label' => esc_html__('Alignment', 'softech-addons-for-elementor'), 'type' => Controls_Manager::CHOOSE, 'default' => 'center', 'options' => ['left' => ['title' => esc_html__('Left', 'softech-addons-for-elementor'), 'icon' => 'eicon-text-align-left'], 'center' => ['title' => esc_html__('Center', 'softech-addons-for-elementor'), 'icon' => 'eicon-text-align-center'], 'right' => ['title' => esc_html__('Right', 'softech-addons-for-elementor'), 'icon' => 'eicon-text-align-right']], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-title' => 'text-align: {{VALUE}};']]);
        $this->add_responsive_control('title_spacing', ['label' => esc_html__('Spacing from Bottom', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px', 'em', 'rem', '%', 'vw', 'vh'], 'range' => ['px' => ['min' => 0, 'max' => 120], 'em' => ['min' => 0, 'max' => 20], 'rem' => ['min' => 0, 'max' => 20], '%' => ['min' => 0, 'max' => 100], 'vw' => ['min' => 0, 'max' => 100], 'vh' => ['min' => 0, 'max' => 100]], 'default' => ['size' => 10, 'unit' => 'px'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-title' => 'margin-bottom: {{SIZE}}{{UNIT}};']]);
        $this->end_controls_section();

        $this->start_controls_section('section_description_style', ['label' => esc_html__('Description', 'softech-addons-for-elementor'), 'tab' => Controls_Manager::TAB_STYLE, 'condition' => ['show_description' => 'yes', 'overlay_on!' => 'none']]);
        $this->add_control('description_color', ['label' => esc_html__('Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#eeeeee', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-description' => 'color: {{VALUE}};']]);
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'description_typography', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-description']);
        $this->add_responsive_control('description_alignment', ['label' => esc_html__('Alignment', 'softech-addons-for-elementor'), 'type' => Controls_Manager::CHOOSE, 'default' => 'center', 'options' => ['left' => ['title' => esc_html__('Left', 'softech-addons-for-elementor'), 'icon' => 'eicon-text-align-left'], 'center' => ['title' => esc_html__('Center', 'softech-addons-for-elementor'), 'icon' => 'eicon-text-align-center'], 'right' => ['title' => esc_html__('Right', 'softech-addons-for-elementor'), 'icon' => 'eicon-text-align-right']], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-description' => 'text-align: {{VALUE}};']]);
        $this->add_responsive_control('description_spacing', ['label' => esc_html__('Spacing from Bottom', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px', 'em', 'rem', '%', 'vw', 'vh'], 'range' => ['px' => ['min' => 0, 'max' => 120], 'em' => ['min' => 0, 'max' => 20], 'rem' => ['min' => 0, 'max' => 20], '%' => ['min' => 0, 'max' => 100], 'vw' => ['min' => 0, 'max' => 100], 'vh' => ['min' => 0, 'max' => 100]], 'default' => ['size' => 10, 'unit' => 'px'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-description' => 'margin-bottom: {{SIZE}}{{UNIT}};']]);
        $this->end_controls_section();

        $this->start_controls_section('section_pagination_style', ['label' => esc_html__('Pagination', 'softech-addons-for-elementor'), 'tab' => Controls_Manager::TAB_STYLE, 'condition' => ['source!' => 'basic_gallery', 'pagination_type!' => 'none']]);
        $this->add_responsive_control('pagination_alignment', ['label' => esc_html__('Alignment', 'softech-addons-for-elementor'), 'type' => Controls_Manager::CHOOSE, 'default' => 'center', 'options' => ['flex-start' => ['title' => esc_html__('Left', 'softech-addons-for-elementor'), 'icon' => 'eicon-text-align-left'], 'center' => ['title' => esc_html__('Center', 'softech-addons-for-elementor'), 'icon' => 'eicon-text-align-center'], 'flex-end' => ['title' => esc_html__('Right', 'softech-addons-for-elementor'), 'icon' => 'eicon-text-align-right']], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-pagination' => 'justify-content: {{VALUE}};']]);
        $this->add_control('pagination_gap', ['label' => esc_html__('Gap Between Buttons', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px', 'em', 'rem', '%', 'vw', 'vh'], 'range' => ['px' => ['min' => 0, 'max' => 120], 'em' => ['min' => 0, 'max' => 20], 'rem' => ['min' => 0, 'max' => 20], '%' => ['min' => 0, 'max' => 100], 'vw' => ['min' => 0, 'max' => 100], 'vh' => ['min' => 0, 'max' => 100]], 'default' => ['size' => 10, 'unit' => 'px'], 'condition' => ['pagination_type' => 'numbers'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-pagination-inner' => 'gap: {{SIZE}}{{UNIT}};']]);
        $this->end_controls_section();

        $this->start_controls_section('section_load_more_style', ['label' => esc_html__('Load More Button', 'softech-addons-for-elementor'), 'tab' => Controls_Manager::TAB_STYLE, 'condition' => ['source!' => 'basic_gallery', 'pagination_type' => 'load-more']]);
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'load_more_typography', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-load-more']);
        $this->add_control('load_more_text_color', ['label' => esc_html__('Text Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-load-more' => 'color: {{VALUE}};']]);
        $this->add_control('load_more_bg_color', ['label' => esc_html__('Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#111827', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-load-more' => 'background-color: {{VALUE}};']]);
        $this->add_control('load_more_hover_text_color', ['label' => esc_html__('Hover Text Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-load-more:hover, {{WRAPPER}} .sitsel-filterable-gallery-load-more:focus-visible' => 'color: {{VALUE}};']]);
        $this->add_control('load_more_hover_bg_color', ['label' => esc_html__('Hover Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#1f2937', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-load-more:hover, {{WRAPPER}} .sitsel-filterable-gallery-load-more:focus-visible' => 'background-color: {{VALUE}};']]);
        $this->add_responsive_control('load_more_padding', ['label' => esc_html__('Padding', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', 'em', 'rem', '%'], 'default' => ['top' => 10, 'right' => 18, 'bottom' => 10, 'left' => 18, 'unit' => 'px', 'isLinked' => false], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-load-more' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_responsive_control('load_more_border_radius', ['label' => esc_html__('Border Radius', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', '%', 'em'], 'default' => ['top' => 4, 'right' => 4, 'bottom' => 4, 'left' => 4, 'unit' => 'px', 'isLinked' => true], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-load-more' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'load_more_border', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-load-more']);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'load_more_shadow', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-load-more']);
        $this->end_controls_section();

        $this->start_controls_section('section_number_pagination_style', ['label' => esc_html__('Number Pagination', 'softech-addons-for-elementor'), 'tab' => Controls_Manager::TAB_STYLE, 'condition' => ['source!' => 'basic_gallery', 'pagination_type' => 'numbers']]);
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'number_pagination_typography', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-page-btn']);
        $this->start_controls_tabs('number_pagination_tabs');

        $this->start_controls_tab('number_pagination_normal_tab', ['label' => esc_html__('Normal', 'softech-addons-for-elementor')]);
        $this->add_control('number_pagination_text_color', ['label' => esc_html__('Text Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-page-btn' => 'color: {{VALUE}};']]);
        $this->add_control('number_pagination_bg_color', ['label' => esc_html__('Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#111827', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-page-btn' => 'background-color: {{VALUE}};']]);
        $this->add_responsive_control('number_pagination_padding', ['label' => esc_html__('Padding', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', 'em', 'rem', '%'], 'default' => ['top' => 10, 'right' => 16, 'bottom' => 10, 'left' => 16, 'unit' => 'px', 'isLinked' => false], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-page-btn' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_responsive_control('number_pagination_border_radius', ['label' => esc_html__('Border Radius', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', '%', 'em'], 'default' => ['top' => 4, 'right' => 4, 'bottom' => 4, 'left' => 4, 'unit' => 'px', 'isLinked' => true], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-page-btn' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'number_pagination_border', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-page-btn']);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'number_pagination_shadow', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-page-btn']);
        $this->end_controls_tab();

        $this->start_controls_tab('number_pagination_active_tab', ['label' => esc_html__('Active', 'softech-addons-for-elementor')]);
        $this->add_control('number_pagination_active_text_color', ['label' => esc_html__('Active Text Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-page-btn.is-active' => 'color: {{VALUE}};']]);
        $this->add_control('number_pagination_active_bg_color', ['label' => esc_html__('Active Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#2563eb', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-page-btn.is-active' => 'background-color: {{VALUE}};']]);
        $this->end_controls_tab();

        $this->start_controls_tab('number_pagination_hover_tab', ['label' => esc_html__('Hover', 'softech-addons-for-elementor')]);
        $this->add_control('number_pagination_hover_text_color', ['label' => esc_html__('Hover Text Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-page-btn:hover, {{WRAPPER}} .sitsel-filterable-gallery-page-btn:focus-visible' => 'color: {{VALUE}};']]);
        $this->add_control('number_pagination_hover_bg_color', ['label' => esc_html__('Hover Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#1f2937', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-page-btn:hover, {{WRAPPER}} .sitsel-filterable-gallery-page-btn:focus-visible' => 'background-color: {{VALUE}};']]);
        $this->end_controls_tab();

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

        $this->start_controls_section('section_lightbox_style', ['label' => esc_html__('Lightbox', 'softech-addons-for-elementor'), 'tab' => Controls_Manager::TAB_STYLE, 'condition' => ['enable_lightbox' => 'yes']]);
        $this->add_control('lightbox_backdrop_color', ['label' => esc_html__('Backdrop Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => 'rgba(0,0,0,0.9)', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-lightbox-backdrop: {{VALUE}};']]);
        $this->add_responsive_control('lightbox_image_max_width', ['label' => esc_html__('Image Max Width', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px', 'em', 'rem', '%', 'vw', 'vh'], 'range' => ['px' => ['min' => 100, 'max' => 1920], 'em' => ['min' => 0, 'max' => 80], 'rem' => ['min' => 0, 'max' => 80], '%' => ['min' => 0, 'max' => 100], 'vw' => ['min' => 0, 'max' => 100], 'vh' => ['min' => 0, 'max' => 100]], 'default' => ['size' => 90, 'unit' => '%'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-lightbox-image-max-width: {{SIZE}}{{UNIT}};']]);
        $this->add_responsive_control('lightbox_image_max_height', ['label' => esc_html__('Image Max Height', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px', 'em', 'rem', '%', 'vw', 'vh'], 'range' => ['px' => ['min' => 100, 'max' => 1200], 'em' => ['min' => 0, 'max' => 80], 'rem' => ['min' => 0, 'max' => 80], '%' => ['min' => 0, 'max' => 100], 'vw' => ['min' => 0, 'max' => 100], 'vh' => ['min' => 0, 'max' => 100]], 'default' => ['size' => 85, 'unit' => 'vh'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-lightbox-image-max-height: {{SIZE}}{{UNIT}};']]);
        $this->add_responsive_control('lightbox_thumbnail_width', ['label' => esc_html__('Thumbnail Width', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px'], 'range' => ['px' => ['min' => 40, 'max' => 220]], 'default' => ['size' => 64, 'unit' => 'px'], 'condition' => ['show_lightbox_thumbnails' => 'yes'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-lightbox-thumb-width: {{SIZE}}{{UNIT}};']]);
        $this->add_responsive_control('lightbox_thumbnail_height', ['label' => esc_html__('Thumbnail Height', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px'], 'range' => ['px' => ['min' => 40, 'max' => 220]], 'default' => ['size' => 64, 'unit' => 'px'], 'condition' => ['show_lightbox_thumbnails' => 'yes'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-lightbox-thumb-height: {{SIZE}}{{UNIT}};']]);
        $this->start_controls_tabs('lightbox_style_tabs');

        $this->start_controls_tab('lightbox_navigation_tab', ['label' => esc_html__('Navs', 'softech-addons-for-elementor')]);
        $this->add_control('lightbox_arrow_color', ['label' => esc_html__('Icon Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-nav' => 'color: {{VALUE}};']]);
        $this->add_control('lightbox_arrow_hover_color', ['label' => esc_html__('Hover Icon Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-nav:hover, {{WRAPPER}} .sitsel-filterable-gallery-lightbox-nav:focus-visible' => 'color: {{VALUE}};']]);
        $this->add_control('lightbox_nav_bg_color', ['label' => esc_html__('Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => 'rgba(0,0,0,0.35)', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-nav' => 'background-color: {{VALUE}};']]);
        $this->add_control('lightbox_nav_bg_hover_color', ['label' => esc_html__('Hover Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => 'rgba(0,0,0,0.55)', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-nav:hover, {{WRAPPER}} .sitsel-filterable-gallery-lightbox-nav:focus-visible' => 'background-color: {{VALUE}};']]);
        $this->add_responsive_control('lightbox_nav_size', ['label' => esc_html__('Nav Button Size', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px', 'em', 'rem', '%', 'vw', 'vh'], 'range' => ['px' => ['min' => 32, 'max' => 120], 'em' => ['min' => 0, 'max' => 20], 'rem' => ['min' => 0, 'max' => 20], '%' => ['min' => 0, 'max' => 100], 'vw' => ['min' => 0, 'max' => 100], 'vh' => ['min' => 0, 'max' => 100]], 'default' => ['size' => 50, 'unit' => 'px'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-lightbox-nav-size: {{SIZE}}{{UNIT}};']]);
        $this->add_responsive_control('lightbox_arrow_size', ['label' => esc_html__('Icon Size', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px', 'em', 'rem', '%', 'vw', 'vh'], 'range' => ['px' => ['min' => 12, 'max' => 80], 'em' => ['min' => 0, 'max' => 12], 'rem' => ['min' => 0, 'max' => 12], '%' => ['min' => 0, 'max' => 100], 'vw' => ['min' => 0, 'max' => 100], 'vh' => ['min' => 0, 'max' => 100]], 'default' => ['size' => 30, 'unit' => 'px'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-lightbox-arrow-size: {{SIZE}}{{UNIT}};']]);
        $this->add_responsive_control('lightbox_nav_padding', ['label' => esc_html__('Padding', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', 'em', 'rem', '%'], 'default' => ['top' => 10, 'right' => 10, 'bottom' => 10, 'left' => 10, 'unit' => 'px', 'isLinked' => false], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-nav' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_responsive_control('lightbox_nav_border_radius', ['label' => esc_html__('Border Radius', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', '%', 'em'], 'default' => ['top' => 999, 'right' => 999, 'bottom' => 999, 'left' => 999, 'unit' => 'px', 'isLinked' => true], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-nav' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'lightbox_nav_border', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-lightbox-nav']);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'lightbox_nav_shadow', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-lightbox-nav']);
        $this->end_controls_tab();

        $this->start_controls_tab('lightbox_actions_tab', ['label' => esc_html__('Actions', 'softech-addons-for-elementor')]);
        $this->add_responsive_control('lightbox_header_gap', ['label' => esc_html__('Header Gap', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px', 'em', 'rem', '%', 'vw', 'vh'], 'range' => ['px' => ['min' => 0, 'max' => 120], 'em' => ['min' => 0, 'max' => 20], 'rem' => ['min' => 0, 'max' => 20], '%' => ['min' => 0, 'max' => 100], 'vw' => ['min' => 0, 'max' => 100], 'vh' => ['min' => 0, 'max' => 100]], 'default' => ['size' => 10, 'unit' => 'px'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-lightbox-header-gap: {{SIZE}}{{UNIT}};']]);
        $this->add_responsive_control('lightbox_header_control_size', ['label' => esc_html__('Header Control Size', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px', 'em', 'rem', '%', 'vw', 'vh'], 'range' => ['px' => ['min' => 28, 'max' => 120], 'em' => ['min' => 0, 'max' => 20], 'rem' => ['min' => 0, 'max' => 20], '%' => ['min' => 0, 'max' => 100], 'vw' => ['min' => 0, 'max' => 100], 'vh' => ['min' => 0, 'max' => 100]], 'default' => ['size' => 38, 'unit' => 'px'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-lightbox-header-control-size: {{SIZE}}{{UNIT}};']]);
        $this->add_responsive_control('lightbox_action_icon_size', ['label' => esc_html__('Action Icon Size', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px', 'em', 'rem', '%', 'vw', 'vh'], 'range' => ['px' => ['min' => 12, 'max' => 80], 'em' => ['min' => 0, 'max' => 12], 'rem' => ['min' => 0, 'max' => 12], '%' => ['min' => 0, 'max' => 100], 'vw' => ['min' => 0, 'max' => 100], 'vh' => ['min' => 0, 'max' => 100]], 'default' => ['size' => 20, 'unit' => 'px'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-lightbox-action-icon-size: {{SIZE}}{{UNIT}};']]);
        $this->add_control('lightbox_action_text_color', ['label' => esc_html__('Icon Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-actions button, {{WRAPPER}} .sitsel-filterable-gallery-lightbox-post-link' => 'color: {{VALUE}};']]);
        $this->add_control('lightbox_action_hover_text_color', ['label' => esc_html__('Hover Icon Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-actions button:hover:not(:disabled), {{WRAPPER}} .sitsel-filterable-gallery-lightbox-actions button:focus-visible:not(:disabled), {{WRAPPER}} .sitsel-filterable-gallery-lightbox-post-link:hover, {{WRAPPER}} .sitsel-filterable-gallery-lightbox-post-link:focus-visible' => 'color: {{VALUE}};']]);
        $this->add_control('lightbox_action_bg_color', ['label' => esc_html__('Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => 'rgba(255,255,255,0.15)', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-actions button, {{WRAPPER}} .sitsel-filterable-gallery-lightbox-post-link' => 'background-color: {{VALUE}};']]);
        $this->add_control('lightbox_action_hover_bg_color', ['label' => esc_html__('Hover Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => 'rgba(255,255,255,0.25)', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-actions button:hover:not(:disabled), {{WRAPPER}} .sitsel-filterable-gallery-lightbox-actions button:focus-visible:not(:disabled), {{WRAPPER}} .sitsel-filterable-gallery-lightbox-post-link:hover, {{WRAPPER}} .sitsel-filterable-gallery-lightbox-post-link:focus-visible' => 'background-color: {{VALUE}};']]);
        $this->add_responsive_control('lightbox_action_border_radius', ['label' => esc_html__('Border Radius', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', '%', 'em'], 'default' => ['top' => 999, 'right' => 999, 'bottom' => 999, 'left' => 999, 'unit' => 'px', 'isLinked' => true], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-actions button, {{WRAPPER}} .sitsel-filterable-gallery-lightbox-post-link' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_responsive_control('lightbox_action_padding', ['label' => esc_html__('Padding', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', 'em', 'rem', '%'], 'default' => ['top' => 0, 'right' => 0, 'bottom' => 0, 'left' => 0, 'unit' => 'px', 'isLinked' => false], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-actions button, {{WRAPPER}} .sitsel-filterable-gallery-lightbox-post-link' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'lightbox_action_border', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-lightbox-actions button, {{WRAPPER}} .sitsel-filterable-gallery-lightbox-post-link']);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'lightbox_action_shadow', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-lightbox-actions button, {{WRAPPER}} .sitsel-filterable-gallery-lightbox-post-link']);
        $this->end_controls_tab();

        $this->start_controls_tab('lightbox_caption_tab', ['label' => esc_html__('Caption', 'softech-addons-for-elementor')]);
        $this->add_control('lightbox_caption_color', ['label' => esc_html__('Caption Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-caption' => 'color: {{VALUE}};']]);
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'lightbox_caption_typography', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-lightbox-caption']);
        $this->end_controls_tab();

        $this->start_controls_tab('lightbox_counter_tab', ['label' => esc_html__('Counter', 'softech-addons-for-elementor')]);
        $this->add_control('lightbox_counter_color', ['label' => esc_html__('Counter Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-counter' => 'color: {{VALUE}};']]);
        $this->add_control('lightbox_counter_bg_color', ['label' => esc_html__('Counter Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => 'rgba(255,255,255,0.15)', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-counter' => 'background-color: {{VALUE}};']]);
        $this->add_control('lightbox_counter_hover_bg_color', ['label' => esc_html__('Counter Hover Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => 'rgba(255,255,255,0.25)', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-counter:hover, {{WRAPPER}} .sitsel-filterable-gallery-lightbox-counter:focus-visible' => 'background-color: {{VALUE}};']]);
        $this->add_responsive_control('lightbox_counter_border_radius', ['label' => esc_html__('Border Radius', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', '%', 'em'], 'default' => ['top' => 999, 'right' => 999, 'bottom' => 999, 'left' => 999, 'unit' => 'px', 'isLinked' => true], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-counter' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_responsive_control('lightbox_counter_padding', ['label' => esc_html__('Padding', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', 'em', 'rem', '%'], 'default' => ['top' => 6, 'right' => 12, 'bottom' => 6, 'left' => 12, 'unit' => 'px', 'isLinked' => false], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-counter' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'lightbox_counter_border', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-lightbox-counter']);
        $this->add_group_control(Group_Control_Typography::get_type(), ['name' => 'lightbox_counter_typography', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-lightbox-counter']);
        $this->end_controls_tab();

        $this->start_controls_tab('lightbox_close_tab', ['label' => esc_html__('Close', 'softech-addons-for-elementor')]);
        $this->add_control('lightbox_close_color', ['label' => esc_html__('Icon Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-lightbox-close-color: {{VALUE}};']]);
        $this->add_control('lightbox_close_hover_color', ['label' => esc_html__('Hover Icon Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => '#ffffff', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-close:hover, {{WRAPPER}} .sitsel-filterable-gallery-lightbox-close:focus-visible' => 'color: {{VALUE}};']]);
        $this->add_control('lightbox_close_bg_color', ['label' => esc_html__('Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => 'rgba(0,0,0,0.35)', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-close' => 'background-color: {{VALUE}};']]);
        $this->add_control('lightbox_close_bg_hover_color', ['label' => esc_html__('Hover Background Color', 'softech-addons-for-elementor'), 'type' => Controls_Manager::COLOR, 'default' => 'rgba(0,0,0,0.55)', 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-close:hover, {{WRAPPER}} .sitsel-filterable-gallery-lightbox-close:focus-visible' => 'background-color: {{VALUE}};']]);
        $this->add_responsive_control('lightbox_close_size', ['label' => esc_html__('Icon Size', 'softech-addons-for-elementor'), 'type' => Controls_Manager::SLIDER, 'size_units' => ['px', 'em', 'rem', '%', 'vw', 'vh'], 'range' => ['px' => ['min' => 12, 'max' => 80], 'em' => ['min' => 0, 'max' => 12], 'rem' => ['min' => 0, 'max' => 12], '%' => ['min' => 0, 'max' => 100], 'vw' => ['min' => 0, 'max' => 100], 'vh' => ['min' => 0, 'max' => 100]], 'default' => ['size' => 24, 'unit' => 'px'], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-wrapper' => '--sitsel-lightbox-close-size: {{SIZE}}{{UNIT}};']]);
        $this->add_responsive_control('lightbox_close_padding', ['label' => esc_html__('Padding', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', 'em', 'rem', '%'], 'default' => ['top' => 10, 'right' => 10, 'bottom' => 10, 'left' => 10, 'unit' => 'px', 'isLinked' => false], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-close' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_responsive_control('lightbox_close_border_radius', ['label' => esc_html__('Border Radius', 'softech-addons-for-elementor'), 'type' => Controls_Manager::DIMENSIONS, 'size_units' => ['px', '%', 'em'], 'default' => ['top' => 999, 'right' => 999, 'bottom' => 999, 'left' => 999, 'unit' => 'px', 'isLinked' => true], 'selectors' => ['{{WRAPPER}} .sitsel-filterable-gallery-lightbox-close' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};']]);
        $this->add_group_control(Group_Control_Border::get_type(), ['name' => 'lightbox_close_border', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-lightbox-close']);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), ['name' => 'lightbox_close_shadow', 'selector' => '{{WRAPPER}} .sitsel-filterable-gallery-lightbox-close']);
        $this->end_controls_tab();

        $this->end_controls_tabs();
        $this->end_controls_section();
    }

    // =========================================================================
    // AJAX HANDLER (unchanged logic — dynamic items are already in payload)
    // =========================================================================

    public function handle_ajax_filter()
    {
        check_ajax_referer('sitsel_filterable_gallery', 'nonce');

        $payload_raw = isset($_POST['payload']) ? sanitize_text_field( wp_unslash( $_POST['payload'] ) ) : '';
        $payload     = $this->decode_payload( $payload_raw );
        $filter  = isset($_POST['category']) ? sanitize_title(wp_unslash($_POST['category'])) : 'all';
        $page    = isset($_POST['page']) ? max(1, absint(wp_unslash($_POST['page']))) : 1;

        if (empty($payload)) {
            wp_send_json_error(['message' => esc_html__('Invalid gallery payload.', 'softech-addons-for-elementor')], 400);
        }

        $settings   = $this->sanitize_payload_settings(isset($payload['settings']) ? $payload['settings'] : []);
        $source     = $this->get_source_type($settings);
        $items      = ('dynamic' === $source)
            ? $this->prepare_dynamic_gallery_items($settings)
            : $this->sanitize_payload_items(isset($payload['items']) ? $payload['items'] : [], $settings);
        $widget_id  = isset($payload['widgetId']) ? sanitize_html_class($payload['widgetId']) : 'sitsel-filterable-gallery-ajax';
        $categories = $this->is_filter_enabled($settings, $source) ? $this->get_category_map($items) : [];
        $filter     = $this->normalize_filter_value($filter, $settings, $categories);
        $result     = $this->get_query_result($items, $settings, $filter, $page);

        wp_send_json_success([
            'html'        => $this->render_gallery_items_html($result['items'], $settings, $widget_id),
            'toolbar'     => $this->render_filter_toolbar_html($settings, $categories, $filter),
            'pagination'  => $this->render_pagination_html($result, $settings),
            'count'       => $result['total_items'],
            'activeFilter'=> $filter,
            'currentPage' => $result['current_page'],
            'totalPages'  => $result['total_pages'],
            'hasMore'     => $result['has_more'],
        ]);
    }

    // =========================================================================
    // RENDER (unchanged except source allowed-values + dynamic items)
    // =========================================================================

    protected function render()
    {
        $settings         = $this->get_settings_for_display();
        $raw_settings     = $this->get_settings();
        $items            = $this->prepare_gallery_items($settings, $raw_settings);
        $widget_id        = 'sitsel-filterable-gallery-' . $this->get_id();
        // ── 'dynamic' added to the allowed-values list ────────────────────
        $source           = $this->get_source_type($settings);
        $filter_enabled   = $this->is_filter_enabled($settings, $source);
        $categories       = $filter_enabled ? $this->get_category_map($items) : [];
        $initial_filter   = $this->get_initial_filter($settings, $categories);
        $layout            = $this->sanitize_value(isset($settings['layout']) ? $settings['layout'] : 'masonry', ['grid', 'masonry'], 'masonry');
        $overlay           = $this->sanitize_value(isset($settings['overlay_on']) ? $settings['overlay_on'] : 'hover', ['hover', 'always', 'none'], 'hover');
        $animation_setting = isset($settings['gallery_animation']) ? $settings['gallery_animation'] : (isset($settings['animation']) ? $settings['animation'] : 'fade');
        $animation_speed   = isset($settings['gallery_animation_speed']['size']) ? absint($settings['gallery_animation_speed']['size']) : (isset($settings['animation_speed']['size']) ? absint($settings['animation_speed']['size']) : 400);
        $animation         = $this->sanitize_value($animation_setting, ['fade', 'zoom-in', 'slide-up', 'slide-down', 'none'], 'fade');
        $payload          = base64_encode(wp_json_encode(['widgetId' => $widget_id, 'settings' => $this->sanitize_payload_settings($settings, $raw_settings), 'items' => $items]));
        $result           = $this->get_query_result($items, $settings, $initial_filter, 1);

        $this->add_render_attribute('_wrapper', 'class', 'sitsel-filterable-gallery-host');

        $this->add_render_attribute('wrapper', [
            'id'                           => $widget_id,
            'class'                        => ['sitsel-filterable-gallery-wrapper', 'sitsel-layout-' . $layout, 'sitsel-overlay-' . $overlay, 'sitsel-motion-' . $animation],
            'data-widget-id'               => $widget_id,
            'data-source'                  => $source,
            'data-layout'                  => $layout,
            'data-sitsel-animation'        => $animation,
            'data-sitsel-animation-speed'  => $animation_speed,
            'data-filter-enabled'          => $filter_enabled ? 'yes' : 'no',
            'data-pagination-enabled'      => $this->is_pagination_enabled($settings) ? 'yes' : 'no',
            'data-pagination-type'         => $this->get_pagination_type($settings),
            'data-images-per-page'         => $this->get_effective_per_page($settings),
            'data-current-filter'          => $initial_filter,
            'data-current-page'            => $result['current_page'],
            'data-total-pages'             => $result['total_pages'],
            'data-enable-lightbox'         => ('yes' === ($settings['enable_lightbox'] ?? '')) ? 'yes' : 'no',
            'data-click-mode'              => $this->get_on_image_click_setting($settings),
            'data-lightbox-title-position' => $this->sanitize_value(isset($settings['lightbox_title_position']) ? $settings['lightbox_title_position'] : 'above', ['above', 'below'], 'above'),
            'data-show-navigation'         => ('yes' === ($settings['show_lightbox_navigation'] ?? '')) ? 'yes' : 'no',
            'data-show-counter'            => ('yes' === ($settings['show_lightbox_counter'] ?? '')) ? 'yes' : 'no',
            'data-show-thumbnails'         => ('yes' === ($settings['show_lightbox_thumbnails'] ?? '')) ? 'yes' : 'no',
            'data-show-post-link'          => ('yes' === ($settings['show_lightbox_post_link'] ?? '')) ? 'yes' : 'no',
            'data-post-link-label'         => isset($settings['lightbox_post_link_label']) ? sanitize_text_field($settings['lightbox_post_link_label']) : esc_html__('Open Post', 'softech-addons-for-elementor'),
            'data-post-link-target'        => $this->sanitize_value(isset($settings['lightbox_post_link_target']) ? $settings['lightbox_post_link_target'] : '_self', ['_self', '_blank'], '_self'),
            'data-close-backdrop'          => ('yes' === ($settings['close_on_backdrop_click'] ?? '')) ? 'yes' : 'no',
            'data-ajax-url'                => esc_url_raw(admin_url('admin-ajax.php')),
            'data-ajax-nonce'              => wp_create_nonce('sitsel_filterable_gallery'),
            'data-gallery-payload'         => $payload,
            'data-empty-text'              => esc_attr__('No gallery items found.', 'softech-addons-for-elementor'),
        ]);

        if (!$this->is_editor_mode()) {
            $this->add_render_attribute('wrapper', 'style', 'opacity:0;visibility:hidden;');
        }
        ?>
        <div <?php $this->print_render_attribute_string('wrapper'); ?>>
            <?php echo wp_kses_post($this->render_filter_toolbar_html($settings, $categories, $initial_filter)); ?>

            <div class="sitsel-filterable-gallery-status" aria-live="polite" aria-atomic="true"></div>
            <div class="sitsel-filterable-gallery-stage">
                <div class="sitsel-filterable-gallery-items">
                    <?php echo wp_kses_post($this->render_gallery_items_html($result['items'], $settings, $widget_id)); ?>
                </div>
                <div class="sitsel-filterable-gallery-empty<?php echo empty($result['items']) ? ' is-visible' : ''; ?>"><?php echo esc_html__('No gallery items found.', 'softech-addons-for-elementor'); ?></div>
            </div>

            <div class="sitsel-filterable-gallery-pagination">
                <?php echo wp_kses_post($this->render_pagination_html($result, $settings)); ?>
            </div>

            <?php if ('yes' === ($settings['enable_lightbox'] ?? '')) : ?>
                <div class="sitsel-filterable-gallery-lightbox" hidden>
                    <div class="sitsel-filterable-gallery-lightbox-backdrop" data-lightbox-close="backdrop"></div>
                    <div class="sitsel-filterable-gallery-lightbox-dialog" role="dialog" aria-modal="true" aria-label="<?php echo esc_attr__('Gallery lightbox', 'softech-addons-for-elementor'); ?>">
                        <div class="sitsel-filterable-gallery-lightbox-header">
                            <div class="sitsel-filterable-gallery-lightbox-caption-title"></div>
                            <div class="sitsel-filterable-gallery-lightbox-actions">
                                <button class="sitsel-filterable-gallery-lightbox-zoom-in" type="button" aria-label="<?php echo esc_attr__('Zoom in', 'softech-addons-for-elementor'); ?>" title="<?php echo esc_attr__('Zoom in', 'softech-addons-for-elementor'); ?>">
                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                        <circle cx="11" cy="11" r="7" stroke="currentColor" stroke-width="1.75"/>
                                        <path d="M11 8V14M8 11H14" stroke="currentColor" stroke-width="1.75" stroke-linecap="round"/>
                                        <path d="M16.5 16.5L21 21" stroke="currentColor" stroke-width="1.75" stroke-linecap="round"/>
                                    </svg>
                                </button>
                                <button class="sitsel-filterable-gallery-lightbox-zoom-out" type="button" aria-label="<?php echo esc_attr__('Zoom out', 'softech-addons-for-elementor'); ?>" title="<?php echo esc_attr__('Zoom out', 'softech-addons-for-elementor'); ?>">
                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                        <circle cx="11" cy="11" r="7" stroke="currentColor" stroke-width="1.75"/>
                                        <path d="M8 11H14" stroke="currentColor" stroke-width="1.75" stroke-linecap="round"/>
                                        <path d="M16.5 16.5L21 21" stroke="currentColor" stroke-width="1.75" stroke-linecap="round"/>
                                    </svg>
                                </button>
                                <button class="sitsel-filterable-gallery-lightbox-zoom-reset" type="button" aria-label="<?php echo esc_attr__('Reset zoom', 'softech-addons-for-elementor'); ?>" title="<?php echo esc_attr__('Reset zoom', 'softech-addons-for-elementor'); ?>">
                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                        <path d="M4 12a8 8 0 0 1 13.66-5.66L19 8.68" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
                                        <path d="M19 5.5V8.7h-3.2" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
                                        <path d="M20 12a8 8 0 0 1-13.66 5.66L5 15.32" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
                                        <path d="M5 18.5v-3.2h3.2" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
                                    </svg>
                                </button>
                                <button class="sitsel-filterable-gallery-lightbox-share" type="button" aria-label="<?php echo esc_attr__('Share', 'softech-addons-for-elementor'); ?>" title="<?php echo esc_attr__('Share', 'softech-addons-for-elementor'); ?>">
                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                        <path d="M15.5 7.5a2.5 2.5 0 1 0-2.31-3.43 2.5 2.5 0 0 0 2.31 3.43Z" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
                                        <path d="M8.5 14.5a2.5 2.5 0 1 0-2.31-3.43A2.5 2.5 0 0 0 8.5 14.5Z" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
                                        <path d="M15.5 21.5a2.5 2.5 0 1 0-2.31-3.43 2.5 2.5 0 0 0 2.31 3.43Z" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
                                        <path d="M10.5 12.3l3.4-2.1M10.5 13.7l3.4 2.1" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round"/>
                                    </svg>
                                </button>
                                <?php if ('dynamic' === $source && 'yes' === ($settings['show_lightbox_post_link'] ?? '')) : ?>
                                    <a class="sitsel-filterable-gallery-lightbox-post-link" href="#" target="<?php echo esc_attr($this->sanitize_value(isset($settings['lightbox_post_link_target']) ? $settings['lightbox_post_link_target'] : '_self', ['_self', '_blank'], '_self')); ?>" rel="nofollow noopener" hidden>
                                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M7 13L13 7" stroke="currentColor" stroke-width="1.7" stroke-linecap="round"/><path d="M8.5 7H13V11.5" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"/><path d="M5 5H15V15H5V5Z" stroke="currentColor" stroke-width="1.5" stroke-linejoin="round"/></svg>
                                        <span class="sitsel-filterable-gallery-lightbox-post-link-label"><?php echo esc_html(isset($settings['lightbox_post_link_label']) ? $settings['lightbox_post_link_label'] : esc_html__('Open Post', 'softech-addons-for-elementor')); ?></span>
                                    </a>
                                <?php endif; ?>
                                <div class="sitsel-filterable-gallery-lightbox-counter"></div>
                                <button class="sitsel-filterable-gallery-lightbox-close" type="button" aria-label="<?php echo esc_attr__('Close lightbox', 'softech-addons-for-elementor'); ?>">
                                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                        <path d="M6 6L18 18" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"/>
                                        <path d="M18 6L6 18" stroke="currentColor" stroke-width="1.9" stroke-linecap="round"/>
                                    </svg>
                                </button>
                            </div>
                        </div>
                        <div class="sitsel-filterable-gallery-lightbox-content">
                            <div class="sitsel-filterable-gallery-lightbox-image-wrapper">
                                <button class="sitsel-filterable-gallery-lightbox-nav is-prev" type="button" aria-label="<?php echo esc_attr__('Previous image', 'softech-addons-for-elementor'); ?>">
                                    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12.5 4.5L7 10L12.5 15.5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>
                                </button>
                                <img class="sitsel-filterable-gallery-lightbox-image" src="" alt="" />
                                <button class="sitsel-filterable-gallery-lightbox-nav is-next" type="button" aria-label="<?php echo esc_attr__('Next image', 'softech-addons-for-elementor'); ?>">
                                    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M7.5 4.5L13 10L7.5 15.5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>
                                </button>
                            </div>
                            <div class="sitsel-filterable-gallery-lightbox-footer">
                                <div class="sitsel-filterable-gallery-lightbox-caption-title-footer"></div>
                                <div class="sitsel-filterable-gallery-lightbox-caption-description"></div>
                                <div class="sitsel-filterable-gallery-lightbox-thumbnails-wrap is-hidden">
                                    <button class="sitsel-filterable-gallery-lightbox-thumbnails-nav is-prev" type="button" aria-label="<?php echo esc_attr__('Previous thumbnails', 'softech-addons-for-elementor'); ?>">
                                        <svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12.5 4.5L7 10L12.5 15.5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>
                                    </button>
                                    <div class="sitsel-filterable-gallery-lightbox-thumbnails is-hidden"></div>
                                    <button class="sitsel-filterable-gallery-lightbox-thumbnails-nav is-next" type="button" aria-label="<?php echo esc_attr__('Next thumbnails', 'softech-addons-for-elementor'); ?>">
                                        <svg width="16" height="16" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M7.5 4.5L13 10L7.5 15.5" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }

    private function render_gallery_items_html($items, $settings, $widget_id)
    {
        if (empty($items)) {
            return '';
        }

        $output = '';

        foreach ($items as $index => $item) {
            $item_key          = $widget_id . '-' . (isset($item['uid']) ? $item['uid'] : $index);
            $image_url         = $this->get_item_image_url($item);
            $lightbox_title    = $this->get_lightbox_title($item, $settings);
            $lightbox_description = $this->get_lightbox_description($item, $settings);
            $lightbox_caption  = $this->get_lightbox_caption($item, $settings);
            $click_mode        = $this->get_click_mode($item, $settings);
            $lightbox_eligible = ('lightbox' === $click_mode && !empty($image_url) && 'yes' === ($settings['enable_lightbox'] ?? 'yes')) ? '1' : '0';
            $item_id           = 'sitsel-filterable-gallery-item-' . sanitize_html_class($item_key);

            $this->add_render_attribute('item-' . $item_key, [
                'id'                     => $item_id,
                'class'                  => 'sitsel-filterable-gallery-item',
                'data-item-index'        => (string)(isset($item['uid']) ? $item['uid'] : $index),
                'data-item-id'           => $item_id,
                'data-category-slugs'    => implode(',', array_keys($item['categories'])),
                'data-lightbox-eligible' => $lightbox_eligible,
                'data-lightbox-src'      => $image_url,
                'data-lightbox-alt'      => $item['title'],
                'data-lightbox-title'    => $lightbox_title,
                'data-lightbox-description' => $lightbox_description,
                'data-lightbox-caption'  => $lightbox_caption,
                'data-post-link'         => isset($item['link']) ? esc_url_raw($item['link']) : '',
                'data-post-target'       => isset($item['link_target']) ? $item['link_target'] : '_self',
            ]);

            $output .= '<article ' . $this->get_render_attribute_string('item-' . $item_key) . '><div class="sitsel-filterable-gallery-card">';

            if ('custom-link' === $click_mode && !empty($item['link'])) {
                $rel     = ('_blank' === $item['link_target']) ? 'noopener noreferrer' : 'nofollow';
                $output .= '<a class="sitsel-filterable-gallery-action" href="' . esc_url($item['link']) . '" target="' . esc_attr($item['link_target']) . '" rel="' . esc_attr($rel) . '" data-click-mode="custom-link">';
            } elseif ('lightbox' === $click_mode) {
                $output .= '<button class="sitsel-filterable-gallery-action" type="button" data-click-mode="lightbox">';
            } else {
                $output .= '<div class="sitsel-filterable-gallery-action" data-click-mode="none">';
            }

            $output .= wp_kses_post($this->get_item_image_html($item, $settings));
            $output .= '<div class="sitsel-filterable-gallery-overlay"><div class="sitsel-filterable-gallery-overlay-inner">';

            if ('yes' === ($settings['show_title'] ?? 'yes') && '' !== $item['title']) {
                $output .= '<h3 class="sitsel-filterable-gallery-title">' . esc_html($item['title']) . '</h3>';
            }

            if ('yes' === ($settings['show_description'] ?? '') && '' !== $item['description']) {
                $output .= '<div class="sitsel-filterable-gallery-description">' . esc_html($item['description']) . '</div>';
            }

            $output .= '</div></div>';
            $output .= ('custom-link' === $click_mode && !empty($item['link'])) ? '</a>' : (('lightbox' === $click_mode) ? '</button>' : '</div>');
            $output .= '</div></article>';
        }

        return $output;
    }

    // =========================================================================
    // PREPARE GALLERY ITEMS
    // =========================================================================

    private function prepare_gallery_items($settings, $raw_settings = [])
    {
        $source = $this->sanitize_value(
            isset($settings['source']) ? $settings['source'] : 'static',
            ['static', 'basic_gallery', 'dynamic'],
            'static'
        );

        // ── NEW: Dynamic Gallery ────────────────────────────────────────
        if ('dynamic' === $source) {
            return $this->prepare_dynamic_gallery_items($settings, $raw_settings);
        }
        // ───────────────────────────────────────────────────────────────

        $items = [];
        $uid   = 0;

        if ('basic_gallery' === $source) {
            foreach ((array)($settings['basic_gallery_images'] ?? []) as $image) {
                $entry = $this->build_gallery_entry($image, '', '', '', '_self', [], $uid, isset($settings['image_size']) ? $settings['image_size'] : 'large');
                if ($entry) {
                    $items[] = $entry;
                    $uid++;
                }
            }
            return $items;
        }

        // 'static' — Category Gallery (unchanged)
        foreach ((array)($settings['gallery_items'] ?? []) as $group_index => $group) {
            $item_number = absint($group_index) + 1;
            $raw_title   = isset($group['title']) ? sanitize_text_field((string) $group['title']) : '';
            $raw_category = isset($group['category']) ? sanitize_text_field((string) $group['category']) : '';

            if (
                '' === $raw_title
                || preg_match('/^gallery item(?:\s+\d+)?$/i', $raw_title)
                || preg_match('/^item\s*#?\s*\d+$/i', $raw_title)
            ) {
                $raw_title = 'Gallery Item ' . $item_number;
            }

            if (
                '' === $raw_category
                || preg_match('/^category(?:[-\s]?\d+)?$/i', $raw_category)
                || preg_match('/^gallery item(?:\s+\d+)?$/i', $raw_category)
                || preg_match('/^item\s*#?\s*\d+$/i', $raw_category)
            ) {
                $raw_category = 'Category ' . $item_number;
            }

            $categories = $this->extract_categories($raw_category);
            $images     = isset($group['images']) && is_array($group['images']) ? $group['images'] : [];

            if (empty($images) && !empty($group['image'])) {
                $images = [$group['image']];
            }

            foreach ($images as $image) {
                $entry = $this->build_gallery_entry(
                    $image,
                    $raw_title,
                    isset($group['description']) ? $group['description'] : '',
                    isset($group['link']) ? $group['link'] : '',
                    isset($group['link_target']) ? $group['link_target'] : '_self',
                    $categories,
                    $uid,
                    isset($settings['image_size']) ? $settings['image_size'] : 'large'
                );

                if ($entry) {
                    $items[] = $entry;
                    $uid++;
                }
            }
        }

        return $items;
    }

    private function get_dynamic_setting_token(array $settings, array $raw_settings, string $control_name): string
    {
        $dynamic_settings = [];

        if (isset($settings[Dynamic_Tags_Manager::DYNAMIC_SETTING_KEY]) && is_array($settings[Dynamic_Tags_Manager::DYNAMIC_SETTING_KEY])) {
            $dynamic_settings = $settings[Dynamic_Tags_Manager::DYNAMIC_SETTING_KEY];
        } elseif (isset($raw_settings[Dynamic_Tags_Manager::DYNAMIC_SETTING_KEY]) && is_array($raw_settings[Dynamic_Tags_Manager::DYNAMIC_SETTING_KEY])) {
            $dynamic_settings = $raw_settings[Dynamic_Tags_Manager::DYNAMIC_SETTING_KEY];
        }

        return isset($dynamic_settings[$control_name]) && is_string($dynamic_settings[$control_name])
            ? $dynamic_settings[$control_name]
            : '';
    }

    private function parse_dynamic_tag_value(string $tag_text, array $dynamic_settings = [])
    {
        if ('' === $tag_text || !class_exists('\Elementor\Plugin')) {
            return '';
        }

        return \Elementor\Plugin::$instance->dynamic_tags->parse_tags_text(
            $tag_text,
            $dynamic_settings,
            [\Elementor\Plugin::$instance->dynamic_tags, 'get_tag_data_content']
        );
    }

    private function sanitize_dynamic_text_value($value): string
    {
        if (is_scalar($value)) {
            return sanitize_text_field((string) $value);
        }

        return '';
    }

    private function sanitize_dynamic_textarea_value($value): string
    {
        if (is_scalar($value)) {
            return sanitize_textarea_field((string) $value);
        }

        return '';
    }

    // ── NEW: fetch posts via Query Manager and convert to gallery entries ──
    /**
     * Query posts with Softech_Post_Query_Manager and build gallery items.
     *
     * Each item gets:
     *   - image   → post featured image (ID + URL)
     *   - title   → post title
     *   - description → post excerpt
     *   - categories  → WP terms from the chosen filter taxonomy (slug => label)
     *   - link    → post permalink (used when on_image_click = custom-link)
     *
     * Posts/pages without featured image use the Elementor placeholder image.
     *
     * @param array $settings Widget settings.
     * @return array          Normalised gallery-item array.
     */
    private function prepare_dynamic_gallery_items( array $settings, array $raw_settings = [] ): array {
        $args                   = Softech_Post_Query_Manager::build_query_args( $settings );
        $per_page               = $this->get_effective_per_page( $settings );
        $args['posts_per_page']  = 100;

        $args['no_found_rows']  = true;

        // Keep page queries compatible even when stale category/tag values exist in saved settings.
        if ( isset( $args['post_type'] ) && 'page' === sanitize_key( (string) $args['post_type'] ) ) {
            unset( $args['category_name'], $args['category__not_in'], $args['tag_slug__in'] );
        }

        $filter_taxonomy       = sanitize_key( $settings['dynamic_filter_taxonomy'] ?? 'category' );
        $dynamic_image         = $this->sanitize_image_data( $settings['dynamic_item_image'] ?? [] );
        $dynamic_title         = sanitize_text_field( $settings['dynamic_item_title'] ?? '' );
        $dynamic_description   = sanitize_textarea_field( $settings['dynamic_item_description'] ?? '' );
        $dynamic_link_data     = isset( $settings['dynamic_item_link'] ) ? $settings['dynamic_item_link'] : [];
        $dynamic_link_url      = is_array( $dynamic_link_data ) ? esc_url_raw( $dynamic_link_data['url'] ?? '' ) : esc_url_raw( $dynamic_link_data );
        $dynamic_link_target   = ( is_array( $dynamic_link_data ) && ! empty( $dynamic_link_data['is_external'] ) ) ? '_blank' : '_self';
        $dynamic_image_tag     = $this->get_dynamic_setting_token( $settings, $raw_settings, 'dynamic_item_image' );
        $dynamic_title_tag     = $this->get_dynamic_setting_token( $settings, $raw_settings, 'dynamic_item_title' );
        $dynamic_description_tag = $this->get_dynamic_setting_token( $settings, $raw_settings, 'dynamic_item_description' );
        $dynamic_link_tag      = $this->get_dynamic_setting_token( $settings, $raw_settings, 'dynamic_item_link' );
        $image_size            = $this->sanitize_value( isset( $settings['image_size'] ) ? $settings['image_size'] : 'large', [ 'thumbnail', 'medium', 'large', 'full' ], 'large' );

        $query = new \WP_Query( $args );

        // In editor, query controls can hydrate asynchronously on initial paint.
        // If the first dynamic query resolves empty, try a safe fallback once.
        if (
            $this->is_editor_mode()
            && ! $query->have_posts()
            && 'dynamic' === $this->sanitize_value( isset( $settings['selection'] ) ? $settings['selection'] : 'dynamic', [ 'dynamic', 'manual' ], 'dynamic' )
        ) {
            $fallback_post_type = sanitize_key((string) ($settings['post_type'] ?? 'post'));
            if ('' === $fallback_post_type) {
                $fallback_post_type = 'post';
            }

            $fallback_query_args = [
                'post_type'           => $fallback_post_type,
                'post_status'         => 'publish',
                'posts_per_page'      => 100,
                'orderby'             => 'date',
                'order'               => 'DESC',
                'ignore_sticky_posts' => true,
                'no_found_rows'       => true,
            ];

            $query = new \WP_Query( $fallback_query_args );
        }

        $items = [];
        $uid   = 0;

        if ( $query->have_posts() ) {
            while ( $query->have_posts() ) {
                $query->the_post();
                $post_id = get_the_ID();

                $featured_image_id  = (int) get_post_thumbnail_id( $post_id );
                $featured_image_url = $featured_image_id ? (string) wp_get_attachment_image_url( $featured_image_id, 'full' ) : '';

                $resolved_dynamic_image = $dynamic_image_tag
                    ? $this->sanitize_image_data( $this->parse_dynamic_tag_value( $dynamic_image_tag, [ 'returnType' => 'object' ] ) )
                    : $dynamic_image;
                $resolved_title       = $dynamic_title_tag ? $this->sanitize_dynamic_text_value( $this->parse_dynamic_tag_value( $dynamic_title_tag ) ) : '';
                $resolved_description = $dynamic_description_tag ? $this->sanitize_dynamic_textarea_value( $this->parse_dynamic_tag_value( $dynamic_description_tag ) ) : '';
                $resolved_link        = $dynamic_link_tag ? esc_url_raw( (string) $this->parse_dynamic_tag_value( $dynamic_link_tag ) ) : '';

                $image_id  = ! empty( $resolved_dynamic_image['id'] ) ? (int) $resolved_dynamic_image['id'] : $featured_image_id;
                $image_url = ! empty( $resolved_dynamic_image['url'] ) ? (string) $resolved_dynamic_image['url'] : $featured_image_url;

                if ( ! $image_id && '' === $image_url ) {
                    $image_url = Utils::get_placeholder_image_src();
                }

                $title       = '' !== $resolved_title ? $resolved_title : ( '' !== $dynamic_title ? $dynamic_title : (string) get_the_title( $post_id ) );
                $description = '' !== $resolved_description ? $resolved_description : ( '' !== $dynamic_description ? $dynamic_description : (string) get_the_excerpt( $post_id ) );
                $link        = '' !== $resolved_link ? $resolved_link : ( '' !== $dynamic_link_url ? $dynamic_link_url : (string) get_permalink( $post_id ) );
                $link_target = ( '' !== $resolved_link || '' !== $dynamic_link_url ) ? $dynamic_link_target : '_self';

                $categories = [];
                if ( taxonomy_exists( $filter_taxonomy ) ) {
                    $terms = get_the_terms( $post_id, $filter_taxonomy );
                    if ( $terms && ! is_wp_error( $terms ) ) {
                        foreach ( $terms as $term ) {
                            $categories[ $term->slug ] = $term->name;
                        }
                    }
                }

                $items[] = [
                    'uid'         => $uid,
                    'image'       => $this->augment_image_data_for_size( [
                        'id'  => $image_id,
                        'url' => esc_url_raw( $image_url ),
                    ], $image_size ),
                    'title'       => sanitize_text_field( $title ),
                    'description' => sanitize_textarea_field( $description ),
                    'link'        => esc_url_raw( $link ),
                    'link_target' => '_blank' === $link_target ? '_blank' : '_self',
                    'categories'  => $categories,
                ];

                $uid++;
            }
            wp_reset_postdata();
        }

        return $items;
    }
    // ─────────────────────────────────────────────────────────────────────

    // =========================================================================
    // SANITIZE PAYLOAD SETTINGS
    // =========================================================================

    private function sanitize_payload_settings($settings, $raw_settings = [])
    {
        $source = $this->get_source_type($settings);
        $raw_dynamic_settings = [];
        $post_type = sanitize_key((string) ($settings['post_type'] ?? 'post'));

        if ('' === $post_type) {
            $post_type = 'post';
        }

        if (isset($settings[Dynamic_Tags_Manager::DYNAMIC_SETTING_KEY]) && is_array($settings[Dynamic_Tags_Manager::DYNAMIC_SETTING_KEY])) {
            $raw_dynamic_settings = $settings[Dynamic_Tags_Manager::DYNAMIC_SETTING_KEY];
        } elseif (is_array($raw_settings) && isset($raw_settings[Dynamic_Tags_Manager::DYNAMIC_SETTING_KEY]) && is_array($raw_settings[Dynamic_Tags_Manager::DYNAMIC_SETTING_KEY])) {
            $raw_dynamic_settings = $raw_settings[Dynamic_Tags_Manager::DYNAMIC_SETTING_KEY];
        }

        return [
            'source'                   => $source,
            'image_size'               => $this->sanitize_value(isset($settings['image_size']) ? $settings['image_size'] : 'large', ['thumbnail', 'medium', 'large', 'full'], 'large'),
            'show_title'               => ('yes' === ($settings['show_title'] ?? 'yes')) ? 'yes' : '',
            'show_description'         => ('yes' === ($settings['show_description'] ?? '')) ? 'yes' : '',
            'show_filter_bar'          => ('yes' === ($settings['show_filter_bar'] ?? '')) ? 'yes' : '',
            'show_all_tab'             => ('yes' === ($settings['show_all_tab'] ?? 'yes')) ? 'yes' : '',
            'limited_items'            => ('yes' === ($settings['limited_items'] ?? '')) ? 'yes' : '',
            'dynamic_filter_taxonomy'  => sanitize_key($settings['dynamic_filter_taxonomy'] ?? 'category'),
            'dynamic_item_image'       => $this->sanitize_image_data($settings['dynamic_item_image'] ?? []),
            'dynamic_item_title'       => sanitize_text_field($settings['dynamic_item_title'] ?? ''),
            'dynamic_item_description' => sanitize_textarea_field($settings['dynamic_item_description'] ?? ''),
            'dynamic_item_link'        => [
                'url'         => esc_url_raw(is_array($settings['dynamic_item_link'] ?? null) ? ($settings['dynamic_item_link']['url'] ?? '') : ($settings['dynamic_item_link'] ?? '')),
                'is_external' => !empty(is_array($settings['dynamic_item_link'] ?? null) ? ($settings['dynamic_item_link']['is_external'] ?? '') : '') ? 'on' : '',
            ],
            'enable_lightbox'          => ('yes' === ($settings['enable_lightbox'] ?? 'yes')) ? 'yes' : '',
            'enable_pagination'        => $this->is_pagination_enabled($settings) ? 'yes' : '',
            'images_per_page'          => $this->get_effective_per_page($settings),
            'pagination_type'          => $this->get_pagination_type($settings),
            'load_more_text'           => isset($settings['load_more_text']) ? sanitize_text_field($settings['load_more_text']) : esc_html__('Load More', 'softech-addons-for-elementor'),
            'all_label'                => $this->get_all_label($settings),
            'on_image_click'           => $this->get_on_image_click_setting($settings),
            'on_image_click_basic'     => $this->sanitize_value(isset($settings['on_image_click_basic']) ? $settings['on_image_click_basic'] : 'lightbox', ['lightbox', 'none'], 'lightbox'),
            'lightbox_caption'         => ('basic_gallery' === $source) ? 'none' : $this->sanitize_value(isset($settings['lightbox_caption']) ? $settings['lightbox_caption'] : 'title', ['title', 'description', 'both', 'none'], 'title'),
            'lightbox_title_position'  => $this->sanitize_value(isset($settings['lightbox_title_position']) ? $settings['lightbox_title_position'] : 'above', ['above', 'below'], 'above'),
            'show_lightbox_navigation' => ('yes' === ($settings['show_lightbox_navigation'] ?? 'yes')) ? 'yes' : '',
            'show_lightbox_counter'    => ('yes' === ($settings['show_lightbox_counter'] ?? 'yes')) ? 'yes' : '',
            'show_lightbox_thumbnails' => ('yes' === ($settings['show_lightbox_thumbnails'] ?? '')) ? 'yes' : '',
            'show_lightbox_post_link'  => ('yes' === ($settings['show_lightbox_post_link'] ?? '')) ? 'yes' : '',
            'lightbox_post_link_label' => isset($settings['lightbox_post_link_label']) ? sanitize_text_field($settings['lightbox_post_link_label']) : esc_html__('Open Post', 'softech-addons-for-elementor'),
            'lightbox_post_link_target'=> $this->sanitize_value(isset($settings['lightbox_post_link_target']) ? $settings['lightbox_post_link_target'] : '_self', ['_self', '_blank'], '_self'),
            'close_on_backdrop_click'  => ('yes' === ($settings['close_on_backdrop_click'] ?? 'yes')) ? 'yes' : '',
            'gallery_animation'        => $this->sanitize_value(isset($settings['gallery_animation']) ? $settings['gallery_animation'] : 'fade', ['fade', 'zoom-in', 'slide-up', 'slide-down', 'none'], 'fade'),
            'gallery_animation_speed'  => isset($settings['gallery_animation_speed']['size']) ? absint($settings['gallery_animation_speed']['size']) : 400,
            'post_type'                => $post_type,
            'selection'                => $this->sanitize_value(isset($settings['selection']) ? $settings['selection'] : 'dynamic', ['dynamic', 'manual'], 'dynamic'),
            'manual_posts'             => array_map('absint', (array)($settings['manual_posts'] ?? [])),
            'categories'               => array_map('sanitize_key', (array)($settings['categories'] ?? [])),
            'exclude_categories'       => array_map('sanitize_key', (array)($settings['exclude_categories'] ?? [])),
            'manual_tags'              => array_map('sanitize_key', (array)($settings['manual_tags'] ?? [])),
            'orderby'                  => sanitize_key($settings['orderby'] ?? 'date'),
            'order'                    => $this->sanitize_value(isset($settings['order']) ? $settings['order'] : 'DESC', ['ASC', 'DESC'], 'DESC'),
            'offset'                   => absint($settings['offset'] ?? 0),
            'posts_per_page'           => $this->normalize_query_per_page_value($settings['posts_per_page'] ?? 6),
            'meta_query_relation'      => $this->sanitize_value(isset($settings['meta_query_relation']) ? $settings['meta_query_relation'] : 'AND', ['AND', 'OR'], 'AND'),
            'meta_query_rows'          => $this->sanitize_meta_query_rows($settings['meta_query_rows'] ?? []),
            Dynamic_Tags_Manager::DYNAMIC_SETTING_KEY => [
                'dynamic_item_image'       => isset($raw_dynamic_settings['dynamic_item_image']) && is_string($raw_dynamic_settings['dynamic_item_image']) ? $raw_dynamic_settings['dynamic_item_image'] : '',
                'dynamic_item_title'       => isset($raw_dynamic_settings['dynamic_item_title']) && is_string($raw_dynamic_settings['dynamic_item_title']) ? $raw_dynamic_settings['dynamic_item_title'] : '',
                'dynamic_item_description' => isset($raw_dynamic_settings['dynamic_item_description']) && is_string($raw_dynamic_settings['dynamic_item_description']) ? $raw_dynamic_settings['dynamic_item_description'] : '',
                'dynamic_item_link'        => isset($raw_dynamic_settings['dynamic_item_link']) && is_string($raw_dynamic_settings['dynamic_item_link']) ? $raw_dynamic_settings['dynamic_item_link'] : '',
            ],
        ];
    }

    private function sanitize_meta_query_rows($rows)
    {
        $sanitized = [];

        if (!is_array($rows)) {
            return $sanitized;
        }

        foreach ($rows as $row) {
            if (!is_array($row)) {
                continue;
            }

            $sanitized[] = [
                'meta_key'     => sanitize_text_field($row['meta_key'] ?? ''),
                'meta_compare' => sanitize_text_field($row['meta_compare'] ?? '='),
                'meta_type'    => sanitize_text_field($row['meta_type'] ?? 'CHAR'),
                'meta_value'   => sanitize_text_field($row['meta_value'] ?? ''),
            ];
        }

        return $sanitized;
    }

    // =========================================================================
    // PRIVATE HELPERS (unchanged except is_filter_enabled)
    // =========================================================================

    private function decode_payload($encoded)
    {
        if (!is_string($encoded) || '' === $encoded) {
            return [];
        }

        $json = base64_decode(preg_replace('/[^A-Za-z0-9+\/=]/', '', $encoded), true);
        if (false === $json) {
            return [];
        }

        $data = json_decode($json, true);
        return is_array($data) ? $data : [];
    }

    private function extract_categories($raw_categories)
    {
        $terms = [];
        $parts = array_filter(array_map('trim', explode(',', (string) $raw_categories)));

        foreach ($parts as $part) {
            $label = sanitize_text_field($part);
            $slug  = sanitize_title($label);

            if ('' === $slug || 'all' === $slug || isset($terms[$slug])) {
                continue;
            }

            $terms[$slug] = $label;
        }

        return $terms;
    }

    private function sanitize_payload_items($items, $settings = [])
    {
        $sanitized = [];

        if (!is_array($items)) {
            return $sanitized;
        }

        foreach ($items as $index => $item) {
            $entry = $this->build_gallery_entry(
                isset($item['image']) ? $item['image'] : [],
                isset($item['title']) ? $item['title'] : '',
                isset($item['description']) ? $item['description'] : '',
                isset($item['link']) ? $item['link'] : '',
                isset($item['link_target']) ? $item['link_target'] : '_self',
                isset($item['categories']) ? $item['categories'] : [],
                isset($item['uid']) ? $item['uid'] : $index,
                isset($settings['image_size']) ? $settings['image_size'] : 'large'
            );

            if ($entry) {
                $sanitized[] = $entry;
            }
        }

        return $sanitized;
    }

    private function build_gallery_entry($image, $title, $description, $link, $link_target, $categories, $uid, $image_size = 'large')
    {
        $image_data = $this->augment_image_data_for_size($this->sanitize_image_data($image), $image_size);
        $link_data  = $this->normalize_link_data($link, $link_target);

        if (empty($image_data['id']) && empty($image_data['url'])) {
            return null;
        }

        return [
            'uid'         => absint($uid),
            'image'       => $image_data,
            'title'       => sanitize_text_field($title),
            'description' => sanitize_textarea_field($description),
            'link'        => $link_data['url'],
            'link_target' => $link_data['target'],
            'categories'  => $this->sanitize_categories_array($categories),
        ];
    }

    private function normalize_link_data($link, $link_target = '_self')
    {
        $url    = is_array($link) ? esc_url_raw($link['url'] ?? '') : esc_url_raw($link);
        $target = is_string($link_target) ? sanitize_key($link_target) : '';

        if ('' === $target && is_array($link) && !empty($link['is_external'])) {
            $target = '_blank';
        }

        return [
            'url'    => $url,
            'target' => '_blank' === $target ? '_blank' : '_self',
        ];
    }

    private function sanitize_image_data($image)
    {
        return [
            'id'  => isset($image['id']) ? absint($image['id']) : 0,
            'url' => isset($image['url']) ? esc_url_raw($image['url']) : '',
        ];
    }

    private function augment_image_data_for_size(array $image_data, string $image_size = 'large'): array
    {
        $resolved_size = $this->sanitize_value($image_size, ['thumbnail', 'medium', 'large', 'full'], 'large');

        $image_data['display_url'] = isset($image_data['url']) ? $image_data['url'] : '';
        $image_data['full_url']    = isset($image_data['url']) ? $image_data['url'] : '';

        if (!empty($image_data['id'])) {
            $attachment_id = absint($image_data['id']);
            $display_src    = wp_get_attachment_image_src($attachment_id, $resolved_size);
            $full_src       = wp_get_attachment_image_src($attachment_id, 'full');

            if (is_array($display_src) && !empty($display_src[0])) {
                $image_data['display_url'] = esc_url_raw($display_src[0]);
            }

            if (is_array($full_src) && !empty($full_src[0])) {
                $image_data['full_url'] = esc_url_raw($full_src[0]);
            }
        }

        if ('' === (string) ($image_data['display_url'] ?? '')) {
            $image_data['display_url'] = isset($image_data['url']) ? $image_data['url'] : '';
        }

        if ('' === (string) ($image_data['full_url'] ?? '')) {
            $image_data['full_url'] = isset($image_data['display_url']) ? $image_data['display_url'] : '';
        }

        return $image_data;
    }

    private function sanitize_categories_array($categories)
    {
        $sanitized = [];

        if (!is_array($categories)) {
            return $sanitized;
        }

        foreach ($categories as $slug => $label) {
            $clean_slug  = sanitize_title(is_string($slug) ? $slug : $label);
            $clean_label = sanitize_text_field($label);

            if ('' === $clean_slug || '' === $clean_label || 'all' === $clean_slug) {
                continue;
            }

            $sanitized[$clean_slug] = $clean_label;
        }

        return $sanitized;
    }

    private function get_category_map($items)
    {
        $map = [];

        foreach ($items as $item) {
            foreach ($item['categories'] as $slug => $label) {
                if (!isset($map[$slug])) {
                    $map[$slug] = $label;
                }
            }
        }

        return $map;
    }

    private function render_filter_toolbar_html($settings, $categories, $active_filter)
    {
        if (empty($categories) || !$this->is_filter_enabled($settings, $this->get_source_type($settings))) {
            return '';
        }

        ob_start();
        ?>
        <div class="sitsel-filterable-gallery-toolbar" role="tablist" aria-label="<?php echo esc_attr__('Gallery filters', 'softech-addons-for-elementor'); ?>">
            <?php if ('yes' === ($settings['show_all_tab'] ?? 'yes')) : ?>
                <button class="sitsel-filterable-gallery-filter<?php echo 'all' === $active_filter ? ' is-active' : ''; ?>" type="button" data-category="all" aria-pressed="<?php echo 'all' === $active_filter ? 'true' : 'false'; ?>"><?php echo esc_html($this->get_all_label($settings)); ?></button>
            <?php endif; ?>
            <?php foreach ($categories as $slug => $label) : ?>
                <button class="sitsel-filterable-gallery-filter<?php echo $slug === $active_filter ? ' is-active' : ''; ?>" type="button" data-category="<?php echo esc_attr($slug); ?>" aria-pressed="<?php echo $slug === $active_filter ? 'true' : 'false'; ?>"><?php echo esc_html($label); ?></button>
            <?php endforeach; ?>
        </div>
        <?php

        return (string) ob_get_clean();
    }

    private function normalize_filter_value($filter, $settings, $categories)
    {
        $normalized_filter = sanitize_title($filter);

        if ('all' === $normalized_filter && 'yes' === ($settings['show_all_tab'] ?? 'yes')) {
            return 'all';
        }

        if (isset($categories[$normalized_filter])) {
            return $normalized_filter;
        }

        return $this->get_initial_filter($settings, $categories);
    }

    private function matches_filter($item, $filter)
    {
        if ('all' === $filter || '' === $filter) {
            return true;
        }

        return isset($item['categories'][$filter]);
    }

    private function get_query_result($items, $settings, $filter, $page)
    {
        $filtered = [];
        foreach ($items as $item) {
            if ($this->matches_filter($item, $filter)) {
                $filtered[] = $item;
            }
        }

        $pagination_enabled = $this->is_pagination_enabled($settings);
        $per_page           = $this->get_effective_per_page($settings);
        $total_items        = count($filtered);
        $total_pages        = $pagination_enabled ? max(1, (int) ceil($total_items / $per_page)) : 1;
        $current_page       = $pagination_enabled ? min(max(1, $page), $total_pages) : 1;
        $page_items         = $pagination_enabled ? array_slice($filtered, ($current_page - 1) * $per_page, $per_page) : $filtered;

        return [
            'items'        => $page_items,
            'total_items'  => $total_items,
            'current_page' => $current_page,
            'total_pages'  => $total_pages,
            'has_more'     => $current_page < $total_pages,
        ];
    }

    private function render_pagination_html($result, $settings)
    {
        $per_page = $this->get_effective_per_page($settings);

        if (!$this->is_pagination_enabled($settings) || $result['total_items'] <= $per_page) {
            return '';
        }

        $pagination_type = $this->get_pagination_type($settings);

        if ('none' === $pagination_type) {
            return '';
        }

        if ('load-more' === $pagination_type) {
            if (!$result['has_more']) {
                return '';
            }

            return '<button class="sitsel-filterable-gallery-load-more" type="button" data-next-page="' . esc_attr($result['current_page'] + 1) . '"' . (!$result['has_more'] ? ' disabled' : '') . '><span class="sitsel-filterable-gallery-button-label">' . esc_html($settings['load_more_text'] ?? esc_html__('Load More', 'softech-addons-for-elementor')) . '</span><span class="sitsel-filterable-gallery-button-loader" aria-hidden="true"></span></button>';
        }

        $output    = '<div class="sitsel-filterable-gallery-pagination-inner sitsel-filterable-gallery-page-links sitsel-pagination-type-numbers">';
        $prev_page = max(1, $result['current_page'] - 1);
        $next_page = min($result['total_pages'], $result['current_page'] + 1);

        $output .= '<button class="sitsel-filterable-gallery-page-btn' . (1 === $result['current_page'] ? ' is-disabled' : '') . '" type="button" data-page="' . esc_attr($prev_page) . '"' . (1 === $result['current_page'] ? ' disabled' : '') . '>' . esc_html__('Prev', 'softech-addons-for-elementor') . '</button>';

        for ($page_number = 1; $page_number <= $result['total_pages']; $page_number++) {
            $output .= '<button class="sitsel-filterable-gallery-page-btn' . ($page_number === $result['current_page'] ? ' is-active' : '') . '" type="button" data-page="' . esc_attr($page_number) . '">' . esc_html($page_number) . '</button>';
        }

        $output .= '<button class="sitsel-filterable-gallery-page-btn' . ($result['current_page'] === $result['total_pages'] ? ' is-disabled' : '') . '" type="button" data-page="' . esc_attr($next_page) . '"' . ($result['current_page'] === $result['total_pages'] ? ' disabled' : '') . '>' . esc_html__('Next', 'softech-addons-for-elementor') . '</button>';
        $output .= '</div>';

        return $output;
    }

    /**
     * Filter bar is enabled when source is 'static' OR 'dynamic' and the
     * show_filter_bar toggle is on. It is never shown for 'basic_gallery'.
     */
    private function is_filter_enabled($settings, $source)
    {
        // ── was: return 'static' === $source && 'yes' === ...
        return in_array( $source, [ 'static', 'dynamic' ], true )
            && 'yes' === ( $settings['show_filter_bar'] ?? '' );
    }

    private function get_initial_filter($settings, $categories)
    {
        if ('yes' === ($settings['show_all_tab'] ?? 'yes')) {
            return 'all';
        }

        if (!is_array($categories) || empty($categories)) {
            return 'all';
        }

        foreach ($categories as $slug => $label) {
            if ('' !== (string) $slug) {
                return (string) $slug;
            }
        }

        return 'all';
    }

    private function is_pagination_enabled($settings)
    {
        return $this->get_effective_per_page($settings) > 0;
    }

    private function get_effective_per_page($settings)
    {
        if ('dynamic' === $this->get_source_type($settings)) {
            return $this->normalize_query_per_page_value($settings['posts_per_page'] ?? 6);
        }

        if ('yes' === ($settings['limited_items'] ?? '')) {
            return 0;
        }

        return max(1, absint($settings['images_per_page'] ?? 10));
    }

    private function get_pagination_type($settings)
    {
        if ('dynamic' !== $this->get_source_type($settings) && 'yes' === ($settings['limited_items'] ?? '')) {
            return 'none';
        }

        $pagination_type = isset($settings['pagination_type']) ? sanitize_key((string) $settings['pagination_type']) : 'none';
        return $this->sanitize_value($pagination_type, ['none', 'load-more', 'numbers'], 'none');
    }

    private function normalize_query_per_page_value($value, int $default = 6)
    {
        if (is_string($value)) {
            $value = trim($value);
        }

        if ('' === $value || null === $value) {
            return $default;
        }

        $value = is_numeric($value) ? (int) $value : $default;

        if (-1 === $value) {
            return -1;
        }

        return max(1, $value);
    }

    private function get_source_type($settings)
    {
        return $this->sanitize_value(isset($settings['source']) ? $settings['source'] : 'static', ['static', 'basic_gallery', 'dynamic'], 'static');
    }

    private function get_on_image_click_setting($settings)
    {
        if ('basic_gallery' === $this->get_source_type($settings)) {
            return $this->sanitize_value(isset($settings['on_image_click_basic']) ? $settings['on_image_click_basic'] : 'lightbox', ['lightbox', 'none'], 'lightbox');
        }

        return $this->sanitize_value(isset($settings['on_image_click']) ? $settings['on_image_click'] : 'lightbox', ['lightbox', 'custom-link', 'none'], 'lightbox');
    }

    private function get_click_mode($item, $settings)
    {
        $mode = $this->get_on_image_click_setting($settings);

        if ('custom-link' === $mode && empty($item['link'])) {
            return 'none';
        }

        if ('lightbox' === $mode && 'yes' !== ($settings['enable_lightbox'] ?? '')) {
            return 'none';
        }

        return $mode;
    }

    private function get_lightbox_title($item, $settings)
    {
        if ('basic_gallery' === $this->get_source_type($settings)) {
            return '';
        }

        $caption_source = $this->sanitize_value(isset($settings['lightbox_caption']) ? $settings['lightbox_caption'] : 'title', ['title', 'description', 'both', 'none'], 'title');

        if (in_array($caption_source, ['title', 'both'], true)) {
            return $item['title'];
        }

        return '';
    }

    private function get_lightbox_description($item, $settings)
    {
        if ('basic_gallery' === $this->get_source_type($settings)) {
            return '';
        }

        $caption_source = $this->sanitize_value(isset($settings['lightbox_caption']) ? $settings['lightbox_caption'] : 'title', ['title', 'description', 'both', 'none'], 'title');

        if ('description' === $caption_source) {
            return $item['description'];
        }

        if ('both' === $caption_source) {
            return $item['description'];
        }

        return '';
    }

    private function get_lightbox_caption($item, $settings)
    {
        $title       = $this->get_lightbox_title($item, $settings);
        $description = $this->get_lightbox_description($item, $settings);

        if ('' !== $title && '' !== $description) {
            return trim($title . ' ' . $description);
        }

        return '' !== $title ? $title : $description;
    }

    private function get_item_image_html($item, $settings)
    {
        $image_size = $this->sanitize_value(isset($settings['image_size']) ? $settings['image_size'] : 'large', ['thumbnail', 'medium', 'large', 'full'], 'large');
        $image_id   = isset($item['image']['id']) ? absint($item['image']['id']) : 0;

        if ($image_id) {
            return wp_get_attachment_image($image_id, $image_size, false, ['class' => 'sitsel-filterable-gallery-image', 'loading' => 'lazy']);
        }

        $image_url = isset($item['image']['display_url']) ? $item['image']['display_url'] : $this->get_item_image_url($item);
        return '<img class="sitsel-filterable-gallery-image" src="' . esc_url($image_url) . '" alt="' . esc_attr($item['title']) . '" loading="lazy" />';
    }

    private function get_item_image_url($item)
    {
        if (!empty($item['image']['full_url'])) {
            return esc_url_raw($item['image']['full_url']);
        }

        if (!empty($item['image']['id'])) {
            $image_url = wp_get_attachment_image_url(absint($item['image']['id']), 'full');
            if ($image_url) {
                return esc_url_raw($image_url);
            }
        }

        if (!empty($item['image']['url'])) {
            return esc_url_raw($item['image']['url']);
        }

        return esc_url_raw(Utils::get_placeholder_image_src());
    }

    private function get_all_label($settings)
    {
        $label = isset($settings['all_label']) ? sanitize_text_field($settings['all_label']) : '';
        return '' !== $label ? $label : esc_html__('All', 'softech-addons-for-elementor');
    }

    /**
     * Helper: return all public taxonomies as slug => label for the
     * "Filter Taxonomy" control in Dynamic Gallery mode.
     *
     * @return array
     */
    private function get_public_taxonomies_for_select(): array
    {
        $exclude = ['post_format', 'elementor_library_category', 'elementor_library_tag'];
        $result  = [];
        foreach ( get_taxonomies( ['public' => true], 'objects' ) as $tax ) {
            if ( ! in_array( $tax->name, $exclude, true ) ) {
                $result[ $tax->name ] = $tax->label;
            }
        }
        return $result;
    }

    // =========================================================================
    // TINY UTILITIES (unchanged)
    // =========================================================================

    private function sanitize_value($value, $allowed, $default)
    {
        $value = is_string($value) ? $value : '';
        return in_array($value, $allowed, true) ? $value : $default;
    }

    private function is_editor_mode()
    {
        return class_exists('\Elementor\Plugin') && \Elementor\Plugin::$instance->editor->is_edit_mode();
    }
}
