// search.js - OPTIMIZED HIGH PERFORMANCE VERSION

$(document).ready(function() {
    console.log('Optimized search.js loaded');
    
    // ==========================================
    // SEARCH CACHE SYSTEM
    // ==========================================
    class SearchCache {
        constructor() {
            this.cache = new Map();
            this.maxSize = 50;
            this.ttl = 5 * 60 * 1000; // 5 minutes
        }
        
        get(query) {
            const cached = this.cache.get(query);
            if (cached && Date.now() - cached.timestamp < this.ttl) {
                console.log('Search cache hit:', query);
                return cached.data;
            }
            return null;
        }
        
        set(query, data) {
            // LRU: Remove oldest if at capacity
            if (this.cache.size >= this.maxSize) {
                const firstKey = this.cache.keys().next().value;
                this.cache.delete(firstKey);
            }
            
            this.cache.set(query, {
                data: data,
                timestamp: Date.now()
            });
        }
        
        clear() {
            this.cache.clear();
        }
    }
    
    // ==========================================
    // SEARCH CONTROLLER
    // ==========================================
    class SearchController {
        constructor() {
            this.cache = new SearchCache();
            this.currentRequest = null;
            this.lastQuery = '';
            this.debounceTimer = null;
            this.debounceDelay = 300;
            this.minQueryLength = 2;
            this.searchHistory = [];
            this.maxHistory = 10;
        }
        
        async execute(query, options = {}) {
            const {
                immediate = false,
                fromCache = true,
                addToHistory = true
            } = options;
            
            // Normalize query
            query = query.trim();
            
            // Check if same as last query
            if (query === this.lastQuery && !options.force) {
                console.log('Same query, skipping:', query);
                return;
            }
            
            // Cancel any pending debounce
            if (this.debounceTimer) {
                clearTimeout(this.debounceTimer);
                this.debounceTimer = null;
            }
            
            // Cancel ongoing request
            if (this.currentRequest) {
                this.currentRequest.abort();
                this.currentRequest = null;
            }
            
            // Validate query
            if (query && !this.isValidQuery(query)) {
                this.showQuickMessage('Search query too short (min 2 characters)');
                return;
            }
            
            // Add to history
            if (addToHistory && query) {
                this.addToHistory(query);
            }
            
            // Update last query
            this.lastQuery = query;
            
            // Execute search
            if (immediate) {
                await this.performSearch(query, fromCache);
            } else {
                this.debounceTimer = setTimeout(() => {
                    this.performSearch(query, fromCache);
                }, this.debounceDelay);
            }
        }
        
        async performSearch(query, useCache = true) {
            console.log('Performing search:', query || '(empty - all feeds)');
            
            // Check cache first
            if (useCache && query) {
                const cached = this.cache.get(query);
                if (cached) {
                    this.processResults(cached, query, true);
                    return;
                }
            }
            
            // Clear and reset
            this.clearResults();
            window.feeds = {};
            window.displayedFeeds = {};
            window.page = 1;
            window.loading = false;
            
            // Update UI
            this.updateSearchUI(query);
            
            // Show loading
            this.showLoadingState();
            
            // Make request
            try {
                const startTime = Date.now();
                
                this.currentRequest = $.ajax({
                    url: 'get_pinfeeds.php',
                    type: 'GET',
                    dataType: 'json',
                    data: { 
                        page: 1, 
                        search: query, 
                        t: Date.now() 
                    }
                });
                
                const data = await this.currentRequest;
                const loadTime = Date.now() - startTime;
                
                console.log(`Search completed in ${loadTime}ms, found ${data.length} results`);
                
                // Cache successful results
                if (query && data.length > 0) {
                    this.cache.set(query, data);
                }
                
                // Process results
                this.processResults(data, query, false);
                
                // Track performance
                if (window.performanceMonitor) {
                    window.performanceMonitor.track('search_time', loadTime);
                }
                
            } catch (error) {
                if (error.statusText !== 'abort') {
                    console.error('Search error:', error);
                    this.showErrorState('Search failed. Please try again.');
                }
            } finally {
                this.currentRequest = null;
                this.hideLoadingState();
            }
        }
        
        processResults(data, query, fromCache) {
            // Add results to feeds
            data.forEach(feed => {
                const key = feed.id || feed.link;
                window.feeds[key] = feed;
            });
            
            // Display results
            if (query === '') {
                window.displayAllFeeds();
            } else {
                window.displayFeeds();
            }
            
            // Show cache indicator
            if (fromCache) {
                this.showCacheIndicator();
            }
            
            // Check if need more content
            setTimeout(() => {
                if (typeof window.checkIfNeedMoreContent === 'function') {
                    window.checkIfNeedMoreContent();
                }
            }, 500);
        }
        
        clearResults() {
            const $feeds = $('#feeds');
            
            // Fade out existing content
            $feeds.find('.result').addClass('fade-out');
            
            setTimeout(() => {
                $feeds.empty().removeClass('loaded');
                
                // Reset masonry
                if (window.masonry) {
                    window.masonry.columnHeights = [];
                    window.masonry.resetColumnHeights();
                    if (window.masonry.container) {
                        window.masonry.container.style.height = '0px';
                    }
                }
                
                $feeds.css('height', 'auto');
            }, 150);
            
            $('#tags-container').empty();
        }
        
        showLoadingState() {
            const loadingHtml = `
                <div class="search-loading-state">
                    <div class="search-spinner">
                        <div class="spinner-circle"></div>
                        <div class="spinner-circle"></div>
                        <div class="spinner-circle"></div>
                    </div>
                    <p class="search-loading-text">Searching feeds...</p>
                    <div class="search-progress-bar">
                        <div class="search-progress-fill"></div>
                    </div>
                </div>
            `;
            
            $('#feeds').html(loadingHtml);
            
            // Animate progress bar
            setTimeout(() => {
                $('.search-progress-fill').css('width', '80%');
            }, 100);
        }
        
        hideLoadingState() {
            $('.search-loading-state').fadeOut(200, function() {
                $(this).remove();
            });
        }
        
        showErrorState(message) {
            const errorHtml = `
                <div class="search-error-state">
                    <div class="error-icon">
                        <i class="fas fa-exclamation-circle"></i>
                    </div>
                    <h3>Oops! Something went wrong</h3>
                    <p>${message}</p>
                    <button class="retry-button" onclick="searchController.retry()">
                        <i class="fas fa-redo"></i> Try Again
                    </button>
                </div>
            `;
            
            $('#feeds').html(errorHtml);
        }
        
        showCacheIndicator() {
            const indicator = $('<div class="cache-indicator">Cached results <i class="fas fa-bolt"></i></div>');
            $('body').append(indicator);
            
            setTimeout(() => {
                indicator.addClass('show');
            }, 100);
            
            setTimeout(() => {
                indicator.removeClass('show');
                setTimeout(() => indicator.remove(), 300);
            }, 2000);
        }
        
        showQuickMessage(message) {
            const $msg = $(`<div class="quick-message">${message}</div>`);
            $('body').append($msg);
            
            setTimeout(() => $msg.addClass('show'), 10);
            setTimeout(() => {
                $msg.removeClass('show');
                setTimeout(() => $msg.remove(), 300);
            }, 3000);
        }
        
        updateSearchUI(query) {
            // Update search field if needed
            if ($('#search-query').val() !== query) {
                $('#search-query').val(query);
            }
            
            // Extract and display tags
            if (query && query.trim() !== '') {
                this.extractAndDisplayTags(query);
            } else {
                $('#tags-container').empty();
            }
            
            // Smooth scroll to top
            $('html, body').animate({ scrollTop: 0 }, 300);
        }
        
        extractAndDisplayTags(query) {
            const $container = $('#tags-container');
            $container.empty();
            
            // Smart keyword extraction
            const keywords = this.extractKeywords(query);
            
            // Create tags with animation
            keywords.forEach((keyword, index) => {
                const $tag = this.createTagElement(keyword);
                $container.append($tag);
                
                // Animate in
                setTimeout(() => {
                    $tag.addClass('tag-visible');
                }, index * 50);
            });
        }
        
        extractKeywords(query) {
            // Remove special search operators
            let cleanQuery = query.replace(/^(source:|author:)/, '');
            
            // Smart keyword extraction
            const words = cleanQuery.split(/\s+/)
                .filter(word => word.length > 2)
                .map(word => word.toLowerCase());
            
            // Remove duplicates
            return [...new Set(words)];
        }
        
        createTagElement(keyword) {
            const displayText = keyword.length > 24 ? 
                keyword.substring(0, 24) + '...' : keyword;
            
            const bgColor = this.stringToColor(keyword);
            const textColor = this.isColorDark(bgColor) ? 'white' : 'black';
            
            const $tag = $(`
                <a href="#" class="search-tag tag-search-link" 
                   data-tag="${keyword}"
                   style="background-color: ${bgColor}; color: ${textColor};">
                    #${displayText}
                </a>
            `);
            
            return $tag;
        }
        
        isValidQuery(query) {
            // Special operators are always valid
            if (query.startsWith('source:') || query.startsWith('author:')) {
                return true;
            }
            
            // Check minimum length
            return query.length >= this.minQueryLength;
        }
        
        addToHistory(query) {
            // Remove if already exists
            this.searchHistory = this.searchHistory.filter(q => q !== query);
            
            // Add to beginning
            this.searchHistory.unshift(query);
            
            // Limit size
            if (this.searchHistory.length > this.maxHistory) {
                this.searchHistory.pop();
            }
            
            // Save to localStorage
            try {
                localStorage.setItem('searchHistory', JSON.stringify(this.searchHistory));
            } catch (e) {
                console.warn('Could not save search history');
            }
        }
        
        loadHistory() {
            try {
                const saved = localStorage.getItem('searchHistory');
                if (saved) {
                    this.searchHistory = JSON.parse(saved);
                }
            } catch (e) {
                console.warn('Could not load search history');
            }
        }
        
        retry() {
            this.execute(this.lastQuery, { immediate: true, force: true });
        }
        
        stringToColor(str) {
            let hash = 0;
            for (let i = 0; i < str.length; i++) {
                hash = str.charCodeAt(i) + ((hash << 5) - hash);
            }
            let color = '#';
            for (let i = 0; i < 3; i++) {
                const value = (hash >> (i * 8)) & 0xFF;
                color += ('00' + value.toString(16)).substr(-2);
            }
            return color;
        }
        
        isColorDark(color) {
            const hex = color.replace('#', '');
            const r = parseInt(hex.substr(0, 2), 16);
            const g = parseInt(hex.substr(2, 2), 16);
            const b = parseInt(hex.substr(4, 2), 16);
            const brightness = ((r * 299) + (g * 587) + (b * 114)) / 1000;
            return brightness < 128;
        }
    }
    
    // ==========================================
    // INITIALIZE SEARCH CONTROLLER
    // ==========================================
    window.searchController = new SearchController();
    searchController.loadHistory();
    
    // ==========================================
    // EVENT HANDLERS
    // ==========================================
    
    // Delegated event handlers for better performance
    $(document).on('click', '.tag-search-link', function(e) {
        e.preventDefault();
        const tag = $(this).data('tag');
        console.log('Tag clicked:', tag);
        searchController.execute(tag, { immediate: true });
    });
    
    $(document).on('click', '.author-search-link', function(e) {
        e.preventDefault();
        const author = $(this).data('author');
        console.log('Author clicked:', author);
        window.location.href = 'author.html?name=' + encodeURIComponent(author);
    });
    
    $(document).on('click', '.source-search-link', function(e) {
        e.preventDefault();
        const sourceDomain = $(this).data('source-domain');
        console.log('Source clicked:', sourceDomain);
        searchController.execute('source:' + sourceDomain, { immediate: true });
    });
    
    // Search button
    $('#search-button').on('click', function(e) {
        e.preventDefault();
        const query = $('#search-query').val();
        searchController.execute(query, { immediate: true });
    });
    
    // Enter key in search field
    $('#search-query').on('keydown', function(e) {
        if (e.key === 'Enter' || e.keyCode === 13) {
            e.preventDefault();
            const query = $(this).val();
            searchController.execute(query, { immediate: true });
        }
    });
    
    // Live search as user types
    let inputTimer;
    $('#search-query').on('input', function() {
        const query = $(this).val();
        
        clearTimeout(inputTimer);
        
        // Clear tags immediately when empty
        if (query.trim() === '') {
            $('#tags-container').empty();
            searchController.execute('', { immediate: true });
        } else if (query.length >= 2) {
            // Search after delay
            inputTimer = setTimeout(() => {
                searchController.execute(query);
            }, 300);
        }
    });
    
    // Search suggestions (optional)
    $('#search-query').on('focus', function() {
        if (searchController.searchHistory.length > 0) {
            showSearchSuggestions();
        }
    });
    
    $('#search-query').on('blur', function() {
        setTimeout(() => {
            hideSearchSuggestions();
        }, 200);
    });
    
    // ==========================================
    // SEARCH SUGGESTIONS
    // ==========================================
    function showSearchSuggestions() {
        const history = searchController.searchHistory.slice(0, 5);
        if (history.length === 0) return;
        
        const suggestionsHtml = `
            <div class="search-suggestions">
                <div class="suggestions-header">Recent Searches</div>
                ${history.map(query => `
                    <div class="suggestion-item" data-query="${query}">
                        <i class="fas fa-history"></i>
                        <span>${query}</span>
                    </div>
                `).join('')}
                <div class="clear-history">
                    <i class="fas fa-trash"></i> Clear History
                </div>
            </div>
        `;
        
        $('.search-suggestions').remove();
        $('#search-query').after(suggestionsHtml);
        
        // Animate in
        setTimeout(() => {
            $('.search-suggestions').addClass('visible');
        }, 10);
    }
    
    function hideSearchSuggestions() {
        $('.search-suggestions').removeClass('visible');
        setTimeout(() => {
            $('.search-suggestions').remove();
        }, 200);
    }
    
    $(document).on('click', '.suggestion-item', function() {
        const query = $(this).data('query');
        searchController.execute(query, { immediate: true });
    });
    
    $(document).on('click', '.clear-history', function(e) {
        e.stopPropagation();
        searchController.searchHistory = [];
        localStorage.removeItem('searchHistory');
        hideSearchSuggestions();
    });
    
    // ==========================================
    // KEYBOARD SHORTCUTS
    // ==========================================
    $(document).on('keydown', function(e) {
        // Ctrl/Cmd + K to focus search
        if ((e.ctrlKey || e.metaKey) && e.key === 'k') {
            e.preventDefault();
            $('#search-query').focus().select();
        }
        
        // ESC to clear search
        if (e.key === 'Escape' && $('#search-query').is(':focus')) {
            $('#search-query').val('').blur();
            searchController.execute('', { immediate: true });
        }
    });
    
    // ==========================================
    // BACK BUTTON HANDLING
    // ==========================================
    window.addEventListener('popstate', function(event) {
        console.log('Navigation detected');
        if (event.state && event.state.search !== undefined) {
            searchController.execute(event.state.search, { 
                immediate: true, 
                addToHistory: false 
            });
        }
    });
    
    // Save search state in history
    function updateBrowserHistory(query) {
        const state = { search: query };
        const title = query ? `Search: ${query}` : 'All Feeds';
        const url = query ? `?search=${encodeURIComponent(query)}` : '?';
        
        history.pushState(state, title, url);
    }
    
    // ==========================================
    // INITIALIZE FROM URL
    // ==========================================
    const urlParams = new URLSearchParams(window.location.search);
    const initialSearch = urlParams.get('search') || '';
    
    if (initialSearch) {
        searchController.execute(initialSearch, { immediate: true });
    }
    
    // ==========================================
    // DEBUG FUNCTIONS
    // ==========================================
    window.debugSearch = function() {
        console.log('=== OPTIMIZED SEARCH DEBUG ===');
        console.log('Current query:', searchController.lastQuery);
        console.log('Cache size:', searchController.cache.cache.size);
        console.log('Search history:', searchController.searchHistory);
        console.log('Active request:', searchController.currentRequest ? 'Yes' : 'No');
        console.log('Feeds loaded:', Object.keys(window.feeds || {}).length);
        console.log('===========================');
    };
    
    // Performance API
    window.searchPerformance = {
        clearCache: () => searchController.cache.clear(),
        getCacheStats: () => ({
            size: searchController.cache.cache.size,
            entries: Array.from(searchController.cache.cache.keys())
        }),
        forceRefresh: () => searchController.execute(searchController.lastQuery, {
            immediate: true,
            fromCache: false,
            force: true
        })
    };
});

