/**
 * Unified "Add Layer" Dropdown UI
 * 
 * Replaces multiple confusing buttons with single intuitive dropdown menu.
 * Handles layer creation for all layer kinds.
 * 
 * @module add-layer-ui
 * @since 5.2.1 - Unified Layer System
 */

import {
    LAYER_KIND_TOKEN_TEXT,
    LAYER_KIND_STATIC_TEXT,
    LAYER_KIND_TOKEN_IMAGE,
    LAYER_KIND_STATIC_IMAGE,
    LAYER_KIND_SLIDESHOW_IMAGE,
    LAYER_KIND_QR_IMAGE,
    LAYER_KIND_BACKGROUND_IMAGE,
    LAYER_KIND_WP_POST,
    LAYER_KIND_VIDEO,
    LAYER_KIND_FEED,
    createTokenTextLayer,
    createStaticTextLayer,
    createTokenImageLayer,
    createStaticImageLayer,
    createSlideshowImageLayer,
    createQrImageLayer,
    createWordPressPostLayer,
    createVideoLayer,
    createFeedLayer,
    getLayerTypeName
} from './layer-constants.js';

/**
 * Attach unified "Add Layer" dropdown to canvas editor
 * 
 * @param {Object} editor - Canvas editor instance
 */
export function attachAddLayerDropdown(editor) {
    // Find the existing Add Layer button in the category tabs
    const mainButton = document.getElementById('ccve-add-layer-btn');
    if (!mainButton) {
        console.warn('[Add Layer UI] Button #ccve-add-layer-btn not found in DOM');
        return;
    }
    
    // Create dropdown container wrapper
    const dropdownContainer = document.createElement('div');
    dropdownContainer.className = 'ccve-add-layer-dropdown';
    dropdownContainer.style.position = 'relative';
    dropdownContainer.style.display = 'inline-block';
    
    // Wrap the existing button
    mainButton.parentNode.insertBefore(dropdownContainer, mainButton);
    dropdownContainer.appendChild(mainButton);
    
    // Create dropdown menu
    const dropdown = document.createElement('div');
    dropdown.className = 'ccve-add-layer-menu';
    dropdown.style.cssText = `
        position: absolute;
        top: 100%;
        left: 0;
        margin-top: 4px;
        background: white;
        border: 1px solid #d1d5db;
        border-radius: 6px;
        box-shadow: 0 4px 6px -1px rgba(0,0,0,0.1), 0 2px 4px -1px rgba(0,0,0,0.06);
        min-width: 280px;
        max-height: 500px;
        overflow-y: auto;
        z-index: 1000;
        display: none;
    `;
    
    // Build menu structure
    dropdown.innerHTML = buildDropdownMenu();
    
    // Toggle dropdown on button click
    mainButton.addEventListener('click', (e) => {
        e.stopPropagation();
        const isVisible = dropdown.style.display === 'block';
        dropdown.style.display = isVisible ? 'none' : 'block';
    });
    
    // Close dropdown when clicking outside
    document.addEventListener('click', (e) => {
        if (!dropdownContainer.contains(e.target)) {
            dropdown.style.display = 'none';
        }
    });
    
    // Handle menu item clicks
    dropdown.addEventListener('click', (e) => {
        const menuItem = e.target.closest('.ccve-menu-item');
        if (!menuItem) return;
        
        const layerKind = menuItem.dataset.layerKind;
        if (layerKind) {
            handleAddLayer(editor, layerKind);
            dropdown.style.display = 'none';
        }
    });
    
    dropdownContainer.appendChild(dropdown);
    
    // Store reference on editor
    editor._addLayerDropdown = dropdownContainer;
}

/**
 * Build dropdown menu HTML
 * 
 * @returns {string} Menu HTML
 */
