/**
 * Campaign Tagging Integration
 * Provides tagging functionality for campaign levels that require photo/video tagging
 */

class CampaignTagging {
    constructor(tagManager, tagUI) {
        this.tagManager = tagManager;
        this.tagUI = tagUI;
        this.requiredTags = [];
        this.requiredTagCount = 0;
        this.targetMediaIds = [];
        this.completionCallback = null;
        
        console.log('🎯 CampaignTagging initialized');
    }

    /**
     * Initialize a tagging task for a campaign level
     * @param {Object} config - Configuration object
     * @param {Array} config.requiredTags - Array of required tag names (optional)
     * @param {number} config.requiredTagCount - Minimum number of tags required per item (optional)
     * @param {Array} config.targetMediaIds - Specific media IDs that must be tagged (optional)
     * @param {Function} config.onComplete - Callback when tagging requirement is met
     */
    initializeTaggingTask(config) {
        this.requiredTags = config.requiredTags || [];
        this.requiredTagCount = config.requiredTagCount || 0;
        this.targetMediaIds = config.targetMediaIds || [];
        this.completionCallback = config.onComplete || null;

        console.log('🎯 Tagging task initialized:', {
            requiredTags: this.requiredTags,
            requiredTagCount: this.requiredTagCount,
            targetMediaCount: this.targetMediaIds.length
        });

        // Setup progress tracking
        this.checkProgress();
    }

    /**
     * Check if tagging requirements are met
     * @returns {Object} Progress object with completion status
     */
    checkProgress() {
        const progress = {
            isComplete: false,
            taggedCount: 0,
            requiredCount: this.targetMediaIds.length || 0,
            missingTags: [],
            details: {}
        };

        if (this.targetMediaIds.length > 0) {
            // Check specific media items
            this.targetMediaIds.forEach(mediaId => {
                const tags = this.tagManager.getTagsForMedia(mediaId);
                const tagNames = tags.map(t => t.name);

                progress.details[mediaId] = {
                    tagCount: tags.length,
                    tags: tagNames,
                    meetsRequirements: this.checkMediaRequirements(mediaId, tags)
                };

                if (progress.details[mediaId].meetsRequirements) {
                    progress.taggedCount++;
                }
            });

            progress.isComplete = progress.taggedCount === progress.requiredCount;
        } else {
            // General requirement: any media can be tagged
            const allTaggedMedia = Object.keys(this.tagManager.mediaTags);
            const validMedia = allTaggedMedia.filter(mediaId => {
                const tags = this.tagManager.getTagsForMedia(mediaId);
                return this.checkMediaRequirements(mediaId, tags);
            });

            progress.taggedCount = validMedia.length;
            progress.isComplete = this.requiredTagCount > 0 
                ? progress.taggedCount > 0 
                : false;
        }

        // Check for missing required tags
        if (this.requiredTags.length > 0) {
            const allUsedTags = new Set();
            Object.keys(this.tagManager.mediaTags).forEach(mediaId => {
                const tags = this.tagManager.getTagsForMedia(mediaId);
                tags.forEach(tag => allUsedTags.add(tag.name));
            });

            progress.missingTags = this.requiredTags.filter(
                reqTag => !allUsedTags.has(reqTag)
            );
        }

        return progress;
    }

    /**
     * Check if a media item meets tagging requirements
     * @param {string} mediaId - Media ID
     * @param {Array} tags - Array of tag objects
     * @returns {boolean} True if requirements are met
     */
    checkMediaRequirements(mediaId, tags) {
        const tagNames = tags.map(t => t.name);

        // Check minimum tag count
        if (this.requiredTagCount > 0 && tags.length < this.requiredTagCount) {
            return false;
        }

        // Check required tags
        if (this.requiredTags.length > 0) {
            const hasAllRequired = this.requiredTags.every(reqTag => 
                tagNames.includes(reqTag)
            );
            if (!hasAllRequired) {
                return false;
            }
        }

        return true;
    }

