/**
 * Global Media Tagging Initialization
 * Initializes the media tagging system for use across the application
 * Include this script after core game initialization
 */

(function() {
    'use strict';

    // Wait for game to be ready
    function initializeGlobalTagging() {
        if (!window.game || !window.game.dataManager) {
            console.log('⏳ Waiting for game initialization...');
            setTimeout(initializeGlobalTagging, 500);
            return;
        }

        try {
            // Initialize tag manager
            if (!window.globalMediaTagManager) {
                window.globalMediaTagManager = new MediaTagManager(window.game.dataManager);
                console.log('✅ Global MediaTagManager initialized');
            }

            // Initialize tag UI
            if (!window.globalMediaTagUI) {
                window.globalMediaTagUI = new MediaTagUI(window.globalMediaTagManager);
                console.log('✅ Global MediaTagUI initialized');
            }

            // Expose convenient global functions
            window.tagMedia = function(mediaId, tags) {
                return window.globalMediaTagManager.addTagsToMedia(mediaId, tags);
            };

            window.getMediaTags = function(mediaId) {
                return window.globalMediaTagManager.getTagsForMedia(mediaId);
            };

            window.findMediaByTags = function(tagNames, matchAll = false) {
                const tags = window.globalMediaTagManager.getAllTags();
                const tagIds = tags
                    .filter(t => tagNames.includes(t.name))
                    .map(t => t.id);
                
                return matchAll 
                    ? window.globalMediaTagManager.getMediaWithAllTags(tagIds)
                    : window.globalMediaTagManager.getMediaWithAnyTags(tagIds);
            };

            window.openTagManager = function() {
                window.globalMediaTagUI.openTagManagementModal();
            };

            console.log('✅ Global tagging functions available');
            console.log('   - tagMedia(mediaId, tags)');
            console.log('   - getMediaTags(mediaId)');
            console.log('   - findMediaByTags(tagNames, matchAll)');
            console.log('   - openTagManager()');

            // Dispatch ready event
            window.dispatchEvent(new CustomEvent('taggingSystemReady', {
                detail: {
                    tagManager: window.globalMediaTagManager,
                    tagUI: window.globalMediaTagUI
                }
            }));

        } catch (error) {
            console.error('❌ Failed to initialize global tagging system:', error);
        }
    }

    // Auto-initialize if classes are available
    if (typeof MediaTagManager !== 'undefined' && typeof MediaTagUI !== 'undefined') {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', initializeGlobalTagging);
        } else {
            initializeGlobalTagging();
        }
    } else {
        console.warn('⚠️ MediaTagManager or MediaTagUI not loaded. Include the required scripts first.');
    }

    // Helper: Add tagging to dynamically created media elements
    window.addTaggingToElement = function(element, mediaId, mediaType = 'photo') {
        if (!window.globalMediaTagUI) {
            console.warn('Tagging system not initialized yet');
            return;
        }

        // Add data attribute
        element.dataset.mediaId = mediaId;

        // Create tag container
        const tagsContainer = document.createElement('div');
        tagsContainer.className = 'media-tags-container';
        
        // Render existing tags
        window.globalMediaTagUI.renderMediaTags(tagsContainer, mediaId, true);
        
        // Add tag button
        const addTagBtn = document.createElement('button');
        addTagBtn.className = 'btn btn-small btn-outline add-tag-btn';
        addTagBtn.innerHTML = '+ Tag';
        addTagBtn.onclick = (e) => {
            e.stopPropagation();
            showQuickTagModal(mediaId, mediaType);
        };

        // Append to element
        element.appendChild(tagsContainer);
        element.appendChild(addTagBtn);
    };

    // Quick tag modal helper
    function showQuickTagModal(mediaId, mediaType) {
        if (!window.globalMediaTagUI) return;

        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>Tag ${mediaType}</h2>
                    <button class="modal-close-btn">×</button>
                </div>
                <div class="modal-body">
                    <div id="quick-tag-input"></div>
                    <div class="current-tags">
                        <h3>Current Tags</h3>
                        <div id="quick-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('#quick-tag-input');
        const currentTagsDisplay = modal.querySelector('#quick-current-tags');
        
        window.globalMediaTagUI.renderTagInput(inputContainer, mediaId);
        window.globalMediaTagUI.renderMediaTags(currentTagsDisplay, mediaId, true);

        const originalCallback = window.globalMediaTagUI.onTagsChanged;
        window.globalMediaTagUI.onTagsChanged = function() {
            originalCallback.call(this);
            window.globalMediaTagUI.renderMediaTags(currentTagsDisplay, mediaId, true);
        };

        const closeModal = () => {
            window.globalMediaTagUI.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);
    }

    // Helper: Create campaign tagging instance
    window.createCampaignTagging = function() {
        if (!window.globalMediaTagManager || !window.globalMediaTagUI) {
            console.error('Tagging system not initialized');
            return null;
        }

        return new CampaignTagging(window.globalMediaTagManager, window.globalMediaTagUI);
    };

    console.log('📋 Global tagging initialization script loaded');
})();
