/**
 * Artwork Items to Slideshow Layer Migration
 * 
 * Converts legacy config.artwork.items[] system to unified slideshow-image layers.
 * Preserves all image data, settings, and slideshow configuration.
 * 
 * @module slideshow-migration
 * @since 5.2.1 - Unified Layer System
 */

import {
    LAYER_KIND_SLIDESHOW_IMAGE,
    createSlideshowImageLayer,
    generateLayerId
} from './layer-constants.js';

/**
 * Migrate artwork items to slideshow layer
 * 
 * Converts config.artwork.items[] into a proper slideshow-image layer.
 * Automatically detects if migration is needed.
 * 
 * @param {Object} config - Content block configuration
 * @returns {Object} Migrated configuration
 */
export function migrateArtworkToLayers(config) {
    if (!config) return config;
    
    // Check if migration needed
    const needsMigration = hasArtworkItems(config) && !hasSlideshowLayer(config);
    
    if (!needsMigration) {
        console.debug('[SlideshowMigration] No migration needed');
        return config;
    }
    
    console.info('[SlideshowMigration] Migrating artwork.items[] to slideshow layer');
    
    // Extract artwork configuration
    const artwork = config.artwork || {};
    const items = artwork.items || [];
    
    if (items.length === 0) {
        console.debug('[SlideshowMigration] No artwork items to migrate');
        return config;
    }
    
    // Convert items to slideshow format
    const slideshowImages = items.map((item, index) => ({
        url: item.src || item.url,
        duration: artwork.slideshow?.interval || 5000,
        alt: item.alt || `Image ${index + 1}`,
        attachment_id: item.attachment_id || null
    }));
    
    // Create slideshow layer with preserved settings
    const slideshowLayer = createSlideshowImageLayer(slideshowImages, {
        x: 0,
        y: 0,
        width: artwork.width || 1920,
        height: artwork.height || 1080,
        zIndex: 0, // Background layer
        visible: artwork.enabled !== false,
        transition: artwork.slideshow?.transition || 'fade',
        transition_duration: 500,
        autoplay: artwork.slideshow?.enabled !== false,
        loop: true,
        current_index: artwork.activeIndex || 0,
        // Preserve original artwork config for reference
        _migrated_from: 'artwork.items',
        _migration_timestamp: Date.now()
    });
    
    // Ensure layers array exists
    if (!config.layers) {
        config.layers = [];
    }
    
    // Add slideshow layer at beginning (background)
    config.layers.unshift(slideshowLayer);
    
    // Mark artwork as migrated (keep for backward compatibility but flag it)
    if (config.artwork) {
        config.artwork._migrated = true;
        config.artwork._migration_timestamp = Date.now();
        // Keep original data for rollback if needed
        config.artwork._original_items = [...items];
    }
    
    console.info('[SlideshowMigration] Migration complete:', {
        itemCount: items.length,
        layerId: slideshowLayer.id,
        autoplay: slideshowLayer.autoplay
    });
    
    return config;
}

/**
 * Check if config has artwork items that need migration
 * 
 * @param {Object} config - Content block configuration
 * @returns {boolean} True if has artwork items
 */
function hasArtworkItems(config) {
    return config.artwork && 
           Array.isArray(config.artwork.items) && 
           config.artwork.items.length > 0 &&
           !config.artwork._migrated;
}

/**
 * Check if config already has a slideshow layer
 * 
 * @param {Object} config - Content block configuration
 * @returns {boolean} True if has slideshow layer
 */
function hasSlideshowLayer(config) {
    return config.layers && 
           Array.isArray(config.layers) &&
           config.layers.some(layer => layer.kind === LAYER_KIND_SLIDESHOW_IMAGE);
}

/**
 * Migrate all content blocks in batch
 * 
 * Used for bulk migration of existing content blocks.
 * 
 * @param {Array} contentBlocks - Array of content block objects
 * @returns {Array} Migrated content blocks
 */