function buildDropdownMenu() {
    return `
        <div class="ccve-menu-section">
            <div class="ccve-menu-header">
                <span style="font-size: 16px; margin-right: 6px;">📝</span>
                <span style="font-weight: 600;">Text Layers</span>
            </div>
            <div class="ccve-menu-item" data-layer-kind="${LAYER_KIND_TOKEN_TEXT}">
                <div class="ccve-menu-item-icon">🔤</div>
                <div class="ccve-menu-item-content">
                    <div class="ccve-menu-item-title">Token Text</div>
                    <div class="ccve-menu-item-desc">Dynamic text from metadata tokens</div>
                </div>
            </div>
            <div class="ccve-menu-item" data-layer-kind="${LAYER_KIND_STATIC_TEXT}">
                <div class="ccve-menu-item-icon">✏️</div>
                <div class="ccve-menu-item-content">
                    <div class="ccve-menu-item-title">Static Text</div>
                    <div class="ccve-menu-item-desc">Custom editable text</div>
                </div>
            </div>
        </div>
        
        <div class="ccve-menu-divider"></div>
        
        <div class="ccve-menu-section">
            <div class="ccve-menu-header">
                <span style="font-size: 16px; margin-right: 6px;">🖼️</span>
                <span style="font-weight: 600;">Image Layers</span>
            </div>
            <div class="ccve-menu-item" data-layer-kind="${LAYER_KIND_TOKEN_IMAGE}">
                <div class="ccve-menu-item-icon">🎨</div>
                <div class="ccve-menu-item-content">
                    <div class="ccve-menu-item-title">Token Image</div>
                    <div class="ccve-menu-item-desc">Dynamic images from tokens (artwork, logos)</div>
                </div>
            </div>
            <div class="ccve-menu-item" data-layer-kind="${LAYER_KIND_STATIC_IMAGE}">
                <div class="ccve-menu-item-icon">🖼️</div>
                <div class="ccve-menu-item-content">
                    <div class="ccve-menu-item-title">Static Image</div>
                    <div class="ccve-menu-item-desc">Upload or select from media library</div>
                </div>
            </div>
            <div class="ccve-menu-item" data-layer-kind="${LAYER_KIND_SLIDESHOW_IMAGE}">
                <div class="ccve-menu-item-icon">🎞️</div>
                <div class="ccve-menu-item-content">
                    <div class="ccve-menu-item-title">Slideshow</div>
                    <div class="ccve-menu-item-desc">Multiple images with transitions</div>
                </div>
            </div>
            <div class="ccve-menu-item" data-layer-kind="${LAYER_KIND_BACKGROUND_IMAGE}">
                <div class="ccve-menu-item-icon">🌄</div>
                <div class="ccve-menu-item-content">
                    <div class="ccve-menu-item-title">Background Image</div>
                    <div class="ccve-menu-item-desc">Full-canvas background</div>
                </div>
            </div>
        </div>
        
        <div class="ccve-menu-divider"></div>
        
        <div class="ccve-menu-section">
            <div class="ccve-menu-header">
                <span style="font-size: 16px; margin-right: 6px;">🎬</span>
                <span style="font-weight: 600;">Video Layers</span>
            </div>
            <div class="ccve-menu-item" data-layer-kind="${LAYER_KIND_VIDEO}">
                <div class="ccve-menu-item-icon">📹</div>
                <div class="ccve-menu-item-content">
                    <div class="ccve-menu-item-title">Video</div>
                    <div class="ccve-menu-item-desc">Embedded video (HLS, MP4)</div>
                </div>
            </div>
        </div>
        
        <div class="ccve-menu-divider"></div>
        
        <div class="ccve-menu-section">
            <div class="ccve-menu-header">
                <span style="font-size: 16px; margin-right: 6px;">📡</span>
                <span style="font-weight: 600;">Feed Layers</span>
            </div>
            <div class="ccve-menu-item" data-layer-kind="${LAYER_KIND_FEED}">
                <div class="ccve-menu-item-icon">📋</div>
                <div class="ccve-menu-item-content">
                    <div class="ccve-menu-item-title">RSS/Podcast Feed</div>
                    <div class="ccve-menu-item-desc">Display content from RSS, Atom, or MRSS</div>
                </div>
            </div>
            <div class="ccve-menu-item" data-layer-kind="${LAYER_KIND_FEED}" data-feed-type="youtube">
                <div class="ccve-menu-item-icon">▶️</div>
                <div class="ccve-menu-item-content">
                    <div class="ccve-menu-item-title">YouTube Playlist</div>
                    <div class="ccve-menu-item-desc">Display YouTube videos from playlist or channel</div>
                </div>
            </div>
            <div class="ccve-menu-item" data-layer-kind="${LAYER_KIND_FEED}" data-feed-type="json">
                <div class="ccve-menu-item-icon">📄</div>
                <div class="ccve-menu-item-content">
                    <div class="ccve-menu-item-title">JSON Feed / API</div>
                    <div class="ccve-menu-item-desc">Custom JSON endpoint or Roku Direct Publisher</div>
                </div>
            </div>
        </div>
        
        <div class="ccve-menu-divider"></div>
        
        <div class="ccve-menu-section">
            <div class="ccve-menu-header">
                <span style="font-size: 16px; margin-right: 6px;">🔧</span>
                <span style="font-weight: 600;">Special Layers</span>
            </div>
            <div class="ccve-menu-item" data-layer-kind="${LAYER_KIND_QR_IMAGE}">
                <div class="ccve-menu-item-icon">
                    <svg style="width: 20px; height: 20px;" fill="currentColor" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm3 2h6v4H7V5zm8 8v2h1v-2h-1zm-2-2H7v4h6v-4zm2 0h1V9h-1v2zm1-4V5h-1v2h1zM5 9H4v2h1V9zm0 4H4v2h1v-2zM5 5H4v2h1V5z" clip-rule="evenodd"/>
                    </svg>
                </div>
                <div class="ccve-menu-item-content">
                    <div class="ccve-menu-item-title">QR Code</div>
                    <div class="ccve-menu-item-desc">Generate scannable QR codes</div>
                </div>
            </div>
            <div class="ccve-menu-item" data-layer-kind="${LAYER_KIND_WP_POST}">
                <div class="ccve-menu-item-icon">📰</div>
                <div class="ccve-menu-item-content">
                    <div class="ccve-menu-item-title">WordPress Post</div>
                    <div class="ccve-menu-item-desc">Link to WordPress post content</div>
                </div>
            </div>
        </div>
        
        <div class="ccve-menu-divider"></div>
        
        <div class="ccve-menu-section">
            <div class="ccve-menu-footer">
                <small style="color: #6b7280; font-size: 11px;">
                    💡 Tip: All layers are draggable, resizable, and support smart guides
                </small>
            </div>
        </div>
    `;
}

