/**
 * Example Campaign Level: Photo Tagging Tutorial
 * Demonstrates how to integrate the media tagging system into campaign levels
 */

// Example level configuration for use in campaign data
const photoTaggingTutorialLevel = {
    id: 'photo-tagging-tutorial',
    title: 'Photo Organization 101',
    description: 'Learn to organize your photos with tags',
    category: 'organization',
    difficulty: 'easy',
    estimatedTime: '10 minutes',
    rewards: {
        points: 100,
        achievements: ['organized-beginner']
    },

    // Instructions shown to the user
    instructions: `
        <h3>Welcome to Photo Organization!</h3>
        <p>In this lesson, you'll learn how to tag your photos for easy organization and retrieval.</p>
        <p><strong>Your Task:</strong></p>
        <ul>
            <li>Add at least 2 tags to each of your recent photos</li>
            <li>Use descriptive tags like "selfie", "outfit", "bedroom", etc.</li>
            <li>Complete all photos to finish this task</li>
        </ul>
        <p><em>Tip: Click on a photo to add tags. You can add multiple tags at once by separating them with commas!</em></p>
    `,

    // Setup function called when level loads
    setup: async function(container) {
        try {
            // Load recent photos
            const photos = await loadRecentPhotos(5);
            
            if (photos.length === 0) {
                showNoPhotosMessage(container);
                return;
            }

            // Initialize tagging system
            const tagManager = new MediaTagManager(window.game.dataManager);
            const tagUI = new MediaTagUI(tagManager);
            const campaignTagging = new CampaignTagging(tagManager, tagUI);

            // Configure the tagging task
            campaignTagging.initializeTaggingTask({
                requiredTagCount: 2,  // At least 2 tags per photo
                targetMediaIds: photos.map(p => p.id),
                onComplete: (progress) => {
                    // Task completed successfully
                    completeLevel(progress);
                }
            });

            // Display the tagging interface
            const mediaItems = photos.map(photo => ({
                id: photo.id,
                url: photo.url,
                type: 'photo',
                timestamp: photo.timestamp
            }));

            campaignTagging.displayTaggingInterface(container, mediaItems);

            // Store reference for cleanup
            this.campaignTagging = campaignTagging;

        } catch (error) {
            console.error('Failed to setup photo tagging tutorial:', error);
            showErrorMessage(container, error.message);
        }
    },

    // Cleanup function called when leaving the level
    cleanup: function() {
        if (this.campaignTagging) {
            // Cleanup if needed
            this.campaignTagging = null;
        }
    }
};

/**
 * Load recent photos for the tutorial
 */
async function loadRecentPhotos(count = 5) {
    if (!window.desktopFileManager || !window.desktopFileManager.isElectron) {
        // Browser mode - use sample data or localStorage
        return loadPhotosFromLocalStorage(count);
    }

    try {
        const allPhotos = await window.desktopFileManager.loadCapturedPhotos();
        
        // Get most recent photos
        const sortedPhotos = allPhotos
            .sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0))
            .slice(0, count);

        return sortedPhotos.map(photo => ({
            id: photo.path || photo.filename,
            url: photo.url || photo.path,
            path: photo.path,
            timestamp: photo.timestamp,
            sessionType: photo.sessionType
        }));
    } catch (error) {
        console.error('Error loading photos:', error);
        return [];
    }
}

/**
 * Load photos from localStorage (browser fallback)
 */
function loadPhotosFromLocalStorage(count) {
    try {
        const verificationPhotos = JSON.parse(localStorage.getItem('verificationPhotos') || '[]');
        
        return verificationPhotos
            .slice(0, count)
            .map((photo, index) => ({
                id: `verification_${index}`,
                url: photo.data || photo.dataUrl,
                timestamp: photo.timestamp,
                sessionType: 'verification'
            }));
    } catch (error) {
        console.error('Error loading verification photos:', error);
        return [];
    }
}

/**
 * Show message when no photos are available
 */
function showNoPhotosMessage(container) {
    container.innerHTML = `
        <div class="campaign-message info">
            <h3>📸 No Photos Available</h3>
            <p>You need to have some photos to complete this tutorial.</p>
            <p>Try playing some other levels first to capture some photos, then come back here!</p>
            <button class="btn btn-primary" onclick="window.history.back()">
                ← Go Back
            </button>
        </div>
    `;
}

/**
 * Show error message
 */
function showErrorMessage(container, message) {
    container.innerHTML = `
        <div class="campaign-message error">
            <h3>❌ Error</h3>
            <p>Something went wrong: ${message}</p>
            <button class="btn btn-primary" onclick="location.reload()">
                🔄 Retry
            </button>
        </div>
    `;
}

/**
 * Complete the level and award rewards
 */
function completeLevel(progress) {
    // Calculate bonus points based on tag variety
    const allTags = new Set();
    Object.values(progress.details || {}).forEach(detail => {
        (detail.tags || []).forEach(tag => allTags.add(tag));
    });

    const basePoints = 100;
    const varietyBonus = Math.min(allTags.size * 10, 100); // Max 100 bonus
    const totalPoints = basePoints + varietyBonus;

    // Award points
    if (window.game && window.game.awardPoints) {
        window.game.awardPoints(totalPoints);
    }

    // Show completion message
    const message = `
        <div style="text-align: center; padding: 2rem;">
            <h2 style="color: var(--color-success);">🎉 Congratulations!</h2>
            <p>You've successfully organized your photos!</p>
            <p><strong>Points Earned:</strong> ${totalPoints}</p>
            <p><small>Base: ${basePoints} + Variety Bonus: ${varietyBonus}</small></p>
            ${allTags.size > 5 ? '<p><em>Great tag variety! Keep it up!</em></p>' : ''}
        </div>
    `;

    if (window.game && window.game.showNotification) {
        window.game.showNotification('Level Complete! 🎉', 'success');
    }

    // Mark level as complete
    if (window.game && window.game.completeCurrentLevel) {
        window.game.completeCurrentLevel();
    }

    // Show completion UI
    const container = document.querySelector('.campaign-tagging-interface');
    if (container) {
        container.innerHTML = message;
    }
}

// Export for use in campaign data
if (typeof module !== 'undefined' && module.exports) {
    module.exports = { photoTaggingTutorialLevel };
}

// Make available globally
if (typeof window !== 'undefined') {
    window.photoTaggingTutorialLevel = photoTaggingTutorialLevel;
}
