/**
 * Library Tagging Integration
 * Integrates the media tagging system into the library management interface
 */

// Global tagging instances
let mediaTagManager = null;
let mediaTagUI = null;

/**
 * Initialize the tagging system
 */
function initializeTaggingSystem() {
    // Add retry limit to prevent infinite loops
    if (!window.game || !window.game.dataManager) {
        if (!initializeTaggingSystem.retryCount) {
            initializeTaggingSystem.retryCount = 0;
        }
        initializeTaggingSystem.retryCount++;
        
        if (initializeTaggingSystem.retryCount < 20) { // Max 10 seconds
            console.log(`⏳ Waiting for DataManager... (attempt ${initializeTaggingSystem.retryCount}/20)`);
            setTimeout(initializeTaggingSystem, 500);
        } else {
            console.error('❌ DataManager not available after maximum retries');
        }
        return;
    }

    try {
        mediaTagManager = new MediaTagManager(window.game.dataManager);
        mediaTagUI = new MediaTagUI(mediaTagManager);
        
        // Override callbacks for library integration
        mediaTagUI.onTagsChanged = function() {
            console.log('🏷️ Tags changed - refreshing gallery');
            refreshCurrentGallery();
            updateTagFilterPanel();
        };

        mediaTagUI.onFilterChanged = function() {
            console.log('🏷️ Filters changed - refreshing gallery');
            applyTagFilters();
        };

        console.log('✅ Tagging system initialized successfully');
        
        // Add tagging controls to the library
        addTaggingControls();
        
    } catch (error) {
        console.error('❌ Failed to initialize tagging system:', error);
    }
}

/**
 * Add tagging controls to library interface
 */
function addTaggingControls() {
    // Attach click handler to manage tags button
    const manageTagsBtn = document.getElementById('manage-tags-btn');
    if (manageTagsBtn) {
        manageTagsBtn.onclick = () => {
            if (mediaTagUI) {
                mediaTagUI.openTagManagementModal();
            } else {
                console.warn('Tag UI not initialized yet');
            }
        };
        console.log('✅ Manage Tags button handler attached');
    } else {
        console.warn('⚠️ Manage Tags button not found in DOM');
    }

    // Add bulk selection toggle to each tab
    addBulkSelectionControls();
    
    // Add tag filter panels
    addTagFilterPanels();
}

/**
 * Add bulk selection controls to tabs
 */
function addBulkSelectionControls() {
    const tabs = [
        { name: 'images', galleryId: 'lib-image-gallery' },
        { name: 'video', galleryId: 'lib-video-gallery' },
        { name: 'gallery', galleryId: 'lib-captured-photos-gallery' }
    ];
    
    tabs.forEach(tab => {
        const tabContent = document.getElementById(`library-${tab.name}-content`);
        if (!tabContent || document.getElementById(`${tab.name}-bulk-controls`)) return;

        const bulkControls = document.createElement('div');
        bulkControls.id = `${tab.name}-bulk-controls`;
        bulkControls.className = 'bulk-selection-controls';
        bulkControls.innerHTML = `
            <div class="bulk-controls-bar">
                <button class="btn btn-outline btn-small toggle-bulk-btn">
                    📋 Select Multiple
                </button>
                <span class="bulk-help-text">Select multiple items to tag them together</span>
            </div>
        `;

        // Insert before the gallery section
        const gallerySection = tabContent.querySelector('.gallery-section, .video-gallery-section, .content-section');
        if (gallerySection) {
            gallerySection.insertBefore(bulkControls, gallerySection.firstChild);
            setupBulkControls(tab.name, tab.galleryId);
        }
    });
}

/**
 * Setup bulk selection controls
 */
function setupBulkControls(tabName, galleryId) {
    const toggleBtn = document.querySelector(`#${tabName}-bulk-controls .toggle-bulk-btn`);
    const gallery = document.getElementById(galleryId);
    
    if (!toggleBtn || !gallery) {
        console.warn(`Could not setup bulk controls for ${tabName}`, { toggleBtn: !!toggleBtn, gallery: !!gallery });
        return;
    }

    let bulkActionsBar = null;

    toggleBtn.addEventListener('click', () => {
        if (mediaTagUI.bulkMode) {
            // Disable bulk mode
            mediaTagUI.disableBulkMode();
            toggleBtn.textContent = '📋 Select Multiple';
            toggleBtn.classList.remove('active');
            gallery.classList.remove('bulk-mode-active');
            
            // Remove selection styling
            gallery.querySelectorAll('.gallery-item').forEach(item => {
                item.classList.remove('selected');
            });

            // Remove bulk actions bar
            if (bulkActionsBar) {
                bulkActionsBar.remove();
                bulkActionsBar = null;
            }
        } else {
            // Enable bulk mode
            mediaTagUI.enableBulkMode();
            toggleBtn.textContent = '✓ Select Mode Active';
            toggleBtn.classList.add('active');
            gallery.classList.add('bulk-mode-active');

            // Create bulk actions bar
            bulkActionsBar = createBulkActionsBar(tabName, galleryId);
            document.body.appendChild(bulkActionsBar);
        }
    });

    // Handle item selection in bulk mode
    gallery.addEventListener('click', (e) => {
        if (!mediaTagUI.bulkMode) return;

        const item = e.target.closest('.gallery-item');
        if (!item) return;

        // Stop the preview from opening in bulk mode
        e.stopPropagation();
        e.preventDefault();

        const mediaId = item.dataset.mediaId || item.dataset.photoPath || item.dataset.videoPath;
        if (!mediaId) return;

        mediaTagUI.toggleMediaSelection(mediaId);
        item.classList.toggle('selected');

        // Update bulk actions bar
        if (bulkActionsBar) {
            updateBulkActionsBar(bulkActionsBar);
        }
    }, true); // Use capture phase to intercept before other handlers
}