/**
 * Handle adding a new layer
 * 
 * @param {Object} editor - Canvas editor instance
 * @param {string} layerKind - Layer kind constant
 */
function handleAddLayer(editor, layerKind) {
    let newLayer;
    
    switch (layerKind) {
        case LAYER_KIND_TOKEN_TEXT:
            newLayer = createTokenTextLayer('{{track.title}}', {
                x: 100,
                y: 100,
                width: 400,
                height: 60,
                font_size: 32,
                font_color: '#ffffff'
            });
            break;
        
        case LAYER_KIND_STATIC_TEXT:
            newLayer = createStaticTextLayer('Edit this text...', {
                x: 100,
                y: 100,
                width: 400,
                height: 60,
                font_size: 24,
                font_color: '#ffffff'
            });
            break;
        
        case LAYER_KIND_TOKEN_IMAGE:
            newLayer = createTokenImageLayer('track.artwork', {
                x: 50,
                y: 50,
                width: 200,
                height: 200
            });
            break;
        
        case LAYER_KIND_STATIC_IMAGE:
            // Open media library immediately
            openMediaLibraryForNewLayer(editor, LAYER_KIND_STATIC_IMAGE);
            return;
        
        case LAYER_KIND_SLIDESHOW_IMAGE:
            // Open media library for multiple images
            openMediaLibraryForNewLayer(editor, LAYER_KIND_SLIDESHOW_IMAGE, true);
            return;
        
        case LAYER_KIND_BACKGROUND_IMAGE:
            openMediaLibraryForNewLayer(editor, LAYER_KIND_BACKGROUND_IMAGE);
            return;
        
        case LAYER_KIND_QR_IMAGE:
            // Open QR code generator modal
            if (editor.openQrCodeGenerator) {
                editor.openQrCodeGenerator();
            } else {
                // Fallback: create default QR layer
                newLayer = createQrImageLayer('https://example.com', {
                    x: 100,
                    y: 100,
                    width: 256,
                    height: 256
                });
            }
            break;
        
        case LAYER_KIND_WP_POST:
            // Create WordPress Post layer with container-appropriate position
            {
                // Get container bounds for proper sizing
                const layout = editor.currentConfig?.layout;
                const containerW = layout?.width || 1280;
                const containerH = layout?.height || 720;
                
                // Size appropriately for container
                const defaultW = Math.min(400, containerW - 120);
                const defaultH = Math.min(150, containerH - 40);
                
                newLayer = createWordPressPostLayer(null, {
                    x: 60,
                    y: 20,
                    width: defaultW,
                    height: defaultH
                });
                
                // Store reference to find in config after adding
                const layerId = newLayer.id;
                
                // Immediately open post selector after adding layer
                setTimeout(() => {
                    // Find the layer in config (in case reference changed)
                    const layerInConfig = (editor.currentConfig?.layers || []).find(l => l.id === layerId);
                    if (editor.openPostSelector && layerInConfig) {
                        editor.openPostSelector(layerInConfig);
                    }
                }, 150);
            }
            break;
        
        case LAYER_KIND_VIDEO:
            // Open video URL modal
            openVideoUrlModal(editor);
            return;
        
        case LAYER_KIND_FEED:
            // Open feed configuration modal
            openFeedConfigModal(editor);
            return;
        
        default:
            console.error('[AddLayerUI] Unknown layer kind:', layerKind);
            return;
    }
    
    // Add layer to config if created
    if (newLayer) {
        addLayerToCanvas(editor, newLayer);
    }
}

/**
 * Open media library and create layer with selected image(s)
 * 
 * @param {Object} editor - Canvas editor instance
 * @param {string} layerKind - Layer kind
 * @param {boolean} multiple - Allow multiple selection
 */
function openMediaLibraryForNewLayer(editor, layerKind, multiple = false) {
    if (!window.wp || !window.wp.media) {
        alert('WordPress media library not available');
        return;
    }
    
    const frame = window.wp.media({
        title: multiple ? 'Select Images' : 'Select Image',
        button: { text: 'Select' },
        multiple: multiple
    });
    
    frame.on('select', () => {
        const selection = frame.state().get('selection');
        let newLayer;
        
        if (multiple) {
            // Slideshow with multiple images
            const images = selection.map(attachment => ({
                url: attachment.toJSON().url,
                duration: 5000
            }));
            
            newLayer = createSlideshowImageLayer(images, {
                x: 0,
                y: 0,
                width: 1920,
                height: 1080,
                zIndex: 0
            });
        } else {
            // Single image
            const url = selection.first().toJSON().url;
            
            if (layerKind === LAYER_KIND_BACKGROUND_IMAGE) {
                newLayer = {
                    ...createStaticImageLayer(url, {
                        x: 0,
                        y: 0,
                        width: 1920,
                        height: 1080,
                        zIndex: 0
                    }),
                    kind: LAYER_KIND_BACKGROUND_IMAGE
                };
            } else {
                newLayer = createStaticImageLayer(url, {
                    x: 100,
                    y: 100,
                    width: 400,
                    height: 300
                });
            }
        }
        
        addLayerToCanvas(editor, newLayer);
    });
    
    frame.open();
}