    /**
     * Display tagging interface for campaign level
     * @param {HTMLElement} container - Container element
     * @param {Array} mediaItems - Array of media items to tag
     */
    displayTaggingInterface(container, mediaItems) {
        const wrapper = document.createElement('div');
        wrapper.className = 'campaign-tagging-interface';

        // Create header with instructions
        const instructions = this.generateInstructions();
        wrapper.innerHTML = `
            <div class="tagging-instructions">
                <h3>📋 Tagging Task</h3>
                <div class="instructions-content">${instructions}</div>
            </div>
            <div class="tagging-progress">
                <div class="progress-bar">
                    <div class="progress-fill" style="width: 0%"></div>
                </div>
                <div class="progress-text">0 / ${this.targetMediaIds.length || mediaItems.length} items tagged</div>
            </div>
            <div class="tagging-media-grid"></div>
            <div class="tagging-actions">
                <button class="btn btn-primary validate-btn">✓ Check Progress</button>
                <button class="btn btn-outline help-btn">? Help</button>
            </div>
        `;

        container.appendChild(wrapper);

        // Render media items
        const mediaGrid = wrapper.querySelector('.tagging-media-grid');
        this.renderMediaItems(mediaGrid, mediaItems);

        // Setup event listeners
        this.setupTaggingInterface(wrapper, mediaItems);

        // Update initial progress
        this.updateProgress(wrapper);
    }

    /**
     * Generate instruction text based on requirements
     */
    generateInstructions() {
        let instructions = '<ul>';

        if (this.requiredTagCount > 0) {
            instructions += `<li>Add at least <strong>${this.requiredTagCount}</strong> tag(s) to each item</li>`;
        }

        if (this.requiredTags.length > 0) {
            instructions += `<li>Each item must include these tags: <strong>${this.requiredTags.join(', ')}</strong></li>`;
        }

        if (this.targetMediaIds.length > 0) {
            instructions += `<li>Tag all <strong>${this.targetMediaIds.length}</strong> items below</li>`;
        } else {
            instructions += '<li>Tag the items with descriptive tags</li>';
        }

        instructions += '</ul>';
        return instructions;
    }

    /**
     * Render media items in the grid
     */
    renderMediaItems(container, mediaItems) {
        container.innerHTML = '';

        mediaItems.forEach((item, index) => {
            const mediaId = item.id || item.path || `media_${index}`;
            const itemElement = document.createElement('div');
            itemElement.className = 'tagging-media-item';
            itemElement.dataset.mediaId = mediaId;

            const mediaPreview = item.url || item.path || item.thumbnail || '';
            const mediaType = item.type || 'photo';

            itemElement.innerHTML = `
                <div class="media-preview">
                    ${mediaType === 'video' 
                        ? `<video src="${mediaPreview}" preload="metadata"></video>`
                        : `<img src="${mediaPreview}" alt="Media ${index + 1}" />`
                    }
                </div>
                <div class="media-tags-section"></div>
                <button class="btn btn-small btn-primary tag-item-btn">+ Add Tags</button>
            `;

            container.appendChild(itemElement);

            // Render existing tags
            const tagsSection = itemElement.querySelector('.media-tags-section');
            this.tagUI.renderMediaTags(tagsSection, mediaId, true);

            // Setup tag button
            const tagBtn = itemElement.querySelector('.tag-item-btn');
            tagBtn.addEventListener('click', () => {
                this.showTagModal(mediaId, mediaType);
            });
        });
    }

    /**
     * Setup event listeners for tagging interface
     */
    setupTaggingInterface(wrapper, mediaItems) {
        const validateBtn = wrapper.querySelector('.validate-btn');
        const helpBtn = wrapper.querySelector('.help-btn');

        validateBtn.addEventListener('click', () => {
            this.validateAndComplete(wrapper);
        });

        helpBtn.addEventListener('click', () => {
            this.showHelp();
        });

        // Listen for tag changes
        window.addEventListener('tagsChanged', () => {
            this.updateProgress(wrapper);
            this.updateMediaTags(wrapper);
        });
    }