export function migrateAllContentBlocks(contentBlocks) {
    if (!Array.isArray(contentBlocks)) return contentBlocks;
    
    let migratedCount = 0;
    
    const migrated = contentBlocks.map(block => {
        if (!block || !block.visual_config) return block;
        
        const originalConfig = typeof block.visual_config === 'string' 
            ? JSON.parse(block.visual_config) 
            : block.visual_config;
        
        const needsMigration = hasArtworkItems(originalConfig);
        
        if (needsMigration) {
            const migratedConfig = migrateArtworkToLayers(originalConfig);
            migratedCount++;
            
            return {
                ...block,
                visual_config: migratedConfig
            };
        }
        
        return block;
    });
    
    console.info(`[SlideshowMigration] Batch migration complete: ${migratedCount}/${contentBlocks.length} blocks migrated`);
    
    return migrated;
}

/**
 * Rollback migration (restore artwork.items from backup)
 * 
 * Use if migration causes issues. Restores original artwork.items[].
 * 
 * @param {Object} config - Migrated configuration
 * @returns {Object} Rolled back configuration
 */
export function rollbackMigration(config) {
    if (!config) return config;
    
    // Check if migration can be rolled back
    if (!config.artwork?._migrated || !config.artwork._original_items) {
        console.warn('[SlideshowMigration] No migration to rollback');
        return config;
    }
    
    console.info('[SlideshowMigration] Rolling back migration');
    
    // Remove migrated slideshow layer
    if (config.layers) {
        config.layers = config.layers.filter(layer => 
            !(layer.kind === LAYER_KIND_SLIDESHOW_IMAGE && layer._migrated_from === 'artwork.items')
        );
    }
    
    // Restore original artwork items
    config.artwork.items = config.artwork._original_items;
    delete config.artwork._migrated;
    delete config.artwork._migration_timestamp;
    delete config.artwork._original_items;
    
    console.info('[SlideshowMigration] Rollback complete');
    
    return config;
}

/**
 * Auto-migrate on config load
 * 
 * Automatically migrates artwork items to layers when config is loaded.
 * Safe to call multiple times - only migrates if needed.
 * 
 * @param {Object} editor - Canvas editor instance
 */
export function autoMigrateOnLoad(editor) {
    if (!editor || !editor.currentConfig) return;
    
    const needsMigration = hasArtworkItems(editor.currentConfig);
    
    if (needsMigration) {
        console.info('[SlideshowMigration] Auto-migration triggered');
        
        // Migrate config
        editor.currentConfig = migrateArtworkToLayers(editor.currentConfig);
        
        // Mark as unsaved so user knows to save migrated version
        if (editor.markUnsavedChanges) {
            editor.markUnsavedChanges();
        }
        
        // Show notification
        showMigrationNotification(editor, 'success');
        
        // Refresh display
        if (editor.refreshLayerManager) {
            editor.refreshLayerManager();
        }
        
        if (editor.triggerPreview) {
            editor.triggerPreview();
        }
    }
}

/**
 * Show migration notification to user
 * 
 * @param {Object} editor - Canvas editor instance
 * @param {string} type - Notification type
 */