/**
 * Create bulk actions bar
 */
function createBulkActionsBar(tabName, galleryId) {
    const bar = document.createElement('div');
    bar.className = 'bulk-actions-bar';
    bar.innerHTML = `
        <span class="selection-count">0 selected</span>
        <div class="actions">
            <button class="btn btn-primary btn-small bulk-tag-btn">
                🏷️ Tag Selected
            </button>
            <button class="btn btn-outline btn-small select-all-btn">
                Select All
            </button>
            <button class="btn btn-outline btn-small clear-selection-btn">
                Clear
            </button>
        </div>
    `;

    // Event listeners
    bar.querySelector('.bulk-tag-btn').addEventListener('click', () => {
        showBulkTagModal();
    });

    bar.querySelector('.select-all-btn').addEventListener('click', () => {
        const gallery = document.getElementById(galleryId);
        const items = gallery.querySelectorAll('.gallery-item');
        const mediaIds = Array.from(items).map(item => 
            item.dataset.mediaId || item.dataset.photoPath || item.dataset.videoPath
        ).filter(id => id);

        mediaTagUI.selectAllMedia(mediaIds);
        items.forEach(item => item.classList.add('selected'));
        updateBulkActionsBar(bar);
    });

    bar.querySelector('.clear-selection-btn').addEventListener('click', () => {
        mediaTagUI.clearSelection();
        const gallery = document.getElementById(galleryId);
        gallery.querySelectorAll('.gallery-item').forEach(item => {
            item.classList.remove('selected');
        });
        updateBulkActionsBar(bar);
    });

    return bar;
}

/**
 * Update bulk actions bar
 */
function updateBulkActionsBar(bar) {
    const count = mediaTagUI.selectedMedia.size;
    const countSpan = bar.querySelector('.selection-count');
    countSpan.textContent = `${count} selected`;
    
    const tagBtn = bar.querySelector('.bulk-tag-btn');
    tagBtn.disabled = count === 0;
}

/**
 * Show bulk tag modal
 */
function showBulkTagModal() {
    if (mediaTagUI.selectedMedia.size === 0) {
        mediaTagUI.showNotification('No items selected', 'warning');
        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 ${mediaTagUI.selectedMedia.size} Items</h2>
                <button class="modal-close-btn">×</button>
            </div>
            <div class="modal-body">
                <div id="bulk-tag-input-container"></div>
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline close-btn">Cancel</button>
            </div>
        </div>
    `;

    document.body.appendChild(modal);

    const inputContainer = modal.querySelector('#bulk-tag-input-container');
    mediaTagUI.renderTagInput(inputContainer);

    // Close handlers
    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);
}

/**
 * Add tag filter panels to tabs
 */
function addTagFilterPanels() {
    const tabs = ['gallery', 'video'];
    
    tabs.forEach(tabName => {
        const tabContent = document.querySelector(`[data-tab="${tabName}"]`)?.nextElementSibling;
        if (!tabContent || document.getElementById(`${tabName}-tag-filter`)) return;

        const filterContainer = document.createElement('div');
        filterContainer.id = `${tabName}-tag-filter`;
        filterContainer.className = 'tag-filter-container';

        const tabContentInner = tabContent.querySelector('.tab-content-inner') || tabContent;
        const gallery = tabContent.querySelector(`#lib-${tabName === 'gallery' ? 'captured-photos-gallery' : tabName + '-gallery'}`);
        
        if (gallery) {
            gallery.parentNode.insertBefore(filterContainer, gallery);
            mediaTagUI.renderTagFilter(filterContainer);
        }
    });
}

/**
 * Add tagging controls to individual gallery items
 */