/**
 * Open video URL modal for adding a video layer
 * 
 * @param {Object} editor - Canvas editor instance
 */
function openVideoUrlModal(editor) {
    // Remove any existing modal
    const existing = document.getElementById('ccve-video-url-modal');
    if (existing) existing.remove();
    
    // Create modal
    const modal = document.createElement('div');
    modal.id = 'ccve-video-url-modal';
    modal.style.cssText = `
        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;
    `;
    
    modal.innerHTML = `
        <div style="
            background: white;
            border-radius: 8px;
            padding: 24px;
            width: 500px;
            max-width: 90vw;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        ">
            <h3 style="margin: 0 0 16px 0; font-size: 18px; font-weight: 600; color: #111827;">
                🎬 Add Video Layer
            </h3>
            <div style="margin-bottom: 16px;">
                <label style="display: block; margin-bottom: 6px; font-size: 14px; font-weight: 500; color: #374151;">
                    Video URL
                </label>
                <input 
                    type="url" 
                    id="ccve-video-url-input"
                    placeholder="https://example.com/video.m3u8 or .mp4"
                    style="
                        width: 100%;
                        padding: 10px 12px;
                        border: 1px solid #d1d5db;
                        border-radius: 6px;
                        font-size: 14px;
                        box-sizing: border-box;
                    "
                />
                <p style="margin: 8px 0 0 0; font-size: 12px; color: #6b7280;">
                    Supports: HLS (.m3u8), MP4, DASH (.mpd), RTMP streams
                </p>
            </div>
            <div style="margin-bottom: 16px;">
                <label style="display: block; margin-bottom: 6px; font-size: 14px; font-weight: 500; color: #374151;">
                    Poster Image (optional)
                </label>
                <input 
                    type="url" 
                    id="ccve-video-poster-input"
                    placeholder="https://example.com/thumbnail.jpg"
                    style="
                        width: 100%;
                        padding: 10px 12px;
                        border: 1px solid #d1d5db;
                        border-radius: 6px;
                        font-size: 14px;
                        box-sizing: border-box;
                    "
                />
            </div>
            <div style="display: flex; gap: 12px; margin-bottom: 16px;">
                <label style="display: flex; align-items: center; gap: 6px; font-size: 14px; color: #374151; cursor: pointer;">
                    <input type="checkbox" id="ccve-video-autoplay" checked />
                    Autoplay
                </label>
                <label style="display: flex; align-items: center; gap: 6px; font-size: 14px; color: #374151; cursor: pointer;">
                    <input type="checkbox" id="ccve-video-loop" checked />
                    Loop
                </label>
                <label style="display: flex; align-items: center; gap: 6px; font-size: 14px; color: #374151; cursor: pointer;">
                    <input type="checkbox" id="ccve-video-muted" />
                    Muted
                </label>
            </div>
            
            <!-- Deep Linking Section -->
            <details style="margin-bottom: 16px; border: 1px solid #e5e7eb; border-radius: 6px; padding: 12px;">
                <summary style="cursor: pointer; font-size: 14px; font-weight: 500; color: #374151; user-select: none;">
                    🔗 Deep Linking (Roku Search)
                </summary>
                <div style="margin-top: 12px;">
                    <p style="margin: 0 0 12px 0; font-size: 12px; color: #6b7280;">
                        Configure how this video appears in Roku Universal Search results.
                    </p>
                    <div style="margin-bottom: 12px;">
                        <label style="display: block; margin-bottom: 4px; font-size: 13px; color: #374151;">
                            Media Type
                        </label>
                        <select id="ccve-video-media-type" style="
                            width: 100%;
                            padding: 8px;
                            border: 1px solid #d1d5db;
                            border-radius: 4px;
                            font-size: 13px;
                        ">
                            <option value="shortFormVideo">Short-form Video (clips &lt;15min)</option>
                            <option value="movie">Movie (standalone film)</option>
                            <option value="episode">Episode (TV/podcast)</option>
                            <option value="live">Live (streaming)</option>
                        </select>
                    </div>
                    <div style="margin-bottom: 12px;">
                        <label style="display: flex; align-items: center; gap: 6px; font-size: 13px; color: #374151; cursor: pointer;">
                            <input type="checkbox" id="ccve-video-searchable" checked />
                            Include in Roku Search
                        </label>
                        <p style="margin: 4px 0 0 22px; font-size: 11px; color: #9ca3af;">
                            When enabled, this video will appear in Roku Universal Search results.
                        </p>
                    </div>
                </div>
            </details>
            
            <div style="display: flex; justify-content: flex-end; gap: 12px;">
                <button 
                    id="ccve-video-cancel-btn"
                    style="
                        padding: 10px 16px;
                        background: #f3f4f6;
                        border: 1px solid #d1d5db;
                        border-radius: 6px;
                        font-size: 14px;
                        cursor: pointer;
                    "
                >Cancel</button>
                <button 
                    id="ccve-video-add-btn"
                    style="
                        padding: 10px 16px;
                        background: #3b82f6;
                        color: white;
                        border: none;
                        border-radius: 6px;
                        font-size: 14px;
                        font-weight: 500;
                        cursor: pointer;
                    "
                >Add Video</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // Focus input
    const urlInput = document.getElementById('ccve-video-url-input');
    urlInput.focus();
    
    // Handle cancel
    document.getElementById('ccve-video-cancel-btn').addEventListener('click', () => {
        modal.remove();
    });
    
    // Handle backdrop click
    modal.addEventListener('click', (e) => {
        if (e.target === modal) modal.remove();
    });
    
    // Handle ESC key
    const handleEsc = (e) => {
        if (e.key === 'Escape') {
            modal.remove();
            document.removeEventListener('keydown', handleEsc);
        }
    };
    document.addEventListener('keydown', handleEsc);
    
    // Handle add
    document.getElementById('ccve-video-add-btn').addEventListener('click', () => {
        const url = urlInput.value.trim();
        if (!url) {
            urlInput.style.borderColor = '#ef4444';
            urlInput.focus();
            return;
        }
        
        const poster = document.getElementById('ccve-video-poster-input').value.trim();
        const autoplay = document.getElementById('ccve-video-autoplay').checked;
        const loop = document.getElementById('ccve-video-loop').checked;
        const muted = document.getElementById('ccve-video-muted').checked;
        
        // Deep linking options
        const mediaType = document.getElementById('ccve-video-media-type').value;
        const searchable = document.getElementById('ccve-video-searchable').checked;
        
        // Create video layer with deep link properties
        const newLayer = createVideoLayer(url, {
            x: 100,
            y: 100,
            width: 400,
            height: 225,  // 16:9 ratio
            poster,
            autoplay,
            loop,
            muted,
            media_type: mediaType,
            searchable
        });
        
        addLayerToCanvas(editor, newLayer);
        modal.remove();
        document.removeEventListener('keydown', handleEsc);
    });
    
    // Handle Enter key in URL input
    urlInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            document.getElementById('ccve-video-add-btn').click();
        }
    });
}

/**
 * Open feed configuration modal for adding feed layers
 * 
 * @param {Object} editor - Canvas editor instance
 */
function openFeedConfigModal(editor) {
    // Remove any existing modal
    const existing = document.getElementById('ccve-feed-config-modal');
    if (existing) existing.remove();
    
    // Create modal
    const modal = document.createElement('div');
    modal.id = 'ccve-feed-config-modal';
    modal.style.cssText = `
        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;
    `;
    
    modal.innerHTML = `
        <div style="
            background: white;
            border-radius: 8px;
            padding: 24px;
            width: 560px;
            max-width: 90vw;
            max-height: 90vh;
            overflow-y: auto;
            box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        ">
            <h3 style="margin: 0 0 16px 0; font-size: 18px; font-weight: 600; color: #111827;">
                📡 Add Feed Layer
            </h3>
            
            <div style="margin-bottom: 16px;">
                <label style="display: block; margin-bottom: 6px; font-size: 14px; font-weight: 500; color: #374151;">
                    Feed URL
                </label>
                <input 
                    type="url" 
                    id="ccve-feed-url-input"
                    placeholder="https://example.com/feed.rss or YouTube playlist URL"
                    style="
                        width: 100%;
                        padding: 10px 12px;
                        border: 1px solid #d1d5db;
                        border-radius: 6px;
                        font-size: 14px;
                        box-sizing: border-box;
                    "
                />
            </div>
            
            <div style="margin-bottom: 16px;">
                <label style="display: block; margin-bottom: 6px; font-size: 14px; font-weight: 500; color: #374151;">
                    Feed Type
                </label>
                <select 
                    id="ccve-feed-type-select"
                    style="
                        width: 100%;
                        padding: 10px 12px;
                        border: 1px solid #d1d5db;
                        border-radius: 6px;
                        font-size: 14px;
                        box-sizing: border-box;
                        background: white;
                    "
                >
                    <option value="auto">Auto-detect</option>
                    <option value="rss">RSS / Podcast</option>
                    <option value="mrss">Media RSS (MRSS)</option>
                    <option value="atom">Atom</option>
                    <option value="json">JSON Feed</option>
                    <option value="roku">Roku Direct Publisher</option>
                    <option value="youtube">YouTube Playlist</option>
                    <option value="soundcloud">SoundCloud</option>
                </select>
            </div>
            
            <div style="margin-bottom: 16px;" id="ccve-feed-api-key-section" style="display: none;">
                <label style="display: block; margin-bottom: 6px; font-size: 14px; font-weight: 500; color: #374151;">
                    API Key (for YouTube/SoundCloud)
                </label>
                <input 
                    type="text" 
                    id="ccve-feed-api-key-input"
                    placeholder="Optional - uses site default if not provided"
                    style="
                        width: 100%;
                        padding: 10px 12px;
                        border: 1px solid #d1d5db;
                        border-radius: 6px;
                        font-size: 14px;
                        box-sizing: border-box;
                    "
                />
            </div>
            
            <div style="display: flex; gap: 16px; margin-bottom: 16px;">
                <div style="flex: 1;">
                    <label style="display: block; margin-bottom: 6px; font-size: 14px; font-weight: 500; color: #374151;">
                        Layout
                    </label>
                    <select 
                        id="ccve-feed-layout-select"
                        style="
                            width: 100%;
                            padding: 10px 12px;
                            border: 1px solid #d1d5db;
                            border-radius: 6px;
                            font-size: 14px;
                            box-sizing: border-box;
                            background: white;
                        "
                    >
                        <option value="grid">Grid</option>
                        <option value="list">List</option>
                        <option value="carousel">Carousel</option>
                        <option value="featured">Featured + List</option>
                    </select>
                </div>
                <div style="flex: 1;">
                    <label style="display: block; margin-bottom: 6px; font-size: 14px; font-weight: 500; color: #374151;">
                        Max Items
                    </label>
                    <input 
                        type="number" 
                        id="ccve-feed-max-items"
                        value="10"
                        min="1"
                        max="50"
                        style="
                            width: 100%;
                            padding: 10px 12px;
                            border: 1px solid #d1d5db;
                            border-radius: 6px;
                            font-size: 14px;
                            box-sizing: border-box;
                        "
                    />
                </div>
            </div>
            
            <div style="display: flex; flex-wrap: wrap; gap: 12px; margin-bottom: 16px;">
                <label style="display: flex; align-items: center; gap: 6px; font-size: 14px; color: #374151; cursor: pointer;">
                    <input type="checkbox" id="ccve-feed-show-thumbnail" checked />
                    Show Thumbnails
                </label>
                <label style="display: flex; align-items: center; gap: 6px; font-size: 14px; color: #374151; cursor: pointer;">
                    <input type="checkbox" id="ccve-feed-show-title" checked />
                    Show Titles
                </label>
                <label style="display: flex; align-items: center; gap: 6px; font-size: 14px; color: #374151; cursor: pointer;">
                    <input type="checkbox" id="ccve-feed-show-duration" checked />
                    Show Duration
                </label>
                <label style="display: flex; align-items: center; gap: 6px; font-size: 14px; color: #374151; cursor: pointer;">
                    <input type="checkbox" id="ccve-feed-show-description" />
                    Show Description
                </label>
            </div>
            
            <div id="ccve-feed-preview" style="
                margin-bottom: 16px;
                padding: 12px;
                background: #f9fafb;
                border-radius: 6px;
                display: none;
            ">
                <div style="font-size: 12px; color: #6b7280; margin-bottom: 8px;">Feed Preview</div>
                <div id="ccve-feed-preview-content" style="font-size: 14px; color: #111827;"></div>
            </div>
            
            <div style="display: flex; justify-content: space-between; align-items: center;">
                <button 
                    id="ccve-feed-preview-btn"
                    style="
                        padding: 10px 16px;
                        background: #f3f4f6;
                        border: 1px solid #d1d5db;
                        border-radius: 6px;
                        font-size: 14px;
                        cursor: pointer;
                    "
                >🔍 Preview Feed</button>
                <div style="display: flex; gap: 12px;">
                    <button 
                        id="ccve-feed-cancel-btn"
                        style="
                            padding: 10px 16px;
                            background: #f3f4f6;
                            border: 1px solid #d1d5db;
                            border-radius: 6px;
                            font-size: 14px;
                            cursor: pointer;
                        "
                    >Cancel</button>
                    <button 
                        id="ccve-feed-add-btn"
                        style="
                            padding: 10px 16px;
                            background: #3b82f6;
                            color: white;
                            border: none;
                            border-radius: 6px;
                            font-size: 14px;
                            font-weight: 500;
                            cursor: pointer;
                        "
                    >Add Feed Layer</button>
                </div>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // Focus input
    const urlInput = document.getElementById('ccve-feed-url-input');
    urlInput.focus();
    
    // Show/hide API key section based on feed type
    const feedTypeSelect = document.getElementById('ccve-feed-type-select');
    const apiKeySection = document.getElementById('ccve-feed-api-key-section');
    feedTypeSelect.addEventListener('change', () => {
        const type = feedTypeSelect.value;
        apiKeySection.style.display = (type === 'youtube' || type === 'soundcloud') ? 'block' : 'none';
    });
    
    // Handle cancel
    document.getElementById('ccve-feed-cancel-btn').addEventListener('click', () => {
        modal.remove();
    });
    
    // Handle backdrop click
    modal.addEventListener('click', (e) => {
        if (e.target === modal) modal.remove();
    });
    
    // Handle ESC key
    const handleEsc = (e) => {
        if (e.key === 'Escape') {
            modal.remove();
            document.removeEventListener('keydown', handleEsc);
        }
    };
    document.addEventListener('keydown', handleEsc);
    
    // Handle preview button
    document.getElementById('ccve-feed-preview-btn').addEventListener('click', async () => {
        const url = urlInput.value.trim();
        if (!url) {
            urlInput.style.borderColor = '#ef4444';
            urlInput.focus();
            return;
        }
        
        const previewDiv = document.getElementById('ccve-feed-preview');
        const previewContent = document.getElementById('ccve-feed-preview-content');
        previewDiv.style.display = 'block';
        previewContent.innerHTML = '<span style="color: #6b7280;">Loading feed...</span>';
        
        try {
            const feedType = feedTypeSelect.value;
            const apiKey = document.getElementById('ccve-feed-api-key-input')?.value || '';
            
            const response = await fetch(castconductorCanvasAjax.rest_url + 'castconductor/v5/feeds/preview', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': castconductorCanvasAjax.nonce
                },
                body: JSON.stringify({
                    url: url,
                    type: feedType,
                    api_key: apiKey,
                    max_items: 3
                })
            });
            
            const data = await response.json();
            
            if (data.success && data.preview) {
                const p = data.preview;
                previewContent.innerHTML = `
                    <div style="font-weight: 600; margin-bottom: 4px;">${p.title || 'Unknown Feed'}</div>
                    <div style="font-size: 12px; color: #6b7280; margin-bottom: 8px;">
                        Type: ${p.type} | ${p.item_count} items
                    </div>
                    <div style="display: flex; flex-direction: column; gap: 6px;">
                        ${p.items.slice(0, 3).map(item => `
                            <div style="display: flex; gap: 8px; align-items: center;">
                                ${item.thumbnail ? `<img src="${item.thumbnail}" style="width: 48px; height: 27px; object-fit: cover; border-radius: 4px;" />` : ''}
                                <div style="flex: 1; min-width: 0;">
                                    <div style="font-size: 13px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">${item.title}</div>
                                    <div style="font-size: 11px; color: #6b7280;">${item.duration_formatted || ''} ${item.published_relative || ''}</div>
                                </div>
                            </div>
                        `).join('')}
                    </div>
                `;
            } else {
                previewContent.innerHTML = `<span style="color: #ef4444;">Error: ${data.message || 'Failed to load feed'}</span>`;
            }
        } catch (err) {
            previewContent.innerHTML = `<span style="color: #ef4444;">Error: ${err.message}</span>`;
        }
    });
    
    // Handle add
    document.getElementById('ccve-feed-add-btn').addEventListener('click', () => {
        const url = urlInput.value.trim();
        if (!url) {
            urlInput.style.borderColor = '#ef4444';
            urlInput.focus();
            return;
        }
        
        const feedType = feedTypeSelect.value;
        const layout = document.getElementById('ccve-feed-layout-select').value;
        const maxItems = parseInt(document.getElementById('ccve-feed-max-items').value, 10) || 10;
        const showThumbnail = document.getElementById('ccve-feed-show-thumbnail').checked;
        const showTitle = document.getElementById('ccve-feed-show-title').checked;
        const showDuration = document.getElementById('ccve-feed-show-duration').checked;
        const showDescription = document.getElementById('ccve-feed-show-description').checked;
        const apiKey = document.getElementById('ccve-feed-api-key-input')?.value || '';
        
        // Create feed layer
        const newLayer = createFeedLayer(url, {
            x: 50,
            y: 50,
            width: 600,
            height: 400,
            feed_type: feedType,
            api_key: apiKey,
            max_items: maxItems,
            layout: layout,
            show_thumbnail: showThumbnail,
            show_title: showTitle,
            show_duration: showDuration,
            show_description: showDescription
        });
        
        addLayerToCanvas(editor, newLayer);
        modal.remove();
        document.removeEventListener('keydown', handleEsc);
    });
    
    // Handle Enter key in URL input
    urlInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            document.getElementById('ccve-feed-add-btn').click();
        }
    });
}