function showMigrationNotification(editor, type = 'info') {
    // Try to use editor's notification system if available
    if (editor.showNotification) {
        editor.showNotification(
            '🔄 Artwork migrated to slideshow layer! Please save your changes.',
            'info'
        );
        return;
    }
    
    // Fallback: Create simple notification
    const notification = document.createElement('div');
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #3b82f6;
        color: white;
        padding: 16px 20px;
        border-radius: 8px;
        box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        z-index: 10000;
        max-width: 400px;
        font-size: 14px;
        line-height: 1.5;
    `;
    notification.innerHTML = `
        <div style="font-weight: 600; margin-bottom: 4px;">🔄 Artwork Migrated</div>
        <div>Your artwork images have been converted to a slideshow layer. Please save your changes.</div>
    `;
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.transition = 'opacity 0.3s';
        notification.style.opacity = '0';
        setTimeout(() => notification.remove(), 300);
    }, 5000);
}

/**
 * Generate migration report
 * 
 * Analyzes config and provides detailed migration information.
 * Useful for debugging and validation.
 * 
 * @param {Object} config - Content block configuration
 * @returns {Object} Migration report
 */
export function generateMigrationReport(config) {
    if (!config) {
        return { error: 'No configuration provided' };
    }
    
    const report = {
        needsMigration: hasArtworkItems(config),
        hasSlideshowLayer: hasSlideshowLayer(config),
        alreadyMigrated: config.artwork?._migrated || false,
        artworkItemCount: config.artwork?.items?.length || 0,
        slideshowLayerCount: config.layers?.filter(l => l.kind === LAYER_KIND_SLIDESHOW_IMAGE).length || 0,
        totalLayerCount: config.layers?.length || 0,
        canRollback: !!(config.artwork?._migrated && config.artwork._original_items),
        timestamp: Date.now()
    };
    
    // Add recommendations
    if (report.needsMigration && !report.hasSlideshowLayer) {
        report.recommendation = 'Migration needed: Run migrateArtworkToLayers()';
    } else if (report.hasSlideshowLayer && report.artworkItemCount > 0 && !report.alreadyMigrated) {
        report.recommendation = 'Warning: Has both slideshow layer and artwork items. Manual review needed.';
    } else if (report.alreadyMigrated) {
        report.recommendation = 'Already migrated. Safe to remove artwork.items[] in cleanup phase.';
    } else {
        report.recommendation = 'No action needed.';
    }
    
    return report;
}

/**
 * Validate migrated configuration
 * 
 * Ensures migration was successful and data is intact.
 * 
 * @param {Object} originalConfig - Original configuration before migration
 * @param {Object} migratedConfig - Configuration after migration
 * @returns {Object} Validation result
 */
export function validateMigration(originalConfig, migratedConfig) {
    const validation = {
        success: true,
        errors: [],
        warnings: []
    };
    
    // Check if slideshow layer was created
    if (!hasSlideshowLayer(migratedConfig)) {
        validation.success = false;
        validation.errors.push('Migration failed: No slideshow layer created');
        return validation;
    }
    
    // Find slideshow layer
    const slideshowLayer = migratedConfig.layers.find(l => 
        l.kind === LAYER_KIND_SLIDESHOW_IMAGE && l._migrated_from === 'artwork.items'
    );
    
    if (!slideshowLayer) {
        validation.success = false;
        validation.errors.push('Migration failed: Slideshow layer not found or not marked as migrated');
        return validation;
    }
    
    // Validate image count
    const originalItemCount = originalConfig.artwork?.items?.length || 0;
    const migratedImageCount = slideshowLayer.images?.length || 0;
    
    if (originalItemCount !== migratedImageCount) {
        validation.success = false;
        validation.errors.push(`Image count mismatch: Original ${originalItemCount}, Migrated ${migratedImageCount}`);
    }
    
    // Validate URLs
    const originalUrls = (originalConfig.artwork?.items || []).map(item => item.src || item.url);
    const migratedUrls = (slideshowLayer.images || []).map(img => img.url);
    
    originalUrls.forEach((url, index) => {
        if (url !== migratedUrls[index]) {
            validation.warnings.push(`URL mismatch at index ${index}: "${url}" vs "${migratedUrls[index]}"`);
        }
    });
    
    // Validate settings preservation
    if (originalConfig.artwork?.slideshow?.interval) {
        const expectedInterval = originalConfig.artwork.slideshow.interval;
        const firstImageDuration = slideshowLayer.images[0]?.duration;
        if (firstImageDuration !== expectedInterval) {
            validation.warnings.push(`Interval not preserved: Expected ${expectedInterval}, Got ${firstImageDuration}`);
        }
    }
    
    // Summary
    validation.summary = {
        originalItems: originalItemCount,
        migratedImages: migratedImageCount,
        layerId: slideshowLayer.id,
        autoplay: slideshowLayer.autoplay,
        transition: slideshowLayer.transition
    };
    
    return validation;
}

export const slideshowMigration = {
    migrateArtworkToLayers,
    migrateAllContentBlocks,
    rollbackMigration,
    autoMigrateOnLoad,
    generateMigrationReport,
    validateMigration,
    hasArtworkItems,
    hasSlideshowLayer
};
