<?php
/**
 * MenuX Free — Menu Builder
 * Drag-and-drop menu item builder for the admin panel.
 * @package MenuX
 */

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

function menux_render_builder($items, $all_pages, $supported_langs = array(), $menux_wp_roles_for_select = array()) {
    $idx = 0;
    ?>
    <div class="menux-panel">

        <!-- ══ ADD SECTION — single card with tabs ══ -->
        <div class="bm-card bm-card-add-unified">
            <div class="bm-card-header">
                <span class="bm-card-icon bm-card-icon-blue">➕</span>
                <div class="bm-card-titles">
                    <h2 class="bm-card-title"><?php esc_html_e( 'Add to Menu', 'giuliomax-menu-builder' ); ?></h2>
                    <p class="bm-card-subtitle"><?php esc_html_e( 'Add a WordPress page or a custom link', 'giuliomax-menu-builder' ); ?></p>
                </div>
            </div>
            <div class="bm-add-tabs">
                <button type="button" class="bm-add-tab-btn active" data-tab="page" onclick="menuxAddTab('page')">📄 <?php esc_html_e( 'Page', 'giuliomax-menu-builder' ); ?></button>
                <button type="button" class="bm-add-tab-btn" data-tab="link" onclick="menuxAddTab('link')">🔗 <?php esc_html_e( 'Custom Link', 'giuliomax-menu-builder' ); ?></button>
                <button type="button" class="bm-add-tab-btn" data-tab="import-wp" onclick="menuxAddTab('import-wp');menux_loadWpMenus()">📋 <?php esc_html_e( 'Import WP', 'giuliomax-menu-builder' ); ?></button>
            </div>

            <!-- Pane: WordPress Page -->
            <div id="bm-add-pane-page" class="bm-add-pane">
                <div style="display:flex;gap:8px;align-items:center;">
                    <select id="page-select" class="bm-input bm-select" style="flex:1;">
                        <option value=""><?php esc_html_e( '-- Select a page --', 'giuliomax-menu-builder' ); ?></option>
                        <?php foreach ($all_pages as $page) : ?>
                            <option value="<?php echo absint($page->ID); ?>" data-title="<?php echo esc_attr($page->post_title); ?>">
                                <?php echo esc_html($page->post_title); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <button type="button" class="bm-btn bm-btn-primary" onclick="menux_addPage()" style="white-space:nowrap;flex-shrink:0;">
                        + <?php esc_html_e( 'Add', 'giuliomax-menu-builder' ); ?>
                    </button>
                </div>
            </div>

            <!-- Pane: Custom Link -->
            <div id="bm-add-pane-link" class="bm-add-pane" style="display:none;">
                <div style="display:flex;gap:8px;align-items:center;margin-bottom:8px;">
                    <input type="text" id="custom-url" class="bm-input" placeholder="<?php esc_attr_e( 'URL (https://...)', 'giuliomax-menu-builder' ); ?>" style="flex:1;">
                    <button type="button" class="bm-btn bm-btn-primary" onclick="menux_addCustom()" style="white-space:nowrap;flex-shrink:0;">
                        + <?php esc_html_e( 'Add', 'giuliomax-menu-builder' ); ?>
                    </button>
                </div>
                <input type="text" id="custom-icon" class="bm-input" placeholder="<?php esc_attr_e( 'Icon (e.g. fas fa-home)', 'giuliomax-menu-builder' ); ?>">
            </div>

            <!-- Pane: Import from WP native menu -->
            <div id="bm-add-pane-import-wp" class="bm-add-pane" style="display:none;">
                <div style="display:flex;gap:8px;align-items:center;">
                    <select id="wp-menu-select" class="bm-input bm-select" style="flex:1;">
                        <option value=""><?php esc_html_e( '-- Select a WordPress menu --', 'giuliomax-menu-builder' ); ?></option>
                    </select>
                    <button type="button" class="bm-btn bm-btn-primary" onclick="menux_importWpMenu()" style="white-space:nowrap;flex-shrink:0;">
                        ↓ <?php esc_html_e( 'Import', 'giuliomax-menu-builder' ); ?>
                    </button>
                </div>
                <p style="font-size:11px;color:#9ca3af;margin:6px 0 0;"><?php esc_html_e( 'Imports items from an existing WordPress menu (Appearance › Menus). The current builder items will be replaced.', 'giuliomax-menu-builder' ); ?></p>
            </div>
        </div>

        <!-- ══ MENU STRUCTURE ══ -->
        <div class="bm-card bm-card-structure">
            <div class="bm-card-header">
                <span class="bm-card-icon bm-card-icon-purple">🧩</span>
                <div class="bm-card-titles">
                    <h2 class="bm-card-title"><?php esc_html_e( 'Menu Structure', 'giuliomax-menu-builder' ); ?></h2>
                    <p class="bm-card-subtitle">↕️ <?php esc_html_e( 'Grab the', 'giuliomax-menu-builder' ); ?> <span class="dashicons dashicons-menu" style="font-size:13px;width:13px;height:13px;vertical-align:text-bottom;"></span> <?php esc_html_e( 'handle to reorder', 'giuliomax-menu-builder' ); ?> &nbsp;·&nbsp; <?php esc_html_e( 'click an item to edit', 'giuliomax-menu-builder' ); ?></p>
                </div>
                <span class="bm-items-count"><?php printf( esc_html__( '%d items', 'giuliomax-menu-builder' ), absint(count($items)) ); ?></span>
            </div>
            <div class="bm-card-body" style="padding:0;">
            <ul id="menux-sortable">
                <?php foreach ($items as $item) :
                    $is_page      = ($item['type'] === 'page');
                    $title        = $is_page ? get_the_title($item['id']) : ($item['url'] ?? '');
                    $icon_val     = $item['icon'] ?? '';
                    $vis          = $item['visibility'] ?? 'all';
                    // Normalize legacy pre-v7 migration values so the select shows
                    // the real setting instead of falling back to "Everyone".
                    if ($vis === 'auth')     $vis = 'logged_in';
                    if ($vis === 'non-auth') $vis = 'logged_out';
                    $badge_val    = $item['badge'] ?? '';
                    $badge_bg     = $item['badge_bg'] ?? '#ef4444';
                    $target       = $item['target'] ?? '';
                    $item_key     = $item['item_key'] ?? ($is_page ? 'page_'.($item['id']??0) : 'c_'.md5($item['url']??''));
                    $has_subs     = !empty($item['children']);
                    $has_advanced = !empty($item['schedule_start']) || !empty($item['schedule_end'])
                                 || !empty($item['cond_roles'])     || !empty($item['cond_devices'])
                                 || !empty($item['cond_pages'])     || !empty($item['cond_time_from'])
                                 || !empty($item['cond_time_to'])   || !empty($item['cond_utm']);
                ?>
                <li class="menux-item<?php echo $has_subs ? ' menux-item-has-subs' : ''; ?>">

                    <!-- ── HEADER ── -->
                    <div class="menux-item-header" onclick="menuxToggleItem(this)">
                        <span class="menux-drag-handle dashicons dashicons-menu" title="<?php esc_attr_e( 'Drag to reorder', 'giuliomax-menu-builder' ); ?>"></span>
                        <?php if ($icon_val): ?>
                            <i class="<?php echo esc_attr($icon_val); ?>" style="font-size:14px;color:#9ca3af;flex-shrink:0;" aria-hidden="true"></i>
                        <?php endif; ?>
                        <span class="menux-item-title">
                            <?php echo $is_page ? '📄' : '🔗'; ?>&nbsp;<?php echo esc_html($title); ?>
                        </span>
                        <span class="menux-item-meta">
                            <?php if ($has_subs): ?>
                                <span class="menux-item-badge"><?php printf( esc_html__( '%d sub', 'giuliomax-menu-builder' ), absint(count($item['children'])) ); ?></span>
                            <?php endif; ?>
                            <?php if (($item['cta_style'] ?? '0') === '1'): ?>
                                <span class="menux-item-badge" style="background:#667eea;color:#fff;" title="<?php esc_attr_e( 'CTA button style active', 'giuliomax-menu-builder' ); ?>">🎯 <?php esc_html_e( 'CTA', 'giuliomax-menu-builder' ); ?></span>
                            <?php endif; ?>
                            <?php if ($has_advanced): ?>
                                <span class="menux-item-badge menux-item-badge-adv" title="<?php esc_attr_e( 'Advanced options active', 'giuliomax-menu-builder' ); ?>">⚙</span>
                            <?php endif; ?>
                        </span>
                        <span class="menux-item-chevron">▾</span>
                        <button type="button" class="menux-item-delete"
                            onclick="event.stopPropagation(); menux_removeItem(this)"
                            title="<?php esc_attr_e( 'Remove', 'giuliomax-menu-builder' ); ?>">&times;</button>
                    </div>

                    <!-- ── BODY ── -->
                    <div class="menux-item-body">

                        <!-- Hidden system fields -->
                        <input type="hidden" name="menu_items[<?php echo absint($idx); ?>][type]"     value="<?php echo esc_attr($item['type']); ?>">
                        <input type="hidden" name="menu_items[<?php echo absint($idx); ?>][item_key]" value="<?php echo esc_attr($item_key); ?>">
                        <?php if ($is_page) : ?>
                            <input type="hidden" name="menu_items[<?php echo absint($idx); ?>][id]"  value="<?php echo intval($item['id']); ?>">
                        <?php else : ?>
                            <input type="hidden" name="menu_items[<?php echo absint($idx); ?>][url]" value="<?php echo esc_url($item['url']); ?>">
                        <?php endif; ?>

                        <!-- Section: Languages -->
                        <div class="bm-item-section">
                            <div class="bm-item-section-title">🌐 <?php esc_html_e( 'Languages', 'giuliomax-menu-builder' ); ?></div>
                            <div class="bm-inputs-row" style="flex-wrap:wrap;gap:6px;">
                                <?php if (!empty($supported_langs)) : ?>
                                    <?php foreach ($supported_langs as $lang) :
                                        $key   = menux_code_to_key($lang['code']);
                                        $short = strtoupper(substr($lang['code'], 0, 2));
                                        $lv    = $item[$key] ?? ($item[strtolower($short)] ?? ($is_page && strtolower($short) === 'it' ? $title : ''));
                                    ?>
                                    <label class="bm-lang-field" title="<?php echo esc_attr($lang['label']); ?>">
                                        <span class="bm-lang-code"><?php echo esc_html($short); ?></span>
                                        <input type="text"
                                               name="menu_items[<?php echo absint($idx); ?>][<?php echo esc_attr($key); ?>]"
                                               value="<?php echo esc_attr($lv); ?>"
                                               placeholder="<?php echo esc_attr($lang['label']); ?>"
                                               class="bm-lang-input">
                                    </label>
                                    <?php endforeach; ?>
                                <?php else : ?>
                                    <label class="bm-lang-field" title="<?php esc_attr_e( 'Italiano', 'giuliomax-menu-builder' ); ?>">
                                        <span class="bm-lang-code">IT</span>
                                        <input type="text" name="menu_items[<?php echo absint($idx); ?>][lang_it_IT]"
                                               value="<?php echo esc_attr($item['lang_it_IT'] ?? $item['it'] ?? ($is_page ? $title : '')); ?>"
                                               placeholder="<?php esc_attr_e( 'Italiano', 'giuliomax-menu-builder' ); ?>" class="bm-lang-input">
                                    </label>
                                    <label class="bm-lang-field" title="<?php esc_attr_e( 'English', 'giuliomax-menu-builder' ); ?>">
                                        <span class="bm-lang-code">EN</span>
                                        <input type="text" name="menu_items[<?php echo absint($idx); ?>][lang_en_US]"
                                               value="<?php echo esc_attr($item['lang_en_US'] ?? $item['en'] ?? ''); ?>"
                                               placeholder="<?php esc_attr_e( 'English', 'giuliomax-menu-builder' ); ?>" class="bm-lang-input">
                                    </label>
                                <?php endif; ?>
                            </div>
                        </div>

                        <!-- Section: Icon & Badge -->
                        <div class="bm-item-section">
                            <div class="bm-item-section-title">🎨 <?php esc_html_e( 'Icon & Badge', 'giuliomax-menu-builder' ); ?></div>
                            <div class="bm-inputs-row" style="flex-wrap:wrap;">
                                <div style="display:inline-flex;align-items:center;gap:5px;flex-shrink:0;">
                                    <?php if (!empty($icon_val)): ?>
                                        <i class="bm-icon-preview-el <?php echo esc_attr($icon_val); ?>" style="font-size:16px;color:#374151;flex-shrink:0;"></i>
                                    <?php endif; ?>
                                    <input type="hidden" name="menu_items[<?php echo absint($idx); ?>][icon]" value="<?php echo esc_attr($icon_val); ?>" class="bm-icon-input">
                                    <button type="button" class="bm-icon-btn" onclick="mxIconPicker.open(this.previousElementSibling)" tabindex="-1">🎨 <?php esc_html_e( 'Icon', 'giuliomax-menu-builder' ); ?></button>
                                </div>
                                <input type="text"
                                       name="menu_items[<?php echo absint($idx); ?>][badge]"
                                       value="<?php echo esc_attr($badge_val); ?>"
                                       placeholder="<?php esc_attr_e( 'Badge (e.g.: New, Hot)', 'giuliomax-menu-builder' ); ?>"
                                       title="<?php esc_attr_e( 'Badge text', 'giuliomax-menu-builder' ); ?>"
                                       class="bm-lang-input" style="max-width:110px;">
                                <input type="color"
                                       name="menu_items[<?php echo absint($idx); ?>][badge_bg]"
                                       value="<?php echo esc_attr($badge_bg); ?>"
                                       title="<?php esc_attr_e( 'Badge color', 'giuliomax-menu-builder' ); ?>"
                                       style="width:30px;height:28px;padding:1px;border:1px solid #ccc;border-radius:4px;cursor:pointer;flex-shrink:0;">
                            </div>
                        </div>

                        <!-- Section: Visibility & Behavior -->
                        <div class="bm-item-section">
                            <div class="bm-item-section-title">👁️ <?php esc_html_e( 'Visibility & Behavior', 'giuliomax-menu-builder' ); ?></div>
                            <div class="bm-inputs-row" style="flex-wrap:wrap;">
                                <select name="menu_items[<?php echo absint($idx); ?>][visibility]" class="menux-visibility">
                                    <?php foreach ($menux_wp_roles_for_select as $role_key => $role_label) : ?>
                                    <option value="<?php echo esc_attr($role_key); ?>" <?php selected($vis, $role_key); ?>>
                                        <?php echo esc_html($role_label); ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                                <select name="menu_items[<?php echo absint($idx); ?>][target]" class="bm-select bm-select-sm">
                                    <option value=""       <?php selected($target, ''); ?>><?php esc_html_e( 'Same tab', 'giuliomax-menu-builder' ); ?></option>
                                    <option value="_blank" <?php selected($target, '_blank'); ?>>↗ <?php esc_html_e( 'New tab', 'giuliomax-menu-builder' ); ?></option>
                                </select>
                                <select name="menu_items[<?php echo absint($idx); ?>][menu_location]" class="bm-select bm-select-sm" title="<?php esc_attr_e( 'Menu location', 'giuliomax-menu-builder' ); ?>">
                                    <?php $cur_loc = $item['menu_location'] ?? 'primary'; ?>
                                    <option value="primary" <?php selected($cur_loc, 'primary'); ?>>📍 <?php esc_html_e( 'Primary', 'giuliomax-menu-builder' ); ?></option>
                                    <option value="footer"  <?php selected($cur_loc, 'footer');  ?>>📍 <?php esc_html_e( 'Footer', 'giuliomax-menu-builder' ); ?></option>
                                    <option value="sidebar" <?php selected($cur_loc, 'sidebar'); ?>>📍 <?php esc_html_e( 'Sidebar', 'giuliomax-menu-builder' ); ?></option>
                                    <option value="mobile"  <?php selected($cur_loc, 'mobile');  ?>>📍 <?php esc_html_e( 'Mobile', 'giuliomax-menu-builder' ); ?></option>
                                </select>
                                <label style="display:flex;align-items:center;gap:4px;font-size:12px;color:#555;cursor:pointer;white-space:nowrap;">
                                    <input type="checkbox"
                                           name="menu_items[<?php echo absint($idx); ?>][notif_dot]"
                                           value="1" <?php checked($item['notif_dot'] ?? '0', '1'); ?>>
                                    🔴 <?php esc_html_e( 'Dot', 'giuliomax-menu-builder' ); ?>
                                </label>
                            </div>
                        </div>

                        <!-- Section: CTA Button Style -->
                        <?php
                        $cta_on = ($item['cta_style'] ?? '0') === '1';
                        $cta_bg_val  = $item['cta_bg']            ?? '#667eea';
                        $cta_clr_val = $item['cta_color']         ?? '#ffffff';
                        $cta_hov_val = $item['cta_hover_bg']      ?? '#5a67d8';
                        $cta_r_val   = $item['cta_border_radius']  ?? 6;
                        ?>
                        <div class="bm-item-section" style="background:#fffbeb;border:1px dashed #fbbf24;border-radius:6px;padding:6px 10px;">
                            <div class="bm-item-section-title" style="color:#92400e;">🎯 <?php esc_html_e( 'CTA Button', 'giuliomax-menu-builder' ); ?></div>
                            <div class="bm-inputs-row" style="flex-wrap:wrap;gap:8px;align-items:center;">
                                <input type="hidden" name="menu_items[<?php echo absint($idx); ?>][cta_style]" value="<?php echo $cta_on ? '1' : '0'; ?>" class="bm-cta-style-h">
                                <label style="display:flex;align-items:center;gap:6px;font-size:12px;font-weight:600;color:#92400e;cursor:pointer;white-space:nowrap;">
                                    <input type="checkbox" class="bm-cta-toggle" value="1" <?php checked($cta_on); ?>
                                           onchange="this.closest('.bm-inputs-row').querySelector('.bm-cta-opts').style.display=this.checked?'flex':'none';this.closest('.bm-inputs-row').querySelector('.bm-cta-style-h').value=this.checked?'1':'0';">
                                    <?php esc_html_e( 'CTA button style', 'giuliomax-menu-builder' ); ?>
                                </label>
                                <div class="bm-cta-opts" style="display:<?php echo $cta_on ? 'flex' : 'none'; ?>;align-items:center;gap:8px;flex-wrap:wrap;">
                                    <label style="display:flex;align-items:center;gap:4px;font-size:11px;color:#555;"><?php esc_html_e( 'BG:', 'giuliomax-menu-builder' ); ?>
                                        <input type="color" name="menu_items[<?php echo absint($idx); ?>][cta_bg]" value="<?php echo esc_attr($cta_bg_val); ?>"
                                               style="width:30px;height:26px;padding:1px;border:1px solid #ccc;border-radius:4px;cursor:pointer;">
                                    </label>
                                    <label style="display:flex;align-items:center;gap:4px;font-size:11px;color:#555;"><?php esc_html_e( 'Text:', 'giuliomax-menu-builder' ); ?>
                                        <input type="color" name="menu_items[<?php echo absint($idx); ?>][cta_color]" value="<?php echo esc_attr($cta_clr_val); ?>"
                                               style="width:30px;height:26px;padding:1px;border:1px solid #ccc;border-radius:4px;cursor:pointer;">
                                    </label>
                                    <label style="display:flex;align-items:center;gap:4px;font-size:11px;color:#555;"><?php esc_html_e( 'Hover:', 'giuliomax-menu-builder' ); ?>
                                        <input type="color" name="menu_items[<?php echo absint($idx); ?>][cta_hover_bg]" value="<?php echo esc_attr($cta_hov_val); ?>"
                                               style="width:30px;height:26px;padding:1px;border:1px solid #ccc;border-radius:4px;cursor:pointer;">
                                    </label>
                                    <label style="display:flex;align-items:center;gap:4px;font-size:11px;color:#555;"><?php esc_html_e( 'Radius:', 'giuliomax-menu-builder' ); ?>
                                        <input type="number" name="menu_items[<?php echo absint($idx); ?>][cta_border_radius]"
                                               value="<?php echo absint($cta_r_val); ?>" min="0" max="50"
                                               style="width:48px;height:26px;padding:2px 4px;font-size:11px;">
                                        <span style="font-size:11px;color:#9ca3af;">px</span>
                                    </label>
                                </div>
                            </div>
                        </div>

                        <!-- Section: Schedule & Conditions -->
                        <details class="bm-item-advanced" <?php echo $has_advanced ? 'open' : ''; ?>>
                            <summary class="bm-item-section-title" style="cursor:pointer;list-style:none;-webkit-appearance:none;">
                                ⚙️ <?php esc_html_e( 'Schedule & Conditions', 'giuliomax-menu-builder' ); ?>
                                <?php if ($has_advanced): ?><span style="color:#4f46e5;margin-left:4px;">●</span><?php endif; ?>
                            </summary>
                            <div style="margin-top:8px;">
                                <div class="bm-inputs-row" style="flex-wrap:wrap;margin-bottom:6px;">
                                    <label style="font-size:11px;color:#6b7280;white-space:nowrap;">📅 <?php esc_html_e( 'From:', 'giuliomax-menu-builder' ); ?></label>
                                    <input type="datetime-local" name="menu_items[<?php echo absint($idx); ?>][schedule_start]"
                                           value="<?php echo esc_attr($item['schedule_start'] ?? ''); ?>"
                                           style="font-size:11px;height:28px;padding:2px 6px;max-width:180px;">
                                    <label style="font-size:11px;color:#6b7280;white-space:nowrap;"><?php esc_html_e( 'to:', 'giuliomax-menu-builder' ); ?></label>
                                    <input type="datetime-local" name="menu_items[<?php echo absint($idx); ?>][schedule_end]"
                                           value="<?php echo esc_attr($item['schedule_end'] ?? ''); ?>"
                                           style="font-size:11px;height:28px;padding:2px 6px;max-width:180px;">
                                </div>
                                <div class="bm-inputs-row" style="flex-wrap:wrap;">
                                    <input type="text" name="menu_items[<?php echo absint($idx); ?>][cond_roles]"
                                           value="<?php echo esc_attr($item['cond_roles'] ?? ''); ?>"
                                           placeholder="<?php esc_attr_e( 'Roles (e.g.: editor,author)', 'giuliomax-menu-builder' ); ?>"
                                           title="<?php esc_attr_e( 'Show only to these WP roles', 'giuliomax-menu-builder' ); ?>"
                                           style="font-size:11px;height:28px;padding:2px 6px;max-width:160px;">
                                    <select name="menu_items[<?php echo absint($idx); ?>][cond_devices]"
                                            style="font-size:11px;height:28px;padding:2px 4px;max-width:120px;" title="<?php esc_attr_e( 'Device', 'giuliomax-menu-builder' ); ?>">
                                        <option value=""        <?php selected($item['cond_devices'] ?? '', ''); ?>>📱 <?php esc_html_e( 'All devices', 'giuliomax-menu-builder' ); ?></option>
                                        <option value="mobile"  <?php selected($item['cond_devices'] ?? '', 'mobile'); ?>>📱 <?php esc_html_e( 'Mobile only', 'giuliomax-menu-builder' ); ?></option>
                                        <option value="desktop" <?php selected($item['cond_devices'] ?? '', 'desktop'); ?>>🖥️ <?php esc_html_e( 'Desktop only', 'giuliomax-menu-builder' ); ?></option>
                                    </select>
                                    <input type="text" name="menu_items[<?php echo absint($idx); ?>][cond_time_from]"
                                           value="<?php echo esc_attr($item['cond_time_from'] ?? ''); ?>"
                                           placeholder="<?php echo esc_attr( '⏰ ' . __( 'From HH:MM', 'giuliomax-menu-builder' ) ); ?>"
                                           style="font-size:11px;height:28px;padding:2px 6px;max-width:80px;">
                                    <input type="text" name="menu_items[<?php echo absint($idx); ?>][cond_time_to]"
                                           value="<?php echo esc_attr($item['cond_time_to'] ?? ''); ?>"
                                           placeholder="<?php echo esc_attr( '⏰ ' . __( 'To HH:MM', 'giuliomax-menu-builder' ) ); ?>"
                                           style="font-size:11px;height:28px;padding:2px 6px;max-width:80px;">
                                    <input type="text" name="menu_items[<?php echo absint($idx); ?>][cond_utm]"
                                           value="<?php echo esc_attr($item['cond_utm'] ?? ''); ?>"
                                           placeholder="<?php esc_attr_e( 'UTM source', 'giuliomax-menu-builder' ); ?>"
                                           style="font-size:11px;height:28px;padding:2px 6px;max-width:100px;">
                                    <input type="text" name="menu_items[<?php echo absint($idx); ?>][cond_pages]"
                                           value="<?php echo esc_attr($item['cond_pages'] ?? ''); ?>"
                                           placeholder="<?php echo esc_attr( '📄 ' . __( 'Page IDs (e.g.: 2,15,42)', 'giuliomax-menu-builder' ) ); ?>"
                                           title="<?php esc_attr_e( 'Show this item only on these page IDs (comma-separated). Empty = all pages.', 'giuliomax-menu-builder' ); ?>"
                                           style="font-size:11px;height:28px;padding:2px 6px;max-width:160px;">
                                </div>
                            </div>
                        </details>

                        <!-- Section: Submenu -->
                        <div class="bm-submenu-zone bm-item-section" id="bm-sm-zone-<?php echo absint($idx); ?>">
                            <div class="bm-item-section-title">📂 <?php esc_html_e( 'Submenu', 'giuliomax-menu-builder' ); ?></div>
                            <button type="button"
                                    class="bm-btn bm-btn-secondary bm-btn-sm"
                                    onclick="menux_toggleSubmenuZone(<?php echo absint($idx); ?>)"
                                    id="bm-sm-toggle-<?php echo absint($idx); ?>">
                                <?php echo $has_subs
                                    ? sprintf( esc_html__( '%d sub-items', 'giuliomax-menu-builder' ), absint(count($item['children'])) ) . ' ▾'
                                    : '+ ' . esc_html__( 'Add submenu', 'giuliomax-menu-builder' ); ?>
                            </button>
                            <div id="bm-sm-body-<?php echo absint($idx); ?>"
                                 style="display:<?php echo $has_subs ? 'block' : 'none'; ?>; margin-top:8px;">
                                <ul class="bm-sm-list" id="bm-sm-list-<?php echo absint($idx); ?>"
                                    style="list-style:none;padding:0;margin:0 0 8px;border-left:3px solid #c3d4e8;padding-left:12px;">
                                <?php if ($has_subs): foreach ($item['children'] as $ci => $child):
                                    $child_is_page = ($child['type'] === 'page');
                                    $child_label   = '';
                                    if (!empty($supported_langs)) {
                                        foreach ($supported_langs as $cl) {
                                            $ck = menux_code_to_key($cl['code']);
                                            if (!empty($child[$ck])) { $child_label = $child[$ck]; break; }
                                        }
                                    }
                                    if (empty($child_label)) {
                                        $child_label = $child_is_page ? get_the_title($child['id']??0) : ($child['url']??'');
                                    }
                                    $child_url      = $child_is_page ? '' : ($child['url']??'');
                                    $grand_children = $child['children'] ?? [];
                                ?>
                                <li class="bm-sm-item" style="background:#f8fafc;border:1px solid #e2e8f0;border-radius:6px;padding:6px 10px;margin-bottom:6px;display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
                                    <span style="font-size:16px;color:#9ca3af;cursor:move;" title="<?php esc_attr_e( 'Drag', 'giuliomax-menu-builder' ); ?>">⠿</span>
                                    <select name="menu_items[<?php echo absint($idx); ?>][children][<?php echo absint($ci); ?>][type]"
                                            class="bm-child-type-sel"
                                            data-parent="<?php echo absint($idx); ?>" data-child="<?php echo absint($ci); ?>"
                                            onchange="menux_toggleChildType(this)"
                                            style="font-size:11px;height:26px;padding:1px 4px;border-radius:4px;border:1px solid #c3d4e8;color:#1d4ed8;background:#dbeafe;font-weight:600;max-width:90px;">
                                        <option value="page"   <?php selected($child['type'],'page');   ?>>📄 <?php esc_html_e( 'Page', 'giuliomax-menu-builder' ); ?></option>
                                        <option value="custom" <?php selected($child['type'],'custom'); ?>>🔗 <?php esc_html_e( 'Link', 'giuliomax-menu-builder' ); ?></option>
                                    </select>
                                    <div class="bm-child-page-wrap" style="display:<?php echo $child_is_page ? 'flex' : 'none'; ?>;align-items:center;gap:4px;">
                                        <select name="menu_items[<?php echo absint($idx); ?>][children][<?php echo absint($ci); ?>][id]"
                                                style="font-size:11px;height:26px;padding:1px 4px;max-width:160px;">
                                            <option value=""><?php esc_html_e( '-- Page --', 'giuliomax-menu-builder' ); ?></option>
                                            <?php foreach (get_pages(['sort_column'=>'post_title']) as $pg): ?>
                                            <option value="<?php echo absint($pg->ID); ?>" <?php selected(intval($child['id']??0), $pg->ID); ?>><?php echo esc_html($pg->post_title); ?></option>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                    <div class="bm-child-url-wrap" style="display:<?php echo !$child_is_page ? 'flex' : 'none'; ?>;align-items:center;gap:4px;">
                                        <input type="text"
                                               name="menu_items[<?php echo absint($idx); ?>][children][<?php echo absint($ci); ?>][url]"
                                               value="<?php echo esc_attr($child_url); ?>"
                                               placeholder="https://..."
                                               style="font-size:11px;width:140px;height:26px;padding:2px 5px;">
                                    </div>
                                    <?php if (!empty($supported_langs)): foreach ($supported_langs as $cl): $ck = menux_code_to_key($cl['code']); ?>
                                    <input type="text"
                                           name="menu_items[<?php echo absint($idx); ?>][children][<?php echo absint($ci); ?>][<?php echo esc_attr($ck); ?>]"
                                           value="<?php echo esc_attr($child[$ck]??''); ?>"
                                           placeholder="<?php echo esc_attr($cl['code']); ?>"
                                           title="<?php echo esc_attr($cl['label']); ?>"
                                           style="font-size:11px;width:80px;height:26px;padding:2px 5px;">
                                    <?php endforeach; else: ?>
                                    <input type="text"
                                           name="menu_items[<?php echo absint($idx); ?>][children][<?php echo absint($ci); ?>][lang_it_IT]"
                                           value="<?php echo esc_attr($child['lang_it_IT']??$child_label); ?>"
                                           placeholder="<?php esc_attr_e( 'Label', 'giuliomax-menu-builder' ); ?>"
                                           style="font-size:11px;width:120px;height:26px;padding:2px 5px;">
                                    <?php endif; ?>
                                    <div style="display:inline-flex;align-items:center;gap:3px;">
                                        <?php if (!empty($child['icon'])): ?>
                                            <i class="bm-icon-preview-el <?php echo esc_attr($child['icon']); ?>" style="font-size:14px;color:#374151;flex-shrink:0;"></i>
                                        <?php endif; ?>
                                        <input type="hidden"
                                               name="menu_items[<?php echo absint($idx); ?>][children][<?php echo absint($ci); ?>][icon]"
                                               value="<?php echo esc_attr($child['icon']??''); ?>"
                                               class="bm-icon-input">
                                        <button type="button" class="bm-icon-btn" onclick="mxIconPicker.open(this.previousElementSibling)" tabindex="-1">🎨</button>
                                    </div>
                                    <select name="menu_items[<?php echo absint($idx); ?>][children][<?php echo absint($ci); ?>][target]"
                                            style="font-size:11px;height:26px;padding:1px 3px;">
                                        <option value=""       <?php selected($child['target']??'','');       ?>><?php esc_html_e( 'Same tab', 'giuliomax-menu-builder' ); ?></option>
                                        <option value="_blank" <?php selected($child['target']??'','_blank'); ?>>↗ <?php esc_html_e( 'New', 'giuliomax-menu-builder' ); ?></option>
                                    </select>
                                    <?php if (!empty($grand_children)): ?>
                                    <span style="font-size:10px;background:#dbeafe;color:#1d4ed8;padding:1px 5px;border-radius:6px;"><?php printf( esc_html__( '%d children', 'giuliomax-menu-builder' ), absint(count($grand_children)) ); ?></span>
                                    <?php foreach ($grand_children as $gi => $gc):
                                        foreach ($gc as $gk => $gv) {
                                            if ($gk === 'children') continue;
                                            echo '<input type="hidden" name="menu_items[' . absint($idx) . '][children][' . absint($ci) . '][children][' . absint($gi) . '][' . esc_attr($gk) . ']" value="' . esc_attr($gv) . '">';
                                        }
                                    endforeach; ?>
                                    <?php endif; ?>
                                    <button type="button"
                                            onclick="this.closest('li').remove(); menux_updateSubCount(<?php echo absint($idx); ?>);"
                                            style="background:#fee2e2;border:1px solid #fca5a5;color:#dc2626;border-radius:4px;padding:2px 8px;font-size:12px;cursor:pointer;margin-left:auto;">&times;</button>
                                </li>
                                <?php endforeach; endif; ?>
                                </ul>
                                <div style="display:flex;gap:6px;align-items:center;">
                                    <button type="button" onclick="menux_addSubBlank(<?php echo absint($idx); ?>)" class="bm-btn bm-btn-secondary bm-btn-sm">+ <?php esc_html_e( 'Add sub-item', 'giuliomax-menu-builder' ); ?></button>
                                    <span style="font-size:11px;color:#9ca3af;"><?php esc_html_e( 'Use the type selector to choose Page or Link', 'giuliomax-menu-builder' ); ?></span>
                                </div>
                            </div>
                        </div>

                    </div><!-- /menux-item-body -->
                </li>
                <?php $idx++; endforeach; ?>
            </ul>
            <p id="menux-empty-msg" class="bm-empty-msg" style="<?php echo !empty($items) ? 'display:none;' : ''; ?>">
                <span class="bm-empty-msg-icon">📋</span>
                <span><?php esc_html_e( 'Your menu is empty — pick a page or paste a URL above and click', 'giuliomax-menu-builder' ); ?> <strong>+ <?php esc_html_e( 'Add', 'giuliomax-menu-builder' ); ?></strong> <?php esc_html_e( 'to get started.', 'giuliomax-menu-builder' ); ?><br>
                <a href="#" onclick="menuxGoSection('structure');return false;" style="color:#667eea;font-weight:600;">→ <?php esc_html_e( 'Go to Menu Structure', 'giuliomax-menu-builder' ); ?></a></span>
            </p>
            </div>
        </div>
    </div>
    <?php
}

