<?php

namespace Unlockafe_addons\Widgets;

use Unlockafe_addons\Traits\Utils as UnlockafeUtils;
use Unlockafe_addons\Traits\Widget_helper;
use Elementor\Widget_Base;
use Elementor\Controls_Manager;
use Elementor\Repeater;
use Elementor\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Background;

if (!defined('ABSPATH'))
    exit; // Exit if accessed directly

/**
 * Table of Contents Widget
 *
 * @since 1.0.0
 */
class Table_Of_Contents extends Widget_Base
{
    use Widget_helper, UnlockafeUtils;

    /**
     * Retrieve the widget name.
     */
    public function get_name()
    {
        return 'unlockafe-table-of-contents';
    }

    /**
     * Retrieve the widget title.
     */
    public function get_title()
    {
        return __('Table of Contents', 'unlock-addons-for-elementor');
    }

    /**
     * Retrieve the widget icon.
     */
    public function get_icon()
    {
        return 'eicon-table-of-contents ulicon';
    }

    /**
     * Retrieve the list of categories.
     */
    public function get_categories()
    {
        return ['unlockafe-addons'];
    }

    /**
     * Retrieve the list of keywords.
     */
    public function get_keywords()
    {
        return ['toc', 'table of contents', 'index', 'navigation', 'outline', 'headings'];
    }

    /**
     * Retrieve the list of scripts.
     */
    public function get_script_depends()
    {
        return ['unlockafe-table-of-contents-scripts'];
    }

    /**
     * Retrieve the list of styles.
     */
    public function get_style_depends()
    {
        return ['unlockafe-table-of-contents-style'];
    }

    /**
     * Register widget controls.
     */
    protected function register_controls()
    {
        $this->register_content_controls();
        $this->register_style_controls();
    }

