<?php
/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * 
 * Copyright (c) 2025 CastConductor.com. All Rights Reserved.
 * 
 * CastConductor Menu Builder Admin Page
 * 
 * Provides the WordPress admin interface for configuring:
 * - Remote button bindings (which button opens which menu/overlay)
 * - Hierarchical menu creation and management
 * - Menu item ordering via drag-and-drop
 * - Menu styling (colors, fonts, etc.)
 * 
 * @package CastConductor
 * @subpackage Admin
 * @since 5.6.9c
 * 
 * END OF HEADER
 */

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

/**
 * Register admin menu
 */
add_action('admin_menu', 'castconductor_register_menu_builder_menu', 20);

function castconductor_register_menu_builder_menu() {
    add_submenu_page(
        'castconductor',
        __('Menu Builder', 'castconductor'),
        __('🎮 Menu Builder', 'castconductor'),
        'manage_options',
        'castconductor-menu-builder',
        'castconductor_menu_builder_page'
    );
}

/**
 * Enqueue admin scripts and styles for Menu Builder page
 */
add_action('admin_enqueue_scripts', 'castconductor_menu_builder_enqueue');

function castconductor_menu_builder_enqueue($hook) {
    if ($hook !== 'castconductor_page_castconductor-menu-builder') {
        return;
    }
    
    // jQuery UI for sortable
    wp_enqueue_script('jquery-ui-sortable');
    
    // Inline styles for the page
    wp_add_inline_style('wp-admin', '
        .cc-menu-builder-wrap {
            max-width: 1200px;
        }
        .cc-section {
            background: #fff;
            border: 1px solid #c3c4c7;
            border-radius: 4px;
            padding: 20px;
            margin-bottom: 20px;
        }
        .cc-section h2 {
            margin-top: 0;
            padding-bottom: 10px;
            border-bottom: 1px solid #eee;
        }
        .cc-button-binding {
            display: flex;
            align-items: flex-start;
            gap: 20px;
            padding: 15px;
            background: #f9f9f9;
            border-radius: 4px;
            margin-bottom: 10px;
        }
        .cc-button-binding .button-icon {
            font-size: 24px;
            width: 50px;
            text-align: center;
            padding-top: 5px;
        }
        .cc-button-binding .button-config {
            flex: 1;
        }
        .cc-button-binding .button-name {
            font-weight: 600;
            font-size: 14px;
            margin-bottom: 10px;
        }
        .cc-button-binding label {
            display: block;
            margin: 5px 0;
        }
        .cc-button-binding .binding-options {
            margin-left: 20px;
            padding: 10px;
            background: #fff;
            border-radius: 4px;
            display: none;
        }
        .cc-button-binding .binding-options.active {
            display: block;
        }
        .cc-menu-card {
            background: #fff;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 15px;
        }
        .cc-menu-card-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 15px;
            background: #f5f5f5;
            border-bottom: 1px solid #ddd;
            cursor: pointer;
        }
        .cc-menu-card-header h3 {
            margin: 0;
            font-size: 16px;
        }
        .cc-menu-card-body {
            padding: 15px;
            display: none;
        }
        .cc-menu-card.expanded .cc-menu-card-body {
            display: block;
        }
        .cc-menu-items {
            list-style: none;
            margin: 0;
            padding: 0;
        }
        .cc-menu-item {
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px 15px;
            background: #f9f9f9;
            border: 1px solid #ddd;
            border-radius: 4px;
            margin-bottom: 5px;
            cursor: grab;
        }
        .cc-menu-item:active {
            cursor: grabbing;
        }
        .cc-menu-item .drag-handle {
            color: #999;
            cursor: grab;
        }
        .cc-menu-item .item-icon {
            font-size: 18px;
        }
        .cc-menu-item .item-label {
            flex: 1;
            font-weight: 500;
        }
        .cc-menu-item .item-type {
            color: #666;
            font-size: 12px;
            background: #e0e0e0;
            padding: 2px 8px;
            border-radius: 10px;
        }
        .cc-menu-item .item-actions {
            display: flex;
            gap: 5px;
        }
        .cc-menu-item .item-actions button {
            padding: 2px 8px;
            font-size: 12px;
        }
        .cc-add-item-row {
            display: flex;
            gap: 10px;
            margin-top: 15px;
            padding-top: 15px;
            border-top: 1px solid #eee;
        }
        .cc-style-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
        }
        .cc-style-field label {
            display: block;
            font-weight: 500;
            margin-bottom: 5px;
        }
        .cc-style-field input[type="text"],
        .cc-style-field input[type="number"],
        .cc-style-field select {
            width: 100%;
        }
        .cc-color-field {
            display: flex;
            gap: 10px;
            align-items: center;
        }
        .cc-color-field input[type="color"] {
            width: 40px;
            height: 30px;
            padding: 0;
            border: 1px solid #ddd;
        }
        .cc-color-field input[type="text"] {
            flex: 1;
        }
        .cc-loading {
            opacity: 0.5;
            pointer-events: none;
        }
        .cc-toast {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 15px 25px;
            background: #2271b1;
            color: #fff;
            border-radius: 4px;
            z-index: 9999;
            animation: slideIn 0.3s ease;
        }
        .cc-toast.success { background: #00a32a; }
        .cc-toast.error { background: #d63638; }
        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        /* Modal styles */
        .cc-modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 100000;
        }
        .cc-modal {
            background: #fff;
            border-radius: 8px;
            width: 500px;
            max-width: 90vw;
            max-height: 80vh;
            overflow: auto;
        }
        .cc-modal-header {
            padding: 15px 20px;
            border-bottom: 1px solid #ddd;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .cc-modal-header h3 {
            margin: 0;
        }
        .cc-modal-body {
            padding: 20px;
        }
        .cc-modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #ddd;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }
        .cc-form-row {
            margin-bottom: 15px;
        }
        .cc-form-row label {
            display: block;
            font-weight: 500;
            margin-bottom: 5px;
        }
        .cc-form-row input,
        .cc-form-row select {
            width: 100%;
        }
    ');
}