// ==========================================
// CSS STYLES FOR OPTIMIZED SEARCH
// ==========================================
const searchStyles = `
<style>
/* Loading State */
.search-loading-state {
    text-align: center;
    padding: 60px 20px;
    animation: fadeIn 0.3s ease-out;
}

.search-spinner {
    display: inline-flex;
    gap: 8px;
}

.spinner-circle {
    width: 12px;
    height: 12px;
    background: #007bff;
    border-radius: 50%;
    animation: bounce 1.4s ease-in-out infinite both;
}

.spinner-circle:nth-child(1) { animation-delay: -0.32s; }
.spinner-circle:nth-child(2) { animation-delay: -0.16s; }

@keyframes bounce {
    0%, 80%, 100% {
        transform: scale(0);
    }
    40% {
        transform: scale(1);
    }
}

.search-progress-bar {
    width: 200px;
    height: 4px;
    background: rgba(0,123,255,0.1);
    border-radius: 2px;
    margin: 20px auto 0;
    overflow: hidden;
}

.search-progress-fill {
    height: 100%;
    background: #007bff;
    width: 0;
    transition: width 0.5s ease-out;
}

/* Error State */
.search-error-state {
    text-align: center;
    padding: 60px 20px;
    animation: fadeIn 0.3s ease-out;
}

.error-icon {
    font-size: 48px;
    color: #ff6b6b;
    margin-bottom: 20px;
}

.retry-button {
    margin-top: 20px;
    padding: 10px 24px;
    background: #007bff;
    color: white;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    font-size: 16px;
    transition: transform 0.2s;
}

.retry-button:hover {
    transform: translateY(-2px);
}

/* Cache Indicator */
.cache-indicator {
    position: fixed;
    top: 20px;
    right: 20px;
    background: #28a745;
    color: white;
    padding: 10px 20px;
    border-radius: 30px;
    font-size: 14px;
    opacity: 0;
    transform: translateY(-20px);
    transition: all 0.3s ease-out;
    z-index: 1000;
}

.cache-indicator.show {
    opacity: 1;
    transform: translateY(0);
}

/* Quick Message */
.quick-message {
    position: fixed;
    bottom: 20px;
    left: 50%;
    transform: translateX(-50%) translateY(20px);
    background: rgba(0,0,0,0.8);
    color: white;
    padding: 12px 24px;
    border-radius: 30px;
    font-size: 14px;
    opacity: 0;
    transition: all 0.3s ease-out;
    z-index: 1000;
}

.quick-message.show {
    opacity: 1;
    transform: translateX(-50%) translateY(0);
}

/* Search Tags */
.search-tag {
    opacity: 0;
    transform: translateY(10px);
    transition: all 0.3s ease-out;
}

.search-tag.tag-visible {
    opacity: 1;
    transform: translateY(0);
}

/* Search Suggestions */
.search-suggestions {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: white;
    border: 1px solid #ddd;
    border-radius: 0 0 8px 8px;
    box-shadow: 0 4px 12px rgba(0,0,0,0.1);
    z-index: 100;
    opacity: 0;
    transform: translateY(-10px);
    transition: all 0.2s ease-out;
}

.search-suggestions.visible {
    opacity: 1;
    transform: translateY(0);
}

.suggestions-header {
    padding: 12px 16px;
    font-size: 12px;
    color: #666;
    border-bottom: 1px solid #eee;
}

.suggestion-item {
    padding: 12px 16px;
    cursor: pointer;
    transition: background 0.2s;
}

.suggestion-item:hover {
    background: #f8f9fa;
}

.clear-history {
    padding: 12px 16px;
    color: #dc3545;
    cursor: pointer;
    border-top: 1px solid #eee;
    font-size: 14px;
}

.clear-history:hover {
    background: #f8f9fa;
}

/* Fade Out Animation */
.result.fade-out {
    opacity: 0;
    transform: scale(0.95);
    transition: all 0.15s ease-out;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}
</style>
`;

// Inject styles
$('head').append(searchStyles);