/**
 * Cast Conductor Proprietary License v5
 * SPDX-License-Identifier: LicenseRef-CastConductor-Proprietary-v5
 * 
 * WordPress Post Selector Module
 * 
 * Provides modal UI for selecting WordPress posts to link to layers.
 * Includes search, filtering, preview, and field configuration.
 * 
 * @module wordpress-post-selector
 * @since 5.2.1 - Phase 2 WordPress Integration
 */

/**
 * Attach WordPress Post Selector to editor
 * 
 * @param {Object} editor - Canvas editor instance
 */
export function attachWordPressPostSelector(editor) {
    if (editor.__wpPostSelectorAttached) return;
    editor.__wpPostSelectorAttached = true;
    
    console.info('[WPPostSelector] Attaching WordPress Post Selector');
    
    // Create modal HTML
    createPostSelectorModal();
    
    // Attach method to editor
    editor.openPostSelector = function(layer) {
        openPostSelector(editor, layer);
    };
}

/**
 * Create post selector modal HTML
 */
function createPostSelectorModal() {
    // Check if modal already exists
    if (document.getElementById('wp-post-selector-modal')) {
        return;
    }
    
    const modal = document.createElement('div');
    modal.id = 'wp-post-selector-modal';
    modal.className = 'ccve-modal';
    // CRITICAL: Use fixed positioning and flex centering for modal
    modal.style.cssText = `
        display: none;
        position: fixed;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        z-index: 100000;
        align-items: center;
        justify-content: center;
        background: transparent;
    `;
    
    modal.innerHTML = `
        <div class="ccve-modal-overlay" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.6);"></div>
        <div class="ccve-modal-container" style="position: relative; max-width: 900px; max-height: 80vh; width: 90%; background: white; border-radius: 12px; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25); display: flex; flex-direction: column; overflow: hidden;">
            <div class="ccve-modal-header" style="display: flex; justify-content: space-between; align-items: center; padding: 16px 20px; border-bottom: 1px solid #e5e7eb;">
                <h2 style="margin: 0; font-size: 20px; display: flex; align-items: center; gap: 8px;">
                    <span>📰</span>
                    <span>Select WordPress Post</span>
                </h2>
                <button class="ccve-modal-close" data-modal-close style="background: none; border: none; font-size: 28px; cursor: pointer; color: #6b7280; padding: 0; line-height: 1;">&times;</button>
            </div>
            
            <div class="ccve-modal-body" style="padding: 20px; overflow-y: auto; flex: 1;">
                <!-- Search Bar -->
                <div style="margin-bottom: 20px;">
                    <input 
                        type="text" 
                        id="wp-post-search" 
                        placeholder="Search posts by title..." 
                        style="width: 100%; padding: 10px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 14px; box-sizing: border-box;"
                    />
                </div>
                
                <!-- Filter Options -->
                <div style="display: flex; gap: 12px; margin-bottom: 20px; flex-wrap: wrap;">
                    <select id="wp-post-status" style="padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 14px;">
                        <option value="publish">Published</option>
                        <option value="draft">Drafts</option>
                        <option value="future">Scheduled</option>
                        <option value="any">All Statuses</option>
                    </select>
                    
                    <select id="wp-post-orderby" style="padding: 8px 12px; border: 1px solid #d1d5db; border-radius: 6px; font-size: 14px;">
                        <option value="date">Date (Newest)</option>
                        <option value="modified">Recently Modified</option>
                        <option value="title">Title (A-Z)</option>
                    </select>
                    
                    <button 
                        id="wp-post-refresh" 
                        style="padding: 8px 16px; background: #6366f1; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 500;"
                    >
                        🔄 Refresh
                    </button>
                </div>
                
                <!-- Loading State -->
                <div id="wp-post-loading" style="display: none; text-align: center; padding: 40px; color: #6b7280;">
                    <div style="font-size: 16px; margin-bottom: 8px;">Loading posts...</div>
                    <div style="font-size: 14px; opacity: 0.7;">Fetching from WordPress REST API</div>
                </div>
                
                <!-- Error State -->
                <div id="wp-post-error" style="display: none; padding: 20px; background: #fef2f2; border: 1px solid #fecaca; border-radius: 6px; color: #dc2626;">
                    <div style="font-weight: 600; margin-bottom: 4px;">Failed to load posts</div>
                    <div id="wp-post-error-message" style="font-size: 14px;"></div>
                </div>
                
                <!-- Posts List -->
                <div id="wp-post-list" style="display: grid; gap: 12px;"></div>
                
                <!-- Empty State -->
                <div id="wp-post-empty" style="display: none; text-align: center; padding: 40px; color: #6b7280;">
                    <div style="font-size: 48px; margin-bottom: 12px;">📭</div>
                    <div style="font-size: 16px; font-weight: 500; margin-bottom: 4px;">No posts found</div>
                    <div style="font-size: 14px; opacity: 0.7;">Try adjusting your search or filters</div>
                </div>
            </div>
            
            <div class="ccve-modal-footer" style="display: flex; justify-content: flex-end; gap: 12px; padding: 16px 20px; border-top: 1px solid #e5e7eb;">
                <button class="ccve-btn-secondary" data-modal-close>Cancel</button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // Attach event listeners
    attachModalEventListeners();
}

/**
 * Attach event listeners to modal elements
 */
function attachModalEventListeners() {
    const modal = document.getElementById('wp-post-selector-modal');
    if (!modal) return;
    
    // Close modal on overlay click or close button
    modal.querySelector('.ccve-modal-overlay')?.addEventListener('click', closePostSelectorModal);
    modal.querySelectorAll('[data-modal-close]').forEach(btn => {
        btn.addEventListener('click', closePostSelectorModal);
    });
    
    // Search input with debounce
    const searchInput = document.getElementById('wp-post-search');
    let searchTimeout;
    searchInput?.addEventListener('input', () => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            if (modal._currentEditor && modal._currentLayer) {
                loadPosts(modal._currentEditor, modal._currentLayer);
            }
        }, 300);
    });
    
    // Filter changes
    document.getElementById('wp-post-status')?.addEventListener('change', () => {
        if (modal._currentEditor && modal._currentLayer) {
            loadPosts(modal._currentEditor, modal._currentLayer);
        }
    });
    
    document.getElementById('wp-post-orderby')?.addEventListener('change', () => {
        if (modal._currentEditor && modal._currentLayer) {
            loadPosts(modal._currentEditor, modal._currentLayer);
        }
    });
    
    // Refresh button
    document.getElementById('wp-post-refresh')?.addEventListener('click', () => {
        if (modal._currentEditor && modal._currentLayer) {
            loadPosts(modal._currentEditor, modal._currentLayer, true);
        }
    });
}

/**
 * Open post selector modal
 * 
 * @param {Object} editor - Canvas editor instance
 * @param {Object} layer - WordPress post layer to configure
 */
function openPostSelector(editor, layer) {
    const modal = document.getElementById('wp-post-selector-modal');
    if (!modal) {
        console.error('[WPPostSelector] Modal not found');
        return;
    }
    
    // Store current context
    modal._currentEditor = editor;
    modal._currentLayer = layer;
    
    // Reset search and filters
    const searchInput = document.getElementById('wp-post-search');
    if (searchInput) searchInput.value = '';
    
    const statusSelect = document.getElementById('wp-post-status');
    if (statusSelect) statusSelect.value = 'publish';
    
    const orderSelect = document.getElementById('wp-post-orderby');
    if (orderSelect) orderSelect.value = 'date';
    
    // Show modal
    modal.style.display = 'flex';
    
    // Load posts
    loadPosts(editor, layer);
}

/**
 * Close post selector modal
 */
function closePostSelectorModal() {
    const modal = document.getElementById('wp-post-selector-modal');
    if (modal) {
        modal.style.display = 'none';
        modal._currentEditor = null;
        modal._currentLayer = null;
    }
}

/**
 * Load posts from WordPress REST API
 * 
 * @param {Object} editor - Canvas editor instance
 * @param {Object} layer - WordPress post layer
 * @param {boolean} forceRefresh - Force cache bypass
 */
async function loadPosts(editor, layer, forceRefresh = false) {
    const loadingEl = document.getElementById('wp-post-loading');
    const errorEl = document.getElementById('wp-post-error');
    const listEl = document.getElementById('wp-post-list');
    const emptyEl = document.getElementById('wp-post-empty');
    
    if (!listEl) return;
    
    // Show loading state
    loadingEl.style.display = 'block';
    errorEl.style.display = 'none';
    listEl.style.display = 'none';
    emptyEl.style.display = 'none';
    
    try {
        // Build query parameters
        const searchInput = document.getElementById('wp-post-search');
        const statusSelect = document.getElementById('wp-post-status');
        const orderSelect = document.getElementById('wp-post-orderby');
        
        const params = new URLSearchParams({
            per_page: 20,
            _embed: 'true',
            status: statusSelect?.value || 'publish',
            orderby: orderSelect?.value || 'date',
            order: 'desc'
        });
        
        const searchTerm = searchInput?.value.trim();
        if (searchTerm) {
            params.append('search', searchTerm);
        }
        
        // Fetch from cc_layer custom post type (CastConductor Layers)
        // Falls back to standard posts if cc_layer endpoint doesn't exist
        let response = await fetch(`/wp-json/wp/v2/cc_layer?${params}`, {
            headers: {
                'X-WP-Nonce': window.castconductorCanvasAjax?.nonce || ''
            }
        });
        
        // If cc_layer endpoint fails (404), fall back to standard posts
        if (response.status === 404) {
            console.warn('[WPPostSelector] cc_layer endpoint not found, falling back to posts');
            response = await fetch(`/wp-json/wp/v2/posts?${params}`, {
                headers: {
                    'X-WP-Nonce': window.castconductorCanvasAjax?.nonce || ''
                }
            });
        }
        
        if (!response.ok) {
            throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        
        const posts = await response.json();
        
        // Hide loading
        loadingEl.style.display = 'none';
        
        // Show results
        if (posts.length === 0) {
            emptyEl.style.display = 'block';
        } else {
            listEl.style.display = 'grid';
            renderPostsList(posts, editor, layer);
        }
    } catch (error) {
        console.error('[WPPostSelector] Failed to load posts:', error);
        loadingEl.style.display = 'none';
        errorEl.style.display = 'block';
        document.getElementById('wp-post-error-message').textContent = error.message;
    }
}

/**
 * Render posts list in modal
 * 
 * @param {Array} posts - WordPress posts
 * @param {Object} editor - Canvas editor instance
 * @param {Object} layer - WordPress post layer
 */
function renderPostsList(posts, editor, layer) {
    const listEl = document.getElementById('wp-post-list');
    if (!listEl) return;
    
    listEl.innerHTML = posts.map(post => {
        // Extract featured image
        let featuredImageUrl = null;
        if (post._embedded && post._embedded['wp:featuredmedia']) {
            const media = post._embedded['wp:featuredmedia'][0];
            featuredImageUrl = media?.media_details?.sizes?.thumbnail?.source_url || 
                             media?.media_details?.sizes?.medium?.source_url || 
                             media?.source_url || null;
        }
        
        // Format date
        const date = new Date(post.date);
        const formattedDate = date.toLocaleDateString('en-US', { 
            year: 'numeric', 
            month: 'short', 
            day: 'numeric' 
        });
        
        // Strip HTML from excerpt
        const excerptText = (post.excerpt?.rendered || '').replace(/<[^>]*>/g, '').trim();
        const shortExcerpt = excerptText.length > 120 ? excerptText.substring(0, 120) + '...' : excerptText;
        
        return `
            <div 
                class="wp-post-item" 
                data-post-id="${post.id}"
                style="
                    display: flex;
                    gap: 16px;
                    padding: 16px;
                    background: #f9fafb;
                    border: 2px solid #e5e7eb;
                    border-radius: 8px;
                    cursor: pointer;
                    transition: all 0.2s;
                "
                onmouseover="this.style.background='#f3f4f6'; this.style.borderColor='#6366f1';"
                onmouseout="this.style.background='#f9fafb'; this.style.borderColor='#e5e7eb';"
            >
                ${featuredImageUrl ? `
                    <div style="flex-shrink: 0; width: 80px; height: 80px; border-radius: 6px; overflow: hidden; background: #e5e7eb;">
                        <img 
                            src="${featuredImageUrl}" 
                            alt="" 
                            style="width: 100%; height: 100%; object-fit: cover;"
                        />
                    </div>
                ` : `
                    <div style="flex-shrink: 0; width: 80px; height: 80px; border-radius: 6px; background: #e5e7eb; display: flex; align-items: center; justify-content: center; font-size: 32px; opacity: 0.5;">
                        📄
                    </div>
                `}
                
                <div style="flex: 1; min-width: 0;">
                    <div style="font-weight: 600; font-size: 16px; color: #111827; margin-bottom: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;">
                        ${post.title.rendered || 'Untitled'}
                    </div>
                    <div style="font-size: 13px; color: #6b7280; margin-bottom: 8px;">
                        ${formattedDate} • Post ID: ${post.id}
                    </div>
                    ${shortExcerpt ? `
                        <div style="font-size: 14px; color: #4b5563; line-height: 1.4;">
                            ${shortExcerpt}
                        </div>
                    ` : ''}
                </div>
            </div>
        `;
    }).join('');
    
    // Attach click handlers
    listEl.querySelectorAll('.wp-post-item').forEach(item => {
        item.addEventListener('click', () => {
            const postId = parseInt(item.getAttribute('data-post-id'), 10);
            selectPost(postId, editor, layer);
        });
    });
}

/**
 * Select a post and "explode" into separate layers
 * 
 * Instead of keeping a composite wordpress-post layer, we:
 * 1. Fetch the full post data
 * 2. Remove the original placeholder layer
 * 3. Create separate static-text layers for title and excerpt
 * 4. Create a static-image layer for the featured image
 * 
 * @param {number} postId - WordPress post ID
 * @param {Object} editor - Canvas editor instance
 * @param {Object} layer - WordPress post layer (to be replaced)
 */
async function selectPost(postId, editor, layer) {
    console.info('[WPPostSelector] Selected post:', postId, '- exploding into separate layers');
    
    try {
        // Fetch full post data with embedded media
        // Try cc_layer first, fall back to posts
        let response = await fetch(`/wp-json/wp/v2/cc_layer/${postId}?_embed=true`, {
            headers: {
                'X-WP-Nonce': window.castconductorCanvasAjax?.nonce || ''
            }
        });
        
        // Fall back to standard posts if cc_layer fails
        if (response.status === 404) {
            response = await fetch(`/wp-json/wp/v2/posts/${postId}?_embed=true`, {
                headers: {
                    'X-WP-Nonce': window.castconductorCanvasAjax?.nonce || ''
                }
            });
        }
        
        if (!response.ok) {
            throw new Error(`Failed to fetch post: HTTP ${response.status}`);
        }
        
        const post = await response.json();
        
        // Get position and sizing info from the original layer
        const baseX = layer.x || 60;
        const baseY = layer.y || 20;
        const containerLayout = editor.currentConfig?.layout;
        const containerW = containerLayout?.width || 1280;
        const containerH = containerLayout?.height || 240;
        
        // Remove the original wordpress-post layer from config
        const layers = editor.currentConfig?.layers || [];
        const layerIndex = layers.findIndex(l => l.id === layer.id);
        if (layerIndex !== -1) {
            layers.splice(layerIndex, 1);
        }
        
        // Remove the DOM element for the original layer
        const existingEl = document.querySelector(`[data-layer-id="${layer.id}"]`);
        if (existingEl) {
            existingEl.remove();
        }
        
        // Import layer creation functions
        const { createStaticTextLayer, createStaticImageLayer } = await import('./layer-constants.js');
        
        // Extract featured image URL
        let featuredImageUrl = null;
        if (post._embedded && post._embedded['wp:featuredmedia']) {
            const media = post._embedded['wp:featuredmedia'][0];
            featuredImageUrl = media?.source_url || 
                             media?.media_details?.sizes?.large?.source_url || 
                             media?.media_details?.sizes?.medium?.source_url || 
                             null;
        }
        
        // Clean title (strip HTML entities)
        const titleText = (post.title?.rendered || 'Untitled Post')
            .replace(/&amp;/g, '&')
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/&quot;/g, '"')
            .replace(/&#039;/g, "'");
        
        // Clean body content (strip HTML tags and entities)
        // Use content.rendered (main post body), NOT excerpt
        const contentText = (post.content?.rendered || '')
            .replace(/<[^>]*>/g, '')
            .replace(/&amp;/g, '&')
            .replace(/&lt;/g, '<')
            .replace(/&gt;/g, '>')
            .replace(/&quot;/g, '"')
            .replace(/&#039;/g, "'")
            .replace(/&nbsp;/g, ' ')
            .trim();
        
        // Track created layers for notification
        const createdLayers = [];
        
        // Create title layer (static-text)
        const titleLayer = createStaticTextLayer(titleText, {
            x: baseX,
            y: baseY,
            width: Math.min(600, containerW - baseX - 20),
            height: 60,
            font_size: 36,
            font_weight: '700',
            color: '#ffffff',
            text_shadow: { x: 2, y: 2, blur: 4, color: 'rgba(0,0,0,0.6)' },
            _wp_post_id: postId,
            _wp_field: 'title'
        });
        layers.push(titleLayer);
        createdLayers.push('Title');
        
        // Create content layer if content exists (static-text)
        if (contentText) {
            // Truncate for display (broadcast overlays need short text)
            const shortContent = contentText.length > 300 
                ? contentText.substring(0, 300) + '...' 
                : contentText;
            
            const contentLayer = createStaticTextLayer(shortContent, {
                x: baseX,
                y: baseY + 70,
                width: Math.min(600, containerW - baseX - 20),
                height: Math.min(100, containerH - baseY - 80),
                font_size: 20,
                font_weight: '400',
                color: '#e0e0e0',
                text_shadow: { x: 1, y: 1, blur: 2, color: 'rgba(0,0,0,0.5)' },
                _wp_post_id: postId,
                _wp_field: 'content'
            });
            layers.push(contentLayer);
            createdLayers.push('Content');
        }
        
        // Create featured image layer if image exists (static-image)
        if (featuredImageUrl) {
            const imageSize = Math.min(150, containerH - 40);
            const featuredLayer = createStaticImageLayer(featuredImageUrl, {
                x: containerW - imageSize - 20,
                y: Math.max(10, (containerH - imageSize) / 2),
                width: imageSize,
                height: imageSize,
                fit: 'cover',
                border_radius: 8,
                _wp_post_id: postId,
                _wp_field: 'featured_image'
            });
            layers.push(featuredLayer);
            createdLayers.push('Featured Image');
        }
        
        // Mark as unsaved
        editor.unsavedChanges = true;
        if (editor.updateSaveButton) {
            editor.updateSaveButton();
        }
        
        // Re-render all layers
        try {
            editor._renderUnifiedLayers && editor._renderUnifiedLayers();
        } catch(e) {
            console.error('[WPPostSelector] Failed to re-render:', e);
        }
        
        // Update layer manager if available
        if (editor.refreshLayerManager) {
            editor.refreshLayerManager();
        }
        
        // Close modal
        closePostSelectorModal();
        
        // Show success notification
        if (editor.showNotification) {
            editor.showNotification(`✅ Post exploded into ${createdLayers.length} layers: ${createdLayers.join(', ')}`, 'success');
        }
        
        console.info('[WPPostSelector] Created layers:', createdLayers);
        
    } catch (error) {
        console.error('[WPPostSelector] Failed to explode post into layers:', error);
        
        if (editor.showNotification) {
            editor.showNotification(`❌ Failed to load post: ${error.message}`, 'error');
        }
    }
}

/**
 * Default export
 */
export default {
    attachWordPressPostSelector
};