/**
 * Add layer to canvas and config
 * 
 * @param {Object} editor - Canvas editor instance
 * @param {Object} layer - Layer object
 */
function addLayerToCanvas(editor, layer) {
    // Ensure config has layers array
    if (!editor.currentConfig) {
        editor.currentConfig = {};
    }
    if (!editor.currentConfig.layers) {
        editor.currentConfig.layers = [];
    }
    
    // Clamp layer position to container bounds
    const layout = editor.currentConfig?.layout;
    if (layout && layout.width && layout.height) {
        const containerW = layout.width;
        const containerH = layout.height;
        const layerW = layer.width || 200;
        const layerH = layer.height || 100;
        
        // Ensure layer fits within container
        layer.x = Math.max(0, Math.min(containerW - layerW, layer.x || 60));
        layer.y = Math.max(0, Math.min(containerH - layerH, layer.y || 60));
        
        console.debug('[AddLayerUI] Layer clamped to container bounds:', {
            container: { w: containerW, h: containerH },
            layer: { x: layer.x, y: layer.y, w: layerW, h: layerH }
        });
    }
    
    // Add layer to config
    editor.currentConfig.layers.push(layer);
    
    // Render layer using unified renderer (already appends to stage)
    if (editor.renderLayer) {
        editor.renderLayer(layer);
    }
    
    // Update layer manager if available
    if (editor.refreshLayerManager) {
        editor.refreshLayerManager();
    }
    
    // Mark unsaved changes
    editor.markUnsavedChanges();
    
    // Show success notification
    showNotification(editor, `${getLayerTypeName(layer.kind)} added successfully!`, 'success');
}

