<?php

namespace Calio\Widgets;

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

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

/**
 * Renders a filterable gallery with editorial cards and lightweight client-side filtering.
 */
class FilterableGalleryWidget extends BaseWidget
{
    public function get_name(): string
    {
        return 'calio-filterable-gallery';
    }

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

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

    public function get_style_depends(): array
    {
        return $this->resolve_widget_style_depends('calio-widget-filterable-gallery');
    }

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

    /**
     * Registers gallery content, filter and style controls.
     */
    protected function register_controls(): void
    {
        $this->start_controls_section('gallery_section', ['label' => esc_html__('Gallery', 'calio-addon')]);
        $this->add_control('layout_skin', [
            'label' => esc_html__('Layout Skin', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'cards',
            'options' => [
                'cards' => esc_html__('Cards', 'calio-addon'),
                'overlay' => esc_html__('Overlay', 'calio-addon'),
                'minimal' => esc_html__('Minimal', 'calio-addon'),
            ],
        ]);
        $this->add_control('columns', [
            'label' => esc_html__('Columns', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => '3',
            'options' => [
                '2' => '2',
                '3' => '3',
                '4' => '4',
            ],
        ]);
        $this->add_control('image_ratio', [
            'label' => esc_html__('Image Ratio', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'landscape',
            'options' => [
                'square' => esc_html__('Square', 'calio-addon'),
                'landscape' => esc_html__('Landscape', 'calio-addon'),
                'portrait' => esc_html__('Portrait', 'calio-addon'),
                'auto' => esc_html__('Auto', 'calio-addon'),
            ],
        ]);
        $this->add_control('grid_flow', [
            'label' => esc_html__('Grid Flow', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'standard',
            'options' => [
                'standard' => esc_html__('Standard', 'calio-addon'),
                'masonry' => esc_html__('Masonry Feel', 'calio-addon'),
            ],
        ]);
        $this->add_control('overlay_chrome', [
            'label' => esc_html__('Overlay Chrome', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'soft',
            'options' => [
                'soft' => esc_html__('Soft', 'calio-addon'),
                'glass' => esc_html__('Glass', 'calio-addon'),
                'editorial' => esc_html__('Editorial', 'calio-addon'),
            ],
            'condition' => ['show_caption' => 'yes'],
        ]);
        $this->add_control('show_filters', [
            'label' => esc_html__('Show Filters', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);
        $this->add_control('filter_skin', [
            'label' => esc_html__('Filter Skin', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'pill',
            'options' => [
                'pill' => esc_html__('Pill', 'calio-addon'),
                'underline' => esc_html__('Underline', 'calio-addon'),
                'soft' => esc_html__('Soft', 'calio-addon'),
            ],
            'condition' => ['show_filters' => 'yes'],
        ]);
        $this->add_control('all_label', [
            'label' => esc_html__('All Label', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('All', 'calio-addon'),
            'condition' => ['show_filters' => 'yes'],
        ]);
        $this->add_control('show_counts', [
            'label' => esc_html__('Show Counts', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
            'condition' => ['show_filters' => 'yes'],
        ]);
        $this->add_control('show_caption', [
            'label' => esc_html__('Show Caption', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);
        $this->add_control('show_meta', [
            'label' => esc_html__('Show Meta', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
            'condition' => ['show_caption' => 'yes'],
        ]);
        $this->add_control('lightbox', [
            'label' => esc_html__('Open in Lightbox', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);
        $this->add_control('show_overlay_cta', [
            'label' => esc_html__('Show Overlay CTA', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);
        $this->add_control('overlay_cta_text', [
            'label' => esc_html__('Overlay CTA Text', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Open Project', 'calio-addon'),
            'condition' => ['show_overlay_cta' => 'yes'],
        ]);
        $this->add_control('featured_cta_text', [
            'label' => esc_html__('Featured CTA Text', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('View Case Study', 'calio-addon'),
            'condition' => ['show_overlay_cta' => 'yes'],
        ]);
        $this->add_control('featured_first', [
            'label' => esc_html__('Featured First Layout', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);
        $this->add_control('filter_motion', [
            'label' => esc_html__('Filter Motion', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'shuffle',
            'options' => [
                'standard' => esc_html__('Standard', 'calio-addon'),
                'shuffle' => esc_html__('Shuffle', 'calio-addon'),
            ],
        ]);
        $this->add_control('sort_mode', [
            'label' => esc_html__('Sort Mode', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'none',
            'options' => [
                'none' => esc_html__('Manual Order', 'calio-addon'),
                'title-asc' => esc_html__('Title A-Z', 'calio-addon'),
                'title-desc' => esc_html__('Title Z-A', 'calio-addon'),
                'category' => esc_html__('Category', 'calio-addon'),
            ],
        ]);
        $this->add_control('featured_hero_style', [
            'label' => esc_html__('Featured Hero Style', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'standard',
            'options' => [
                'standard' => esc_html__('Standard', 'calio-addon'),
                'split' => esc_html__('Split', 'calio-addon'),
                'spotlight' => esc_html__('Spotlight', 'calio-addon'),
            ],
            'condition' => ['featured_first' => 'yes'],
        ]);
        $this->add_control('show_results_status', [
            'label' => esc_html__('Show Results Status', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);
        $this->add_control('show_search', [
            'label' => esc_html__('Show Search', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => 'yes',
        ]);
        $this->add_control('search_placeholder', [
            'label' => esc_html__('Search Placeholder', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Search projects', 'calio-addon'),
            'condition' => ['show_search' => 'yes'],
        ]);
        $this->add_control('enable_load_more', [
            'label' => esc_html__('Enable Load More', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => '',
        ]);
        $this->add_control('initial_items', [
            'label' => esc_html__('Initially Visible Items', 'calio-addon'),
            'type' => Controls_Manager::NUMBER,
            'default' => 6,
            'min' => 1,
            'max' => 24,
            'condition' => ['enable_load_more' => 'yes'],
        ]);
        $this->add_control('load_more_count', [
            'label' => esc_html__('Load More Count', 'calio-addon'),
            'type' => Controls_Manager::NUMBER,
            'default' => 3,
            'min' => 1,
            'max' => 12,
            'condition' => ['enable_load_more' => 'yes'],
        ]);
        $this->add_control('load_more_text', [
            'label' => esc_html__('Load More Text', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Load More', 'calio-addon'),
            'condition' => ['enable_load_more' => 'yes'],
        ]);
        $this->add_control('all_loaded_text', [
            'label' => esc_html__('All Loaded Text', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('All items loaded', 'calio-addon'),
            'condition' => ['enable_load_more' => 'yes'],
        ]);
        $this->add_control('empty_title', [
            'label' => esc_html__('Empty State Title', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('No matching projects', 'calio-addon'),
        ]);
        $this->add_control('empty_text', [
            'label' => esc_html__('Empty State Text', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Try another filter or a different keyword to widen the gallery view.', 'calio-addon'),
        ]);
        $this->add_control('reset_label', [
            'label' => esc_html__('Reset View Label', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Reset View', 'calio-addon'),
        ]);
        $this->add_control('gap', [
            'label' => esc_html__('Gap', 'calio-addon'),
            'type' => Controls_Manager::SLIDER,
            'range' => ['px' => ['min' => 0, 'max' => 40]],
            'selectors' => [
                '{{WRAPPER}} .calio-filterable-gallery-grid' => 'gap: {{SIZE}}{{UNIT}};',
                '{{WRAPPER}} .calio-filterable-gallery-filters' => 'gap: {{SIZE}}{{UNIT}};',
            ],
        ]);

        $repeater = new Repeater();
        $repeater->add_control('image', [
            'label' => esc_html__('Image', 'calio-addon'),
            'type' => Controls_Manager::MEDIA,
            'default' => ['url' => ''],
        ]);
        $repeater->add_control('title', [
            'label' => esc_html__('Title', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Gallery Item', 'calio-addon'),
            'label_block' => true,
        ]);
        $repeater->add_control('category', [
            'label' => esc_html__('Filter Category', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Branding', 'calio-addon'),
            'label_block' => true,
        ]);
        $repeater->add_control('categories', [
            'label' => esc_html__('Extra Categories', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => '',
            'label_block' => true,
            'description' => esc_html__('Comma separated. Example: Branding, Campaign, Motion', 'calio-addon'),
        ]);
        $repeater->add_control('featured', [
            'label' => esc_html__('Featured Item', 'calio-addon'),
            'type' => Controls_Manager::SWITCHER,
            'return_value' => 'yes',
            'default' => '',
        ]);
        $repeater->add_control('featured_label', [
            'label' => esc_html__('Featured Label', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => esc_html__('Featured', 'calio-addon'),
            'condition' => ['featured' => 'yes'],
        ]);
        $repeater->add_control('size_preset', [
            'label' => esc_html__('Size Preset', 'calio-addon'),
            'type' => Controls_Manager::SELECT,
            'default' => 'standard',
            'options' => [
                'standard' => esc_html__('Standard', 'calio-addon'),
                'wide' => esc_html__('Wide', 'calio-addon'),
                'tall' => esc_html__('Tall', 'calio-addon'),
            ],
        ]);
        $repeater->add_control('meta', [
            'label' => esc_html__('Meta Label', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => '',
        ]);
        $repeater->add_control('overlay_note', [
            'label' => esc_html__('Overlay Note', 'calio-addon'),
            'type' => Controls_Manager::TEXT,
            'default' => '',
        ]);
        $repeater->add_control('caption', [
            'label' => esc_html__('Caption', 'calio-addon'),
            'type' => Controls_Manager::TEXTAREA,
            'default' => '',
        ]);
        $repeater->add_control('link_url', [
            'label' => esc_html__('Item Link', 'calio-addon'),
            'type' => Controls_Manager::URL,
            'default' => ['url' => ''],
        ]);

        $this->add_control('items', [
            'type' => Controls_Manager::REPEATER,
            'fields' => $repeater->get_controls(),
            'title_field' => '{{{ title }}}',
            'default' => $this->get_default_items(),
        ]);
        $this->end_controls_section();

        $this->start_controls_section('style_filters', ['label' => esc_html__('Filters', 'calio-addon'), 'tab' => Controls_Manager::TAB_STYLE, 'condition' => ['show_filters' => 'yes']]);
        $this->add_group_control(Group_Control_Typography::get_type(), [
            'name' => 'filter_typography',
            'selector' => '{{WRAPPER}} .calio-filterable-gallery-filter',
        ]);
        $this->add_style_heading('filterable_gallery_filter_spacing_heading', esc_html__('Shape & Spacing', 'calio-addon'));
        $this->add_dimensions_control('filter_padding', esc_html__('Padding', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-filter', 'padding');
        $this->add_dimensions_control('filter_margin', esc_html__('Margin', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-filter', 'margin');
        $this->add_dimensions_control('filter_radius', esc_html__('Radius', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-filter', 'border-radius', ['size_units' => ['px', '%']]);
        $this->add_style_heading('filterable_gallery_filter_surface_heading', esc_html__('Surface States', 'calio-addon'));
        $this->start_controls_tabs('filter_state_tabs');
        $this->start_controls_tab('filter_state_normal', ['label' => esc_html__('Normal', 'calio-addon')]);
        $this->add_text_paint_controls('filter_text_normal', esc_html__('Text Color', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-filter');
        $this->add_background_type_control('filter_bg_normal_group', '{{WRAPPER}} .calio-filterable-gallery-filter');
        $this->add_border_paint_controls('filter_border_normal', esc_html__('Border Color', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-filter');
        $this->end_controls_tab();
        $this->start_controls_tab('filter_state_hover', ['label' => esc_html__('Hover', 'calio-addon')]);
        $this->add_text_paint_controls('filter_text_hover', esc_html__('Text Color', 'calio-addon'), ['{{WRAPPER}} .calio-filterable-gallery-filter:hover', '{{WRAPPER}} .calio-filterable-gallery-filter:focus-visible']);
        $this->add_background_type_control('filter_bg_hover_group', ['{{WRAPPER}} .calio-filterable-gallery-filter:hover', '{{WRAPPER}} .calio-filterable-gallery-filter:focus-visible']);
        $this->add_border_paint_controls('filter_border_hover', esc_html__('Border Color', 'calio-addon'), ['{{WRAPPER}} .calio-filterable-gallery-filter:hover', '{{WRAPPER}} .calio-filterable-gallery-filter:focus-visible']);
        $this->end_controls_tab();
        $this->start_controls_tab('filter_state_active', ['label' => esc_html__('Active', 'calio-addon')]);
        $this->add_text_paint_controls('filter_text_active', esc_html__('Text Color', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-filter.is-active');
        $this->add_background_type_control('filter_bg_active_group', '{{WRAPPER}} .calio-filterable-gallery-filter.is-active');
        $this->add_border_paint_controls('filter_border_active', esc_html__('Border Color', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-filter.is-active');
        $this->end_controls_tab();
        $this->end_controls_tabs();
        $this->add_style_heading('filterable_gallery_filter_outline_heading', esc_html__('Border Type & Shadow', 'calio-addon'));
        $this->add_group_control(Group_Control_Border::get_type(), [
            'name' => 'filter_border_group',
            'selector' => '{{WRAPPER}} .calio-filterable-gallery-filter',
        ]);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), [
            'name' => 'filter_shadow_group',
            'selector' => '{{WRAPPER}} .calio-filterable-gallery-filter',
        ]);
        $this->add_style_heading('filterable_gallery_filter_meta_heading', esc_html__('Counts', 'calio-addon'));
        $this->add_text_paint_controls('filter_count_text', esc_html__('Count Text', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-count');
        $this->add_background_type_control('filter_count_bg_group', '{{WRAPPER}} .calio-filterable-gallery-count');
        $this->end_controls_section();

        $this->start_controls_section('style_cards', ['label' => esc_html__('Cards', 'calio-addon'), 'tab' => Controls_Manager::TAB_STYLE]);
        $this->add_style_heading('filterable_gallery_card_spacing_heading', esc_html__('Shape & Spacing', 'calio-addon'));
        $this->add_dimensions_control('card_radius', esc_html__('Radius', 'calio-addon'), ['{{WRAPPER}} .calio-filterable-gallery-item', '{{WRAPPER}} .calio-filterable-gallery-media', '{{WRAPPER}} .calio-filterable-gallery-media img'], 'border-radius', ['size_units' => ['px', '%']]);
        $this->add_dimensions_control('card_padding', esc_html__('Padding', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-item', 'padding');
        $this->add_dimensions_control('card_margin', esc_html__('Margin', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-item', 'margin');
        $this->add_style_heading('filterable_gallery_card_surface_heading', esc_html__('Surface States', 'calio-addon'));
        $this->start_controls_tabs('card_state_tabs');
        $this->start_controls_tab('card_state_normal', ['label' => esc_html__('Normal', 'calio-addon')]);
        $this->add_background_type_control('gallery_card_bg_normal_group', '{{WRAPPER}} .calio-filterable-gallery-item');
        $this->add_border_paint_controls('gallery_card_border_normal', esc_html__('Border Color', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-item');
        $this->end_controls_tab();
        $this->start_controls_tab('card_state_hover', ['label' => esc_html__('Hover', 'calio-addon')]);
        $this->add_background_type_control('gallery_card_bg_hover_group', '{{WRAPPER}} .calio-filterable-gallery-item:hover');
        $this->add_border_paint_controls('gallery_card_border_hover', esc_html__('Border Color', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-item:hover');
        $this->end_controls_tab();
        $this->start_controls_tab('card_state_active', ['label' => esc_html__('Active', 'calio-addon')]);
        $this->add_background_type_control('gallery_card_bg_active_group', '{{WRAPPER}} .calio-filterable-gallery-item:focus-within');
        $this->add_border_paint_controls('gallery_card_border_active', esc_html__('Border Color', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-item:focus-within');
        $this->end_controls_tab();
        $this->end_controls_tabs();
        $this->add_style_heading('filterable_gallery_card_outline_heading', esc_html__('Outline & Shadow', 'calio-addon'));
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), [
            'name' => 'gallery_card_shadow',
            'selector' => '{{WRAPPER}} .calio-filterable-gallery-item',
        ]);
        $this->add_group_control(Group_Control_Border::get_type(), [
            'name' => 'gallery_card_border',
            'selector' => '{{WRAPPER}} .calio-filterable-gallery-item',
        ]);
        $this->add_style_heading('filterable_gallery_card_featured_heading', esc_html__('Featured Surface', 'calio-addon'));
        $this->add_text_paint_controls('gallery_featured_text', esc_html__('Featured Label Text', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-featured');
        $this->add_background_type_control('gallery_featured_bg_group', '{{WRAPPER}} .calio-filterable-gallery-featured');
        $this->add_background_type_control('gallery_featured_surface_bg_group', '{{WRAPPER}} .calio-filterable-gallery-item.is-featured');
        $this->add_text_paint_controls('gallery_featured_cta_text', esc_html__('Featured CTA Text', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-overlay-link.is-featured-link');
        $this->add_background_type_control('gallery_featured_cta_bg_group', '{{WRAPPER}} .calio-filterable-gallery-overlay-link.is-featured-link');
        $this->end_controls_section();

        $this->start_controls_section('style_content', ['label' => esc_html__('Caption', 'calio-addon'), 'tab' => Controls_Manager::TAB_STYLE, 'condition' => ['show_caption' => 'yes']]);
        $this->add_group_control(Group_Control_Typography::get_type(), [
            'name' => 'gallery_caption_typography',
            'selector' => '{{WRAPPER}} .calio-filterable-gallery-title, {{WRAPPER}} .calio-filterable-gallery-caption, {{WRAPPER}} .calio-filterable-gallery-meta',
        ]);
        $this->add_style_heading('filterable_gallery_caption_spacing_heading', esc_html__('Shape & Spacing', 'calio-addon'));
        $this->add_dimensions_control('gallery_caption_padding', esc_html__('Padding', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-copy', 'padding');
        $this->add_dimensions_control('gallery_caption_margin', esc_html__('Margin', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-copy', 'margin');
        $this->add_dimensions_control('gallery_caption_radius', esc_html__('Radius', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-copy', 'border-radius', ['size_units' => ['px', '%']]);
        $this->add_style_heading('filterable_gallery_caption_surface_heading', esc_html__('Surface', 'calio-addon'));
        $this->add_text_paint_controls('gallery_title_text', esc_html__('Title Color', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-title');
        $this->add_text_paint_controls('gallery_meta_text', esc_html__('Meta Color', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-meta');
        $this->add_text_paint_controls('gallery_caption_text', esc_html__('Caption Color', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-caption');
        $this->add_background_type_control('gallery_caption_bg_group', '{{WRAPPER}} .calio-filterable-gallery-copy');
        $this->add_style_heading('filterable_gallery_caption_outline_heading', esc_html__('Border Type & Shadow', 'calio-addon'));
        $this->add_group_control(Group_Control_Border::get_type(), [
            'name' => 'gallery_caption_border_group',
            'selector' => '{{WRAPPER}} .calio-filterable-gallery-copy',
        ]);
        $this->add_group_control(Group_Control_Box_Shadow::get_type(), [
            'name' => 'gallery_caption_shadow_group',
            'selector' => '{{WRAPPER}} .calio-filterable-gallery-copy',
        ]);
        $this->add_style_heading('filterable_gallery_caption_overlay_heading', esc_html__('Overlay Notes', 'calio-addon'));
        $this->add_text_paint_controls('gallery_overlay_note_text', esc_html__('Overlay Note Color', 'calio-addon'), '{{WRAPPER}} .calio-filterable-gallery-overlay-note');
        $this->add_background_type_control('gallery_overlay_note_bg_group', '{{WRAPPER}} .calio-filterable-gallery-overlay-note');
        $this->end_controls_section();
    }

    /**
     * Outputs filter buttons and gallery items.
     */
    protected function render(): void
    {
        $settings = $this->get_settings_for_display();
        $items = $settings['items'] ?? [];

        if (!is_array($items) || empty($items)) {
            echo '<div class="calio-filterable-gallery-empty">' . esc_html__('Add at least one gallery item.', 'calio-addon') . '</div>';
            return;
        }

        $widget_id = 'calio-filterable-gallery-' . $this->get_id();
        $filters = $this->build_filters($items);
        $show_filters = ($settings['show_filters'] ?? 'yes') === 'yes' && !empty($filters);
        $show_counts = ($settings['show_counts'] ?? 'yes') === 'yes';
        $show_caption = ($settings['show_caption'] ?? 'yes') === 'yes';
        $show_meta = ($settings['show_meta'] ?? 'yes') === 'yes';
        $lightbox = ($settings['lightbox'] ?? 'yes') === 'yes';
        $show_overlay_cta = ($settings['show_overlay_cta'] ?? 'yes') === 'yes';
        $featured_first = ($settings['featured_first'] ?? 'yes') === 'yes';
        $show_results_status = ($settings['show_results_status'] ?? 'yes') === 'yes';
        $show_search = ($settings['show_search'] ?? 'yes') === 'yes';
        $enable_load_more = ($settings['enable_load_more'] ?? '') === 'yes';
        $initial_items = max(1, min(24, (int) ($settings['initial_items'] ?? 6)));
        $load_more_count = max(1, min(12, (int) ($settings['load_more_count'] ?? 3)));
        $show_toolbar = $show_filters || $show_results_status || $show_search;

        $classes = [
            'calio-filterable-gallery',
            'skin-' . sanitize_html_class((string) ($settings['layout_skin'] ?? 'cards')),
            'cols-' . sanitize_html_class((string) ($settings['columns'] ?? '3')),
            'ratio-' . sanitize_html_class((string) ($settings['image_ratio'] ?? 'landscape')),
            'filter-skin-' . sanitize_html_class((string) ($settings['filter_skin'] ?? 'pill')),
            'flow-' . sanitize_html_class((string) ($settings['grid_flow'] ?? 'standard')),
            'overlay-chrome-' . sanitize_html_class((string) ($settings['overlay_chrome'] ?? 'soft')),
            'filter-motion-' . sanitize_html_class((string) ($settings['filter_motion'] ?? 'shuffle')),
            'featured-hero-' . sanitize_html_class((string) ($settings['featured_hero_style'] ?? 'standard')),
        ];
        if ($featured_first) {
            $classes[] = 'has-featured-first';
        }
        if ($show_overlay_cta) {
            $classes[] = 'has-overlay-cta';
        }
        if ($show_results_status) {
            $classes[] = 'has-results-status';
        }

        echo '<div id="' . esc_attr($widget_id) . '" class="' . esc_attr(implode(' ', $classes)) . '" data-load-more="' . esc_attr($enable_load_more ? 'yes' : 'no') . '" data-initial-items="' . esc_attr((string) $initial_items) . '" data-load-more-count="' . esc_attr((string) $load_more_count) . '" data-all-loaded-text="' . esc_attr((string) ($settings['all_loaded_text'] ?? esc_html__('All items loaded', 'calio-addon'))) . '" data-sort-mode="' . esc_attr((string) ($settings['sort_mode'] ?? 'none')) . '">';

        if ($show_toolbar) {
            $all_label = trim((string) ($settings['all_label'] ?? esc_html__('All', 'calio-addon')));
            if ($all_label === '') {
                $all_label = esc_html__('All', 'calio-addon');
            }

            echo '<div class="calio-filterable-gallery-toolbar">';
            echo '<div class="calio-filterable-gallery-toolbar-main">';
            if ($show_filters) {
                echo '<div class="calio-filterable-gallery-filters" role="tablist">';
                echo '<button class="calio-filterable-gallery-filter is-active" type="button" data-filter="all" aria-selected="true">';
                echo '<span>' . esc_html($all_label) . '</span>';
                if ($show_counts) {
                    echo '<span class="calio-filterable-gallery-count">' . esc_html(number_format_i18n(count($items))) . '</span>';
                }
                echo '</button>';

                foreach ($filters as $slug => $filter) {
                    echo '<button class="calio-filterable-gallery-filter" type="button" data-filter="' . esc_attr($slug) . '" aria-selected="false">';
                    echo '<span>' . esc_html($filter['label']) . '</span>';
                    if ($show_counts) {
                        echo '<span class="calio-filterable-gallery-count">' . esc_html(number_format_i18n((int) $filter['count'])) . '</span>';
                    }
                    echo '</button>';
                }

                echo '</div>';
            }
            if ($show_search) {
                echo '<label class="calio-filterable-gallery-search">';
                echo '<span class="screen-reader-text">' . esc_html__('Search gallery items', 'calio-addon') . '</span>';
                echo '<input class="calio-filterable-gallery-search-input" type="search" placeholder="' . esc_attr((string) ($settings['search_placeholder'] ?? esc_html__('Search projects', 'calio-addon'))) . '" />';
                echo '</label>';
            }
            echo '</div>';
            echo '<div class="calio-filterable-gallery-toolbar-side">';
            if ($show_results_status) {
                echo '<div class="calio-filterable-gallery-status">' . esc_html(sprintf(
                    /* translators: %d: number of visible gallery items. */
                    esc_html__('%1$d items', 'calio-addon'),
                    count($items)
                )) . '</div>';
            }
            echo '<div class="calio-filterable-gallery-badges" hidden></div>';
            echo '</div>';
        }

        echo '<div class="calio-filterable-gallery-grid">';
        foreach (array_values($items) as $index => $item) {
            $image = is_array($item['image'] ?? null) ? $item['image'] : [];
            $url = (string) ($image['url'] ?? '');
            if ($url === '') {
                continue;
            }

            $title = trim((string) ($item['title'] ?? ''));
            $categories = $this->parse_categories(
                trim((string) ($item['category'] ?? '')),
                trim((string) ($item['categories'] ?? ''))
            );
            $primary_category = $categories[0] ?? '';
            $meta = trim((string) ($item['meta'] ?? ''));
            $overlay_note = trim((string) ($item['overlay_note'] ?? ''));
            $caption = trim((string) ($item['caption'] ?? ''));
            $alt = trim((string) ($image['alt'] ?? ''));
            $is_featured = (($item['featured'] ?? '') === 'yes');
            $size_preset = sanitize_html_class((string) ($item['size_preset'] ?? 'standard'));
            $group_slugs = array_map('sanitize_title', $categories);
            $search_text = trim(implode(' ', array_filter([
                $title,
                implode(' ', $categories),
                $meta,
                $caption,
            ])));
            if (empty($group_slugs)) {
                $group_slugs = ['uncategorized'];
            }
            $link = is_array($item['link_url'] ?? null) ? $item['link_url'] : ['url' => ''];
            $has_overlay_link = $lightbox || !empty($link['url']);

            echo '<figure class="calio-filterable-gallery-item size-' . esc_attr($size_preset) . ($is_featured ? ' is-featured' : '') . '" data-filter-groups="' . esc_attr(implode(',', $group_slugs)) . '" data-search-text="' . esc_attr(strtolower($search_text)) . '" data-sort-title="' . esc_attr(strtolower($title)) . '" data-sort-category="' . esc_attr(strtolower($primary_category)) . '">';
            echo '<div class="calio-filterable-gallery-media">';
            if ($is_featured) {
                $featured_label = trim((string) ($item['featured_label'] ?? ''));
                if ($featured_label === '') {
                    $featured_label = esc_html__('Featured', 'calio-addon');
                }
                echo '<span class="calio-filterable-gallery-featured">' . esc_html($featured_label) . '</span>';
            }
            if ($lightbox) {
                echo '<a href="' . esc_url($url) . '" data-elementor-open-lightbox="yes">';
            }
            echo '<img src="' . esc_url($url) . '" alt="' . esc_attr($alt) . '" loading="lazy" />';
            if ($lightbox) {
                echo '</a>';
            }
            if ($show_overlay_cta && $has_overlay_link) {
                echo wp_kses_post($this->build_overlay_link(
                    $is_featured
                        ? trim((string) ($settings['featured_cta_text'] ?? esc_html__('View Case Study', 'calio-addon')))
                        : trim((string) ($settings['overlay_cta_text'] ?? esc_html__('Open Project', 'calio-addon'))),
                    $lightbox,
                    $url,
                    $link,
                    $is_featured
                ));
            }
            if ($overlay_note !== '') {
                echo '<span class="calio-filterable-gallery-overlay-note">' . esc_html($overlay_note) . '</span>';
            }
            if ($show_caption) {
                echo '<figcaption class="calio-filterable-gallery-copy">';
                if ($show_meta && $primary_category !== '') {
                    echo '<span class="calio-filterable-gallery-meta">' . esc_html($primary_category) . '</span>';
                }
                if ($title !== '') {
                    echo '<span class="calio-filterable-gallery-title">' . esc_html($title) . '</span>';
                }
                if ($show_meta && $meta !== '') {
                    echo '<span class="calio-filterable-gallery-submeta">' . esc_html($meta) . '</span>';
                }
                if ($caption !== '') {
                    echo '<span class="calio-filterable-gallery-caption">' . esc_html($caption) . '</span>';
                }
                echo '</figcaption>';
            }
            echo '</div>';
            echo '</figure>';
        }
        echo '</div>';
        echo '<div class="calio-filterable-gallery-empty-state" hidden>';
        echo '<div class="calio-filterable-gallery-empty-title">' . esc_html((string) ($settings['empty_title'] ?? esc_html__('No matching projects', 'calio-addon'))) . '</div>';
        echo '<div class="calio-filterable-gallery-empty-copy">' . esc_html((string) ($settings['empty_text'] ?? esc_html__('Try another filter or a different keyword to widen the gallery view.', 'calio-addon'))) . '</div>';
        echo '<button class="calio-filterable-gallery-reset" type="button">' . esc_html((string) ($settings['reset_label'] ?? esc_html__('Reset View', 'calio-addon'))) . '</button>';
        echo '</div>';
        if ($enable_load_more) {
            echo '<div class="calio-filterable-gallery-footer">';
            echo '<button class="calio-filterable-gallery-load-more" type="button">' . esc_html((string) ($settings['load_more_text'] ?? esc_html__('Load More', 'calio-addon'))) . '</button>';
            echo '</div>';
        }
        echo '</div>';
    }

    /**
     * Builds the filter set from gallery items.
     *
     * @param array<int, array<string, mixed>> $items Gallery repeater items.
     * @return array<string, array{label: string, count: int}>
     */
    private function build_filters(array $items): array
    {
        $filters = [];

        foreach ($items as $item) {
            foreach ($this->parse_categories(trim((string) ($item['category'] ?? '')), trim((string) ($item['categories'] ?? ''))) as $category) {
                $slug = sanitize_title($category);
                if (!isset($filters[$slug])) {
                    $filters[$slug] = [
                        'label' => $category,
                        'count' => 0,
                    ];
                }

                $filters[$slug]['count']++;
            }
        }

        return $filters;
    }

    /**
     * Combines the primary category and extra comma-separated categories.
     *
     * @return array<int, string>
     */
    private function parse_categories(string $primary, string $extra): array
    {
        $values = array_filter(array_map('trim', array_merge(
            $primary !== '' ? [$primary] : [],
            preg_split('/\s*,\s*/', $extra, -1, PREG_SPLIT_NO_EMPTY) ?: []
        )));

        return array_values(array_unique($values));
    }

    /**
     * Builds a media overlay CTA for either lightbox or a custom item link.
     *
     * @param array<string, mixed> $link URL control payload.
     */
    private function build_overlay_link(string $label, bool $lightbox, string $image_url, array $link, bool $is_featured = false): string
    {
        $label = trim($label) !== '' ? $label : esc_html__('Open Project', 'calio-addon');
        $classes = 'calio-filterable-gallery-overlay-link' . ($is_featured ? ' is-featured-link' : '');

        if ($lightbox) {
            return '<a class="' . esc_attr($classes) . '" href="' . esc_url($image_url) . '" data-elementor-open-lightbox="yes">' . esc_html($label) . '</a>';
        }

        $rel = [];
        if (!empty($link['is_external'])) {
            $rel[] = 'noopener';
            $rel[] = 'noreferrer';
        }
        if (!empty($link['nofollow'])) {
            $rel[] = 'nofollow';
        }
        $output = '<a class="' . esc_attr($classes) . '" href="' . esc_url((string) ($link['url'] ?? '')) . '"';
        if (!empty($link['is_external'])) {
            $output .= ' target="' . esc_attr('_blank') . '"';
        }
        if (!empty($rel)) {
            $output .= ' rel="' . esc_attr(implode(' ', array_unique($rel))) . '"';
        }

        return $output . '>' . esc_html($label) . '</a>';
    }

    /**
     * Provides richer starter gallery items for the initial widget drop.
     *
     * @return array<int, array<string, mixed>>
     */
    private function get_default_items(): array
    {
        return [
            [
                'title' => esc_html__('Campaign Frames', 'calio-addon'),
                'category' => esc_html__('Branding', 'calio-addon'),
                'categories' => esc_html__('Campaign, Editorial', 'calio-addon'),
                'featured' => 'yes',
                'size_preset' => 'wide',
                'meta' => esc_html__('Identity System', 'calio-addon'),
                'overlay_note' => esc_html__('Launch Story', 'calio-addon'),
                'caption' => esc_html__('Editorial visuals for launch positioning.', 'calio-addon'),
                'featured_label' => esc_html__('Hero', 'calio-addon'),
            ],
            [
                'title' => esc_html__('Product Motion', 'calio-addon'),
                'category' => esc_html__('Motion', 'calio-addon'),
                'categories' => esc_html__('Campaign, Launch', 'calio-addon'),
                'size_preset' => 'tall',
                'meta' => esc_html__('Launch Sequence', 'calio-addon'),
                'overlay_note' => esc_html__('Motion System', 'calio-addon'),
                'caption' => esc_html__('Frames focused on narrative rhythm and reveal.', 'calio-addon'),
            ],
            [
                'title' => esc_html__('Studio Textures', 'calio-addon'),
                'category' => esc_html__('Editorial', 'calio-addon'),
                'categories' => esc_html__('Print, Moodboard', 'calio-addon'),
                'meta' => esc_html__('Print-Led', 'calio-addon'),
                'overlay_note' => esc_html__('Material Lab', 'calio-addon'),
                'caption' => esc_html__('Material-led compositions for premium sections.', 'calio-addon'),
            ],
        ];
    }
}