function addTagsToGalleryItem(item, mediaId, mediaType = 'photo') {
    if (!mediaTagManager || !mediaTagUI) return;

    // Add media ID to item
    item.dataset.mediaId = mediaId;

    // Create tags display container
    const tagsContainer = document.createElement('div');
    tagsContainer.className = 'gallery-item-tags';
    
    // Render existing tags
    mediaTagUI.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();
        showSingleItemTagModal(mediaId, mediaType);
    };

    // Append to item
    const itemInfo = item.querySelector('.gallery-item-info') || item;
    itemInfo.appendChild(tagsContainer);
    itemInfo.appendChild(addTagBtn);
}

/**
 * Show tag modal for single item
 */
function showSingleItemTagModal(mediaId, mediaType) {
    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="single-tag-input-container"></div>
                <div class="current-tags">
                    <h3>Current Tags</h3>
                    <div id="current-tags-display"></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('#single-tag-input-container');
    const currentTagsDisplay = modal.querySelector('#current-tags-display');
    
    mediaTagUI.renderTagInput(inputContainer, mediaId);
    mediaTagUI.renderMediaTags(currentTagsDisplay, mediaId, true);

    // Override onTagsChanged to update current tags display
    const originalCallback = mediaTagUI.onTagsChanged;
    mediaTagUI.onTagsChanged = function() {
        originalCallback.call(this);
        mediaTagUI.renderMediaTags(currentTagsDisplay, mediaId, true);
    };

    // Close handlers
    const closeModal = () => {
        mediaTagUI.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 tag filter panel
 */
function updateTagFilterPanel() {
    const filterPanels = document.querySelectorAll('.tag-filter-panel');
    filterPanels.forEach(panel => {
        mediaTagUI.updateTagFilterList(panel);
    });
}

// Expose globally for library manager
window.mediaTaggingIntegration = {
    addTagsToGalleryItem: addTagsToGalleryItem
};

/**
 * Apply tag filters to current gallery
 */
function applyTagFilters() {
    // Get active tab
    const activeTab = document.querySelector('.library-tab.active');
    if (!activeTab) return;

    const tabType = activeTab.getAttribute('data-tab');
    
    // Apply filters based on tab type
    switch(tabType) {
        case 'gallery':
            filterPhotoGallery();
            break;
        case 'video':
            filterVideoGallery();
            break;
    }
}

/**
 * Filter photo gallery by tags
 */
function filterPhotoGallery() {
    const gallery = document.getElementById('lib-captured-photos-gallery');
    if (!gallery) return;

    const allItems = gallery.querySelectorAll('.gallery-item');
    const allPhotos = Array.from(allItems).map(item => ({
        element: item,
        id: item.dataset.mediaId || item.dataset.photoPath
    }));

    if (mediaTagUI.activeFilters.size === 0) {
        // Show all
        allItems.forEach(item => item.style.display = '');
        return;
    }

    const filteredPhotos = mediaTagUI.getFilteredMedia(allPhotos);
    const filteredIds = new Set(filteredPhotos.map(p => p.id));

    allItems.forEach(item => {
        const itemId = item.dataset.mediaId || item.dataset.photoPath;
        item.style.display = filteredIds.has(itemId) ? '' : 'none';
    });
}

/**
 * Filter video gallery by tags
 */
function filterVideoGallery() {
    const gallery = document.getElementById('lib-video-gallery');
    if (!gallery) return;

    const allItems = gallery.querySelectorAll('.gallery-item');
    const allVideos = Array.from(allItems).map(item => ({
        element: item,
        id: item.dataset.mediaId || item.dataset.videoPath
    }));

    if (mediaTagUI.activeFilters.size === 0) {
        // Show all
        allItems.forEach(item => item.style.display = '');
        return;
    }

    const filteredVideos = mediaTagUI.getFilteredMedia(allVideos);
    const filteredIds = new Set(filteredVideos.map(v => v.id));

    allItems.forEach(item => {
        const itemId = item.dataset.mediaId || item.dataset.videoPath;
        item.style.display = filteredIds.has(itemId) ? '' : 'none';
    });
}

/**
 * Refresh current gallery
 */
function refreshCurrentGallery() {
    const activeTab = document.querySelector('.library-tab.active');
    if (!activeTab) return;

    const tabType = activeTab.getAttribute('data-tab');
    
    switch(tabType) {
        case 'gallery':
            if (typeof loadCapturedPhotosForGallery === 'function') {
                loadCapturedPhotosForGallery();
            }
            break;
        case 'video':
            if (typeof setupLibraryVideoTab === 'function') {
                setupLibraryVideoTab();
            }
            break;
    }
}

// Initialize on page load
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initializeTaggingSystem);
} else {
    initializeTaggingSystem();
}

// Export for use in other scripts
window.mediaTaggingIntegration = {
    initializeTaggingSystem,
    addTagsToGalleryItem,
    showSingleItemTagModal,
    refreshCurrentGallery
};