/**
 * Show notification toast
 * 
 * @param {Object} editor - Canvas editor instance
 * @param {string} message - Notification message
 * @param {string} type - Notification type (success, error, info)
 */
function showNotification(editor, message, type = 'info') {
    // Create or get notification container
    let container = document.getElementById('ccve-notifications');
    if (!container) {
        container = document.createElement('div');
        container.id = 'ccve-notifications';
        Object.assign(container.style, {
            position: 'fixed',
            top: '20px',
            right: '20px',
            zIndex: '10000',
            display: 'flex',
            flexDirection: 'column',
            gap: '8px'
        });
        document.body.appendChild(container);
    }
    
    // Create notification
    const notification = document.createElement('div');
    notification.className = `ccve-notification ccve-notification-${type}`;
    
    const colors = {
        success: { bg: '#10b981', text: '#ffffff' },
        error: { bg: '#ef4444', text: '#ffffff' },
        info: { bg: '#3b82f6', text: '#ffffff' }
    };
    
    const color = colors[type] || colors.info;
    
    Object.assign(notification.style, {
        background: color.bg,
        color: color.text,
        padding: '12px 16px',
        borderRadius: '6px',
        boxShadow: '0 4px 6px -1px rgba(0,0,0,0.1)',
        fontSize: '14px',
        fontWeight: '500',
        minWidth: '250px',
        maxWidth: '400px',
        animation: 'ccve-slide-in 0.3s ease-out'
    });
    
    notification.textContent = message;
    container.appendChild(notification);
    
    // Auto-remove after 3 seconds
    setTimeout(() => {
        notification.style.animation = 'ccve-slide-out 0.3s ease-in';
        setTimeout(() => notification.remove(), 300);
    }, 3000);
}