    /**
     * Show tagging modal for a media item
     */
    showTagModal(mediaId, mediaType) {
        const modal = document.createElement('div');
        modal.className = 'modal active';
        
        const suggestedTags = this.requiredTags.length > 0 
            ? `<div class="suggested-tags">
                <strong>Required tags:</strong> ${this.requiredTags.map(tag => 
                    `<span class="tag-chip" style="background-color: ${this.tagManager.generateRandomColor()}">${tag}</span>`
                ).join('')}
               </div>`
            : '';

        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Tag ${mediaType}</h2>
                    <button class="modal-close-btn">×</button>
                </div>
                <div class="modal-body">
                    ${suggestedTags}
                    <div id="campaign-tag-input"></div>
                    <div class="current-tags">
                        <h3>Current Tags</h3>
                        <div id="campaign-current-tags"></div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline close-btn">Close</button>
                </div>
            </div>
        `;

        document.body.appendChild(modal);

        const inputContainer = modal.querySelector('#campaign-tag-input');
        const currentTagsDisplay = modal.querySelector('#campaign-current-tags');
        
        this.tagUI.renderTagInput(inputContainer, mediaId);
        this.tagUI.renderMediaTags(currentTagsDisplay, mediaId, true);

        // Override onTagsChanged to update display
        const originalCallback = this.tagUI.onTagsChanged;
        this.tagUI.onTagsChanged = () => {
            originalCallback.call(this.tagUI);
            this.tagUI.renderMediaTags(currentTagsDisplay, mediaId, true);
        };

        // Close handlers
        const closeModal = () => {
            this.tagUI.onTagsChanged = originalCallback;
            modal.classList.remove('active');
            setTimeout(() => modal.remove(), 300);
        };

        modal.querySelector('.modal-overlay').addEventListener('click', closeModal);
        modal.querySelector('.modal-close-btn').addEventListener('click', closeModal);
        modal.querySelector('.close-btn').addEventListener('click', closeModal);
    }

    /**
     * Update progress display
     */
    updateProgress(wrapper) {
        const progress = this.checkProgress();
        const progressFill = wrapper.querySelector('.progress-fill');
        const progressText = wrapper.querySelector('.progress-text');

        const percentage = progress.requiredCount > 0 
            ? (progress.taggedCount / progress.requiredCount) * 100 
            : 0;

        if (progressFill) {
            progressFill.style.width = `${percentage}%`;
            progressFill.style.backgroundColor = progress.isComplete 
                ? 'var(--color-success)' 
                : 'var(--color-primary)';
        }

        if (progressText) {
            progressText.textContent = `${progress.taggedCount} / ${progress.requiredCount || '?'} items tagged`;
        }

        // Highlight items that meet requirements
        const mediaItems = wrapper.querySelectorAll('.tagging-media-item');
        mediaItems.forEach(item => {
            const mediaId = item.dataset.mediaId;
            if (progress.details[mediaId]?.meetsRequirements) {
                item.classList.add('tagged-complete');
            } else {
                item.classList.remove('tagged-complete');
            }
        });
    }

    /**
     * Update media tags display
     */
    updateMediaTags(wrapper) {
        const mediaItems = wrapper.querySelectorAll('.tagging-media-item');
        mediaItems.forEach(item => {
            const mediaId = item.dataset.mediaId;
            const tagsSection = item.querySelector('.media-tags-section');
            if (tagsSection) {
                this.tagUI.renderMediaTags(tagsSection, mediaId, true);
            }
        });
    }

    /**
     * Validate completion and trigger callback
     */
    validateAndComplete(wrapper) {
        const progress = this.checkProgress();

        if (progress.isComplete) {
            this.showSuccessMessage();
            if (this.completionCallback) {
                this.completionCallback(progress);
            }
        } else {
            this.showIncompleteMessage(progress);
        }
    }

    /**
     * Show success message
     */
    showSuccessMessage() {
        const message = 'Congratulations! You have completed the tagging task.';
        if (window.game && window.game.showNotification) {
            window.game.showNotification(message, 'success');
        } else {
            alert(message);
        }
    }

    /**
     * Show incomplete message
     */
    showIncompleteMessage(progress) {
        let message = `Tagging incomplete!\n\n`;
        message += `Tagged: ${progress.taggedCount} / ${progress.requiredCount}\n`;
        
        if (progress.missingTags.length > 0) {
            message += `\nMissing required tags: ${progress.missingTags.join(', ')}`;
        }

        if (window.game && window.game.showNotification) {
            window.game.showNotification(message, 'warning');
        } else {
            alert(message);
        }
    }

    /**
     * Show help dialog
     */
    showHelp() {
        const helpText = `
            <h3>How to Tag Media</h3>
            <ul>
                <li>Click "+ Add Tags" on any item to add tags</li>
                <li>Type tag names separated by commas</li>
                <li>Use the suggested tags if provided</li>
                <li>You can add multiple tags at once</li>
                <li>Click "Check Progress" to see if you've met the requirements</li>
            </ul>
        `;

        const modal = document.createElement('div');
        modal.className = 'modal active';
        modal.innerHTML = `
            <div class="modal-overlay"></div>
            <div class="modal-content">
                <div class="modal-header">
                    <h2>Help</h2>
                    <button class="modal-close-btn">×</button>
                </div>
                <div class="modal-body">
                    ${helpText}
                </div>
                <div class="modal-footer">
                    <button class="btn btn-primary close-btn">Got it!</button>
                </div>
            </div>
        `;

        document.body.appendChild(modal);

        const closeModal = () => {
            modal.classList.remove('active');
            setTimeout(() => modal.remove(), 300);
        };

        modal.querySelector('.modal-overlay').addEventListener('click', closeModal);
        modal.querySelector('.modal-close-btn').addEventListener('click', closeModal);
        modal.querySelector('.close-btn').addEventListener('click', closeModal);
    }
}

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