<?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\Group_Control_Typography;
use Elementor\Group_Control_Border;
use Elementor\Group_Control_Box_Shadow;
use Elementor\Group_Control_Background;
use Elementor\Repeater;

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

/**
 * One Page Navigation Widget
 *
 * @since 1.0.0
 */
class One_Page_Navigation extends Widget_Base
{
    use Widget_helper, UnlockafeUtils;

    /**
     * Retrieve the widget name.
     */
    public function get_name()
    {
        return 'unlockafe-one-page-navigation';
    }

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

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

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

    /**
     * Retrieve the list of keywords.
     */
    public function get_keywords()
    {
        return ['navigation', 'menu', 'scroll', 'one page', 'spy', 'anchor', 'smooth'];
    }

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

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

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

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

        $repeater = new Repeater();

        $repeater->add_control(
            'nav_label',
            [
                'label' => __('Label', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => __('Home', 'unlock-addons-for-elementor'),
                'placeholder' => __('Enter label', 'unlock-addons-for-elementor'),
            ]
        );

        $repeater->add_control(
            'nav_anchor',
            [
                'label' => __('Section ID/Anchor', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::TEXT,
                'default' => __('home', 'unlock-addons-for-elementor'),
                'placeholder' => __('e.g., home, about, services', 'unlock-addons-for-elementor'),
                'description' => __('Enter the section ID (without #) that this navigation item should scroll to.', 'unlock-addons-for-elementor'),
            ]
        );

        $repeater->add_control(
            'nav_icon',
            [
                'label' => __('Icon', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::ICONS,
                'default' => [
                    'value' => '',
                    'library' => '',
                ],
            ]
        );

        $this->add_control(
            'navigation_items',
            [
                'label' => __('Navigation Items', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::REPEATER,
                'fields' => $repeater->get_controls(),
                'default' => [
                    [
                        'nav_label' => __('Home', 'unlock-addons-for-elementor'),
                        'nav_anchor' => 'home',
                    ],
                    [
                        'nav_label' => __('About', 'unlock-addons-for-elementor'),
                        'nav_anchor' => 'about',
                    ],
                    [
                        'nav_label' => __('Services', 'unlock-addons-for-elementor'),
                        'nav_anchor' => 'services',
                    ],
                    [
                        'nav_label' => __('Contact', 'unlock-addons-for-elementor'),
                        'nav_anchor' => 'contact',
                    ],
                ],
                'title_field' => '{{{ nav_label }}}',
            ]
        );

        $this->end_controls_section();

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

        $this->add_control(
            'nav_style',
            [
                'label' => __('Navigation Style', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'horizontal' => __('Horizontal Menu', 'unlock-addons-for-elementor'),
                    'vertical' => __('Vertical Menu', 'unlock-addons-for-elementor'),
                    'dots' => __('Dots Navigation', 'unlock-addons-for-elementor'),
                    'sidebar' => __('Sidebar Menu', 'unlock-addons-for-elementor'),
                ],
                'default' => 'horizontal',
            ]
        );

        $this->add_control(
            'nav_position',
            [
                'label' => __('Position', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'top' => __('Top', 'unlock-addons-for-elementor'),
                    'bottom' => __('Bottom', 'unlock-addons-for-elementor'),
                    'left' => __('Left', 'unlock-addons-for-elementor'),
                    'right' => __('Right', 'unlock-addons-for-elementor'),
                ],
                'default' => 'top',
                'condition' => [
                    'nav_style' => ['horizontal', 'dots'],
                ],
            ]
        );

        $this->add_control(
            'sticky_nav',
            [
                'label' => __('Sticky Navigation', '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(
            '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_offset',
            [
                'label' => __('Scroll Offset (px)', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::NUMBER,
                'default' => 80,
                'min' => 0,
                'max' => 300,
                'step' => 10,
                'description' => __('Distance from top when scrolling to section', 'unlock-addons-for-elementor'),
            ]
        );

        $this->add_control(
            'show_active_indicator',
            [
                'label' => __('Show Active Indicator', '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->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-one-page-nav',
            ]
        );

        $this->add_responsive_control(
            'container_margin_top',
            [
                'label' => __('Margin Top', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em', '%'],
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 500,
                        'step' => 1,
                    ],
                    'em' => [
                        'min' => 0,
                        'max' => 30,
                        'step' => 0.1,
                    ],
                    '%' => [
                        'min' => 0,
                        'max' => 50,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 0,
                ],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-one-page-nav' => 'margin-top: {{SIZE}}{{UNIT}} !important;',
                ],
            ]
        );

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

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

        $this->add_control(
            'container_border_radius',
            [
                'label' => __('Border Radius', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .unlockafe-one-page-nav' => '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-one-page-nav',
            ]
        );

        $this->end_controls_section();

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

        $this->add_responsive_control(
            'menu_items_gap',
            [
                'label' => __('Gap Between Items', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', 'em'],
                'range' => [
                    'px' => [
                        'min' => 0,
                        'max' => 100,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 20,
                ],
                'selectors' => [
                    '{{WRAPPER}} .nav-menu.horizontal .nav-item' => 'margin-right: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .nav-menu.vertical .nav-item' => 'margin-bottom: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .nav-menu.dots .nav-item' => 'margin-bottom: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

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

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'menu_item_typography',
                'selector' => '{{WRAPPER}} .nav-link',
            ]
        );

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

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

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

        $this->end_controls_section();

        // Active Indicator Style
        $this->start_controls_section(
            'indicator_style_section',
            [
                'label' => __('Active Indicator', 'unlock-addons-for-elementor'),
                'tab' => Controls_Manager::TAB_STYLE,
                'condition' => [
                    'show_active_indicator' => 'yes',
                ],
            ]
        );

        $this->add_control(
            'indicator_type',
            [
                'label' => __('Indicator Type', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SELECT,
                'options' => [
                    'underline' => __('Underline', 'unlock-addons-for-elementor'),
                    'background' => __('Background', 'unlock-addons-for-elementor'),
                    'dot' => __('Dot', 'unlock-addons-for-elementor'),
                    'border' => __('Border', 'unlock-addons-for-elementor'),
                ],
                'default' => 'underline',
            ]
        );

        $this->add_control(
            'indicator_color',
            [
                'label' => __('Indicator Color', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::COLOR,
                'default' => '#667eea',
                'selectors' => [
                    '{{WRAPPER}} .nav-link.active::after' => 'background-color: {{VALUE}};',
                    '{{WRAPPER}} .nav-link.active .indicator-dot' => 'background-color: {{VALUE}};',
                    '{{WRAPPER}} .nav-link.active' => 'border-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'indicator_size',
            [
                'label' => __('Indicator Size', 'unlock-addons-for-elementor'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px'],
                'range' => [
                    'px' => [
                        'min' => 1,
                        'max' => 10,
                        'step' => 1,
                    ],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 3,
                ],
                'selectors' => [
                    '{{WRAPPER}} .nav-link.active::after' => 'height: {{SIZE}}{{UNIT}};',
                ],
                'condition' => [
                    'indicator_type' => 'underline',
                ],
            ]
        );

        $this->end_controls_section();
    }


    /**
     * Render widget output on the frontend.
     */
    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $nav_style = $settings['nav_style'];
        $nav_position = $settings['nav_position'];
        $sticky = $settings['sticky_nav'] === 'yes' ? 'sticky' : '';
        $smooth_scroll = $settings['smooth_scroll'] === 'yes' ? 'smooth-scroll' : '';
        $show_indicator = $settings['show_active_indicator'] === 'yes';
        $indicator_type = $settings['indicator_type'] ?? 'underline';
        $scroll_offset = $settings['scroll_offset'] ?? 80;
        
        // Check if we're in Elementor editor or preview mode
        $is_editor_mode = \Elementor\Plugin::$instance->editor->is_edit_mode();
        $is_preview_mode = \Elementor\Plugin::$instance->preview->is_preview_mode();

        $nav_class = 'unlockafe-one-page-nav';
        $nav_class .= ' nav-' . esc_attr($nav_style);
        $nav_class .= ' nav-' . esc_attr($nav_position);
        if ($sticky) {
            $nav_class .= ' ' . $sticky;
        }
        if ($smooth_scroll) {
            $nav_class .= ' ' . $smooth_scroll;
        }

        ?>
        <nav class="<?php echo esc_attr($nav_class); ?>" 
             data-scroll-offset="<?php echo esc_attr($scroll_offset); ?>"
             data-smooth-scroll="<?php echo esc_attr($settings['smooth_scroll']); ?>">
            <ul class="nav-menu <?php echo esc_attr($nav_style); ?>">
                <?php foreach ($settings['navigation_items'] as $index => $item): 
                    $anchor = !empty($item['nav_anchor']) ? esc_attr($item['nav_anchor']) : '';
                    $label = !empty($item['nav_label']) ? esc_html($item['nav_label']) : '';
                    $active_class = $index === 0 ? 'active' : '';
                    
                    // Build anchor link
                    $anchor_link = $anchor ? '#' . $anchor : '#';
                ?>
                    <li class="nav-item">
                        <a href="<?php echo esc_url($anchor_link); ?>" 
                           class="nav-link <?php echo esc_attr($active_class); ?>"
                           data-anchor="<?php echo esc_attr($anchor); ?>"
                           data-indicator-type="<?php echo esc_attr($indicator_type); ?>">
                            <?php if (!empty($item['nav_icon']['value'])): ?>
                                <span class="nav-icon">
                                    <?php
                                    if ($item['nav_icon']['library'] === 'svg') {
                                        echo '<img src="' . esc_url($item['nav_icon']['value']['url']) . '" alt="' . esc_attr($label) . '">';
                                    } else {
                                        \Elementor\Icons_Manager::render_icon($item['nav_icon'], ['aria-hidden' => 'true']);
                                    }
                                    ?>
                                </span>
                            <?php endif; ?>
                            <span class="nav-label"><?php echo $label; ?></span>
                            <?php if ($show_indicator && $indicator_type === 'dot'): ?>
                                <span class="indicator-dot"></span>
                            <?php endif; ?>
                        </a>
                    </li>
                <?php endforeach; ?>
            </ul>
        </nav>
        <?php
        
        // Add inline script for editor/preview mode and after save initialization
        if ($is_editor_mode || $is_preview_mode || !$is_editor_mode) {
            ?>
            <script type="text/javascript">
            (function() {
                function initOnePageNav() {
                    if (typeof jQuery === 'undefined') {
                        setTimeout(initOnePageNav, 100);
                        return;
                    }
                    
                    var $ = jQuery;
                    var $widget = $('.elementor-widget-unlockafe-one-page-navigation').last();
                    var $nav = $widget.find('.unlockafe-one-page-nav');
                    
                    if ($nav.length === 0) {
                        setTimeout(initOnePageNav, 100);
                        return;
                    }
                    
                    // Check if already initialized
                    if ($nav.data('onePageNavInitialized')) {
                        return;
                    }
                    
                    // Mark as initialized
                    $nav.data('onePageNavInitialized', true);
                    
                    var scrollOffset = parseInt($nav.data('scroll-offset')) || 80;
                    var smoothScroll = $nav.data('smooth-scroll') === 'yes' || $nav.data('smooth-scroll') === true;
                    var $navLinks = $nav.find('.nav-link');
                    
                    console.log('One Page Navigation: Inline script initializing', $navLinks.length, 'links');
                    
                    // Enable smooth scroll on html if needed
                    if (smoothScroll) {
                        $('html').addClass('smooth-scroll-enabled');
                    }
                    
                    // Smooth scroll to section
                    function scrollToSection(anchor, offset) {
                        var $target = $(anchor);
                        if ($target.length) {
                            var targetPosition = $target.offset().top - offset;
                            if (smoothScroll) {
                                $('html, body').animate({
                                    scrollTop: targetPosition
                                }, 800, 'swing');
                            } else {
                                $('html, body').scrollTop(targetPosition);
                            }
                        }
                    }
                    
                    // Update active navigation item based on scroll position
                    function updateActiveNav() {
                        var scrollPos = $(window).scrollTop() + scrollOffset + 50;
                        var currentSection = '';
                        
                        $navLinks.each(function() {
                            var $link = $(this);
                            var anchor = $link.data('anchor');
                            if (anchor) {
                                var $section = $('#' + anchor);
                                if ($section.length) {
                                    var sectionTop = $section.offset().top;
                                    var sectionBottom = sectionTop + $section.outerHeight();
                                    if (scrollPos >= sectionTop && scrollPos < sectionBottom) {
                                        currentSection = anchor;
                                        return false;
                                    }
                                }
                            }
                        });
                        
                        $navLinks.removeClass('active');
                        if (currentSection) {
                            $navLinks.filter('[data-anchor="' + currentSection + '"]').addClass('active');
                        } else {
                            $navLinks.first().addClass('active');
                        }
                    }
                    
                    // Handle navigation link clicks - Use event delegation
                    $nav.off('click.onePageNavInline', '.nav-link').on('click.onePageNavInline', '.nav-link', function(e) {
                        e.preventDefault();
                        e.stopPropagation();
                        var $link = $(this);
                        var anchor = $link.data('anchor') || $link.attr('data-anchor');
                        
                        console.log('One Page Navigation: Inline script - Link clicked', anchor);
                        
                        if (anchor) {
                            $nav.find('.nav-link').removeClass('active');
                            $link.addClass('active');
                            scrollToSection('#' + anchor, scrollOffset);
                        } else {
                            console.warn('One Page Navigation: Inline script - No anchor found');
                        }
                    });
                    
                    // Update active nav on scroll
                    var scrollTimeout;
                    $(window).off('scroll.onePageNav').on('scroll.onePageNav', function() {
                        clearTimeout(scrollTimeout);
                        scrollTimeout = setTimeout(function() {
                            updateActiveNav();
                        }, 10);
                    });
                    
                    // Update active nav on page load
                    updateActiveNav();
                    
                    // Mark as initialized (already done above)
                    console.log('One Page Navigation: Inline script initialized successfully');
                }
                
                // Start initialization
                if (document.readyState === 'loading') {
                    document.addEventListener('DOMContentLoaded', function() {
                        setTimeout(initOnePageNav, 100);
                    });
                } else {
                    setTimeout(initOnePageNav, 100);
                }
                
                // Also try after delays
                setTimeout(initOnePageNav, 300);
                setTimeout(initOnePageNav, 600);
                $(window).on('load', function() {
                    setTimeout(initOnePageNav, 200);
                });
            })();
            </script>
            <?php
        }
    }
}