    /**
     * Register content controls.
     */
    protected function register_content_controls()
    {
        // General Settings
        $this->start_controls_section(
            'general_section',
            [
                'label' => __('General Settings', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'toc_title',
            [
                'label' => __('Title', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => __('Table of Contents', 'unlock-addons-for-elementor'),
                'placeholder' => __('Enter title', 'unlock-addons-for-elementor'),
                'dynamic' => [
                    'active' => true,
                ],
            ]
        );

        $this->add_control(
            'toc_style',
            [
                'label' => __('Style', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'style-1' => __('Style 1 - Orange Header', 'unlock-addons-for-elementor'),
                    'style-2' => __('Style 2 - Numbered', 'unlock-addons-for-elementor'),
                    'style-3' => __('Style 3 - Clean Lines', 'unlock-addons-for-elementor'),
                    'style-4' => __('Style 4 - Numbered with Icons', 'unlock-addons-for-elementor'),
                    'style-5' => __('Style 5 - Dark Theme', 'unlock-addons-for-elementor'),
                ],
                'default' => 'style-1',
            ]
        );

        $this->add_control(
            'heading_levels',
            [
                'label' => __('Include Heading Levels', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT2,
                'multiple' => true,
                'options' => [
                    'h1' => 'H1',
                    'h2' => 'H2',
                    'h3' => 'H3',
                    'h4' => 'H4',
                    'h5' => 'H5',
                    'h6' => 'H6',
                ],
                'default' => ['h2', 'h3', 'h4'],
                'description' => __('Select which heading levels to include in the table of contents.', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'toc_scope',
            [
                'label' => __('Content Scope', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'page' => __('Current Page Content', 'unlock-addons-for-elementor'),
                    'post' => __('Current Post Content', 'unlock-addons-for-elementor'),
                    'custom' => __('Custom Selector', 'unlock-addons-for-elementor'),
                ],
                'default' => 'page',
            ]
        );

        $this->add_control(
            'custom_selector',
            [
                'label' => __('Custom Selector', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => '.elementor-post__content',
                'placeholder' => __('e.g., .content, #main-content', 'unlock-addons-for-elementor'),
                'condition' => [
                    'toc_scope' => 'custom',
                ],
                'description' => __('Enter CSS selector for the container to scan for headings.', 'unlock-addons-for-elementor'),
                'dynamic' => [
                    'active' => true,
                ],
            ]
        );

        $this->add_control(
            'use_manual_items',
            [
                'label' => __('Use Manual TOC Items', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'no',
                'description' => __('Enable to manually add/edit TOC items instead of auto-generating from headings.', 'unlock-addons-for-elementor'),
                'separator' => 'before',
            ]
        );

        $repeater = new Repeater();

        $repeater->add_control(
            'item_text',
            [
                'label' => __('Item Text', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => __('TOC Item', 'unlock-addons-for-elementor'),
                'placeholder' => __('Enter item text', 'unlock-addons-for-elementor'),
                'dynamic' => [
                    'active' => true,
                ],
            ]
        );

        $repeater->add_control(
            'item_link',
            [
                'label' => __('Item Link', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::URL,
                'placeholder' => __('#section-id or https://...', 'unlock-addons-for-elementor'),
                'default' => [
                    'url' => '#',
                ],
                'dynamic' => [
                    'active' => true,
                ],
            ]
        );

        $repeater->add_control(
            'item_level',
            [
                'label' => __('Heading Level', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    '1' => __('Level 1 (H1)', 'unlock-addons-for-elementor'),
                    '2' => __('Level 2 (H2)', 'unlock-addons-for-elementor'),
                    '3' => __('Level 3 (H3)', 'unlock-addons-for-elementor'),
                    '4' => __('Level 4 (H4)', 'unlock-addons-for-elementor'),
                    '5' => __('Level 5 (H5)', 'unlock-addons-for-elementor'),
                    '6' => __('Level 6 (H6)', 'unlock-addons-for-elementor'),
                ],
                'default' => '2',
            ]
        );

        $this->add_control(
            'manual_toc_items',
            [
                'label' => __('Manual TOC Items', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::REPEATER,
                'fields' => $repeater->get_controls(),
                'default' => [],
                'title_field' => '{{{ item_text }}}',
                'condition' => [
                    'use_manual_items' => 'yes',
                ],
            ]
        );

        $this->end_controls_section();

        // Behavior Settings
        $this->start_controls_section(
            'behavior_section',
            [
                'label' => __('Behavior', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'sticky_toc',
            [
                'label' => __('Sticky TOC', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'no',
            ]
        );

        $this->add_control(
            'smooth_scroll',
            [
                'label' => __('Smooth Scroll', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'scroll_spy',
            [
                'label' => __('Scroll Spy (Highlight Active)', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_control(
            'scroll_offset',
            [
                'label' => __('Scroll Offset (px)', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::NUMBER,
                'default' => 100,
                'min' => 0,
                'max' => 300,
                'step' => 10,
                'description' => __('Distance from top when scrolling to heading', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'collapsible',
            [
                'label' => __('Collapsible', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'no',
            ]
        );

        $this->add_control(
            'collapsed_by_default',
            [
                'label' => __('Collapsed by Default', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'no',
                'condition' => [
                    'collapsible' => 'yes',
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Register style controls.
     */
    protected function register_style_controls()
    {
        // Container Style
        $this->start_controls_section(
            'container_style_section',
            [
                'label' => __('Container', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Background::get_type(),
            [
                'name' => 'container_background',
                'label' => __('Background', 'unlock-addons-for-elementor'),
                'types' => ['classic', 'gradient'],
                'selector' => '{{WRAPPER}} .unlockafe-toc',
            ]
        );

        $this->add_responsive_control(
            'container_padding',
            [
                'label' => __('Padding', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-toc' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'container_border',
                'selector' => '{{WRAPPER}} .unlockafe-toc',
            ]
        );

        $this->add_control(
            'container_border_radius',
            [
                'label' => __('Border Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-toc' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'container_box_shadow',
                'selector' => '{{WRAPPER}} .unlockafe-toc',
            ]
        );

        $this->end_controls_section();

        // Title Style
        $this->start_controls_section(
            'title_style_section',
            [
                'label' => __('Title', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'title_color',
            [
                'label' => __('Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#333333',
                'selectors' => [
                    '{{WRAPPER}} .toc-title' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'title_typography',
                'selector' => '{{WRAPPER}} .toc-title',
            ]
        );

        $this->add_responsive_control(
            'title_margin',
            [
                'label' => __('Margin', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .toc-title' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();

        // List Items Style
        $this->start_controls_section(
            'list_items_style_section',
            [
                'label' => __('List Items', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'item_color',
            [
                'label' => __('Text Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#666666',
                'selectors' => [
                    '{{WRAPPER}} .toc-item a' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'item_typography',
                'selector' => '{{WRAPPER}} .toc-item a',
            ]
        );

        $this->add_responsive_control(
            'item_padding',
            [
                'label' => __('Item Padding', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .toc-item a' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'item_border',
                'label' => __('Item Border', 'unlock-addons-for-elementor'),
                'selector' => '{{WRAPPER}} .toc-item a',
            ]
        );

        $this->add_control(
            'item_border_radius',
            [
                'label' => __('Border Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .toc-item a' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_control(
            'item_background',
            [
                'label' => __('Item Background Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .toc-item a' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'item_hover_color',
            [
                'label' => __('Hover Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .toc-item a:hover' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'item_active_color',
            [
                'label' => __('Active Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#667eea',
                'selectors' => [
                    '{{WRAPPER}} .toc-item.active > a' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'item_active_background',
            [
                'label' => __('Active Background Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .toc-item.active > a' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'item_active_font_weight',
            [
                'label' => __('Active Font Weight', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'normal' => __('Normal', 'unlock-addons-for-elementor'),
                    '500' => __('Medium', 'unlock-addons-for-elementor'),
                    '600' => __('Semi Bold', 'unlock-addons-for-elementor'),
                    '700' => __('Bold', 'unlock-addons-for-elementor'),
                ],
                'default' => '600',
                'selectors' => [
                    '{{WRAPPER}} .toc-item.active > a' => 'font-weight: {{VALUE}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'item_active_padding',
            [
                'label' => __('Active Item Padding', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', 'em', '%'],
                'selectors' => [
                    '{{WRAPPER}} .toc-item.active > a' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'item_active_border',
                'label' => __('Active Item Border', 'unlock-addons-for-elementor'),
                'selector' => '{{WRAPPER}} .toc-item.active > a',
            ]
        );

        $this->add_control(
            'indent_levels',
            [
                'label' => __('Indent Sub-items', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => __('Yes', 'unlock-addons-for-elementor'),
                'label_off' => __('No', 'unlock-addons-for-elementor'),
                'return_value' => 'yes',
                'default' => 'yes',
            ]
        );

        $this->add_responsive_control(
            'indent_size',
            [
                'label' => __('Indent Size', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em'],
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 100,
                        'step' => 5,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 20,
                ],
                'selectors' => [
                    '{{WRAPPER}} .toc-item.toc-level-3 > a' => 'padding-left: calc(var(--toc-base-padding, 10px) + {{SIZE}}{{UNIT}});',
                    '{{WRAPPER}} .toc-item.toc-level-4 > a' => 'padding-left: calc(var(--toc-base-padding, 10px) + calc({{SIZE}}{{UNIT}} * 2));',
                    '{{WRAPPER}} .toc-item.toc-level-5 > a' => 'padding-left: calc(var(--toc-base-padding, 10px) + calc({{SIZE}}{{UNIT}} * 3));',
                    '{{WRAPPER}} .toc-item.toc-level-6 > a' => 'padding-left: calc(var(--toc-base-padding, 10px) + calc({{SIZE}}{{UNIT}} * 4));',
                ],
                'condition' => [
                    'indent_levels' => 'yes',
                ],
            ]
        );

        $this->end_controls_section();
    }

    /**
     * Render widget output on the frontend.
     */
    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $toc_style = $settings['toc_style'];
        $toc_title = !empty($settings['toc_title']) ? esc_html($settings['toc_title']) : '';
        $heading_levels = !empty($settings['heading_levels']) ? $settings['heading_levels'] : ['h2', 'h3', 'h4'];
        $toc_scope = $settings['toc_scope'] ?? 'page';
        $custom_selector = !empty($settings['custom_selector']) ? esc_attr($settings['custom_selector']) : '';
        $sticky = $settings['sticky_toc'] === 'yes' ? 'sticky' : '';
        $smooth_scroll = $settings['smooth_scroll'] === 'yes' ? 'yes' : 'no';
        $scroll_spy = $settings['scroll_spy'] === 'yes' ? 'yes' : 'no';
        $scroll_offset = $settings['scroll_offset'] ?? 100;
        $collapsible = $settings['collapsible'] === 'yes' ? 'collapsible' : '';
        $collapsed = ($settings['collapsible'] === 'yes' && $settings['collapsed_by_default'] === 'yes') ? 'collapsed' : '';

        $toc_class = 'unlockafe-toc';
        $toc_class .= ' toc-' . esc_attr($toc_style);
        if ($sticky) {
            $toc_class .= ' ' . $sticky;
        }
        if ($collapsible) {
            $toc_class .= ' ' . $collapsible;
        }
        if ($collapsed) {
            $toc_class .= ' ' . $collapsed;
        }

        // Build heading levels string
        $heading_levels_str = implode(',', $heading_levels);

        ?>
        <div class="<?php echo esc_attr($toc_class); ?>"
             data-heading-levels="<?php echo esc_attr($heading_levels_str); ?>"
             data-scope="<?php echo esc_attr($toc_scope); ?>"
             data-custom-selector="<?php echo esc_attr($custom_selector); ?>"
             data-smooth-scroll="<?php echo esc_attr($smooth_scroll); ?>"
             data-scroll-spy="<?php echo esc_attr($scroll_spy); ?>"
             data-scroll-offset="<?php echo esc_attr($scroll_offset); ?>">
            
            <?php if ($toc_title): ?>
                <div class="toc-header">
                    <h3 class="toc-title">
                        <?php echo $toc_title; ?>
                        <?php if ($collapsible): ?>
                            <span class="toc-toggle">
                                <i class="fas fa-chevron-down"></i>
                            </span>
                        <?php endif; ?>
                    </h3>
                </div>
            <?php endif; ?>

            <div class="toc-content">
                <ul class="toc-list">
                    <li class="toc-loading"><?php esc_html_e('Loading table of contents...', 'unlock-addons-for-elementor'); ?></li>
                </ul>
            </div>
        </div>
        <?php
    }
}