function menux_get_preview_markup($items, $supported_langs = array()) {
    if (empty($items)) return '<div style="padding:20px; text-align:center; color:#9ca3af; font-size:13px;">' . esc_html__( 'No menu items yet — add pages or links in', 'giuliomax-menu-builder' ) . ' <strong>' . esc_html__( 'Menu Structure', 'giuliomax-menu-builder' ) . '</strong>.</div>';

    $logo_html = '';
    if ( class_exists( 'Menux_Logo' ) ) {
        $logo_settings = Menux_Logo::get_settings();
        $logo_url = '';
        if ( (int)($logo_settings['desktop_id'] ?? 0) > 0 ) {
            $logo_url = (string) wp_get_attachment_image_url( (int)$logo_settings['desktop_id'], 'full' );
        }
        if ( ! $logo_url && ! empty( $logo_settings['desktop_url'] ) ) {
            $logo_url = $logo_settings['desktop_url'];
        }
        if ( $logo_url ) {
            $logo_html = '<a class="menux-logo menux-logo-desktop" href="#"><img src="' . esc_url( $logo_url ) . '" class="menux-logo-img" alt="' . esc_attr__( 'Logo', 'giuliomax-menu-builder' ) . '" style="max-height:48px;width:auto;display:block;"></a>';
        }
    }

    $logo_pos = class_exists('Menux_Logo') ? (Menux_Logo::get_settings()['position'] ?? 'left') : 'left';
    $ham  = '<div class="menux-hamburger" onclick="this.classList.toggle(\'open\'); this.nextElementSibling.classList.toggle(\'show\');"><span></span><span></span><span></span></div>';

    $out  = '<nav id="menux-preview-nav" class="menux-container menux-user-guest" style="width:100%; font-family:sans-serif;">';
    if ( $logo_pos === 'center' ) {
        $out .= $ham . '<div class="menux-logo-center-wrap" style="flex:1;display:flex;justify-content:center;">' . $logo_html . '</div>';
    } elseif ( $logo_pos === 'right' ) {
        // logo appended after ul below
    } else {
        $out .= $ham . $logo_html;
    }
    $out .= '<ul class="menux-list" style="padding:10px;">';
    foreach ($items as $item) {
        $is_page = ($item['type'] === 'page');
        $label   = '';
        if (!empty($supported_langs)) {
            foreach ($supported_langs as $lang) {
                $key = menux_code_to_key($lang['code']);
                if (!empty($item[$key])) { $label = $item[$key]; break; }
            }
        }
        if (empty($label)) {
            $label = !empty($item['it']) ? $item['it'] : (!empty($item['en']) ? $item['en'] : ($is_page ? get_the_title($item['id']) : $item['url']));
        }
        $url      = $is_page ? get_permalink($item['id']) : $item['url'];
        $icon     = !empty($item['icon']) ? '<i class="'.esc_attr($item['icon']).'" style="margin-right:8px;"></i>' : '';
        $vis      = $item['visibility'] ?? 'all';
        $li_class = '';
        if ($vis === 'auth')     $li_class = 'bs-show-only-when-auth';
        if ($vis === 'non-auth') $li_class = 'bs-show-only-when-non-auth';
        $out .= '<li class="' . esc_attr($li_class) . '"><a href="' . esc_url($url) . '" class="menux-link">'.$icon.'<span class="menux-label">' . esc_html($label) . '</span></a></li>';
    }
    $out .= '</ul>';
    if ( $logo_pos === 'right' ) $out .= $logo_html;
    $out .= '</nav>';
    return $out;
}
