<?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;
}

/**
 * Essential-style accordion focused on smooth open/close interaction.
 */
class AccordionWidget extends BaseWidget
{
    public function get_name(): string
    {
        return 'calio-accordion';
    }

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

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

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

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

    protected function register_controls(): void
    {
        $this->register_content_general_controls();
        $this->register_content_tabs_controls();
        $this->register_style_tab_controls();
        $this->register_style_content_controls();
        $this->register_style_toggle_icon_controls();
    }

    private function register_content_general_controls(): void
    {
        $this->start_controls_section(
            'section_settings',
            [
                'label' => esc_html__('General Settings', 'calio-addon'),
            ]
        );

        $this->add_control(
            'accordion_type',
            [
                'label' => esc_html__('Accordion Type', 'calio-addon'),
                'type' => Controls_Manager::CHOOSE,
                'default' => 'accordion',
                'toggle' => false,
                'options' => [
                    'accordion' => [
                        'title' => esc_html__('Accordion', 'calio-addon'),
                        'icon' => 'eicon-accordion',
                    ],
                    'toggle' => [
                        'title' => esc_html__('Toggle', 'calio-addon'),
                        'icon' => 'eicon-toggle',
                    ],
                ],
            ]
        );

        $this->add_control(
            'title_tag',
            [
                'label' => esc_html__('Tab Title Tag', 'calio-addon'),
                'type' => Controls_Manager::SELECT,
                'default' => 'span',
                'options' => [
                    'h1' => 'H1',
                    'h2' => 'H2',
                    'h3' => 'H3',
                    'h4' => 'H4',
                    'h5' => 'H5',
                    'h6' => 'H6',
                    'span' => 'Span',
                    'p' => 'P',
                    'div' => 'Div',
                ],
            ]
        );

        $this->add_control(
            'show_toggle_icon',
            [
                'label' => esc_html__('Enable Toggle Icon', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'default' => 'yes',
                'return_value' => 'yes',
            ]
        );

        $this->add_control(
            'toggle_icon_position',
            [
                'label' => esc_html__('Toggle Icon Position', 'calio-addon'),
                'type' => Controls_Manager::SELECT,
                'default' => 'right',
                'options' => [
                    'left' => esc_html__('Left', 'calio-addon'),
                    'right' => esc_html__('Right', 'calio-addon'),
                ],
                'condition' => [
                    'show_toggle_icon' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'toggle_icon',
            [
                'label' => esc_html__('Toggle Icon', 'calio-addon'),
                'type' => Controls_Manager::ICONS,
                'default' => [
                    'value' => 'fas fa-angle-right',
                    'library' => 'fa-solid',
                ],
                'condition' => [
                    'show_toggle_icon' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'toggle_speed',
            [
                'label' => esc_html__('Toggle Speed (ms)', 'calio-addon'),
                'type' => Controls_Manager::NUMBER,
                'default' => 300,
                'min' => 0,
            ]
        );

        $this->add_control(
            'custom_id_offset',
            [
                'label' => esc_html__('Custom ID Offset', 'calio-addon'),
                'description' => esc_html__('Use offset to adjust target scrolling position.', 'calio-addon'),
                'type' => Controls_Manager::NUMBER,
                'default' => 0,
                'min' => 0,
            ]
        );

        $this->add_control(
            'scroll_speed',
            [
                'label' => esc_html__('Scroll Speed (ms)', 'calio-addon'),
                'type' => Controls_Manager::NUMBER,
                'default' => 300,
                'min' => 0,
            ]
        );

        $this->add_control(
            'scroll_on_click',
            [
                'label' => esc_html__('Scroll on Click', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'default' => 'no',
                'return_value' => 'yes',
            ]
        );

        $this->add_control(
            'faq_schema',
            [
                'label' => esc_html__('Enable FAQ Schema', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'default' => 'no',
                'return_value' => 'yes',
                'separator' => 'before',
            ]
        );

        $this->end_controls_section();
    }

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

        $repeater = new Repeater();

        $repeater->add_control(
            'tab_default_active',
            [
                'label' => esc_html__('Active as Default', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'default' => 'no',
                'return_value' => 'yes',
            ]
        );

        $repeater->add_control(
            'tab_icon_show',
            [
                'label' => esc_html__('Enable Tab Icon', 'calio-addon'),
                'type' => Controls_Manager::SWITCHER,
                'default' => 'yes',
                'return_value' => 'yes',
            ]
        );

        $repeater->start_controls_tabs('tab_icons');

        $repeater->start_controls_tab(
            'tab_icon_opened',
            [
                'label' => esc_html__('Opened Tab', 'calio-addon'),
                'condition' => [
                    'tab_icon_show' => 'yes',
                ],
            ]
        );

        $repeater->add_control(
            'tab_title_icon_opened',
            [
                'label' => esc_html__('Icon', 'calio-addon'),
                'type' => Controls_Manager::ICONS,
                'default' => [
                    'value' => 'fas fa-minus',
                    'library' => 'fa-solid',
                ],
                'condition' => [
                    'tab_icon_show' => 'yes',
                ],
            ]
        );

        $repeater->end_controls_tab();

        $repeater->start_controls_tab(
            'tab_icon_closed',
            [
                'label' => esc_html__('Closed Tab', 'calio-addon'),
                'condition' => [
                    'tab_icon_show' => 'yes',
                ],
            ]
        );

        $repeater->add_control(
            'tab_title_icon_closed',
            [
                'label' => esc_html__('Icon', 'calio-addon'),
                'type' => Controls_Manager::ICONS,
                'default' => [
                    'value' => 'fas fa-plus',
                    'library' => 'fa-solid',
                ],
                'condition' => [
                    'tab_icon_show' => 'yes',
                ],
            ]
        );

        $repeater->end_controls_tab();
        $repeater->end_controls_tabs();

        $repeater->add_control(
            'tab_title',
            [
                'label' => esc_html__('Tab Title', 'calio-addon'),
                'type' => Controls_Manager::TEXT,
                'label_block' => true,
                'default' => esc_html__('Accordion Item', 'calio-addon'),
                'dynamic' => [
                    'active' => true,
                ],
                'separator' => 'before',
            ]
        );

        $repeater->add_control(
            'tab_id',
            [
                'label' => esc_html__('Custom ID', 'calio-addon'),
                'type' => Controls_Manager::TEXT,
                'description' => esc_html__('Unique ID used by hash links.', 'calio-addon'),
            ]
        );

        $repeater->add_control(
            'tab_content',
            [
                'label' => esc_html__('Tab Content', 'calio-addon'),
                'type' => Controls_Manager::WYSIWYG,
                'default' => esc_html__('Accordion content', 'calio-addon'),
                'show_label' => false,
                'dynamic' => [
                    'active' => true,
                ],
            ]
        );

        $repeater->add_control(
            'tab_faq_schema_text',
            [
                'label' => esc_html__('FAQ Schema Text', 'calio-addon'),
                'type' => Controls_Manager::TEXTAREA,
                'description' => esc_html__('Optional custom answer text for schema.', 'calio-addon'),
            ]
        );

        $this->add_control(
            'tabs',
            [
                'type' => Controls_Manager::REPEATER,
                'fields' => $repeater->get_controls(),
                'title_field' => '{{{ tab_title }}}',
                'default' => [
                    [
                        'tab_title' => esc_html__('Accordion Item', 'calio-addon'),
                        'tab_content' => esc_html__('Accordion content', 'calio-addon'),
                        'tab_default_active' => 'yes',
                    ],
                    [
                        'tab_title' => esc_html__('Accordion Item', 'calio-addon'),
                        'tab_content' => esc_html__('Accordion content', 'calio-addon'),
                    ],
                    [
                        'tab_title' => esc_html__('Accordion Item', 'calio-addon'),
                        'tab_content' => esc_html__('Accordion content', 'calio-addon'),
                    ],
                ],
            ]
        );

        $this->end_controls_section();
    }

    private function register_style_tab_controls(): void
    {
        $this->start_controls_section(
            'section_style_tab',
            [
                'label' => esc_html__('Tab Style', 'calio-addon'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'tab_typography',
                'selector' => '{{WRAPPER}} .calio-accordion-header, {{WRAPPER}} .calio-accordion-tab-title',
            ]
        );

        $this->add_control(
            'icon_size',
            [
                'label' => esc_html__('Icon Size', 'calio-addon'),
                'type' => Controls_Manager::SLIDER,
                'range' => [
                    'px' => [
                        'min' => 8,
                        'max' => 80,
                    ],
                ],
                'selectors' => [
                    '{{WRAPPER}} .calio-accordion-header .fa-toggle' => 'font-size: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .calio-accordion-header .fa-accordion-icon' => 'font-size: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .calio-accordion-header svg.fa-toggle, {{WRAPPER}} .calio-accordion-header svg.fa-accordion-icon' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .calio-accordion-header .fa-accordion-icon-svg svg' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_control(
            'icon_gap',
            [
                'label' => esc_html__('Icon Gap', 'calio-addon'),
                'type' => Controls_Manager::SLIDER,
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 80,
                    ],
                ],
                'selectors' => [
                    '{{WRAPPER}} .calio-accordion-header > .fa-toggle, {{WRAPPER}} .calio-accordion-header > .fa-accordion-icon, {{WRAPPER}} .calio-accordion-header > .fa-accordion-icon-svg, {{WRAPPER}} .calio-accordion-header > .calio-toggle-icon-wrap, {{WRAPPER}} .calio-accordion-header > .calio-advanced-accordion-icon-closed, {{WRAPPER}} .calio-accordion-header > .calio-advanced-accordion-icon-opened' => 'margin-right: {{SIZE}}{{UNIT}};',
                    '.rtl {{WRAPPER}} .calio-accordion-header > .fa-toggle, .rtl {{WRAPPER}} .calio-accordion-header > .fa-accordion-icon, .rtl {{WRAPPER}} .calio-accordion-header > .fa-accordion-icon-svg, .rtl {{WRAPPER}} .calio-accordion-header > .calio-toggle-icon-wrap, .rtl {{WRAPPER}} .calio-accordion-header > .calio-advanced-accordion-icon-closed, .rtl {{WRAPPER}} .calio-accordion-header > .calio-advanced-accordion-icon-opened' => 'margin-right: 0; margin-left: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_control(
            'item_distance',
            [
                'label' => esc_html__('Distance', 'calio-addon'),
                'type' => Controls_Manager::SLIDER,
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 80,
                    ],
                ],
                'selectors' => [
                    '{{WRAPPER}} .calio-adv-accordion .calio-accordion-list' => 'margin-bottom: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .calio-adv-accordion .calio-accordion-list:last-child' => 'margin-bottom: 0;',
                ],
            ]
        );

        $this->add_dimensions_control(
            'tab_padding',
            esc_html__('Padding', 'calio-addon'),
            '{{WRAPPER}} .calio-accordion-header',
            'padding'
        );

        $this->add_dimensions_control(
            'tab_margin',
            esc_html__('Margin', 'calio-addon'),
            '{{WRAPPER}} .calio-accordion-header',
            'margin'
        );

        $this->start_controls_tabs('tab_state_tabs');

        $this->start_controls_tab(
            'tab_state_normal',
            [
                'label' => esc_html__('Normal', 'calio-addon'),
            ]
        );

        $this->add_text_paint_controls(
            'tab_text_normal',
            esc_html__('Text Color', 'calio-addon'),
            '{{WRAPPER}} .calio-accordion-header'
        );

        $this->add_control(
            'tab_icon_color_normal',
            [
                'label' => esc_html__('Icon Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-accordion-header .fa-toggle, {{WRAPPER}} .calio-accordion-header .fa-accordion-icon, {{WRAPPER}} .calio-accordion-header .fa-accordion-icon-svg' => 'color: {{VALUE}};',
                    '{{WRAPPER}} .calio-accordion-header svg.fa-toggle, {{WRAPPER}} .calio-accordion-header svg.fa-accordion-icon, {{WRAPPER}} .calio-accordion-header .fa-toggle svg, {{WRAPPER}} .calio-accordion-header .fa-accordion-icon svg, {{WRAPPER}} .calio-accordion-header .fa-accordion-icon-svg svg, {{WRAPPER}} .calio-accordion-header svg.fa-toggle path, {{WRAPPER}} .calio-accordion-header svg.fa-accordion-icon path' => 'fill: {{VALUE}};',
                ],
            ]
        );

        $this->add_background_type_control(
            'tab_bg_normal',
            '{{WRAPPER}} .calio-accordion-header'
        );

        $this->end_controls_tab();

        $this->start_controls_tab(
            'tab_state_hover',
            [
                'label' => esc_html__('Hover', 'calio-addon'),
            ]
        );

        $this->add_text_paint_controls(
            'tab_text_hover',
            esc_html__('Text Color', 'calio-addon'),
            '{{WRAPPER}} .calio-accordion-header:hover'
        );

        $this->add_control(
            'tab_icon_color_hover',
            [
                'label' => esc_html__('Icon Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-accordion-header:hover .fa-toggle, {{WRAPPER}} .calio-accordion-header:hover .fa-accordion-icon, {{WRAPPER}} .calio-accordion-header:hover .fa-accordion-icon-svg' => 'color: {{VALUE}};',
                    '{{WRAPPER}} .calio-accordion-header:hover svg.fa-toggle, {{WRAPPER}} .calio-accordion-header:hover svg.fa-accordion-icon, {{WRAPPER}} .calio-accordion-header:hover .fa-toggle svg, {{WRAPPER}} .calio-accordion-header:hover .fa-accordion-icon svg, {{WRAPPER}} .calio-accordion-header:hover .fa-accordion-icon-svg svg, {{WRAPPER}} .calio-accordion-header:hover svg.fa-toggle path, {{WRAPPER}} .calio-accordion-header:hover svg.fa-accordion-icon path' => 'fill: {{VALUE}};',
                ],
            ]
        );

        $this->add_background_type_control(
            'tab_bg_hover',
            '{{WRAPPER}} .calio-accordion-header:hover'
        );

        $this->end_controls_tab();

        $this->start_controls_tab(
            'tab_state_active',
            [
                'label' => esc_html__('Active', 'calio-addon'),
            ]
        );

        $this->add_text_paint_controls(
            'tab_text_active',
            esc_html__('Text Color', 'calio-addon'),
            '{{WRAPPER}} .calio-accordion-header.active'
        );

        $this->add_control(
            'tab_icon_color_active',
            [
                'label' => esc_html__('Icon Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-accordion-header.active .fa-toggle, {{WRAPPER}} .calio-accordion-header.active .fa-accordion-icon, {{WRAPPER}} .calio-accordion-header.active .fa-accordion-icon-svg' => 'color: {{VALUE}};',
                    '{{WRAPPER}} .calio-accordion-header.active svg.fa-toggle, {{WRAPPER}} .calio-accordion-header.active svg.fa-accordion-icon, {{WRAPPER}} .calio-accordion-header.active .fa-toggle svg, {{WRAPPER}} .calio-accordion-header.active .fa-accordion-icon svg, {{WRAPPER}} .calio-accordion-header.active .fa-accordion-icon-svg svg, {{WRAPPER}} .calio-accordion-header.active svg.fa-toggle path, {{WRAPPER}} .calio-accordion-header.active svg.fa-accordion-icon path' => 'fill: {{VALUE}};',
                ],
            ]
        );

        $this->add_background_type_control(
            'tab_bg_active',
            '{{WRAPPER}} .calio-accordion-header.active'
        );

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

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'tab_border',
                'selector' => '{{WRAPPER}} .calio-accordion-header',
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'tab_shadow',
                'selector' => '{{WRAPPER}} .calio-accordion-header',
            ]
        );

        $this->add_dimensions_control(
            'tab_radius',
            esc_html__('Border Radius', 'calio-addon'),
            '{{WRAPPER}} .calio-accordion-header',
            'border-radius',
            ['size_units' => ['px', '%']]
        );

        $this->end_controls_section();
    }

    private function register_style_content_controls(): void
    {
        $this->start_controls_section(
            'section_style_content',
            [
                'label' => esc_html__('Content Style', 'calio-addon'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'content_typography',
                'selector' => '{{WRAPPER}} .calio-accordion-content',
            ]
        );

        $this->add_text_paint_controls(
            'content_text_color',
            esc_html__('Text Color', 'calio-addon'),
            '{{WRAPPER}} .calio-accordion-content'
        );

        $this->add_background_type_control(
            'content_bg',
            '{{WRAPPER}} .calio-accordion-content'
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'content_border',
                'selector' => '{{WRAPPER}} .calio-accordion-content',
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'content_shadow',
                'selector' => '{{WRAPPER}} .calio-accordion-content',
            ]
        );

        $this->add_dimensions_control(
            'content_padding',
            esc_html__('Padding', 'calio-addon'),
            '{{WRAPPER}} .calio-accordion-content',
            'padding'
        );

        $this->add_dimensions_control(
            'content_margin',
            esc_html__('Margin', 'calio-addon'),
            '{{WRAPPER}} .calio-accordion-content',
            'margin'
        );

        $this->add_dimensions_control(
            'content_radius',
            esc_html__('Border Radius', 'calio-addon'),
            '{{WRAPPER}} .calio-accordion-content',
            'border-radius',
            ['size_units' => ['px', '%']]
        );

        $this->end_controls_section();
    }

    private function register_style_toggle_icon_controls(): void
    {
        $this->start_controls_section(
            'section_style_caret',
            [
                'label' => esc_html__('Toggle Icon Style', 'calio-addon'),
                'tab' => Controls_Manager::TAB_STYLE,
                'condition' => [
                    'show_toggle_icon' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'caret_size',
            [
                'label' => esc_html__('Size', 'calio-addon'),
                'type' => Controls_Manager::SLIDER,
                'range' => [
                    'px' => [
                        'min' => 8,
                        'max' => 80,
                    ],
                ],
                'selectors' => [
                    '{{WRAPPER}} .calio-accordion-header .fa-toggle' => 'font-size: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .calio-accordion-header svg.fa-toggle' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .calio-accordion-header .fa-toggle-svg svg' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->start_controls_tabs('caret_state_tabs');

        $this->start_controls_tab(
            'caret_state_normal',
            [
                'label' => esc_html__('Normal', 'calio-addon'),
            ]
        );

        $this->add_control(
            'caret_color_normal',
            [
                'label' => esc_html__('Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-accordion-header .fa-toggle, {{WRAPPER}} .calio-accordion-header .fa-toggle-svg' => 'color: {{VALUE}};',
                    '{{WRAPPER}} .calio-accordion-header svg.fa-toggle, {{WRAPPER}} .calio-accordion-header .fa-toggle svg, {{WRAPPER}} .calio-accordion-header .fa-toggle-svg svg, {{WRAPPER}} .calio-accordion-header svg.fa-toggle path' => 'fill: {{VALUE}};',
                ],
            ]
        );

        $this->add_background_type_control(
            'caret_bg_normal',
            '{{WRAPPER}} .calio-accordion-header .fa-toggle, {{WRAPPER}} .calio-accordion-header .fa-toggle-svg'
        );

        $this->end_controls_tab();

        $this->start_controls_tab(
            'caret_state_hover',
            [
                'label' => esc_html__('Hover', 'calio-addon'),
            ]
        );

        $this->add_control(
            'caret_color_hover',
            [
                'label' => esc_html__('Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-accordion-header:hover .fa-toggle, {{WRAPPER}} .calio-accordion-header:hover .fa-toggle-svg' => 'color: {{VALUE}};',
                    '{{WRAPPER}} .calio-accordion-header:hover svg.fa-toggle, {{WRAPPER}} .calio-accordion-header:hover .fa-toggle svg, {{WRAPPER}} .calio-accordion-header:hover .fa-toggle-svg svg, {{WRAPPER}} .calio-accordion-header:hover svg.fa-toggle path' => 'fill: {{VALUE}};',
                ],
            ]
        );

        $this->add_background_type_control(
            'caret_bg_hover',
            '{{WRAPPER}} .calio-accordion-header:hover .fa-toggle, {{WRAPPER}} .calio-accordion-header:hover .fa-toggle-svg'
        );

        $this->end_controls_tab();

        $this->start_controls_tab(
            'caret_state_active',
            [
                'label' => esc_html__('Active', 'calio-addon'),
            ]
        );

        $this->add_control(
            'caret_color_active',
            [
                'label' => esc_html__('Color', 'calio-addon'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .calio-accordion-header.active .fa-toggle, {{WRAPPER}} .calio-accordion-header.active .fa-toggle-svg' => 'color: {{VALUE}};',
                    '{{WRAPPER}} .calio-accordion-header.active svg.fa-toggle, {{WRAPPER}} .calio-accordion-header.active .fa-toggle svg, {{WRAPPER}} .calio-accordion-header.active .fa-toggle-svg svg, {{WRAPPER}} .calio-accordion-header.active svg.fa-toggle path' => 'fill: {{VALUE}};',
                ],
            ]
        );

        $this->add_background_type_control(
            'caret_bg_active',
            '{{WRAPPER}} .calio-accordion-header.active .fa-toggle, {{WRAPPER}} .calio-accordion-header.active .fa-toggle-svg'
        );

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

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'caret_border',
                'selector' => '{{WRAPPER}} .calio-accordion-header .fa-toggle, {{WRAPPER}} .calio-accordion-header .fa-toggle-svg',
            ]
        );

        $this->add_dimensions_control(
            'caret_radius',
            esc_html__('Border Radius', 'calio-addon'),
            '{{WRAPPER}} .calio-accordion-header .fa-toggle, {{WRAPPER}} .calio-accordion-header .fa-toggle-svg',
            'border-radius',
            ['size_units' => ['px', '%']]
        );

        $this->end_controls_section();
    }

    protected function render(): void
    {
        $settings = $this->get_settings_for_display();
        $tabs = $settings['tabs'] ?? [];

        if (!is_array($tabs) || empty($tabs)) {
            return;
        }

        $title_tag = (string) ($settings['title_tag'] ?? 'span');
        if (!in_array($title_tag, ['h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'span', 'p', 'div'], true)) {
            $title_tag = 'span';
        }

        $accordion_type = ($settings['accordion_type'] ?? 'accordion') === 'toggle' ? 'toggle' : 'accordion';
        $show_toggle_icon = ($settings['show_toggle_icon'] ?? 'yes') === 'yes';
        $toggle_icon_position = ($settings['toggle_icon_position'] ?? 'right') === 'left' ? 'left' : 'right';
        $toggle_speed = isset($settings['toggle_speed']) ? max(0, (int) $settings['toggle_speed']) : 300;
        $scroll_speed = isset($settings['scroll_speed']) ? max(0, (int) $settings['scroll_speed']) : 300;
        $scroll_on_click = ($settings['scroll_on_click'] ?? 'no') === 'yes' ? 'yes' : 'no';
        $custom_id_offset = isset($settings['custom_id_offset']) ? max(0, (float) $settings['custom_id_offset']) : 0.0;
        $widget_uid = sanitize_html_class((string) $this->get_id());
        if ($widget_uid === '') {
            $widget_uid = substr((string) $this->get_id_int(), 0, 6);
        }
        $faq_schema_enabled = ($settings['faq_schema'] ?? 'no') === 'yes';

        $has_active_default = false;
        foreach ($tabs as $tab) {
            if (($tab['tab_default_active'] ?? 'no') === 'yes') {
                $has_active_default = true;
                break;
            }
        }

        $this->add_render_attribute('accordion', 'class', 'calio-adv-accordion');
        $this->add_render_attribute('accordion', 'id', 'calio-adv-accordion-' . esc_attr($this->get_id()));
        $this->add_render_attribute('accordion', 'data-accordion-id', esc_attr($this->get_id()));
        $this->add_render_attribute('accordion', 'data-accordion-type', esc_attr($accordion_type));
        $this->add_render_attribute('accordion', 'data-toogle-speed', esc_attr((string) $toggle_speed));
        $this->add_render_attribute('accordion', 'data-scroll-on-click', esc_attr($scroll_on_click));
        $this->add_render_attribute('accordion', 'data-scroll-speed', esc_attr((string) $scroll_speed));
        if ($custom_id_offset > 0) {
            $this->add_render_attribute('accordion', 'data-custom-id-offset', esc_attr((string) $custom_id_offset));
        }

        $schema = [];
        $used_tab_ids = [];

        echo '<div ' . wp_kses_post($this->get_render_attribute_string('accordion')) . '>';

        foreach ($tabs as $index => $tab) {
            $title = trim((string) ($tab['tab_title'] ?? ''));
            $content = (string) ($tab['tab_content'] ?? '');
            if ($title === '' && trim(wp_strip_all_tags($content)) === '') {
                continue;
            }

            $tab_count = $index + 1;
            $is_default_active = ($tab['tab_default_active'] ?? 'no') === 'yes';
            if (!$has_active_default && $index === 0) {
                $is_default_active = true;
            }

            $raw_tab_id = trim((string) ($tab['tab_id'] ?? ''));
            $fallback_id = sanitize_title($title !== '' ? $title : 'tab-' . $tab_count);
            $fallback_id = $fallback_id . '-' . $widget_uid;
            $tab_id = sanitize_html_class($raw_tab_id !== '' ? $raw_tab_id : $fallback_id);
            if ($tab_id === '') {
                $tab_id = 'calio-tab-' . $widget_uid . '-' . $tab_count;
            }
            if ($tab_id === 'safari') {
                $tab_id = 'calio-safari';
            }
            if (in_array($tab_id, $used_tab_ids, true)) {
                $tab_id .= '-' . $tab_count;
            }
            $used_tab_ids[] = $tab_id;

            $title_key = $this->get_repeater_setting_key('tab_title', 'tabs', $index);
            $content_key = $this->get_repeater_setting_key('tab_content', 'tabs', $index);
            $panel_id = 'calio-tab-content-' . $widget_uid . '-' . $tab_count;

            $title_classes = ['elementor-tab-title', 'calio-accordion-header'];
            $content_classes = ['calio-accordion-content', 'clearfix'];

            if ($is_default_active) {
                $title_classes[] = 'active-default';
                $content_classes[] = 'active-default';
            }

            $this->add_render_attribute(
                $title_key,
                [
                    'id' => $tab_id,
                    'class' => $title_classes,
                    'tabindex' => '0',
                    'data-tab' => (string) $tab_count,
                    'aria-controls' => $panel_id,
                    'role' => 'button',
                    'aria-expanded' => $is_default_active ? 'true' : 'false',
                ]
            );

            $this->add_render_attribute(
                $content_key,
                [
                    'id' => $panel_id,
                    'class' => $content_classes,
                    'data-tab' => (string) $tab_count,
                    'aria-labelledby' => $tab_id,
                    'role' => 'region',
                    'aria-hidden' => $is_default_active ? 'false' : 'true',
                    'style' => $is_default_active ? 'display:block;' : 'display:none;',
                ]
            );

            echo '<div class="calio-accordion-list">';
            echo '<div ' . wp_kses_post($this->get_render_attribute_string($title_key)) . '>';

            if ($show_toggle_icon && $toggle_icon_position === 'left') {
                $this->print_toggle_icon($settings);
            }

            if ($toggle_icon_position === 'left') {
                echo '<' . tag_escape($title_tag) . ' class="calio-accordion-tab-title">' . esc_html($title) . '</' . tag_escape($title_tag) . '>';
            }

            if (($tab['tab_icon_show'] ?? 'yes') === 'yes') {
                $closed_icon = $this->resolve_icon_control(
                    $tab['tab_title_icon_closed'] ?? [],
                    $settings['icon'] ?? []
                );
                $opened_icon = $this->resolve_icon_control(
                    $tab['tab_title_icon_opened'] ?? [],
                    $settings['icon_active'] ?? []
                );

                echo '<span class="calio-advanced-accordion-icon-closed">';
                $this->render_control_icon(
                    $closed_icon,
                    'fa-accordion-icon',
                    '+'
                );
                echo '</span>';

                echo '<span class="calio-advanced-accordion-icon-opened">';
                $this->render_control_icon(
                    $opened_icon,
                    'fa-accordion-icon',
                    '-'
                );
                echo '</span>';
            }

            if ($toggle_icon_position === 'right') {
                echo '<' . tag_escape($title_tag) . ' class="calio-accordion-tab-title">' . esc_html($title) . '</' . tag_escape($title_tag) . '>';
            }

            if ($show_toggle_icon && $toggle_icon_position === 'right') {
                $this->print_toggle_icon($settings);
            }

            echo '</div>';

            echo '<div ' . wp_kses_post($this->get_render_attribute_string($content_key)) . '>';
            echo wp_kses_post($this->parse_text_editor($content));
            echo '</div>';

            echo '</div>';

            if ($faq_schema_enabled) {
                $schema_answer = trim((string) ($tab['tab_faq_schema_text'] ?? ''));
                $schema[] = [
                    '@type' => 'Question',
                    'name' => wp_strip_all_tags($title),
                    'acceptedAnswer' => [
                        '@type' => 'Answer',
                        'text' => wp_strip_all_tags($schema_answer !== '' ? $schema_answer : $content),
                    ],
                ];
            }
        }

        echo '</div>';

        if (!empty($schema)) {
            $schema_json = wp_json_encode(
                [
                    '@context' => 'https://schema.org',
                    '@type' => 'FAQPage',
                    'mainEntity' => $schema,
                ],
                JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
            );

            if (is_string($schema_json) && $schema_json !== '') {
                wp_print_inline_script_tag($schema_json, ['type' => 'application/ld+json']);
            }
        }
    }

    private function print_toggle_icon(array $settings): void
    {
        $toggle_icon = $this->resolve_icon_control(
            $settings['toggle_icon'] ?? [],
            $settings['icon'] ?? []
        );

        echo '<span class="calio-toggle-icon-wrap">';
        $this->render_control_icon($toggle_icon, 'fa-toggle', '+');
        echo '</span>';
    }

    /**
     * Keeps icon output compatible with widgets saved before the current
     * per-item open/closed icon controls were introduced.
     *
     * @param mixed $preferred Current icon control value.
     * @param mixed $legacy    Legacy widget-level icon control value.
     *
     * @return array<string, mixed>
     */
    private function resolve_icon_control($preferred, $legacy): array
    {
        if (is_array($preferred) && !empty($preferred['value'])) {
            return $preferred;
        }

        return is_array($legacy) && !empty($legacy['value']) ? $legacy : [];
    }

    /**
     * Renders an Elementor icon control value, with a safe text fallback.
     *
     * @param mixed  $icon     Control value from Icons control.
     * @param string $class    Output class name.
     * @param string $fallback Fallback character when icon data is empty.
     */
    private function render_control_icon($icon, string $class, string $fallback): void
    {
        if (is_array($icon) && !empty($icon['value'])) {
            $icon_value = trim((string) $icon['value']);
            $library = sanitize_key((string) ($icon['library'] ?? ''));

            if ($this->is_font_awesome_icon($icon_value, $library)) {
                $svg = $this->get_font_awesome_svg($icon_value, $library, $class);
                if ($svg !== '') {
                    echo wp_kses($svg, $this->calio_allowed_icon_markup());
                    return;
                }
            }

            $markup = $this->get_icon_markup($icon, ['class' => $class]);
            if ($markup !== '') {
                echo wp_kses_post($markup);
                return;
            }
        }

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

    private function is_font_awesome_icon(string $value, string $library): bool
    {
        if (strpos($library, 'fa-') === 0 || $library === 'font-awesome') {
            return true;
        }

        return (bool) preg_match('/(?:^|\s)fa[bdklrs]?(?:\s|$)/', $value);
    }

    private function get_font_awesome_svg(string $value, string $library, string $class): string
    {
        static $catalogs = [];

        $catalog_name = [
            'fa-solid' => 'solid',
            'fa-regular' => 'regular',
            'fa-brands' => 'brands',
        ][$library] ?? '';

        if ($catalog_name === '') {
            if (preg_match('/(?:^|\s)far(?:\s|$)/', $value)) {
                $catalog_name = 'regular';
            } elseif (preg_match('/(?:^|\s)fab(?:\s|$)/', $value)) {
                $catalog_name = 'brands';
            } else {
                $catalog_name = 'solid';
            }
        }

        $icon_name = '';
        $classes = preg_split('/\s+/', $value);
        foreach (is_array($classes) ? $classes : [] as $candidate) {
            if (strpos($candidate, 'fa-') === 0 && !in_array($candidate, ['fa-solid', 'fa-regular', 'fa-brands'], true)) {
                $icon_name = sanitize_key(substr($candidate, 3));
                break;
            }
        }

        if ($icon_name === '') {
            return '';
        }

        if (!array_key_exists($catalog_name, $catalogs)) {
            $catalogs[$catalog_name] = [];
            try {
                $reflection = new \ReflectionClass(\Elementor\Icons_Manager::class);
                $manager_file = $reflection->getFileName();
                if (!is_string($manager_file) || $manager_file === '') {
                    return '';
                }

                $elementor_root = dirname($manager_file, 3);
                $catalog_path = trailingslashit($elementor_root) . 'assets/lib/font-awesome/json/' . $catalog_name . '.json';
                $decoded = wp_json_file_decode($catalog_path, ['associative' => true]);
                if (is_array($decoded) && isset($decoded['icons']) && is_array($decoded['icons'])) {
                    $catalogs[$catalog_name] = $decoded['icons'];
                }
            } catch (\ReflectionException $exception) {
                return '';
            }
        }

        $icon_data = $catalogs[$catalog_name][$icon_name] ?? null;
        if (!is_array($icon_data) || count($icon_data) < 5) {
            return '';
        }

        $width = absint($icon_data[0] ?? 0);
        $height = absint($icon_data[1] ?? 0);
        $path = (string) ($icon_data[4] ?? '');
        if ($width < 1 || $height < 1 || $path === '') {
            return '';
        }

        return sprintf(
            '<svg class="%1$s" aria-hidden="true" focusable="false" viewBox="0 0 %2$d %3$d" role="img"><path fill="currentColor" d="%4$s"></path></svg>',
            esc_attr(sanitize_html_class($class)),
            $width,
            $height,
            esc_attr($path)
        );
    }
}