/**
 * Render Menu Builder admin page
 */
function castconductor_menu_builder_page() {
    global $wpdb;
    $db = new CastConductor_Database();
    
    // Get current data
    $menus_table = $db->get_table_name('menus');
    $items_table = $db->get_table_name('menu_items');
    $bindings_table = $db->get_table_name('button_bindings');
    $blocks_table = $db->get_table_name('content_blocks');
    
    // Check if tables exist
    $tables_exist = $wpdb->get_var("SHOW TABLES LIKE '{$menus_table}'") === $menus_table;
    
    if (!$tables_exist) {
        echo '<div class="wrap"><h1>🎮 Menu Builder</h1>';
        echo '<div class="notice notice-warning"><p>Menu Builder tables not found. Please deactivate and reactivate the plugin to create the required database tables.</p></div>';
        echo '</div>';
        return;
    }
    
    // Fetch data
    $menus = $wpdb->get_results("SELECT * FROM {$menus_table} ORDER BY id ASC");
    $bindings = $wpdb->get_results("SELECT * FROM {$bindings_table} ORDER BY trigger_button ASC");
    $content_blocks = $wpdb->get_results("SELECT id, name, type FROM {$blocks_table} ORDER BY name ASC");
    
    // Default button bindings if none exist
    $default_buttons = [
        'menu' => ['icon' => '☰', 'name' => 'MENU Button'],
        'up' => ['icon' => '⬆️', 'name' => 'UP Button'],
        'down' => ['icon' => '⬇️', 'name' => 'DOWN Button'],
        'left' => ['icon' => '⬅️', 'name' => 'LEFT Button'],
        'right' => ['icon' => '➡️', 'name' => 'RIGHT Button'],
    ];
    
    // Index bindings by button
    $bindings_map = [];
    foreach ($bindings as $b) {
        $bindings_map[$b->trigger_button] = $b;
    }
    
    // Get menu items for each menu
    $menu_items = [];
    foreach ($menus as $menu) {
        $menu_items[$menu->id] = $wpdb->get_results($wpdb->prepare("
            SELECT mi.*, cb.name as content_block_name, cb.type as content_block_type
            FROM {$items_table} mi
            LEFT JOIN {$blocks_table} cb ON mi.content_block_id = cb.id
            WHERE mi.menu_id = %d
            ORDER BY mi.sort_order ASC
        ", $menu->id));
    }
    
    ?>
    <div class="wrap cc-menu-builder-wrap">
        <h1>🎮 Menu Builder</h1>
        <p>Configure navigation menus for your Roku channel. Map remote buttons to menus or direct content block overlays.</p>
        
        <!-- Button Bindings Section -->
        <div class="cc-section" id="button-bindings-section">
            <h2>🎛️ Remote Button Bindings</h2>
            <p>Configure what happens when viewers press these remote buttons:</p>
            
            <?php foreach ($default_buttons as $btn_key => $btn_info): 
                $binding = isset($bindings_map[$btn_key]) ? $bindings_map[$btn_key] : null;
                $binding_type = $binding ? $binding->binding_type : 'disabled';
            ?>
            <div class="cc-button-binding" data-button="<?php echo esc_attr($btn_key); ?>">
                <div class="button-icon"><?php echo $btn_info['icon']; ?></div>
                <div class="button-config">
                    <div class="button-name"><?php echo esc_html($btn_info['name']); ?></div>
                    
                    <label>
                        <input type="radio" name="binding_<?php echo esc_attr($btn_key); ?>" value="disabled" 
                               <?php checked($binding_type, 'disabled'); ?>
                               onchange="ccUpdateBindingType('<?php echo esc_attr($btn_key); ?>', 'disabled')">
                        <strong>Disabled</strong> - Button handled by Roku natively
                    </label>
                    
                    <label>
                        <input type="radio" name="binding_<?php echo esc_attr($btn_key); ?>" value="menu" 
                               <?php checked($binding_type, 'menu'); ?>
                               onchange="ccUpdateBindingType('<?php echo esc_attr($btn_key); ?>', 'menu')">
                        <strong>Opens Menu</strong> - Hierarchical navigation menu
                    </label>
                    
                    <div class="binding-options menu-options <?php echo $binding_type === 'menu' ? 'active' : ''; ?>">
                        <label>Select Menu:
                            <select name="menu_id_<?php echo esc_attr($btn_key); ?>" onchange="ccUpdateBindingMenu('<?php echo esc_attr($btn_key); ?>', this.value)">
                                <option value="">— Select —</option>
                                <?php foreach ($menus as $menu): ?>
                                <option value="<?php echo esc_attr($menu->id); ?>" 
                                        <?php selected($binding && $binding->menu_id == $menu->id); ?>>
                                    <?php echo esc_html($menu->name); ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                    </div>
                    
                    <label>
                        <input type="radio" name="binding_<?php echo esc_attr($btn_key); ?>" value="content_block" 
                               <?php checked($binding_type, 'content_block'); ?>
                               onchange="ccUpdateBindingType('<?php echo esc_attr($btn_key); ?>', 'content_block')">
                        <strong>Opens Content Block</strong> - Direct overlay shortcut
                    </label>
                    
                    <div class="binding-options content-block-options <?php echo $binding_type === 'content_block' ? 'active' : ''; ?>">
                        <label>Content Block:
                            <select name="content_block_id_<?php echo esc_attr($btn_key); ?>">
                                <option value="">— Select —</option>
                                <?php foreach ($content_blocks as $cb): ?>
                                <option value="<?php echo esc_attr($cb->id); ?>"
                                        <?php selected($binding && $binding->content_block_id == $cb->id); ?>>
                                    <?php echo esc_html($cb->name); ?> (<?php echo esc_html($cb->type); ?>)
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </label>
                        <br>
                        <label style="display: inline-block; margin-right: 15px;">Position:
                            <select name="overlay_position_<?php echo esc_attr($btn_key); ?>">
                                <option value="bottom" <?php selected($binding && $binding->overlay_position, 'bottom'); ?>>Bottom</option>
                                <option value="top" <?php selected($binding && $binding->overlay_position, 'top'); ?>>Top</option>
                                <option value="left" <?php selected($binding && $binding->overlay_position, 'left'); ?>>Left</option>
                                <option value="right" <?php selected($binding && $binding->overlay_position, 'right'); ?>>Right</option>
                            </select>
                        </label>
                        <label style="display: inline-block;">Animation:
                            <select name="overlay_animation_<?php echo esc_attr($btn_key); ?>">
                                <option value="slide" <?php selected($binding && $binding->overlay_animation, 'slide'); ?>>Slide</option>
                                <option value="fade" <?php selected($binding && $binding->overlay_animation, 'fade'); ?>>Fade</option>
                                <option value="none" <?php selected($binding && $binding->overlay_animation, 'none'); ?>>None</option>
                            </select>
                        </label>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
            
            <p class="submit">
                <button type="button" class="button button-primary" onclick="ccSaveButtonBindings()">
                    💾 Save Button Bindings
                </button>
            </p>
        </div>
        
        <!-- Menus Section -->
        <div class="cc-section" id="menus-section">
            <h2 style="display: flex; justify-content: space-between; align-items: center;">
                <span>📋 Menus</span>
                <button type="button" class="button button-primary" onclick="ccCreateMenu()">
                    + New Menu
                </button>
            </h2>
            
            <div id="menus-container">
                <?php if (empty($menus)): ?>
                <p style="color: #666; font-style: italic;">No menus created yet. Click "New Menu" to get started.</p>
                <?php else: ?>
                    <?php foreach ($menus as $menu): 
                        $items = isset($menu_items[$menu->id]) ? $menu_items[$menu->id] : [];
                    ?>
                    <div class="cc-menu-card" data-menu-id="<?php echo esc_attr($menu->id); ?>">
                        <div class="cc-menu-card-header" onclick="ccToggleMenuCard(this)">
                            <h3>
                                📋 <?php echo esc_html($menu->name); ?>
                                <?php if ($menu->trigger_button): ?>
                                <span style="font-weight: normal; color: #666; font-size: 13px;">
                                    (Trigger: <?php echo esc_html(strtoupper($menu->trigger_button)); ?>)
                                </span>
                                <?php endif; ?>
                            </h3>
                            <span class="dashicons dashicons-arrow-down-alt2"></span>
                        </div>
                        <div class="cc-menu-card-body">
                            <!-- Menu Items -->
                            <h4>Menu Items</h4>
                            <ul class="cc-menu-items" data-menu-id="<?php echo esc_attr($menu->id); ?>">
                                <?php if (empty($items)): ?>
                                <li class="cc-menu-item-empty" style="color: #666; font-style: italic; padding: 15px; text-align: center;">
                                    No items in this menu. Add some below.
                                </li>
                                <?php else: ?>
                                    <?php foreach ($items as $item): ?>
                                    <li class="cc-menu-item" data-item-id="<?php echo esc_attr($item->id); ?>">
                                        <span class="drag-handle dashicons dashicons-menu"></span>
                                        <span class="item-icon"><?php echo $item->icon ?: '📄'; ?></span>
                                        <span class="item-label"><?php echo esc_html($item->display_label); ?></span>
                                        <span class="item-type">
                                            <?php 
                                            if ($item->item_type === 'content_block' && $item->content_block_name) {
                                                echo esc_html($item->content_block_name);
                                            } elseif ($item->item_type === 'submenu') {
                                                echo 'Submenu';
                                            } elseif ($item->item_type === 'action') {
                                                echo 'Action: ' . esc_html($item->action_type);
                                            } else {
                                                echo esc_html($item->item_type);
                                            }
                                            ?>
                                        </span>
                                        <span class="item-actions">
                                            <button type="button" class="button button-small" onclick="ccEditMenuItem(<?php echo esc_attr($item->id); ?>, <?php echo esc_attr($menu->id); ?>)">✏️</button>
                                            <button type="button" class="button button-small" onclick="ccDeleteMenuItem(<?php echo esc_attr($item->id); ?>, <?php echo esc_attr($menu->id); ?>)">🗑️</button>
                                        </span>
                                    </li>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </ul>
                            
                            <div class="cc-add-item-row">
                                <button type="button" class="button" onclick="ccAddMenuItem(<?php echo esc_attr($menu->id); ?>)">
                                    + Add Menu Item
                                </button>
                            </div>
                            
                            <!-- Menu Style Settings -->
                            <h4 style="margin-top: 25px;">Menu Style</h4>
                            <div class="cc-style-grid">
                                <div class="cc-style-field">
                                    <label>Position</label>
                                    <select name="menu_position_<?php echo esc_attr($menu->id); ?>" 
                                            onchange="ccUpdateMenuStyle(<?php echo esc_attr($menu->id); ?>, 'position', this.value)">
                                        <option value="left" <?php selected($menu->position, 'left'); ?>>Left</option>
                                        <option value="right" <?php selected($menu->position, 'right'); ?>>Right</option>
                                        <option value="bottom" <?php selected($menu->position, 'bottom'); ?>>Bottom</option>
                                        <option value="top" <?php selected($menu->position, 'top'); ?>>Top</option>
                                    </select>
                                </div>
                                <div class="cc-style-field">
                                    <label>Animation</label>
                                    <select name="menu_animation_<?php echo esc_attr($menu->id); ?>"
                                            onchange="ccUpdateMenuStyle(<?php echo esc_attr($menu->id); ?>, 'animation', this.value)">
                                        <option value="slide" <?php selected($menu->animation, 'slide'); ?>>Slide</option>
                                        <option value="fade" <?php selected($menu->animation, 'fade'); ?>>Fade</option>
                                        <option value="none" <?php selected($menu->animation, 'none'); ?>>None</option>
                                    </select>
                                </div>
                                <div class="cc-style-field">
                                    <label>Width</label>
                                    <input type="number" value="<?php echo esc_attr($menu->width); ?>" 
                                           onchange="ccUpdateMenuStyle(<?php echo esc_attr($menu->id); ?>, 'width', this.value)">
                                </div>
                                <div class="cc-style-field">
                                    <label>Height</label>
                                    <input type="number" value="<?php echo esc_attr($menu->height); ?>"
                                           onchange="ccUpdateMenuStyle(<?php echo esc_attr($menu->id); ?>, 'height', this.value)">
                                </div>
                                <div class="cc-style-field">
                                    <label>Background Color</label>
                                    <div class="cc-color-field">
                                        <input type="color" value="<?php echo esc_attr(substr($menu->background_color, 0, 7)); ?>"
                                               onchange="ccUpdateMenuColor(<?php echo esc_attr($menu->id); ?>, 'background_color', this)">
                                        <input type="text" value="<?php echo esc_attr($menu->background_color); ?>"
                                               onchange="ccUpdateMenuStyle(<?php echo esc_attr($menu->id); ?>, 'background_color', this.value)">
                                    </div>
                                </div>
                                <div class="cc-style-field">
                                    <label>Background Image</label>
                                    <div class="cc-image-field" style="display: flex; gap: 8px; align-items: center;">
                                        <input type="text" id="menu-bg-image-<?php echo esc_attr($menu->id); ?>" 
                                               value="<?php echo esc_attr($menu->background_image ?? ''); ?>"
                                               placeholder="Image URL or use media library"
                                               style="flex: 1;"
                                               onchange="ccUpdateMenuStyle(<?php echo esc_attr($menu->id); ?>, 'background_image', this.value)">
                                        <button type="button" class="button" onclick="ccSelectMenuBackgroundImage(<?php echo esc_attr($menu->id); ?>)">
                                            📁
                                        </button>
                                        <?php if (!empty($menu->background_image)) : ?>
                                        <button type="button" class="button" onclick="ccClearMenuBackgroundImage(<?php echo esc_attr($menu->id); ?>)" title="Clear image">
                                            ✕
                                        </button>
                                        <?php endif; ?>
                                    </div>
                                    <?php if (!empty($menu->background_image)) : ?>
                                    <div style="margin-top: 8px;">
                                        <img src="<?php echo esc_url($menu->background_image); ?>" 
                                             style="max-width: 100%; max-height: 100px; border-radius: 4px; border: 1px solid #ddd;">
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <div class="cc-style-field">
                                    <label>Text Color</label>
                                    <div class="cc-color-field">
                                        <input type="color" value="<?php echo esc_attr($menu->text_color); ?>"
                                               onchange="ccUpdateMenuColor(<?php echo esc_attr($menu->id); ?>, 'text_color', this)">
                                        <input type="text" value="<?php echo esc_attr($menu->text_color); ?>"
                                               onchange="ccUpdateMenuStyle(<?php echo esc_attr($menu->id); ?>, 'text_color', this.value)">
                                    </div>
                                </div>
                                <div class="cc-style-field">
                                    <label>Accent Color</label>
                                    <div class="cc-color-field">
                                        <input type="color" value="<?php echo esc_attr($menu->accent_color); ?>"
                                               onchange="ccUpdateMenuColor(<?php echo esc_attr($menu->id); ?>, 'accent_color', this)">
                                        <input type="text" value="<?php echo esc_attr($menu->accent_color); ?>"
                                               onchange="ccUpdateMenuStyle(<?php echo esc_attr($menu->id); ?>, 'accent_color', this.value)">
                                    </div>
                                </div>
                                <div class="cc-style-field">
                                    <label>Font Size (px)</label>
                                    <input type="number" value="<?php echo esc_attr($menu->font_size ?? 18); ?>" min="12" max="36" step="1"
                                           onchange="ccUpdateMenuStyle(<?php echo esc_attr($menu->id); ?>, 'font_size', this.value)">
                                </div>
                                <div class="cc-style-field">
                                    <label>Background Overlay</label>
                                    <div style="display: flex; gap: 10px; align-items: center;">
                                        <label style="display: flex; align-items: center; gap: 5px; margin: 0;">
                                            <input type="checkbox" id="overlay_enabled_<?php echo esc_attr($menu->id); ?>"
                                                   <?php checked($menu->overlay_enabled ?? 1, 1); ?>
                                                   onchange="ccUpdateMenuStyle(<?php echo esc_attr($menu->id); ?>, 'overlay_enabled', this.checked ? 1 : 0)">
                                            Enable
                                        </label>
                                        <input type="range" id="overlay_opacity_<?php echo esc_attr($menu->id); ?>"
                                               value="<?php echo esc_attr(($menu->overlay_opacity ?? 0.9) * 100); ?>"
                                               min="0" max="100" step="5"
                                               style="flex: 1;"
                                               onchange="ccUpdateMenuStyle(<?php echo esc_attr($menu->id); ?>, 'overlay_opacity', this.value / 100); document.getElementById('opacity_val_<?php echo esc_attr($menu->id); ?>').textContent = this.value + '%'">
                                        <span id="opacity_val_<?php echo esc_attr($menu->id); ?>" style="min-width: 40px;"><?php echo esc_html(round(($menu->overlay_opacity ?? 0.9) * 100)); ?>%</span>
                                    </div>
                                </div>
                                <div class="cc-style-field">
                                    <label style="display: flex; align-items: center; gap: 10px;">
                                        <input type="checkbox" id="show_live_stream_button_<?php echo esc_attr($menu->id); ?>"
                                               <?php checked($menu->show_live_stream_button ?? 1, 1); ?>
                                               onchange="ccUpdateMenuStyle(<?php echo esc_attr($menu->id); ?>, 'show_live_stream_button', this.checked ? 1 : 0)">
                                        Show "Play Live Stream" Button
                                    </label>
                                    <p class="description" style="margin: 5px 0 0; color: #666; font-size: 12px;">Adds a persistent button to return to the main audio stream</p>
                                </div>
                            </div>
                            
                            <div style="margin-top: 20px; padding-top: 15px; border-top: 1px solid #eee; display: flex; justify-content: space-between;">
                                <button type="button" class="button button-primary" onclick="ccSaveMenuStyle(<?php echo esc_attr($menu->id); ?>)">
                                    💾 Save Menu Style
                                </button>
                                <button type="button" class="button" style="color: #d63638;" onclick="ccDeleteMenu(<?php echo esc_attr($menu->id); ?>)">
                                    🗑️ Delete Menu
                                </button>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
    
    <!-- Add/Edit Menu Item Modal Template -->
    <div id="cc-menu-item-modal" class="cc-modal-overlay" style="display: none;">
        <div class="cc-modal">
            <div class="cc-modal-header">
                <h3 id="cc-modal-title">Add Menu Item</h3>
                <button type="button" class="button" onclick="ccCloseModal()">&times;</button>
            </div>
            <div class="cc-modal-body">
                <input type="hidden" id="modal-item-id" value="">
                <input type="hidden" id="modal-menu-id" value="">
                
                <div class="cc-form-row">
                    <label for="modal-display-label">Display Label</label>
                    <input type="text" id="modal-display-label" placeholder="e.g., Mixshow Archive">
                </div>
                
                <div class="cc-form-row">
                    <label for="modal-icon">Icon (emoji)</label>
                    <input type="text" id="modal-icon" placeholder="e.g., 🎧" maxlength="10">
                </div>
                
                <div class="cc-form-row">
                    <label for="modal-item-type">Item Type</label>
                    <select id="modal-item-type" onchange="ccModalTypeChange()">
                        <option value="content_block">Content Block</option>
                        <option value="submenu">Submenu</option>
                        <option value="action">Action</option>
                    </select>
                </div>
                
                <div class="cc-form-row" id="modal-content-block-row">
                    <label for="modal-content-block-id">Content Block</label>
                    <select id="modal-content-block-id">
                        <option value="">— Select —</option>
                        <?php foreach ($content_blocks as $cb): ?>
                        <option value="<?php echo esc_attr($cb->id); ?>">
                            <?php echo esc_html($cb->name); ?> (<?php echo esc_html($cb->type); ?>)
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="cc-form-row" id="modal-submenu-row" style="display: none;">
                    <label for="modal-submenu-id">Submenu</label>
                    <select id="modal-submenu-id">
                        <option value="">— Select —</option>
                        <?php foreach ($menus as $menu): ?>
                        <option value="<?php echo esc_attr($menu->id); ?>">
                            <?php echo esc_html($menu->name); ?>
                        </option>
                        <?php endforeach; ?>
                    </select>
                </div>
                
                <div class="cc-form-row" id="modal-action-row" style="display: none;">
                    <label for="modal-action-type">Action</label>
                    <select id="modal-action-type">
                        <option value="settings">Open Settings</option>
                        <option value="about">Show About</option>
                        <option value="switch_scene">Switch Scene</option>
                    </select>
                </div>
            </div>
            <div class="cc-modal-footer">
                <button type="button" class="button" onclick="ccCloseModal()">Cancel</button>
                <button type="button" class="button button-primary" onclick="ccSaveMenuItem()">Save Item</button>
            </div>
        </div>
    </div>
    
    <!-- Create Menu Modal -->
    <div id="cc-create-menu-modal" class="cc-modal-overlay" style="display: none;">
        <div class="cc-modal">
            <div class="cc-modal-header">
                <h3>Create New Menu</h3>
                <button type="button" class="button" onclick="ccCloseCreateMenuModal()">&times;</button>
            </div>
            <div class="cc-modal-body">
                <div class="cc-form-row">
                    <label for="new-menu-name">Menu Name</label>
                    <input type="text" id="new-menu-name" placeholder="e.g., Main Menu">
                </div>
            </div>
            <div class="cc-modal-footer">
                <button type="button" class="button" onclick="ccCloseCreateMenuModal()">Cancel</button>
                <button type="button" class="button button-primary" onclick="ccSaveNewMenu()">Create Menu</button>
            </div>
        </div>
    </div>
    
    <script>
    (function($) {
        const API_BASE = '<?php echo esc_url(rest_url('castconductor/v5')); ?>';
        const NONCE = '<?php echo wp_create_nonce('wp_rest'); ?>';
        
        // Initialize sortable for menu items
        $(document).ready(function() {
            $('.cc-menu-items').sortable({
                handle: '.drag-handle',
                update: function(event, ui) {
                    const menuId = $(this).data('menu-id');
                    const itemIds = $(this).find('.cc-menu-item').map(function() {
                        return $(this).data('item-id');
                    }).get();
                    
                    ccReorderMenuItems(menuId, itemIds);
                }
            });
        });
        
        // Toggle menu card expansion
        window.ccToggleMenuCard = function(header) {
            $(header).closest('.cc-menu-card').toggleClass('expanded');
        };
        
        // Update binding type radio change
        window.ccUpdateBindingType = function(button, type) {
            const container = $(`[data-button="${button}"]`);
            container.find('.binding-options').removeClass('active');
            
            if (type === 'menu') {
                container.find('.menu-options').addClass('active');
            } else if (type === 'content_block') {
                container.find('.content-block-options').addClass('active');
            }
        };
        
        // Save all button bindings
        window.ccSaveButtonBindings = function() {
            const bindings = [];
            
            $('.cc-button-binding').each(function() {
                const button = $(this).data('button');
                const type = $(`input[name="binding_${button}"]:checked`).val();
                
                const binding = {
                    trigger_button: button,
                    binding_type: type
                };
                
                if (type === 'menu') {
                    binding.menu_id = $(`select[name="menu_id_${button}"]`).val() || null;
                } else if (type === 'content_block') {
                    binding.content_block_id = $(`select[name="content_block_id_${button}"]`).val() || null;
                    binding.overlay_position = $(`select[name="overlay_position_${button}"]`).val();
                    binding.overlay_animation = $(`select[name="overlay_animation_${button}"]`).val();
                }
                
                bindings.push(binding);
            });
            
            $.ajax({
                url: API_BASE + '/button-bindings',
                method: 'PUT',
                headers: { 'X-WP-Nonce': NONCE },
                contentType: 'application/json',
                data: JSON.stringify({ bindings: bindings }),
                success: function() {
                    ccShowToast('Button bindings saved!', 'success');
                },
                error: function(xhr) {
                    ccShowToast('Error saving bindings: ' + xhr.responseText, 'error');
                }
            });
        };
        
        // Create new menu
        window.ccCreateMenu = function() {
            $('#new-menu-name').val('');
            $('#cc-create-menu-modal').show();
        };
        
        window.ccCloseCreateMenuModal = function() {
            $('#cc-create-menu-modal').hide();
        };
        
        window.ccSaveNewMenu = function() {
            const name = $('#new-menu-name').val().trim();
            if (!name) {
                alert('Please enter a menu name');
                return;
            }
            
            $.ajax({
                url: API_BASE + '/menus',
                method: 'POST',
                headers: { 'X-WP-Nonce': NONCE },
                contentType: 'application/json',
                data: JSON.stringify({ name: name }),
                success: function() {
                    ccShowToast('Menu created!', 'success');
                    location.reload();
                },
                error: function(xhr) {
                    ccShowToast('Error creating menu: ' + xhr.responseText, 'error');
                }
            });
        };
        
        // Delete menu
        window.ccDeleteMenu = function(menuId) {
            if (!confirm('Are you sure you want to delete this menu and all its items?')) {
                return;
            }
            
            $.ajax({
                url: API_BASE + '/menus/' + menuId,
                method: 'DELETE',
                headers: { 'X-WP-Nonce': NONCE },
                success: function() {
                    ccShowToast('Menu deleted!', 'success');
                    $(`.cc-menu-card[data-menu-id="${menuId}"]`).fadeOut(function() {
                        $(this).remove();
                    });
                },
                error: function(xhr) {
                    ccShowToast('Error deleting menu: ' + xhr.responseText, 'error');
                }
            });
        };
        
        // Update menu style
        window.ccUpdateMenuStyle = function(menuId, field, value) {
            // Store for batch save
            if (!window.menuStyleChanges) window.menuStyleChanges = {};
            if (!window.menuStyleChanges[menuId]) window.menuStyleChanges[menuId] = {};
            window.menuStyleChanges[menuId][field] = value;
        };
        
        window.ccUpdateMenuColor = function(menuId, field, input) {
            const textInput = $(input).siblings('input[type="text"]');
            const currentValue = textInput.val();
            // Preserve alpha if present
            const alpha = currentValue.length > 7 ? currentValue.slice(7) : '';
            const newValue = input.value + alpha;
            textInput.val(newValue);
            ccUpdateMenuStyle(menuId, field, newValue);
        };
        
        // Select background image from media library
        window.ccSelectMenuBackgroundImage = function(menuId) {
            if (!window.wp || !window.wp.media) {
                alert('WordPress media library not available');
                return;
            }
            const frame = wp.media({
                title: 'Select Menu Background Image',
                button: { text: 'Use as Background' },
                multiple: false
            });
            frame.on('select', function() {
                const attachment = frame.state().get('selection').first().toJSON();
                const input = document.getElementById('menu-bg-image-' + menuId);
                if (input) {
                    input.value = attachment.url;
                    ccUpdateMenuStyle(menuId, 'background_image', attachment.url);
                    ccShowToast('Background image selected. Click "Save Menu Style" to apply.', 'info');
                }
            });
            frame.open();
        };
        
        // Clear background image
        window.ccClearMenuBackgroundImage = function(menuId) {
            const input = document.getElementById('menu-bg-image-' + menuId);
            if (input) {
                input.value = '';
                ccUpdateMenuStyle(menuId, 'background_image', '');
                ccShowToast('Background image cleared. Click "Save Menu Style" to apply.', 'info');
            }
        };
        
        window.ccSaveMenuStyle = function(menuId) {
            const changes = window.menuStyleChanges && window.menuStyleChanges[menuId];
            if (!changes || Object.keys(changes).length === 0) {
                ccShowToast('No changes to save', 'info');
                return;
            }
            
            $.ajax({
                url: API_BASE + '/menus/' + menuId,
                method: 'PUT',
                headers: { 'X-WP-Nonce': NONCE },
                contentType: 'application/json',
                data: JSON.stringify(changes),
                success: function() {
                    ccShowToast('Menu style saved!', 'success');
                    window.menuStyleChanges[menuId] = {};
                },
                error: function(xhr) {
                    ccShowToast('Error saving style: ' + xhr.responseText, 'error');
                }
            });
        };
        
        // Menu item modal
        window.ccAddMenuItem = function(menuId) {
            $('#cc-modal-title').text('Add Menu Item');
            $('#modal-item-id').val('');
            $('#modal-menu-id').val(menuId);
            $('#modal-display-label').val('');
            $('#modal-icon').val('');
            $('#modal-item-type').val('content_block');
            $('#modal-content-block-id').val('');
            $('#modal-submenu-id').val('');
            $('#modal-action-type').val('settings');
            ccModalTypeChange();
            $('#cc-menu-item-modal').show();
        };
        
        window.ccEditMenuItem = function(itemId, menuId) {
            // Fetch item data
            $.ajax({
                url: API_BASE + '/menus/' + menuId,
                method: 'GET',
                headers: { 'X-WP-Nonce': NONCE },
                success: function(response) {
                    const items = response.data.items || [];
                    const item = items.find(i => i.id == itemId);
                    if (!item) {
                        alert('Item not found');
                        return;
                    }
                    
                    $('#cc-modal-title').text('Edit Menu Item');
                    $('#modal-item-id').val(item.id);
                    $('#modal-menu-id').val(menuId);
                    $('#modal-display-label').val(item.display_label);
                    $('#modal-icon').val(item.icon || '');
                    $('#modal-item-type').val(item.item_type);
                    $('#modal-content-block-id').val(item.content_block_id || '');
                    $('#modal-submenu-id').val(item.submenu_id || '');
                    $('#modal-action-type').val(item.action_type || 'settings');
                    ccModalTypeChange();
                    $('#cc-menu-item-modal').show();
                }
            });
        };
        
        window.ccModalTypeChange = function() {
            const type = $('#modal-item-type').val();
            $('#modal-content-block-row').toggle(type === 'content_block');
            $('#modal-submenu-row').toggle(type === 'submenu');
            $('#modal-action-row').toggle(type === 'action');
        };
        
        window.ccCloseModal = function() {
            $('#cc-menu-item-modal').hide();
        };
        
        window.ccSaveMenuItem = function() {
            const itemId = $('#modal-item-id').val();
            const menuId = $('#modal-menu-id').val();
            const isEdit = !!itemId;
            
            const data = {
                display_label: $('#modal-display-label').val().trim(),
                icon: $('#modal-icon').val().trim(),
                item_type: $('#modal-item-type').val(),
                content_block_id: $('#modal-content-block-id').val() || null,
                submenu_id: $('#modal-submenu-id').val() || null,
                action_type: $('#modal-action-type').val()
            };
            
            if (!data.display_label) {
                alert('Please enter a display label');
                return;
            }
            
            const url = isEdit 
                ? API_BASE + '/menus/items/' + itemId
                : API_BASE + '/menus/' + menuId + '/items';
            
            $.ajax({
                url: url,
                method: isEdit ? 'PUT' : 'POST',
                headers: { 'X-WP-Nonce': NONCE },
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function() {
                    ccShowToast(isEdit ? 'Item updated!' : 'Item added!', 'success');
                    ccCloseModal();
                    location.reload();
                },
                error: function(xhr) {
                    ccShowToast('Error saving item: ' + xhr.responseText, 'error');
                }
            });
        };
        
        window.ccDeleteMenuItem = function(itemId, menuId) {
            if (!confirm('Delete this menu item?')) return;
            
            $.ajax({
                url: API_BASE + '/menus/items/' + itemId,
                method: 'DELETE',
                headers: { 'X-WP-Nonce': NONCE },
                success: function() {
                    ccShowToast('Item deleted!', 'success');
                    $(`.cc-menu-item[data-item-id="${itemId}"]`).fadeOut(function() {
                        $(this).remove();
                    });
                },
                error: function(xhr) {
                    ccShowToast('Error deleting item: ' + xhr.responseText, 'error');
                }
            });
        };
        
        // Reorder menu items
        window.ccReorderMenuItems = function(menuId, itemIds) {
            $.ajax({
                url: API_BASE + '/menus/' + menuId + '/reorder',
                method: 'POST',
                headers: { 'X-WP-Nonce': NONCE },
                contentType: 'application/json',
                data: JSON.stringify({ item_ids: itemIds }),
                success: function() {
                    ccShowToast('Order saved!', 'success');
                },
                error: function(xhr) {
                    ccShowToast('Error saving order: ' + xhr.responseText, 'error');
                }
            });
        };
        
        // Toast notification
        window.ccShowToast = function(message, type) {
            const toast = $(`<div class="cc-toast ${type || ''}">${message}</div>`);
            $('body').append(toast);
            setTimeout(() => toast.fadeOut(() => toast.remove()), 3000);
        };
        
    })(jQuery);
    </script>
    <?php
}
