<?php
/**
 * MenuX Free — Admin Page
 * Registers admin menu and renders the main configuration page.
 * @package MenuX
 */

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

add_action('admin_menu', 'menux_register_admin_page');
function menux_register_admin_page() {
    add_menu_page('Giuliomax Menu Builder', 'Menu Builder', 'manage_options', 'menux', 'menux_render_admin_html', 'dashicons-menu-alt3', 100);
}

function menux_render_admin_html() {
    if (!current_user_can('manage_options')) return;

    if (isset($_POST['menux_save_all']) && check_admin_referer('menux_save_action', 'menux_nonce')) {

        // Detect active languages from installed multilingual plugins
        $supported_langs = menux_get_supported_languages();
        $valid_lang_codes = array_column($supported_langs, 'code');

        $menu_items = array();
        if (!empty($_POST['menu_items']) && is_array($_POST['menu_items'])) {
            foreach ( wp_unslash( $_POST['menu_items'] ) as $item ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
                $type = sanitize_text_field($item['type']);
                $visibility = sanitize_text_field($item['visibility'] ?? 'all');
                // Accept 'all', 'logged_in', 'logged_out', or any valid WP role slug
                $valid_vis = array_merge(array('all','logged_in','logged_out'), array_keys(wp_roles()->roles));
                if (!in_array($visibility, $valid_vis, true)) {
                    $visibility = 'all';
                }

                $menu_item_data = array(
                    'type'       => $type,
                    'icon'       => sanitize_text_field($item['icon'] ?? ''),
                    'visibility' => $visibility,
                    // Badge
                    'badge'      => sanitize_text_field($item['badge'] ?? ''),
                    'badge_color'=> !empty($item['badge_color']) ? sanitize_hex_color($item['badge_color']) : '',
                    'badge_bg'   => !empty($item['badge_bg'])    ? sanitize_hex_color($item['badge_bg'])    : '',
                    // Link target
                    'target'     => in_array($item['target'] ?? '', array('','_blank'), true) ? ($item['target'] ?? '') : '',
                    // Item key univoco per statistiche
                    'item_key'   => !empty($item['item_key']) ? sanitize_key($item['item_key']) : '',
                    // Submenu (JSON-encoded array di voci figlie)
                    'children'   => array(),
                    // ──── FEATURE: Notification Dot ────
                    'notif_dot'  => !empty($item['notif_dot']) ? '1' : '0',
                    // ──── FEATURE: CTA Button Style ────
                    'cta_style'         => !empty($item['cta_style']) && $item['cta_style'] === '1' ? '1' : '0',
                    'cta_bg'            => !empty($item['cta_bg'])       ? sanitize_hex_color($item['cta_bg'])       : '#667eea',
                    'cta_color'         => !empty($item['cta_color'])    ? sanitize_hex_color($item['cta_color'])    : '#ffffff',
                    'cta_hover_bg'      => !empty($item['cta_hover_bg']) ? sanitize_hex_color($item['cta_hover_bg']) : '',
                    'cta_border_radius' => isset($item['cta_border_radius']) ? absint($item['cta_border_radius']) : 6,
                    // ──── FEATURE: Scheduled Items ────
                    'schedule_start' => sanitize_text_field($item['schedule_start'] ?? ''),
                    'schedule_end'   => sanitize_text_field($item['schedule_end']   ?? ''),
                    // ──── FEATURE: Condizionali avanzati ────
                    'cond_roles'    => sanitize_text_field($item['cond_roles']   ?? ''),  // comma-separated WP roles
                    'cond_devices'  => sanitize_text_field($item['cond_devices'] ?? ''),  // mobile,tablet,desktop
                    'cond_pages'    => sanitize_text_field($item['cond_pages']   ?? ''),  // page IDs comma-separated
                    'cond_time_from'=> sanitize_text_field($item['cond_time_from']?? ''), // HH:MM
                    'cond_time_to'  => sanitize_text_field($item['cond_time_to'] ?? ''),  // HH:MM
                    'cond_utm'      => sanitize_text_field($item['cond_utm']     ?? ''),  // utm_source value
                    // ──── FEATURE: Multi-menu location ────
                    'menu_location' => sanitize_key($item['menu_location'] ?? 'primary'),
                    // ──── Mega Menu (filled in a second pass from mega_data[item_key]) ────
                    'mega_menu'       => '0',
                    'mega_full_width' => '1',
                    'mega_columns'    => array(),
                );

                // Salva le etichette per ogni lingua disponibile (codici dinamici)
                if (!empty($valid_lang_codes)) {
                    foreach ($valid_lang_codes as $code) {
                        $safe_key = menux_code_to_key($code);
                        $menu_item_data[$safe_key] = sanitize_text_field($item[$safe_key] ?? '');
                    }
                } else {
                    // Fallback: salva campi generici se l'API non è configurata
                    foreach ($item as $k => $v) {
                        if (preg_match('/^lang_[a-zA-Z0-9_]+$/', $k)) {
                            $menu_item_data[$k] = sanitize_text_field($v);
                        }
                    }
                }

                if ($type === 'page') {
                    $menu_item_data['id'] = intval($item['id']);
                    if (empty($menu_item_data['item_key'])) $menu_item_data['item_key'] = 'page_' . intval($item['id']);
                    // Salva figli
                    if (!empty($item['children']) && is_array($item['children'])) {
                        foreach ($item['children'] as $child) {
                            $ch = array(
                                'type'     => sanitize_text_field($child['type'] ?? 'custom'),
                                'icon'     => sanitize_text_field($child['icon'] ?? ''),
                                'target'   => in_array($child['target'] ?? '', array('','_blank'), true) ? ($child['target'] ?? '') : '',
                                'children' => array(),
                            );
                            foreach ($child as $ck => $cv) {
                                if (preg_match('/^lang_[a-zA-Z0-9_]+$/', $ck)) $ch[$ck] = sanitize_text_field($cv);
                            }
                            if ($ch['type'] === 'page')   { $ch['id']  = intval($child['id'] ?? 0); }
                            else                           { $ch['url'] = esc_url_raw($child['url'] ?? ''); }
                            // 3° livello
                            if (!empty($child['children']) && is_array($child['children'])) {
                                foreach ($child['children'] as $gc) {
                                    $gch = array(
                                        'type'   => sanitize_text_field($gc['type'] ?? 'custom'),
                                        'icon'   => sanitize_text_field($gc['icon'] ?? ''),
                                        'target' => in_array($gc['target'] ?? '', array('','_blank'), true) ? ($gc['target'] ?? '') : '',
                                    );
                                    foreach ($gc as $gk => $gv) {
                                        if (preg_match('/^lang_[a-zA-Z0-9_]+$/', $gk)) $gch[$gk] = sanitize_text_field($gv);
                                    }
                                    if ($gch['type'] === 'page') $gch['id']  = intval($gc['id'] ?? 0);
                                    else                          $gch['url'] = esc_url_raw($gc['url'] ?? '');
                                    $ch['children'][] = $gch;
                                }
                            }
                            $menu_item_data['children'][] = $ch;
                        }
                    }
                    $menu_items[] = $menu_item_data;
                } elseif ($type === 'custom') {
                    if (empty($item['url'])) continue;
                    $menu_item_data['url'] = esc_url_raw($item['url']);
                    if (empty($menu_item_data['item_key'])) $menu_item_data['item_key'] = 'custom_' . md5($item['url']);
                    if (!empty($item['children']) && is_array($item['children'])) {
                        foreach ($item['children'] as $child) {
                            $ch = array(
                                'type'     => sanitize_text_field($child['type'] ?? 'custom'),
                                'icon'     => sanitize_text_field($child['icon'] ?? ''),
                                'target'   => in_array($child['target'] ?? '', array('','_blank'), true) ? ($child['target'] ?? '') : '',
                                'children' => array(),
                            );
                            foreach ($child as $ck => $cv) {
                                if (preg_match('/^lang_[a-zA-Z0-9_]+$/', $ck)) $ch[$ck] = sanitize_text_field($cv);
                            }
                            if ($ch['type'] === 'page') $ch['id']  = intval($child['id'] ?? 0);
                            else                         $ch['url'] = esc_url_raw($child['url'] ?? '');
                            $menu_item_data['children'][] = $ch;
                        }
                    }
                    $menu_items[] = $menu_item_data;
                }
            }
        }
        // ── Apply mega settings keyed by item_key (order-independent fix) ──
        $mega_post = array();
        if ( ! empty( $_POST['mega_data'] ) && is_array( $_POST['mega_data'] ) ) {
            foreach ( wp_unslash( $_POST['mega_data'] ) as $raw_key => $mdata ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
                if ( ! is_array( $mdata ) ) continue;
                $key = sanitize_key( $raw_key );
                $mega_post[ $key ] = array(
                    'mega_menu'       => ( ! empty( $mdata['mega_menu'] ) && $mdata['mega_menu'] === '1' ) ? '1' : '0',
                    'mega_full_width' => ! empty( $mdata['mega_full_width'] ) ? '1' : '0',
                    'mega_columns'    => Menux_MegaMenu::sanitize_columns( $mdata['mega_columns_json'] ?? '' ),
                    'mega_style'      => Menux_MegaMenu::sanitize_style( $mdata['mega_style_json'] ?? '' ),
                );
            }
        }
        // Build a fallback map from the current DB so mega config is not erased when
        // JS fails to submit mega_data for a particular item (e.g. a JS error during
        // serialisation would otherwise silently reset mega_menu to '0').
        $existing_mega = array();
        foreach ( get_option( 'menux_menu_items', array() ) as $ei ) {
            $ekey = $ei['item_key'] ?? '';
            if ( $ekey && ( $ei['mega_menu'] ?? '0' ) === '1' ) {
                $existing_mega[ $ekey ] = array(
                    'mega_menu'       => '1',
                    'mega_full_width' => $ei['mega_full_width'] ?? '1',
                    'mega_columns'    => $ei['mega_columns']    ?? array(),
                    'mega_style'      => $ei['mega_style']      ?? array(),
                );
            }
        }

        foreach ( $menu_items as &$saved_item ) {
            $key = $saved_item['item_key'] ?? '';
            if ( $key && isset( $mega_post[ $key ] ) ) {
                $saved_item['mega_menu']       = $mega_post[ $key ]['mega_menu'];
                $saved_item['mega_full_width'] = $mega_post[ $key ]['mega_full_width'];
                $saved_item['mega_columns']    = $mega_post[ $key ]['mega_columns'];
                $saved_item['mega_style']      = $mega_post[ $key ]['mega_style'];
            } elseif ( $key && isset( $existing_mega[ $key ] ) ) {
                // mega_data not submitted for this item — preserve existing DB state.
                // INVARIANT: a user disabling the mega toggle does NOT land here, because
                // the panel's always-rendered hidden inputs (mega_columns_json/mega_style_json
                // in megamenu-panel.php) keep the mega_data[key] entry present in the POST
                // with mega_menu absent → the if-branch above saves '0'. This branch only
                // fires when the entire entry is missing (item row never rendered, or POST
                // truncated by max_input_vars). Do not make those hidden inputs conditional,
                // or disabling a mega menu would silently resurrect it from the DB.
                $saved_item['mega_menu']       = $existing_mega[ $key ]['mega_menu'];
                $saved_item['mega_full_width'] = $existing_mega[ $key ]['mega_full_width'];
                $saved_item['mega_columns']    = $existing_mega[ $key ]['mega_columns'];
                $saved_item['mega_style']      = $existing_mega[ $key ]['mega_style'];
            }
        }
        unset( $saved_item );

        update_option('menux_menu_items', $menu_items);

        // Salva stile
        $raw_style  = isset($_POST['menux_style']) && is_array($_POST['menux_style']) ? wp_unslash( $_POST['menux_style'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        $use_flags  = isset($_POST['menux_style_use']) && is_array($_POST['menux_style_use']) ? wp_unslash( $_POST['menux_style_use'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        
        $color_keys = array(
            'container_bg', 'container_border',
            'link_color', 'link_hover_color', 'link_hover_bg',
            'link_active_color', 'link_active_border', 'link_active_bg',
            'hamburger_color', 'hamburger_bg', 'sticky_bg',
            'submenu_bg', 'submenu_border', 'submenu_link_color',
            'submenu_hover_bg', 'submenu_hover_link_color',
            'last_item_color', 'last_item_hover_color', 'last_item_bg',
            'close_btn_color', 'close_btn_bg',
            'mobile_link_color', 'mobile_link_hover_color', 'mobile_link_active_color',
        );
        
        $saved_style = array();
        foreach ($color_keys as $k) {
            $saved_style[$k] = (!empty($use_flags[$k]) && !empty($raw_style[$k])) ? sanitize_hex_color($raw_style[$k]) : '';
        }
        $saved_style['container_bg_gradient']   = isset( $raw_style['container_bg_gradient'] )   ? str_replace( array( ';', '{', '}' ), '', wp_strip_all_tags( $raw_style['container_bg_gradient'] ) )   : '';
        $saved_style['link_hover_bg_gradient']  = isset( $raw_style['link_hover_bg_gradient'] )  ? str_replace( array( ';', '{', '}' ), '', wp_strip_all_tags( $raw_style['link_hover_bg_gradient'] ) )  : '';
        $saved_style['link_active_bg_gradient'] = isset( $raw_style['link_active_bg_gradient'] ) ? str_replace( array( ';', '{', '}' ), '', wp_strip_all_tags( $raw_style['link_active_bg_gradient'] ) ) : '';
        $saved_style['font_size']               = isset($raw_style['font_size'])          && $raw_style['font_size']         !== '' ? intval($raw_style['font_size'])              : '';
        $saved_style['font_weight']             = isset($raw_style['font_weight'])        && $raw_style['font_weight']       !== '' ? sanitize_text_field($raw_style['font_weight']) : '';
        $saved_style['gap']                     = isset($raw_style['gap'])                && $raw_style['gap']               !== '' ? intval($raw_style['gap'])                    : '20';
        $saved_style['padding_x']               = isset($raw_style['padding_x'])          && $raw_style['padding_x']         !== '' ? intval($raw_style['padding_x'])              : '0';
        $saved_style['padding_y']               = isset($raw_style['padding_y'])          && $raw_style['padding_y']         !== '' ? intval($raw_style['padding_y'])              : '0';
        $saved_style['link_border_radius']      = isset($raw_style['link_border_radius']) && $raw_style['link_border_radius'] !== '' ? intval($raw_style['link_border_radius'])     : '';
        $saved_style['mobile_breakpoint']       = isset($raw_style['mobile_breakpoint'])  && $raw_style['mobile_breakpoint'] !== '' ? intval($raw_style['mobile_breakpoint'])      : '768';
        $saved_style['mobile_breakpoint_mode']  = in_array($raw_style['mobile_breakpoint_mode'] ?? 'manual', array('manual','auto'), true) ? ($raw_style['mobile_breakpoint_mode'] ?? 'manual') : 'manual';
        $saved_style['hamburger_style']         = isset($raw_style['hamburger_style'])    ? sanitize_text_field($raw_style['hamburger_style'])    : 'classic';
        $saved_style['hamburger_align']         = isset($raw_style['hamburger_align'])    ? sanitize_text_field($raw_style['hamburger_align'])    : 'flex-end';
        $saved_style['mobile_menu_pad']         = isset($raw_style['mobile_menu_pad'])    ? intval($raw_style['mobile_menu_pad'])                 : '0';
        $saved_style['mobile_menu_shadow']      = isset($raw_style['mobile_menu_shadow']) ? '1' : '0';
        // ──── Nuovi: modalità apertura ────
        $saved_style['mobile_open_style']        = in_array($raw_style['mobile_open_style'] ?? 'dropdown', array('dropdown','fullscreen','drawer-left','drawer-right'), true) ? ($raw_style['mobile_open_style'] ?? 'dropdown') : 'dropdown';
        $saved_style['mobile_overlay_bg']        = !empty($raw_style['mobile_overlay_bg']) ? ( sanitize_hex_color($raw_style['mobile_overlay_bg']) ?: '#000000' ) : '#000000';
        $saved_style['mobile_overlay_opacity']   = isset($raw_style['mobile_overlay_opacity']) ? min(1, max(0, floatval($raw_style['mobile_overlay_opacity']))) : '0.9';
        $saved_style['mobile_overlay_blur']      = isset($raw_style['mobile_overlay_blur'])    ? intval($raw_style['mobile_overlay_blur'])    : '0';
        $saved_style['mobile_fullscreen_align']  = in_array($raw_style['mobile_fullscreen_align'] ?? 'center', array('center','flex-start','flex-end'), true) ? ($raw_style['mobile_fullscreen_align'] ?? 'center') : 'center';
        $saved_style['mobile_drawer_width']      = isset($raw_style['mobile_drawer_width'])    ? intval($raw_style['mobile_drawer_width'])     : '280';
        $saved_style['mobile_open_animation']    = in_array($raw_style['mobile_open_animation'] ?? 'fade', array('fade','slide','scale'), true) ? ($raw_style['mobile_open_animation'] ?? 'fade') : 'fade';
        $saved_style['mobile_accordion']         = isset( $raw_style['mobile_accordion'] ) ? '1' : '0';
        // Typography avanzata
        $saved_style['google_font']             = isset($raw_style['google_font'])        ? sanitize_text_field($raw_style['google_font'])        : '';
        $saved_style['font_family']             = isset($raw_style['font_family'])        ? sanitize_text_field($raw_style['font_family'])        : '';
        $saved_style['letter_spacing']          = isset($raw_style['letter_spacing'])     ? floatval($raw_style['letter_spacing'])                : '';
        $saved_style['text_transform']          = in_array($raw_style['text_transform'] ?? '', array('none','uppercase','lowercase','capitalize'), true) ? ($raw_style['text_transform'] ?? 'none') : 'none';
        $saved_style['link_transition']         = isset($raw_style['link_transition'])    && is_numeric($raw_style['link_transition']) ? floatval($raw_style['link_transition']) : '0.3';
        // Link avanzato
        $saved_style['link_active_font_weight'] = isset($raw_style['link_active_font_weight']) ? sanitize_text_field($raw_style['link_active_font_weight']) : '';
        // Animazioni
        $saved_style['link_animation']          = in_array($raw_style['link_animation'] ?? 'none', array('none','pulse','shake','bounce','glow','lift','scale','underline'), true) ? ($raw_style['link_animation'] ?? 'none') : 'none';
        // Layout avanzato
        $saved_style['nav_justify']             = in_array($raw_style['nav_justify'] ?? 'flex-end', array('flex-start','center','flex-end','space-between','space-evenly'), true) ? ($raw_style['nav_justify'] ?? 'flex-end') : 'flex-end';
        $saved_style['push_last_item']          = isset($raw_style['push_last_item'])     ? '1' : '0';
        // Entrance animation
        $saved_style['entrance_animation']      = in_array($raw_style['entrance_animation'] ?? 'none', array('none','fadeIn','slideDown','slideUp','slideLeft','slideRight','zoomIn','flipX'), true) ? ($raw_style['entrance_animation'] ?? 'none') : 'none';
        $saved_style['entrance_duration']       = isset($raw_style['entrance_duration'])   && is_numeric($raw_style['entrance_duration']) ? round(floatval($raw_style['entrance_duration']), 2) : '0.5';
        $saved_style['entrance_delay']          = isset($raw_style['entrance_delay'])      && is_numeric($raw_style['entrance_delay'])    ? round(floatval($raw_style['entrance_delay']), 2)    : '0';
        $saved_style['entrance_stagger']        = isset($raw_style['entrance_stagger'])    && is_numeric($raw_style['entrance_stagger'])  ? round(floatval($raw_style['entrance_stagger']), 3)  : '0';
        // Sticky
        $saved_style['container_border_radius']  = isset($raw_style['container_border_radius']) && $raw_style['container_border_radius'] !== '' ? intval($raw_style['container_border_radius']) : '';
        $saved_style['sticky']                  = isset($raw_style['sticky'])             ? '1' : '0';
        $saved_style['sticky_mirror']           = isset($raw_style['sticky_mirror'])      ? '1' : '0';
        $saved_style['sticky_shadow']           = isset($raw_style['sticky_shadow'])      ? '1' : '0';
        $saved_style['sticky_z_index']          = isset($raw_style['sticky_z_index'])     ? intval($raw_style['sticky_z_index'])                  : '9999';
        $saved_style['sticky_justify']          = in_array($raw_style['sticky_justify'] ?? 'flex-start', array('flex-start','center','flex-end','space-between'), true) ? ($raw_style['sticky_justify'] ?? 'flex-start') : 'flex-start';
        $saved_style['sticky_align_items']      = in_array($raw_style['sticky_align_items'] ?? 'center', array('flex-start','center','flex-end'), true) ? ($raw_style['sticky_align_items'] ?? 'center') : 'center';
        $saved_style['sticky_padding_x']        = isset($raw_style['sticky_padding_x']) && $raw_style['sticky_padding_x'] !== '' ? intval($raw_style['sticky_padding_x']) : '';
        $saved_style['sticky_padding_y']        = isset($raw_style['sticky_padding_y']) && $raw_style['sticky_padding_y'] !== '' ? intval($raw_style['sticky_padding_y']) : '';
        $saved_style['sticky_transition']       = isset($raw_style['sticky_transition']) && is_numeric($raw_style['sticky_transition']) ? max(0, min(2, round(floatval($raw_style['sticky_transition']), 2))) : '0.3';
        $saved_style['sticky_shrink']           = isset($raw_style['sticky_shrink'])      ? '1' : '0';
        // Scroll progress bar
        $saved_style['progress_bar_enabled']    = isset($raw_style['progress_bar_enabled']) ? '1' : '0';
        $saved_style['progress_bar_color']      = isset($raw_style['progress_bar_color']) ? ( sanitize_hex_color($raw_style['progress_bar_color']) ?: '#667eea' ) : '#667eea';
        $saved_style['progress_bar_height']     = isset($raw_style['progress_bar_height']) && $raw_style['progress_bar_height'] !== '' ? max(1, min(10, intval($raw_style['progress_bar_height']))) : '3';
        $saved_style['progress_bar_position']   = in_array($raw_style['progress_bar_position'] ?? 'bottom', array('bottom','top'), true) ? ($raw_style['progress_bar_position'] ?? 'bottom') : 'bottom';
        // Scroll spy
        $saved_style['scroll_spy']        = isset( $raw_style['scroll_spy'] ) ? '1' : '0';
        $saved_style['scroll_spy_offset'] = isset( $raw_style['scroll_spy_offset'] ) && is_numeric( $raw_style['scroll_spy_offset'] ) ? max( 0, min( 500, intval( $raw_style['scroll_spy_offset'] ) ) ) : 80;
        $saved_style['scroll_spy_smooth'] = isset( $raw_style['scroll_spy_smooth'] ) ? '1' : '0';
        // Dark mode
        $saved_style['dark_mode']               = in_array($raw_style['dark_mode'] ?? 'light', array('light','dark','auto'), true) ? ($raw_style['dark_mode'] ?? 'light') : 'light';
        // Dropdown indicator
        $saved_style['dropdown_indicator']       = in_array( $raw_style['dropdown_indicator'] ?? 'triangle', array('triangle','chevron','dot','none'), true ) ? ( $raw_style['dropdown_indicator'] ?? 'triangle' ) : 'triangle';
        $saved_style['dropdown_indicator_color'] = ! empty( $use_flags['dropdown_indicator_color'] ) && ! empty( $raw_style['dropdown_indicator_color'] ) ? ( sanitize_hex_color( $raw_style['dropdown_indicator_color'] ) ?: '' ) : '';
        $saved_style['dropdown_indicator_size']  = isset( $raw_style['dropdown_indicator_size'] ) && is_numeric( $raw_style['dropdown_indicator_size'] ) ? max( 6, min( 24, intval( $raw_style['dropdown_indicator_size'] ) ) ) : 10;
        $saved_style['dropdown_indicator_rotate']= isset( $raw_style['dropdown_indicator_rotate'] ) ? '1' : '0';
        // Submenu
        $saved_style['submenu_shadow']          = isset($raw_style['submenu_shadow'])     ? '1' : '0';
        $saved_style['submenu_animation']       = in_array($raw_style['submenu_animation'] ?? 'fade', array('fade','slide','none'), true) ? ($raw_style['submenu_animation'] ?? 'fade') : 'fade';
        $saved_style['submenu_border_radius']   = isset($raw_style['submenu_border_radius'])  && $raw_style['submenu_border_radius']  !== '' ? max(0, min(32, intval($raw_style['submenu_border_radius'])))  : '10';
        $saved_style['submenu_padding_x']       = isset($raw_style['submenu_padding_x'])      && $raw_style['submenu_padding_x']      !== '' ? max(0, min(48, intval($raw_style['submenu_padding_x'])))      : '16';
        $saved_style['submenu_padding_y']       = isset($raw_style['submenu_padding_y'])      && $raw_style['submenu_padding_y']      !== '' ? max(0, min(32, intval($raw_style['submenu_padding_y'])))      : '9';
        $saved_style['submenu_font_size']       = isset($raw_style['submenu_font_size'])      && $raw_style['submenu_font_size']      !== '' ? max(10, min(22, intval($raw_style['submenu_font_size'])))      : '14';
        $saved_style['submenu_font_weight']     = in_array($raw_style['submenu_font_weight'] ?? '400', array('300','400','500','600','700'), true) ? ($raw_style['submenu_font_weight'] ?? '400') : '400';
        $saved_style['submenu_min_width']       = isset($raw_style['submenu_min_width'])      && $raw_style['submenu_min_width']      !== '' ? max(80, min(600, intval($raw_style['submenu_min_width'])))     : '200';
        // ── Mega Menu panel appearance ──
        $saved_style['mega_bg']             = ! empty( $use_flags['mega_bg'] ) && ! empty( $raw_style['mega_bg'] ) ? sanitize_hex_color( $raw_style['mega_bg'] ) : '';
        $saved_style['mega_bg_gradient']    = ! empty( $raw_style['mega_bg_gradient'] ) ? wp_strip_all_tags( wp_unslash( $raw_style['mega_bg_gradient'] ) ) : '';
        $saved_style['mega_padding_y']      = isset( $raw_style['mega_padding_y'] )      && is_numeric( $raw_style['mega_padding_y'] )      ? (int) $raw_style['mega_padding_y']      : 24;
        $saved_style['mega_padding_x']      = isset( $raw_style['mega_padding_x'] )      && is_numeric( $raw_style['mega_padding_x'] )      ? (int) $raw_style['mega_padding_x']      : 32;
        $saved_style['mega_max_width']      = isset( $raw_style['mega_max_width'] )      && is_numeric( $raw_style['mega_max_width'] )      ? (int) $raw_style['mega_max_width']      : 0;
        $saved_style['mega_col_gap']        = isset( $raw_style['mega_col_gap'] )        && is_numeric( $raw_style['mega_col_gap'] )        ? (int) $raw_style['mega_col_gap']        : 16;
        $saved_style['mega_mobile_layout']  = in_array( $raw_style['mega_mobile_layout'] ?? 'list', array( 'list', 'grid2', 'hide' ), true ) ? ( $raw_style['mega_mobile_layout'] ?? 'list' ) : 'list';
        // Keep the legacy flag in sync for anything still reading it.
        $saved_style['mega_mobile_disable'] = ( $saved_style['mega_mobile_layout'] === 'hide' ) ? '1' : '0';
        // ── Search ──
        $saved_style['search_enabled']     = isset( $raw_style['search_enabled'] )   ? '1' : '0';
        $saved_style['search_icon_color']  = ! empty( $use_flags['search_icon_color'] ) && ! empty( $raw_style['search_icon_color'] ) ? sanitize_hex_color( $raw_style['search_icon_color'] ) : '';
        $saved_style['search_position']    = in_array( $raw_style['search_position'] ?? 'right', array( 'left', 'right' ), true ) ? ( $raw_style['search_position'] ?? 'right' ) : 'right';
        // ── WooCommerce cart ──
        $saved_style['woo_cart_enabled']    = isset( $raw_style['woo_cart_enabled'] )    ? '1' : '0';
        $saved_style['woo_cart_position']   = in_array( $raw_style['woo_cart_position'] ?? 'right', array( 'left', 'right' ), true ) ? ( $raw_style['woo_cart_position'] ?? 'right' ) : 'right';
        $saved_style['woo_cart_icon']       = in_array( $raw_style['woo_cart_icon'] ?? 'cart', array( 'cart', 'bag', 'basket' ), true ) ? ( $raw_style['woo_cart_icon'] ?? 'cart' ) : 'cart';
        $saved_style['woo_cart_show_count'] = isset( $raw_style['woo_cart_show_count'] ) ? '1' : '0';
        $saved_style['woo_cart_show_total'] = isset( $raw_style['woo_cart_show_total'] ) ? '1' : '0';
        $saved_style['woo_cart_minicart']   = in_array( $raw_style['woo_cart_minicart'] ?? 'hover', array( 'hover', 'click', 'off' ), true ) ? ( $raw_style['woo_cart_minicart'] ?? 'hover' ) : 'hover';
        $saved_style['woo_cart_hide_empty'] = isset( $raw_style['woo_cart_hide_empty'] ) ? '1' : '0';
        $saved_style['woo_cart_icon_color'] = ! empty( $use_flags['woo_cart_icon_color'] ) && ! empty( $raw_style['woo_cart_icon_color'] ) ? sanitize_hex_color( $raw_style['woo_cart_icon_color'] ) : '';
        $saved_style['woo_cart_badge_bg']   = ! empty( $raw_style['woo_cart_badge_bg'] ) ? ( sanitize_hex_color( $raw_style['woo_cart_badge_bg'] ) ?: '#ef4444' ) : '#ef4444';
        $saved_style['mega_border_radius']  = isset( $raw_style['mega_border_radius'] )  && is_numeric( $raw_style['mega_border_radius'] )  ? (int) $raw_style['mega_border_radius']  : 14;
        $saved_style['mega_font_size']      = isset( $raw_style['mega_font_size'] )      && is_numeric( $raw_style['mega_font_size'] )      ? (int) $raw_style['mega_font_size']      : 0;
        $saved_style['mega_link_color']       = ! empty( $use_flags['mega_link_color'] )       && ! empty( $raw_style['mega_link_color'] )       ? sanitize_hex_color( $raw_style['mega_link_color'] )       : '';
        $saved_style['mega_heading_color']    = ! empty( $use_flags['mega_heading_color'] )    && ! empty( $raw_style['mega_heading_color'] )    ? sanitize_hex_color( $raw_style['mega_heading_color'] )    : '';
        $saved_style['mega_accent_color']     = ! empty( $use_flags['mega_accent_color'] )     && ! empty( $raw_style['mega_accent_color'] )     ? sanitize_hex_color( $raw_style['mega_accent_color'] )     : '';
        $saved_style['mega_link_hover_color'] = ! empty( $use_flags['mega_link_hover_color'] ) && ! empty( $raw_style['mega_link_hover_color'] ) ? sanitize_hex_color( $raw_style['mega_link_hover_color'] ) : '';
        $saved_style['mega_desc_color']       = ! empty( $use_flags['mega_desc_color'] )       && ! empty( $raw_style['mega_desc_color'] )       ? sanitize_hex_color( $raw_style['mega_desc_color'] )       : '';
        $saved_style['mega_divider_color']    = ! empty( $use_flags['mega_divider_color'] ) && ! empty( $raw_style['mega_divider_color'] ) ? sanitize_hex_color( $raw_style['mega_divider_color'] ) : '';
        $saved_style['mega_divider_style']    = in_array( $raw_style['mega_divider_style'] ?? 'solid', array( 'solid', 'dashed', 'dotted' ), true ) ? ( $raw_style['mega_divider_style'] ?? 'solid' ) : 'solid';
        $saved_style['mega_open_duration']    = isset( $raw_style['mega_open_duration'] ) && is_numeric( $raw_style['mega_open_duration'] ) ? max( 0, min( 800, (int) $raw_style['mega_open_duration'] ) ) : 200;
        // Announcement bar
        $saved_style['announcement_enabled']      = isset( $raw_style['announcement_enabled'] ) ? '1' : '0';
        $saved_style['announcement_text']         = isset( $raw_style['announcement_text'] ) ? sanitize_text_field( wp_unslash( $raw_style['announcement_text'] ) ) : '';
        $saved_style['announcement_link']         = isset( $raw_style['announcement_link'] ) ? esc_url_raw( wp_unslash( $raw_style['announcement_link'] ) ) : '';
        $saved_style['announcement_link_target']  = ( isset( $raw_style['announcement_link_target'] ) && $raw_style['announcement_link_target'] === '_blank' ) ? '_blank' : '_self';
        $saved_style['announcement_bg']           = ! empty( $raw_style['announcement_bg'] ) ? ( sanitize_hex_color( $raw_style['announcement_bg'] ) ?: '#667eea' ) : '#667eea';
        $saved_style['announcement_text_color']   = ! empty( $raw_style['announcement_text_color'] ) ? ( sanitize_hex_color( $raw_style['announcement_text_color'] ) ?: '#ffffff' ) : '#ffffff';
        $saved_style['announcement_position']     = in_array( $raw_style['announcement_position'] ?? 'above', array( 'above', 'below' ), true ) ? ( $raw_style['announcement_position'] ?? 'above' ) : 'above';
        $saved_style['announcement_dismissible']  = isset( $raw_style['announcement_dismissible'] ) ? '1' : '0';
        $saved_style['announcement_dismiss_days'] = isset( $raw_style['announcement_dismiss_days'] ) && is_numeric( $raw_style['announcement_dismiss_days'] ) ? max( 1, min( 365, intval( $raw_style['announcement_dismiss_days'] ) ) ) : 7;
        $saved_style['announcement_font_size']    = isset( $raw_style['announcement_font_size'] ) && is_numeric( $raw_style['announcement_font_size'] ) ? max( 10, min( 24, intval( $raw_style['announcement_font_size'] ) ) ) : 14;
        $saved_style['announcement_padding_y']    = isset( $raw_style['announcement_padding_y'] ) && is_numeric( $raw_style['announcement_padding_y'] ) ? max( 4, min( 32, intval( $raw_style['announcement_padding_y'] ) ) ) : 10;
        $saved_style['announcement_countdown_enabled'] = isset( $raw_style['announcement_countdown_enabled'] ) ? '1' : '0';
        $cd_date_raw = sanitize_text_field( wp_unslash( $raw_style['announcement_countdown_date'] ?? '' ) );
        $saved_style['announcement_countdown_date']    = ( $cd_date_raw !== '' && strtotime( $cd_date_raw ) !== false ) ? $cd_date_raw : '';
        $saved_style['announcement_countdown_label']   = sanitize_text_field( wp_unslash( $raw_style['announcement_countdown_label'] ?? 'Ends in:' ) );
        $saved_style['announcement_countdown_expired'] = sanitize_text_field( wp_unslash( $raw_style['announcement_countdown_expired'] ?? '' ) );

        update_option('menux_style', $saved_style);
        // Invalida font cache
        delete_transient('menux_gfont_loaded');

        // ── Save Logo settings ──
        if ( isset( $_POST['menux_logo'] ) && is_array( $_POST['menux_logo'] ) ) {
            Menux_Logo::save( wp_unslash( $_POST['menux_logo'] ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        }

        // ── Save Accessibility settings ──
        if ( isset( $_POST['menux_accessibility'] ) && is_array( $_POST['menux_accessibility'] ) ) {
            Menux_Accessibility::save( wp_unslash( $_POST['menux_accessibility'] ) ); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
        }

        // Save WP Nav replacements
        $raw_replacements = isset( $_POST['menux_wp_nav_replacements'] ) && is_array( $_POST['menux_wp_nav_replacements'] )
            ? wp_unslash( $_POST['menux_wp_nav_replacements'] ) // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
            : array();
        $saved_replacements = array();
        foreach ( $raw_replacements as $theme_loc => $menux_loc ) {
            $theme_loc = sanitize_key( $theme_loc );
            $menux_loc = sanitize_key( $menux_loc );
            if ( $theme_loc && $menux_loc ) $saved_replacements[ $theme_loc ] = $menux_loc;
        }
        update_option( 'menux_wp_nav_replacements', $saved_replacements );

        $restored_section = sanitize_key( $_POST['menux_active_section'] ?? 'structure' );
        echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__( 'Settings saved successfully!', 'giuliomax-menu-builder' ) . '</p></div>';
        echo '<script>document.addEventListener("DOMContentLoaded",function(){ if(typeof menuxGoSection==="function") menuxGoSection(' . wp_json_encode( $restored_section ) . '); });</script>';
    }

    // Handle full reset
    if ( isset( $_POST['menux_reset_all'] ) && check_admin_referer( 'menux_reset_action', 'menux_reset_nonce' ) && current_user_can( 'manage_options' ) ) {
        delete_option( 'menux_menu_items' );
        delete_option( 'menux_style' );
        delete_option( 'menux_logo' );
        delete_option( 'menux_wp_nav_replacements' );
        delete_option( Menux_Accessibility::OPTION_KEY );
        Menux_Accessibility::clear_cache();
        delete_transient( 'menux_gfont_loaded' );
        menux_invalidate_css_cache();
        echo '<div class="notice notice-warning is-dismissible"><p><strong>' . esc_html__( 'Reset complete.', 'giuliomax-menu-builder' ) . '</strong> ' . esc_html__( 'All menu items, styles and settings have been deleted.', 'giuliomax-menu-builder' ) . '</p></div>';
    }

    $menu_items   = get_option('menux_menu_items', array());
    $menux_style = get_option('menux_style', array());
    $all_wp_pages = get_pages(array('sort_column' => 'post_title', 'sort_order' => 'ASC'));
    $supported_langs = menux_get_supported_languages();
    // Build WP roles array for visibility dropdown
    $menux_wp_roles_for_select = array_merge(
        array('all' => esc_html__( 'Everyone', 'giuliomax-menu-builder' ), 'logged_in' => esc_html__( 'Any logged-in user', 'giuliomax-menu-builder' ), 'logged_out' => esc_html__( 'Guests only (not logged in)', 'giuliomax-menu-builder' )),
        array_map(function($r){ /* translators: %s is the WordPress role name */ return sprintf( esc_html__( '%s only', 'giuliomax-menu-builder' ), translate_user_role($r['name']) ); }, wp_roles()->roles)
    );
    ?>
    <div class="wrap bm-admin-modern">
        <h1 class="wp-heading-inline" style="display:none;"><?php esc_html_e( 'MenuX Configuration', 'giuliomax-menu-builder' ); ?></h1>

        <form method="POST" id="menux-form" novalidate>
            <?php wp_nonce_field('menux_save_action', 'menux_nonce'); ?>
            <input type="hidden" name="menux_active_section" id="menux-active-section" value="<?php echo esc_attr( $_POST['menux_active_section'] ?? 'structure' ); ?>">

            <!-- ============== TOPBAR ============== -->
            <div class="bm-topbar">
                <div class="bm-topbar-brand">
                    <span class="bm-topbar-icon">🐝</span>
                    <span class="bm-topbar-title">Giuliomax menu builder</span>
                </div>
                <div class="bm-topbar-actions">
                    <button type="button" onclick="menuxHelpOpen()" class="bm-topbar-btn" style="background:rgba(255,255,255,.15);border:1px solid rgba(255,255,255,.3);color:#fff;padding:7px 16px;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;" title="<?php echo esc_attr__( 'Help &amp; Documentation', 'giuliomax-menu-builder' ); ?>">❓ <?php esc_html_e( 'Help', 'giuliomax-menu-builder' ); ?></button>
                    <input type="submit" name="menux_save_all" class="bm-topbar-btn bm-topbar-btn-save" value="<?php echo esc_attr( '💾 ' . __( 'Save Menu', 'giuliomax-menu-builder' ) ); ?>">
                </div>
            </div>
            <!-- ============== FINE TOPBAR ============== -->

            <!-- ============== STICKY PREVIEW BAR ============== -->
            <div class="bm-preview-sticky">
                <div class="bm-preview-sticky-inner">
                    <div class="bm-preview-toolbar">
                        <div class="bm-device-switcher" id="bm-device-switcher">
                            <button type="button" class="bm-device-btn active" data-device="desktop" onclick="menux_setDevice('desktop')" title="<?php echo esc_attr__( 'Desktop', 'giuliomax-menu-builder' ); ?>">🖥️ <?php esc_html_e( 'Desktop', 'giuliomax-menu-builder' ); ?></button>
                            <button type="button" class="bm-device-btn" data-device="tablet" onclick="menux_setDevice('tablet')" title="<?php echo esc_attr__( 'Tablet (768px)', 'giuliomax-menu-builder' ); ?>">📱 <?php esc_html_e( 'Tablet', 'giuliomax-menu-builder' ); ?></button>
                            <button type="button" class="bm-device-btn" data-device="mobile" onclick="menux_setDevice('mobile')" title="<?php echo esc_attr__( 'Mobile (375px)', 'giuliomax-menu-builder' ); ?>">📲 <?php esc_html_e( 'Mobile', 'giuliomax-menu-builder' ); ?></button>
                        </div>
                        <span style="color:#d1d5db;">|</span>
                        <span style="font-size:12px;color:#6b7280;">👤</span>
                        <select id="preview-auth-toggle" onchange="menux_updatePreviewAuth()" class="bm-select bm-select-sm">
                            <option value="guest"><?php esc_html_e( 'Guest', 'giuliomax-menu-builder' ); ?></option>
                            <option value="logged"><?php esc_html_e( 'Logged in', 'giuliomax-menu-builder' ); ?></option>
                        </select>
                        <span id="bm-active-theme-badge" style="display:none;" class="bm-active-theme-badge"></span>
                        <button type="button" id="bm-tutorial-btn" onclick="menuxTutorial.start()" class="bm-btn bm-btn-secondary bm-btn-sm" title="<?php echo esc_attr__( 'Restart the guided tour', 'giuliomax-menu-builder' ); ?>">✨ <?php esc_html_e( 'Tutorial', 'giuliomax-menu-builder' ); ?></button>

                        <span id="bm-preview-device-label" class="bm-preview-tip">🖥️ <?php esc_html_e( 'Desktop — full width', 'giuliomax-menu-builder' ); ?></span>
                    </div>
                    <div id="bm-device-frame-wrap" class="bm-device-frame-wrap bm-device-frame-compact">
                        <div id="bm-device-outer" class="bm-device-outer bm-device-desktop">
                            <div id="bm-device-chrome" class="bm-device-chrome" style="display:none;">
                                <div class="bm-device-chrome-bar">
                                    <span class="bm-chrome-dot" style="background:#ff5f57;"></span>
                                    <span class="bm-chrome-dot" style="background:#febc2e;"></span>
                                    <span class="bm-chrome-dot" style="background:#28c840;"></span>
                                    <span class="bm-chrome-urlbar"></span>
                                </div>
                            </div>
                            <div class="bm-preview-frame">
                                <div id="menux-preview-wrap" class="bm-preview-canvas">
                                    <?php echo wp_kses_post( menux_get_preview_markup( $menu_items, $supported_langs ) ); ?>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <!-- ============== FINE STICKY PREVIEW BAR ============== -->

            <!-- ============== MAIN LAYOUT ============== -->
            <div class="bm-admin-layout">

                <!-- SIDEBAR -->
                <aside class="bm-admin-sidebar">
                    <nav class="bm-sidebar-nav">
                        <div class="bm-sidebar-group">
                            <div class="bm-sidebar-group-label"><?php esc_html_e( 'Structure', 'giuliomax-menu-builder' ); ?></div>
                            <button type="button" class="bm-sidebar-item active" data-section="structure" onclick="menuxGoSection('structure')">
                                🧩 <?php esc_html_e( 'Menu Structure', 'giuliomax-menu-builder' ); ?>
                            </button>
                            <button type="button" class="bm-sidebar-item" data-section="megamenu" onclick="menuxGoSection('megamenu')">⚡ <?php esc_html_e( 'Mega Menu', 'giuliomax-menu-builder' ); ?></button>
                        </div>
                        <div class="bm-sidebar-group">
                            <div class="bm-sidebar-group-label"><?php esc_html_e( 'Style', 'giuliomax-menu-builder' ); ?></div>
                            <button type="button" class="bm-sidebar-item" data-section="themes"   onclick="menuxGoSection('themes')">✨ <?php esc_html_e( 'Themes', 'giuliomax-menu-builder' ); ?></button>
                            <button type="button" class="bm-sidebar-item" data-section="colors"   onclick="menuxGoSection('colors')">🎨 <?php esc_html_e( 'Colors', 'giuliomax-menu-builder' ); ?></button>
                            <button type="button" class="bm-sidebar-item" data-section="logo"     onclick="menuxGoSection('logo')">🖼️ <?php esc_html_e( 'Logo', 'giuliomax-menu-builder' ); ?></button>
                            <button type="button" class="bm-sidebar-item" data-section="typo"     onclick="menuxGoSection('typo')">🔤 <?php esc_html_e( 'Typography', 'giuliomax-menu-builder' ); ?></button>
                            <button type="button" class="bm-sidebar-item" data-section="layout"   onclick="menuxGoSection('layout')">📐 <?php esc_html_e( 'Layout', 'giuliomax-menu-builder' ); ?></button>
                            <button type="button" class="bm-sidebar-item" data-section="mobile"   onclick="menuxGoSection('mobile')">📱 <?php esc_html_e( 'Mobile', 'giuliomax-menu-builder' ); ?></button>
                        </div>
                        <div class="bm-sidebar-group">
                            <div class="bm-sidebar-group-label"><?php esc_html_e( 'Features', 'giuliomax-menu-builder' ); ?></div>
                            <button type="button" class="bm-sidebar-item" data-section="announcement" onclick="menuxGoSection('announcement')">📢 <?php esc_html_e( 'Announcement', 'giuliomax-menu-builder' ); ?></button>
                            <button type="button" class="bm-sidebar-item" data-section="search" onclick="menuxGoSection('search')">🔍 <?php esc_html_e( 'Search', 'giuliomax-menu-builder' ); ?></button>
                            <button type="button" class="bm-sidebar-item" data-section="woocommerce" onclick="menuxGoSection('woocommerce')">🛒 <?php esc_html_e( 'WooCommerce', 'giuliomax-menu-builder' ); ?></button>
                            <button type="button" class="bm-sidebar-item" data-section="accessibility" onclick="menuxGoSection('accessibility')">♿ <?php esc_html_e( 'Accessibility', 'giuliomax-menu-builder' ); ?></button>
                        </div>
                        <div class="bm-sidebar-group">
                            <div class="bm-sidebar-group-label"><?php esc_html_e( 'Tools', 'giuliomax-menu-builder' ); ?></div>
                            <button type="button" class="bm-sidebar-item" data-section="wpnav" onclick="menuxGoSection('wpnav')">🔗 <?php esc_html_e( 'WP Integration', 'giuliomax-menu-builder' ); ?></button>
                            <button type="button" class="bm-sidebar-item" data-section="import-export" onclick="menuxGoSection('import-export')">📦 <?php esc_html_e( 'Import / Export', 'giuliomax-menu-builder' ); ?></button>
                            <?php if (!empty($supported_langs)): ?>
                            <button type="button" class="bm-sidebar-item" data-section="multilingual" onclick="menuxGoSection('multilingual')">🌐 <?php esc_html_e( 'Multilingual', 'giuliomax-menu-builder' ); ?></button>
                            <?php endif; ?>
                        </div>
                    </nav>
                    <div class="bm-sidebar-footer">
                        <input type="submit" name="menux_save_all" class="bm-btn bm-btn-primary bm-btn-block" value="<?php echo esc_attr( '💾 ' . __( 'Save Menu', 'giuliomax-menu-builder' ) ); ?>">
                        <button type="button" onclick="menuxGoSection('reset')" style="margin-top:8px;width:100%;background:none;border:1px solid #fca5a5;color:#ef4444;border-radius:8px;padding:8px;font-size:12px;cursor:pointer;">🗑 <?php esc_html_e( 'Reset Everything', 'giuliomax-menu-builder' ); ?></button>
                    </div>
                </aside>
                <!-- /SIDEBAR -->

                <!-- CONTENT -->
                <main class="bm-admin-content">

                    <!-- Panel: Menu Structure -->
                    <div id="panel-structure" class="bm-panel">
                        <?php menux_render_builder($menu_items, $all_wp_pages, $supported_langs, $menux_wp_roles_for_select); ?>
                    </div>

                    <!-- Panel: Style (all style tabs) -->
                    <div id="panel-style" class="bm-panel" style="display:none;">
                        <?php menux_render_style_panel($menux_style); ?>
                    </div>



                    <!-- Panel: Logo -->
                    <div id="panel-logo" class="bm-panel" style="display:none;">
                        <?php menux_render_logo_panel(); ?>
                    </div>

                    <!-- Panel: Mega Menu -->
                    <div id="panel-megamenu" class="bm-panel" style="display:none;">
                        <?php menux_render_megamenu_panel( $menu_items ); ?>
                    </div>

                    <!-- Panel: Announcement Bar -->
                    <div id="panel-announcement" class="bm-panel" style="display:none;">
                        <?php menux_render_announcement_panel( $menux_style ); ?>
                    </div>

                    <!-- Panel: Search -->
                    <div id="panel-search" class="bm-panel" style="display:none;">
                        <?php menux_render_search_panel( $menux_style ); ?>
                    </div>

                    <!-- Panel: WooCommerce -->
                    <div id="panel-woocommerce" class="bm-panel" style="display:none;">
                        <?php menux_render_woocommerce_panel( $menux_style ); ?>
                    </div>

                    <!-- Panel: Accessibility -->
                    <div id="panel-accessibility" class="bm-panel" style="display:none;">
                        <?php menux_render_accessibility_panel(); ?>
                    </div>

                    <!-- Panel: WP Nav Integration -->
                    <div id="panel-wpnav" class="bm-panel" style="display:none;">
                        <?php
                        $theme_locations    = get_registered_nav_menus();
                        $saved_replacements = get_option( 'menux_wp_nav_replacements', array() );
                        $menux_locations    = array( 'primary' );
                        $menux_loc_counts   = array( 'primary' => 0 );
                        foreach ( get_option( 'menux_menu_items', array() ) as $item ) {
                            $loc = ! empty( $item['menu_location'] ) ? $item['menu_location'] : 'primary';
                            if ( ! in_array( $loc, $menux_locations, true ) ) { $menux_locations[] = $loc; $menux_loc_counts[ $loc ] = 0; }
                            $menux_loc_counts[ $loc ] = ( $menux_loc_counts[ $loc ] ?? 0 ) + 1;
                        }
                        ?>
                        <div class="bm-card">
                            <div class="bm-card-header">
                                <span class="bm-card-icon">🔗</span>
                                <div class="bm-card-titles">
                                    <h2 class="bm-card-title"><?php esc_html_e( 'WP Menu Integration', 'giuliomax-menu-builder' ); ?></h2>
                                    <p class="bm-card-subtitle"><?php esc_html_e( 'Replace your theme\'s native menus with MenuX — works with classic PHP themes that call wp_nav_menu()', 'giuliomax-menu-builder' ); ?></p>
                                </div>
                            </div>
                            <div class="bm-card-body">
                                <?php if ( empty( $theme_locations ) ) : ?>
                                    <p style="color:#6b7280;font-size:13px;"><?php echo wp_kses( __( 'No theme menu locations registered. Your active theme must call <code>register_nav_menus()</code>.', 'giuliomax-menu-builder' ), array( 'code' => array() ) ); ?></p>
                                <?php else : ?>
                                <p style="color:#6b7280;font-size:13px;margin-bottom:16px;"><?php echo wp_kses( __( 'Map each WordPress theme location to a MenuX location. Leave <em>— Don\'t replace —</em> to keep the theme\'s original menu.', 'giuliomax-menu-builder' ), array( 'em' => array() ) ); ?></p>
                                <table style="width:100%;border-collapse:collapse;">
                                    <thead><tr>
                                        <th style="text-align:left;padding:8px 12px 8px 0;font-size:12px;font-weight:600;color:#6b7280;text-transform:uppercase;border-bottom:1px solid #e5e7eb;"><?php esc_html_e( 'Theme Location', 'giuliomax-menu-builder' ); ?></th>
                                        <th style="text-align:left;padding:8px 0;font-size:12px;font-weight:600;color:#6b7280;text-transform:uppercase;border-bottom:1px solid #e5e7eb;"><?php esc_html_e( 'Replace with MenuX location', 'giuliomax-menu-builder' ); ?></th>
                                    </tr></thead>
                                    <tbody>
                                        <?php foreach ( $theme_locations as $slug => $label ) :
                                            $current = $saved_replacements[ $slug ] ?? ''; ?>
                                        <tr>
                                            <td style="padding:10px 12px 10px 0;font-size:13px;font-weight:500;vertical-align:middle;border-bottom:1px solid #f3f4f6;">
                                                <code><?php echo esc_html( $slug ); ?></code>
                                                <span style="display:block;color:#9ca3af;font-size:11px;margin-top:2px;"><?php echo esc_html( $label ); ?></span>
                                            </td>
                                            <td style="padding:10px 0;vertical-align:middle;border-bottom:1px solid #f3f4f6;">
                                                <select name="menux_wp_nav_replacements[<?php echo esc_attr($slug); ?>]" class="bm-select" style="min-width:180px;">
                                                    <option value=""><?php esc_html_e( '— Don\'t replace —', 'giuliomax-menu-builder' ); ?></option>
                                                    <?php foreach ( $menux_locations as $mloc ) :
                                                        $cnt = $menux_loc_counts[ $mloc ] ?? 0; ?>
                                                    <option value="<?php echo esc_attr($mloc); ?>"<?php selected($current,$mloc); ?>><?php
                                                        if ( $cnt > 0 ) {
                                                            /* translators: 1: MenuX location slug, 2: number of items */
                                                            echo esc_html( sprintf( _n( '%1$s (%2$d item)', '%1$s (%2$d items)', $cnt, 'giuliomax-menu-builder' ), $mloc, $cnt ) );
                                                        } else {
                                                            /* translators: %s: MenuX location slug */
                                                            echo esc_html( sprintf( __( '%s ⚠ no items', 'giuliomax-menu-builder' ), $mloc ) );
                                                        }
                                                    ?></option>
                                                    <?php endforeach; ?>
                                                </select>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                                <p style="margin-top:12px;font-size:12px;color:#9ca3af;"><?php echo wp_kses( __( 'Save after making changes. A location marked <strong>⚠ no items</strong> will keep the theme\'s original menu.', 'giuliomax-menu-builder' ), array( 'strong' => array() ) ); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>

                    <!-- Panel: Import / Export -->
                    <div id="panel-import-export" class="bm-panel" style="display:none;">
                        <div class="bm-card">
                            <div class="bm-card-header">
                                <span class="bm-card-icon">📦</span>
                                <div class="bm-card-titles">
                                    <h2 class="bm-card-title"><?php esc_html_e( 'Import / Export Configuration', 'giuliomax-menu-builder' ); ?></h2>
                                    <p class="bm-card-subtitle"><?php esc_html_e( 'Backup or transfer your setup between sites', 'giuliomax-menu-builder' ); ?></p>
                                </div>
                            </div>
                            <div class="bm-card-body">
                                <div class="bm-impexp-grid">
                                    <div class="bm-impexp-action">
                                        <div class="bm-impexp-action-icon">⬇️</div>
                                        <div class="bm-impexp-action-content">
                                            <strong><?php esc_html_e( 'Export configuration', 'giuliomax-menu-builder' ); ?></strong>
                                            <p><?php esc_html_e( 'Download a JSON file with menu items, style, logo, accessibility and the footer.', 'giuliomax-menu-builder' ); ?></p>
                                            <button type="button" class="bm-btn bm-btn-secondary" onclick="menux_exportConfig()">⬇️ <?php esc_html_e( 'Export', 'giuliomax-menu-builder' ); ?></button>
                                        </div>
                                    </div>
                                    <div class="bm-impexp-action">
                                        <div class="bm-impexp-action-icon">⬆️</div>
                                        <div class="bm-impexp-action-content">
                                            <strong><?php esc_html_e( 'Import configuration', 'giuliomax-menu-builder' ); ?></strong>
                                            <p><?php esc_html_e( 'From a JSON file. Overwrites current settings and reloads the page.', 'giuliomax-menu-builder' ); ?></p>
                                            <label class="bm-btn bm-btn-secondary" style="cursor:pointer;">
                                                ⬆️ <?php esc_html_e( 'Choose file', 'giuliomax-menu-builder' ); ?>
                                                <input type="file" id="menux-import-file" accept=".json" style="display:none;" onchange="menux_importConfig(this)">
                                            </label>
                                            <span id="menux-import-msg" style="display:none; margin-left:10px; font-size:13px;"></span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Panel: Multilingual -->
                    <?php if (!empty($supported_langs)): ?>
                    <div id="panel-multilingual" class="bm-panel" style="display:none;">
                        <div class="bm-card">
                            <div class="bm-card-header">
                                <span class="bm-card-icon">🌐</span>
                                <div class="bm-card-titles">
                                    <h2 class="bm-card-title"><?php esc_html_e( 'Multilingual Support', 'giuliomax-menu-builder' ); ?></h2>
                                    <p class="bm-card-subtitle"><?php esc_html_e( 'Each menu item can be translated into these languages', 'giuliomax-menu-builder' ); ?></p>
                                </div>
                            </div>
                            <div class="bm-card-body">
                                <div class="bm-lang-chips">
                                    <?php foreach ($supported_langs as $lang): ?>
                                        <span class="bm-lang-chip">
                                            <strong><?php echo esc_html($lang['code']); ?></strong>
                                            <span class="bm-lang-chip-label"><?php echo esc_html($lang['label']); ?></span>
                                        </span>
                                    <?php endforeach; ?>
                                    <button type="button" id="menux-reload-langs-btn" class="bm-btn bm-btn-secondary bm-btn-sm" onclick="menux_reloadLanguages()">🔄 <?php esc_html_e( 'Refresh', 'giuliomax-menu-builder' ); ?></button>
                                </div>
                                <p style="font-size:12px;color:#64748b;margin:12px 0 0;line-height:1.6;">
                                    <?php echo wp_kses( __( 'English, Italian and Russian are built in — no extra plugin required. The label shown on the front end follows the page\'s language (<code>&lt;html lang&gt;</code>). Install <strong>WPML</strong> or <strong>Polylang</strong> to manage your own language set instead.', 'giuliomax-menu-builder' ), array( 'code' => array(), 'strong' => array() ) ); ?>
                                </p>
                                <span id="menux-reload-langs-msg" style="display:none; margin-left:10px; font-size:13px;"></span>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Panel: Reset -->
                    <div id="panel-reset" class="bm-panel" style="display:none;">
                        <div class="bm-card" style="border:1px solid #fca5a5;">
                            <div class="bm-card-header" style="background:#fff5f5;">
                                <span class="bm-card-icon">🗑</span>
                                <div class="bm-card-titles">
                                    <h2 class="bm-card-title" style="color:#dc2626;"><?php esc_html_e( 'Reset Everything', 'giuliomax-menu-builder' ); ?></h2>
                                    <p class="bm-card-subtitle"><?php esc_html_e( 'Permanently delete all saved data — this cannot be undone', 'giuliomax-menu-builder' ); ?></p>
                                </div>
                            </div>
                            <div class="bm-card-body">
                                <p style="font-size:13px;color:#374151;margin-bottom:16px;"><?php esc_html_e( 'This will permanently delete:', 'giuliomax-menu-builder' ); ?></p>
                                <ul style="font-size:13px;color:#374151;margin:0 0 20px 20px;line-height:1.8;">
                                    <li><?php esc_html_e( 'All menu items and locations', 'giuliomax-menu-builder' ); ?></li>
                                    <li><?php esc_html_e( 'All style settings (colors, fonts, layout)', 'giuliomax-menu-builder' ); ?></li>
                                    <li><?php esc_html_e( 'WP Integration mappings', 'giuliomax-menu-builder' ); ?></li>
                                </ul>
                                <form method="POST" onsubmit="return confirm('Are you sure? This will delete ALL menu items, styles and settings. This cannot be undone.');">
                                    <?php wp_nonce_field( 'menux_reset_action', 'menux_reset_nonce' ); ?>
                                    <button type="submit" name="menux_reset_all" value="1" style="background:#dc2626;color:#fff;border:none;border-radius:8px;padding:10px 24px;font-size:14px;font-weight:600;cursor:pointer;">🗑 <?php esc_html_e( 'Delete all data and reset', 'giuliomax-menu-builder' ); ?></button>
                                </form>
                            </div>
                        </div>
                    </div>

                </main>
                <!-- /CONTENT -->

            </div>
            <!-- ============== FINE MAIN LAYOUT ============== -->

            <!-- ===== FINE THEME MODAL ===== -->

        </form>
    </div>

    <?php require_once __DIR__ . '/help-modal.php'; ?>

    <?php menux_render_tutorial(); ?>

    <?php /* Admin CSS and JS are enqueued via menux_admin_assets() in includes/assets.php. */ ?>
    <?php
    /* Inject PHP-dynamic data for admin.js via the WordPress enqueue API */
    $preview_logo_settings = class_exists( 'Menux_Logo' ) ? Menux_Logo::get_settings() : array();
    $preview_logo_url = '';
    if ( ! empty( $preview_logo_settings['desktop_id'] ) && (int) $preview_logo_settings['desktop_id'] > 0 ) {
        $preview_logo_url = (string) wp_get_attachment_image_url( (int) $preview_logo_settings['desktop_id'], 'full' );
    }
    if ( ! $preview_logo_url && ! empty( $preview_logo_settings['desktop_url'] ) ) {
        $preview_logo_url = $preview_logo_settings['desktop_url'];
    }
    $preview_logo_pos = $preview_logo_settings['position'] ?? 'left';
    $menux_admin_data = 'var menux_index = ' . (int) count( $menu_items ) . ';'
        . 'var menux_supported_langs = ' . wp_json_encode( $supported_langs ) . ';'
        . 'var menux_wp_roles = ' . wp_json_encode( $menux_wp_roles_for_select ) . ';'
        . 'var menux_all_pages = ' . wp_json_encode( array_map( function( $p ) { return array( 'id' => $p->ID, 'title' => $p->post_title ); }, $all_wp_pages ) ) . ';'
        . 'var menux_reload_langs_nonce = ' . wp_json_encode( wp_create_nonce( 'menux_reload_languages_nonce' ) ) . ';'
        . 'var menux_export_config_nonce = ' . wp_json_encode( wp_create_nonce( 'menux_export_config_nonce' ) ) . ';'
        . 'var menux_import_config_nonce = ' . wp_json_encode( wp_create_nonce( 'menux_import_config_nonce' ) ) . ';'
        . 'var menux_import_wp_menu_nonce = ' . wp_json_encode( wp_create_nonce( 'menux_import_wp_menu_nonce' ) ) . ';'
        . 'var menux_preview_logo = ' . wp_json_encode( array( 'url' => $preview_logo_url, 'pos' => $preview_logo_pos ) ) . ';';
    wp_add_inline_script( 'menux-admin-js', $menux_admin_data, 'before' );
    ?>
    <?php
}
