<?php
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_Image_Size;
use Elementor\Utils;

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

class megamenukaveh extends Widget_Base
{
    public function get_name()
    {
        return 'megamenukaveh';
    }

    public function get_title()
    {
        return esc_html__('Advanced Mega Menu', 'newTheme');
    }

    public function get_icon()
    {
        return 'eicon-nav-menu';
    }

    public function get_categories()
    {
        return ['new-theme-elements'];
    }

    public function get_script_depends()
    {
        return ['elementor-frontend'];
    }

    public function get_style_depends()
    {
        return ['elementor-frontend'];
    }

    /**
     * Enqueue Elementor CSS for mega menu posts
     */
    protected function enqueue_mega_menu_styles($post_id)
    {
        if (class_exists('\Elementor\Plugin') && \Elementor\Plugin::$instance->documents->get($post_id)->is_built_with_elementor()) {
            // Enqueue Elementor CSS for this specific post
            if (class_exists('\Elementor\Core\Files\CSS\Post')) {
                $css_file = new \Elementor\Core\Files\CSS\Post($post_id);
                $css_file->enqueue();
            }
            
            // Also enqueue global Elementor styles if not already done
            if (class_exists('\Elementor\Core\Files\CSS\Global_CSS')) {
                $global_css = new \Elementor\Core\Files\CSS\Global_CSS('global.css');
                $global_css->enqueue();
            }
            
            // Force inline CSS output for immediate loading
            $this->output_inline_elementor_css($post_id);
        }
    }
    
    /**
     * Output inline CSS for Elementor posts to ensure immediate styling
     */
    protected function output_inline_elementor_css($post_id)
    {
        if (class_exists('\Elementor\Core\Files\CSS\Post')) {
            $css_file = new \Elementor\Core\Files\CSS\Post($post_id);
            $css_content = $css_file->get_content();
            
            if (!empty($css_content)) {
                echo '<style id="elementor-post-' . $post_id . '">' . $css_content . '</style>';
            }
        }
    }

    /**
     * Pre-load all mega menu styles for the current widget instance
     */
    protected function preload_mega_menu_styles($settings)
    {
        if ($settings['menu_style'] === 'repeater' && !empty($settings['menu_items'])) {
            foreach ($settings['menu_items'] as $item) {
                if ($item['show_submenu'] === 'yes' && $item['submenu_type'] === 'mega_menu' && !empty($item['submenu_mega_menu'])) {
                    $this->enqueue_mega_menu_styles($item['submenu_mega_menu']);
                }
            }
        }
    }