/**
 * Add CSS animations for notifications
 */
function addNotificationStyles() {
    if (document.getElementById('ccve-notification-styles')) return;
    
    const style = document.createElement('style');
    style.id = 'ccve-notification-styles';
    style.textContent = `
        @keyframes ccve-slide-in {
            from {
                transform: translateX(400px);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
        
        @keyframes ccve-slide-out {
            from {
                transform: translateX(0);
                opacity: 1;
            }
            to {
                transform: translateX(400px);
                opacity: 0;
            }
        }
        
        .ccve-menu-item {
            display: flex;
            align-items: center;
            padding: 10px 16px;
            cursor: pointer;
            transition: background 0.15s ease;
        }
        
        .ccve-menu-item:hover {
            background: #f3f4f6;
        }
        
        .ccve-menu-item-phase2 {
            opacity: 0.6;
            pointer-events: none;
        }
        
        .ccve-menu-item-icon {
            width: 32px;
            height: 32px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            margin-right: 12px;
            flex-shrink: 0;
        }
        
        .ccve-menu-item-content {
            flex: 1;
            min-width: 0;
        }
        
        .ccve-menu-item-title {
            font-weight: 600;
            font-size: 13px;
            color: #1f2937;
            margin-bottom: 2px;
        }
        
        .ccve-menu-item-desc {
            font-size: 11px;
            color: #6b7280;
            line-height: 1.3;
        }
        
        .ccve-menu-item-badge {
            display: inline-block;
            background: #3b82f6;
            color: white;
            font-size: 9px;
            padding: 2px 6px;
            border-radius: 3px;
            margin-top: 4px;
            font-weight: 600;
        }
        
        .ccve-menu-header {
            display: flex;
            align-items: center;
            padding: 8px 16px;
            color: #374151;
            font-size: 13px;
            border-bottom: 1px solid #e5e7eb;
        }
        
        .ccve-menu-divider {
            height: 1px;
            background: #e5e7eb;
            margin: 4px 0;
        }
        
        .ccve-menu-footer {
            padding: 8px 16px;
            background: #f9fafb;
            border-top: 1px solid #e5e7eb;
        }
    `;
    document.head.appendChild(style);
}

// Initialize styles
addNotificationStyles();

export const addLayerUI = {
    attachAddLayerDropdown,
    handleAddLayer,
    showNotification
};