    protected function register_controls()
    {
        $menus = wp_get_nav_menus();
        $menu_options = ['' => esc_html__('Select Menu', 'newTheme')];
        foreach ($menus as $menu) {
            $menu_options[$menu->term_id] = $menu->name;
        }

        // Mega Menu Posts
        $mega_menu_posts = get_posts([
            'post_type' => 'c-mega-menu',
            'numberposts' => -1,
            'post_status' => 'publish',
        ]);
        $mega_menu_options = ['' => esc_html__('Select Mega Menu', 'newTheme')];
        foreach ($mega_menu_posts as $post) {
            $mega_menu_options[$post->ID] = $post->post_title;
        }

        // Content: Menu Settings
        $this->start_controls_section(
            'section_menu_content',
            [
                'label' => esc_html__('Menu Settings', 'newTheme'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'menu_style',
            [
                'label' => esc_html__('Menu Type', 'newTheme'),
                'type' => Controls_Manager::SELECT,
                'default' => 'wordpress',
                'options' => [
                    'wordpress' => esc_html__('WordPress Menu', 'newTheme'),
                    'repeater' => esc_html__('Custom Menu (Repeater)', 'newTheme'),
                ],
            ]
        );

        $this->add_control(
            'wordpress_menu',
            [
                'label' => esc_html__('Select Menu', 'newTheme'),
                'type' => Controls_Manager::SELECT,
                'options' => $menu_options,
                'default' => '',
                'condition' => [
                    'menu_style' => 'wordpress',
                ],
            ]
        );

        $repeater = new \Elementor\Repeater();

        $repeater->add_control(
            'menu_title',
            [
                'label' => esc_html__('Title', 'newTheme'),
                'type' => Controls_Manager::TEXT,
                'default' => esc_html__('Menu Item', 'newTheme'),
                'dynamic' => ['active' => true],
            ]
        );

        $repeater->add_control(
            'menu_link',
            [
                'label' => esc_html__('Link', 'newTheme'),
                'type' => Controls_Manager::URL,
                'default' => ['url' => '#'],
                'dynamic' => ['active' => true],
            ]
        );

        $repeater->add_control(
            'menu_icon_type',
            [
                'label' => esc_html__('Icon Type', 'newTheme'),
                'type' => Controls_Manager::SELECT,
                'default' => 'none',
                'options' => [
                    'none' => esc_html__('None', 'newTheme'),
                    'icon' => esc_html__('Icon', 'newTheme'),
                    'image' => esc_html__('Image', 'newTheme'),
                ],
            ]
        );

        $repeater->add_control(
            'menu_icon_position',
            [
                'label' => esc_html__('Icon Position', 'newTheme'),
                'type' => Controls_Manager::SELECT,
                'default' => 'left',
                'options' => [
                    'left' => esc_html__('Left', 'newTheme'),
                    'right' => esc_html__('Right', 'newTheme'),
                    'top' => esc_html__('Top', 'newTheme'),
                    'bottom' => esc_html__('Bottom', 'newTheme'),
                ],
                'condition' => [
                    'menu_icon_type!' => 'none',
                ],
            ]
        );

        $repeater->add_control(
            'menu_icon',
            [
                'label' => esc_html__('Icon', 'newTheme'),
                'type' => Controls_Manager::ICONS,
                'skin' => 'inline',
                'exclude_inline_options' => ['svg'],
                'default' => [
                    'value' => 'fas fa-star',
                    'library' => 'fa-solid',
                ],
                'condition' => [
                    'menu_icon_type' => 'icon',
                ],
            ]
        );

        $repeater->add_control(
            'menu_image',
            [
                'label' => esc_html__('Image', 'newTheme'),
                'type' => Controls_Manager::MEDIA,
                'default' => [],
                'condition' => [
                    'menu_icon_type' => 'image',
                ],
            ]
        );

        $repeater->add_group_control(
            Group_Control_Image_Size::get_type(),
            [
                'name' => 'menu_image',
                'default' => 'thumbnail',
                'condition' => [
                    'menu_icon_type' => 'image',
                ],
            ]
        );

        $repeater->add_control(
            'show_new_badge',
            [
                'label' => esc_html__('Show "New" Badge', 'newTheme'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'newTheme'),
                'label_off' => esc_html__('No', 'newTheme'),
                'return_value' => 'yes',
                'default' => 'no',
            ]
        );

        $repeater->add_control(
            'show_submenu',
            [
                'label' => esc_html__('Show Submenu', 'newTheme'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'newTheme'),
                'label_off' => esc_html__('No', 'newTheme'),
                'return_value' => 'yes',
                'default' => 'no',
            ]
        );

        $repeater->add_control(
            'submenu_type',
            [
                'label' => esc_html__('Submenu Type', 'newTheme'),
                'type' => Controls_Manager::SELECT,
                'default' => 'wordpress',
                'options' => [
                    'wordpress' => esc_html__('WordPress Menu', 'newTheme'),
                    'mega_menu' => esc_html__('Mega Menu Post', 'newTheme'),
                ],
                'condition' => [
                    'show_submenu' => 'yes',
                ],
            ]
        );

        $repeater->add_control(
            'submenu_wordpress',
            [
                'label' => esc_html__('WordPress Submenu', 'newTheme'),
                'type' => Controls_Manager::SELECT,
                'options' => $menu_options,
                'condition' => [
                    'show_submenu' => 'yes',
                    'submenu_type' => 'wordpress',
                ],
            ]
        );

        $repeater->add_control(
            'submenu_mega_menu',
            [
                'label' => esc_html__('Mega Menu Post', 'newTheme'),
                'type' => Controls_Manager::SELECT,
                'options' => $mega_menu_options,
                'condition' => [
                    'show_submenu' => 'yes',
                    'submenu_type' => 'mega_menu',
                ],
            ]
        );

        $this->add_control(
            'menu_items',
            [
                'label' => esc_html__('Menu Items', 'newTheme'),
                'type' => Controls_Manager::REPEATER,
                'fields' => $repeater->get_controls(),
                'condition' => [
                    'menu_style' => 'repeater',
                ],
                'title_field' => '{{{ menu_title }}}',
            ]
        );

        $this->add_control(
            'menu_alignment',
            [
                'label' => esc_html__('Alignment', 'newTheme'),
                'type' => Controls_Manager::CHOOSE,
                'default' => 'center',
                'options' => [
                    'flex-start' => [
                        'title' => esc_html__('Left', 'newTheme'),
                        'icon' => 'eicon-h-align-left',
                    ],
                    'center' => [
                        'title' => esc_html__('Center', 'newTheme'),
                        'icon' => 'eicon-h-align-center',
                    ],
                    'flex-end' => [
                        'title' => esc_html__('Right', 'newTheme'),
                        'icon' => 'eicon-h-align-right',
                    ],
                ],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__nav' => 'justify-content: {{VALUE}};',
                    '[dir="rtl"] {{WRAPPER}} .adv-mega-menu__nav[style*="flex-start"]' => 'justify-content: flex-end !important;',
                    '[dir="rtl"] {{WRAPPER}} .adv-mega-menu__nav[style*="flex-end"]' => 'justify-content: flex-start !important;',
                ],
            ]
        );

        $this->add_control(
            'sticky_menu',
            [
                'label' => esc_html__('Sticky Menu', 'newTheme'),
                'type' => Controls_Manager::SWITCHER,
                'label_on' => esc_html__('Yes', 'newTheme'),
                'label_off' => esc_html__('No', 'newTheme'),
                'return_value' => 'yes',
                'default' => 'no',
            ]
        );

        $this->add_control(
            'submenu_animation',
            [
                'label' => esc_html__('Submenu Animation', 'newTheme'),
                'type' => Controls_Manager::SELECT,
                'default' => 'fade',
                'options' => [
                    'none' => esc_html__('None', 'newTheme'),
                    'fade' => esc_html__('Fade', 'newTheme'),
                    'slide' => esc_html__('Slide', 'newTheme'),
                    'scale' => esc_html__('Scale', 'newTheme'),
                ],
            ]
        );

        $this->end_controls_section();

        // Content: Mega Menu Settings
        $this->start_controls_section(
            'section_mega_menu_content',
            [
                'label' => esc_html__('Mega Menu Settings', 'newTheme'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_responsive_control(
            'mega_menu_width',
            [
                'label' => esc_html__('Mega Menu Width', 'newTheme'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', '%', 'vw'],
                'range' => [
                    'px' => ['min' => 200, 'max' => 1200],
                    '%' => ['min' => 20, 'max' => 100],
                    'vw' => ['min' => 20, 'max' => 100],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 800,
                ],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__megamenu' => 'width: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_control(
            'mega_menu_position',
            [
                'label' => esc_html__('Mega Menu Position', 'newTheme'),
                'type' => Controls_Manager::SELECT,
                'default' => 'left',
                'options' => [
                    'left' => esc_html__('Start (Left/Right in RTL)', 'newTheme'),
                    'center' => esc_html__('Center', 'newTheme'),
                    'right' => esc_html__('End (Right/Left in RTL)', 'newTheme'),
                    'full' => esc_html__('Full Width', 'newTheme'),
                ],
            ]
        );

        $this->end_controls_section();

        // Content: Mobile Menu
        $this->start_controls_section(
            'section_mobile_menu',
            [
                'label' => esc_html__('Mobile Menu', 'newTheme'),
                'tab' => Controls_Manager::TAB_CONTENT,
            ]
        );

        $this->add_control(
            'mobile_breakpoint',
            [
                'label' => esc_html__('Mobile Breakpoint', 'newTheme'),
                'type' => Controls_Manager::SELECT,
                'default' => 'lg',
                'options' => [
                    'sm' => esc_html__('Mobile (576px)', 'newTheme'),
                    'md' => esc_html__('Tablet (768px)', 'newTheme'),
                    'lg' => esc_html__('Laptop (992px)', 'newTheme'),
                    'xl' => esc_html__('Desktop (1200px)', 'newTheme'),
                ],
            ]
        );

        $this->add_control(
            'hamburger_icon',
            [
                'label' => esc_html__('Hamburger Icon', 'newTheme'),
                'type' => Controls_Manager::ICONS,
                'skin' => 'inline',
                'exclude_inline_options' => ['svg'],
                'default' => [
                    'value' => 'fas fa-bars',
                    'library' => 'fa-solid',
                ],
            ]
        );

        $this->add_control(
            'hamburger_alignment',
            [
                'label' => esc_html__('Hamburger Alignment', 'newTheme'),
                'type' => Controls_Manager::CHOOSE,
                'default' => 'flex-end',
                'options' => [
                    'flex-start' => [
                        'title' => esc_html__('Left', 'newTheme'),
                        'icon' => 'eicon-h-align-left',
                    ],
                    'center' => [
                        'title' => esc_html__('Center', 'newTheme'),
                        'icon' => 'eicon-h-align-center',
                    ],
                    'flex-end' => [
                        'title' => esc_html__('Right', 'newTheme'),
                        'icon' => 'eicon-h-align-right',
                    ],
                ],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__hamburger' => 'justify-content: {{VALUE}};',
                    '[dir="rtl"] {{WRAPPER}} .adv-mega-menu__hamburger[style*="flex-start"]' => 'justify-content: flex-end !important;',
                    '[dir="rtl"] {{WRAPPER}} .adv-mega-menu__hamburger[style*="flex-end"]' => 'justify-content: flex-start !important;',
                ],
            ]
        );

        $this->end_controls_section();

        // Style: Main Menu
        $this->start_controls_section(
            'style_main_menu',
            [
                'label' => esc_html__('Main Menu', 'newTheme'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'menu_typography',
                'label' => esc_html__('Typography', 'newTheme'),
                'selector' => '{{WRAPPER}} .adv-mega-menu__item > a',
            ]
        );

        $this->add_responsive_control(
            'menu_icon_size',
            [
                'label' => esc_html__('Icon/Image Size', 'newTheme'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px'],
                'range' => [
                    'px' => ['min' => 10, 'max' => 50],
                ],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__item > a > i' => 'font-size: {{SIZE}}{{UNIT}};',
                    '{{WRAPPER}} .adv-mega-menu__item > a > img' => 'width: {{SIZE}}{{UNIT}}; height: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'menu_icon_spacing',
            [
                'label' => esc_html__('Icon/Image Spacing', 'newTheme'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px'],
                'range' => [
                    'px' => ['min' => 0, 'max' => 30],
                ],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__link--icon-left > i, {{WRAPPER}} .adv-mega-menu__link--icon-left > img' => 'margin-inline-end: {{SIZE}}{{UNIT}} !important;',
                    '{{WRAPPER}} .adv-mega-menu__link--icon-right > i, {{WRAPPER}} .adv-mega-menu__link--icon-right > img' => 'margin-inline-start: {{SIZE}}{{UNIT}} !important;',
                    '{{WRAPPER}} .adv-mega-menu__link--icon-top > i, {{WRAPPER}} .adv-mega-menu__link--icon-top > img' => 'margin-bottom: {{SIZE}}{{UNIT}} !important;',
                    '{{WRAPPER}} .adv-mega-menu__link--icon-bottom > i, {{WRAPPER}} .adv-mega-menu__link--icon-bottom > img' => 'margin-top: {{SIZE}}{{UNIT}} !important;',
                ],
            ]
        );

        $this->start_controls_tabs('menu_style_tabs');

        $this->start_controls_tab(
            'menu_normal',
            [
                'label' => esc_html__('Normal', 'newTheme'),
            ]
        );

        $this->add_control(
            'menu_color',
            [
                'label' => esc_html__('Text Color', 'newTheme'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__item > a' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'menu_bg_color',
            [
                'label' => esc_html__('Background Color', 'newTheme'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__item > a' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'menu_border',
                'selector' => '{{WRAPPER}} .adv-mega-menu__item > a',
            ]
        );

        $this->add_responsive_control(
            'menu_border_radius',
            [
                'label' => esc_html__('Border Radius', 'newTheme'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__item > a' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'menu_box_shadow',
                'selector' => '{{WRAPPER}} .adv-mega-menu__item > a',
            ]
        );

        $this->add_responsive_control(
            'menu_padding',
            [
                'label' => esc_html__('Padding', 'newTheme'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px'],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__item > a' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'menu_margin',
            [
                'label' => esc_html__('Margin', 'newTheme'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px'],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__item' => 'margin: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_tab();

        $this->start_controls_tab(
            'menu_hover',
            [
                'label' => esc_html__('Hover', 'newTheme'),
            ]
        );

        $this->add_control(
            'menu_hover_color',
            [
                'label' => esc_html__('Text Color', 'newTheme'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__item:hover > a' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'menu_hover_bg_color',
            [
                'label' => esc_html__('Background Color', 'newTheme'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__item:hover > a' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'menu_hover_border',
                'selector' => '{{WRAPPER}} .adv-mega-menu__item:hover > a',
            ]
        );

        $this->add_responsive_control(
            'menu_hover_border_radius',
            [
                'label' => esc_html__('Border Radius', 'newTheme'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__item:hover > a' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'menu_hover_box_shadow',
                'selector' => '{{WRAPPER}} .adv-mega-menu__item:hover > a',
            ]
        );

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

        $this->end_controls_section();

        // Style: Submenu
        $this->start_controls_section(
            'style_submenu',
            [
                'label' => esc_html__('Submenu', 'newTheme'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'submenu_typography',
                'label' => esc_html__('Typography', 'newTheme'),
                'selector' => '{{WRAPPER}} .adv-mega-menu__submenu a',
            ]
        );

        $this->add_control(
            'submenu_bg_color',
            [
                'label' => esc_html__('Background Color', 'newTheme'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__submenu' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'submenu_padding',
            [
                'label' => esc_html__('Padding', 'newTheme'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px'],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__submenu' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'submenu_border_radius',
            [
                'label' => esc_html__('Border Radius', 'newTheme'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__submenu' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'submenu_box_shadow',
                'selector' => '{{WRAPPER}} .adv-mega-menu__submenu',
            ]
        );

        $this->start_controls_tabs('submenu_style_tabs');

        $this->start_controls_tab(
            'submenu_normal',
            [
                'label' => esc_html__('Normal', 'newTheme'),
            ]
        );

        $this->add_control(
            'submenu_color',
            [
                'label' => esc_html__('Text Color', 'newTheme'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__submenu a' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'submenu_item_bg_color',
            [
                'label' => esc_html__('Item Background Color', 'newTheme'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__submenu a' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'submenu_border',
                'selector' => '{{WRAPPER}} .adv-mega-menu__submenu a',
            ]
        );

        $this->add_responsive_control(
            'submenu_item_border_radius',
            [
                'label' => esc_html__('Item Border Radius', 'newTheme'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__submenu a' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'submenu_item_padding',
            [
                'label' => esc_html__('Item Padding', 'newTheme'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px'],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__submenu a' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_tab();

        $this->start_controls_tab(
            'submenu_hover',
            [
                'label' => esc_html__('Hover', 'newTheme'),
            ]
        );

        $this->add_control(
            'submenu_hover_color',
            [
                'label' => esc_html__('Text Color', 'newTheme'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__submenu a:hover' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'submenu_item_hover_bg_color',
            [
                'label' => esc_html__('Item Background Color', 'newTheme'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__submenu a:hover' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Border::get_type(),
            [
                'name' => 'submenu_hover_border',
                'selector' => '{{WRAPPER}} .adv-mega-menu__submenu a:hover',
            ]
        );

        $this->add_responsive_control(
            'submenu_item_hover_border_radius',
            [
                'label' => esc_html__('Item Border Radius', 'newTheme'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__submenu a:hover' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

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

        $this->end_controls_section();

        // Style: Mega Menu
        $this->start_controls_section(
            'style_mega_menu',
            [
                'label' => esc_html__('Mega Menu', 'newTheme'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_control(
            'mega_menu_bg_color',
            [
                'label' => esc_html__('Background Color', 'newTheme'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__megamenu' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'mega_menu_padding',
            [
                'label' => esc_html__('Padding', 'newTheme'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px'],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__megamenu' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'mega_menu_border_radius',
            [
                'label' => esc_html__('Border Radius', 'newTheme'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px', '%'],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__megamenu' => 'border-radius: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Box_Shadow::get_type(),
            [
                'name' => 'mega_menu_box_shadow',
                'selector' => '{{WRAPPER}} .adv-mega-menu__megamenu',
            ]
        );

        $this->add_responsive_control(
            'mega_menu_spacing',
            [
                'label' => esc_html__('Spacing from Menu', 'newTheme'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px'],
                'range' => [
                    'px' => ['min' => 0, 'max' => 50],
                ],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__megamenu' => 'top: calc(100% + {{SIZE}}{{UNIT}});',
                ],
            ]
        );

        $this->end_controls_section();

        // Style: Mobile Menu
        $this->start_controls_section(
            'style_mobile_menu',
            [
                'label' => esc_html__('Mobile Menu', 'newTheme'),
                'tab' => Controls_Manager::TAB_STYLE,
            ]
        );

        $this->add_responsive_control(
            'hamburger_icon_size',
            [
                'label' => esc_html__('Hamburger Icon Size', 'newTheme'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px'],
                'range' => [
                    'px' => ['min' => 10, 'max' => 50],
                ],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__hamburger-toggle i' => 'font-size: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_control(
            'hamburger_icon_color',
            [
                'label' => esc_html__('Hamburger Icon Color', 'newTheme'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__hamburger-toggle i' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'mobile_menu_bg_color',
            [
                'label' => esc_html__('Menu Background Color', 'newTheme'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__mobile-content' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'mobile_menu_width',
            [
                'label' => esc_html__('Menu Width', 'newTheme'),
                'type' => Controls_Manager::SLIDER,
                'size_units' => ['px', '%'],
                'range' => [
                    'px' => ['min' => 200, 'max' => 500],
                    '%' => ['min' => 50, 'max' => 100],
                ],
                'default' => [
                    'unit' => 'px',
                    'size' => 300,
                ],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__mobile-content' => 'width: {{SIZE}}{{UNIT}};',
                ],
            ]
        );

        $this->add_group_control(
            Group_Control_Typography::get_type(),
            [
                'name' => 'mobile_menu_typography',
                'label' => esc_html__('Typography', 'newTheme'),
                'selector' => '{{WRAPPER}} .adv-mega-menu__mobile-nav a',
            ]
        );

        $this->add_control(
            'mobile_menu_item_color',
            [
                'label' => esc_html__('Item Color', 'newTheme'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__mobile-nav a' => 'color: {{VALUE}};',
                ],
            ]
        );

        $this->add_control(
            'mobile_menu_item_bg_color',
            [
                'label' => esc_html__('Item Background Color', 'newTheme'),
                'type' => Controls_Manager::COLOR,
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__mobile-nav a' => 'background-color: {{VALUE}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'mobile_menu_item_padding',
            [
                'label' => esc_html__('Item Padding', 'newTheme'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px'],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__mobile-nav a' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->add_responsive_control(
            'mobile_submenu_padding',
            [
                'label' => esc_html__('Submenu Padding', 'newTheme'),
                'type' => Controls_Manager::DIMENSIONS,
                'size_units' => ['px'],
                'selectors' => [
                    '{{WRAPPER}} .adv-mega-menu__mobile-nav ul ul' => 'padding: {{TOP}}{{UNIT}} {{RIGHT}}{{UNIT}} {{BOTTOM}}{{UNIT}} {{LEFT}}{{UNIT}};',
                ],
            ]
        );

        $this->end_controls_section();
    }

    protected function render()
    {
        $settings = $this->get_settings_for_display();
        $widget_id = $this->get_id();
        
        // Pre-load all mega menu post styles
        $this->preload_mega_menu_styles($settings);
        
        $is_sticky = $settings['sticky_menu'] === 'yes' ? 'adv-mega-menu--sticky' : '';
        $animation_class = 'animation-' . $settings['submenu_animation'];
        $mega_menu_position = 'position-' . $settings['mega_menu_position'];
        $breakpoint = $settings['mobile_breakpoint'];

        // Map breakpoint to Bootstrap classes
        $desktop_class = "d-none d-{$breakpoint}-flex";
        $mobile_class = "d-{$breakpoint}-none";
        ?>
        <div class="adv-mega-menu <?php echo esc_attr($is_sticky); ?>" data-widget-id="<?php echo esc_attr($widget_id); ?>">
                <!-- Desktop Menu -->
                <nav class="adv-mega-menu__desktop <?php echo esc_attr($desktop_class); ?>">
                    <ul class="adv-mega-menu__nav">
                        <?php
                        if ($settings['menu_style'] === 'repeater') {
                            $this->render_repeater_menu($settings);
                        } else {
                            $menu_items = wp_get_nav_menu_items($settings['wordpress_menu']);
                            if ($menu_items) {
                                $this->render_wordpress_menu($menu_items, 0, $animation_class, $mega_menu_position);
                            } else {
                                echo '<li>' . esc_html__('No menu items found. Please select a valid WordPress menu.', 'newTheme') . '</li>';
                            }
                        }
                        ?>
                    </ul>
                </nav>

                <!-- Mobile Menu -->
                <div class="adv-mega-menu__hamburger <?php echo esc_attr($mobile_class); ?>">
                    <button class="adv-mega-menu__hamburger-toggle" aria-label="<?php esc_attr_e('Toggle Menu', 'newTheme'); ?>">
                        <i class="<?php echo esc_attr($settings['hamburger_icon']['value']); ?>"></i>
                    </button>
                </div>
                <div class="adv-mega-menu__mobile-menu">
                    <div class="adv-mega-menu__mobile-overlay"></div>
                    <div class="adv-mega-menu__mobile-content">
                        <button class="adv-mega-menu__mobile-close" aria-label="<?php esc_attr_e('Close Menu', 'newTheme'); ?>">×</button>
                        <ul class="adv-mega-menu__mobile-nav">
                            <?php
                            if ($settings['menu_style'] === 'repeater') {
                                $this->render_repeater_mobile_menu($settings);
                            } else {
                                $menu_items = wp_get_nav_menu_items($settings['wordpress_menu']);
                                if ($menu_items) {
                                    $this->render_wordpress_mobile_menu($menu_items);
                                } else {
                                    echo '<li>' . esc_html__('No menu items found. Please select a valid WordPress menu.', 'newTheme') . '</li>';
                                }
                            }
                            ?>
                        </ul>
                    </div>
                </div>
            </div>

        <?php
    }

    protected function render_repeater_menu($settings)
    {
        foreach ($settings['menu_items'] as $index => $item) {
            $has_submenu = $item['show_submenu'] === 'yes' && (
                ($item['submenu_type'] === 'wordpress' && !empty($item['submenu_wordpress'])) ||
                ($item['submenu_type'] === 'mega_menu' && !empty($item['submenu_mega_menu']))
            );
            $animation_class = 'animation-' . $settings['submenu_animation'];
            $mega_menu_position = 'position-' . $settings['mega_menu_position'];
            ?>

            <li class="adv-mega-menu__item <?php echo $has_submenu ? 'has-submenu' : ''; ?>">
                <?php if (!empty($item['show_new_badge']) && $item['show_new_badge'] === 'yes'): ?>
                    <span class="adv-mega-menu__new-badge">New</span>
                <?php endif; ?>

                <?php 
                $icon_position = !empty($item['menu_icon_position']) ? $item['menu_icon_position'] : 'left';
                $link_class = 'adv-mega-menu__link adv-mega-menu__link--icon-' . $icon_position;
                ?>
                <a href="<?php echo esc_url($item['menu_link']['url']); ?>" class="<?php echo esc_attr($link_class); ?>">
                    <?php if (($icon_position === 'top' || $icon_position === 'left') && $item['menu_icon_type'] === 'icon' && !empty($item['menu_icon']['value'])): ?>
                        <i class="<?php echo esc_attr($item['menu_icon']['value']); ?>"></i>
                    <?php elseif (($icon_position === 'top' || $icon_position === 'left') && $item['menu_icon_type'] === 'image' && !empty($item['menu_image']['url'])): ?>
                        <img src="<?php echo esc_url($item['menu_image']['url']); ?>" alt="<?php echo esc_attr($item['menu_title']); ?>" />
                    <?php endif; ?>
                    
                    <span><?php echo esc_html($item['menu_title']); ?></span>
                    
                    <?php if (($icon_position === 'bottom' || $icon_position === 'right') && $item['menu_icon_type'] === 'icon' && !empty($item['menu_icon']['value'])): ?>
                        <i class="<?php echo esc_attr($item['menu_icon']['value']); ?>"></i>
                    <?php elseif (($icon_position === 'bottom' || $icon_position === 'right') && $item['menu_icon_type'] === 'image' && !empty($item['menu_image']['url'])): ?>
                        <img src="<?php echo esc_url($item['menu_image']['url']); ?>" alt="<?php echo esc_attr($item['menu_title']); ?>" />
                    <?php endif; ?>
                </a>

                
                <?php if ($has_submenu): ?>
                    <?php if ($item['submenu_type'] === 'wordpress' && !empty($item['submenu_wordpress'])): ?>
                        <ul class="adv-mega-menu__submenu <?php echo esc_attr($animation_class); ?>">
                            <?php
                            $submenu_items = wp_get_nav_menu_items($item['submenu_wordpress']);
                            if ($submenu_items) {
                                $this->render_wordpress_menu($submenu_items, 0, $animation_class, $mega_menu_position);
                            }
                            ?>
                        </ul>
                    <?php elseif ($item['submenu_type'] === 'mega_menu' && !empty($item['submenu_mega_menu'])): ?>
                        <div class="adv-mega-menu__megamenu <?php echo esc_attr($animation_class . ' ' . $mega_menu_position); ?>">
                            <?php
                            $mega_menu_post = get_post($item['submenu_mega_menu']);
                            if ($mega_menu_post) {
                                // Enqueue Elementor styles for this post
                                $this->enqueue_mega_menu_styles($mega_menu_post->ID);
                                
                                // Check if Elementor is active and this post was built with Elementor
                                if (class_exists('\Elementor\Plugin') && \Elementor\Plugin::$instance->documents->get($mega_menu_post->ID)->is_built_with_elementor()) {
                                    // Render with Elementor frontend
                                    echo \Elementor\Plugin::$instance->frontend->get_builder_content_for_display($mega_menu_post->ID);
                                } else {
                                    // Fallback for non-Elementor content
                                    echo apply_filters('the_content', $mega_menu_post->post_content);
                                }
                            }
                            ?>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>
            </li>
            <?php
        }
    }

    protected function render_repeater_mobile_menu($settings)
    {
        foreach ($settings['menu_items'] as $item) {
            $has_submenu = $item['show_submenu'] === 'yes' && $item['submenu_type'] === 'wordpress' && !empty($item['submenu_wordpress']);
            ?>
            <li class="<?php echo $has_submenu ? 'has-submenu' : ''; ?>">
                <?php 
                $icon_position = !empty($item['menu_icon_position']) ? $item['menu_icon_position'] : 'left';
                $mobile_link_class = 'adv-mega-menu__mobile-link adv-mega-menu__mobile-link--icon-' . $icon_position;
                ?>
                <a href="<?php echo esc_url($item['menu_link']['url']); ?>" class="<?php echo esc_attr($mobile_link_class); ?>">
                    <?php if (($icon_position === 'top' || $icon_position === 'left') && $item['menu_icon_type'] === 'icon' && !empty($item['menu_icon']['value'])): ?>
                        <i class="<?php echo esc_attr($item['menu_icon']['value']); ?>"></i>
                    <?php elseif (($icon_position === 'top' || $icon_position === 'left') && $item['menu_icon_type'] === 'image' && !empty($item['menu_image']['url'])): ?>
                        <img src="<?php echo esc_url($item['menu_image']['url']); ?>" alt="<?php echo esc_attr($item['menu_title']); ?>" />
                    <?php endif; ?>
                    
                    <span><?php echo esc_html($item['menu_title']); ?></span>
                    
                    <?php if (($icon_position === 'bottom' || $icon_position === 'right') && $item['menu_icon_type'] === 'icon' && !empty($item['menu_icon']['value'])): ?>
                        <i class="<?php echo esc_attr($item['menu_icon']['value']); ?>"></i>
                    <?php elseif (($icon_position === 'bottom' || $icon_position === 'right') && $item['menu_icon_type'] === 'image' && !empty($item['menu_image']['url'])): ?>
                        <img src="<?php echo esc_url($item['menu_image']['url']); ?>" alt="<?php echo esc_attr($item['menu_title']); ?>" />
                    <?php endif; ?>
                </a>
                <?php if ($has_submenu): ?>
                    <ul>
                        <?php
                        $submenu_items = wp_get_nav_menu_items($item['submenu_wordpress']);
                        if ($submenu_items) {
                            $this->render_wordpress_mobile_menu($submenu_items);
                        }
                        ?>
                    </ul>
                <?php endif; ?>
            </li>
            <?php
        }
    }

    protected function render_wordpress_menu($items, $parent_id = 0, $animation_class = '', $mega_menu_position = '')
    {
        $menu_tree = [];
        foreach ($items as $item) {
            $menu_tree[$item->menu_item_parent][] = $item;
        }

        if (!isset($menu_tree[$parent_id])) {
            return;
        }

        foreach ($menu_tree[$parent_id] as $item) {
            $has_children = isset($menu_tree[$item->ID]);
            $classes = $has_children ? 'adv-mega-menu__item has-submenu' : 'adv-mega-menu__item';
            ?>
            <li class="<?php echo esc_attr($classes); ?>">
                <a href="<?php echo esc_url($item->url); ?>">
                    <?php echo esc_html($item->title); ?>
                </a>
                <?php if ($has_children): ?>
                    <ul class="adv-mega-menu__submenu <?php echo esc_attr($animation_class); ?>">
                        <?php $this->render_wordpress_menu($items, $item->ID, $animation_class, $mega_menu_position); ?>
                    </ul>
                <?php endif; ?>
            </li>
            <?php
        }
    }

    protected function render_wordpress_mobile_menu($items, $parent_id = 0)
    {
        $menu_tree = [];
        foreach ($items as $item) {
            $menu_tree[$item->menu_item_parent][] = $item;
        }

        if (!isset($menu_tree[$parent_id])) {
            return;
        }

        foreach ($menu_tree[$parent_id] as $item) {
            $has_children = isset($menu_tree[$item->ID]);
            ?>
            <li class="<?php echo $has_children ? 'has-submenu' : ''; ?>">
                <a href="<?php echo esc_url($item->url); ?>">
                    <?php echo esc_html($item->title); ?>
                </a>
                <?php if ($has_children): ?>
                    <ul>
                        <?php $this->render_wordpress_mobile_menu($items, $item->ID); ?>
                    </ul>
                <?php endif; ?>
            </li>
            <?php
        }
    }
}

