// ============================================
// AniCineHub - Search Functionality
// ============================================

let searchTimeout;
const SEARCH_DELAY = 300; // ms

// Initialize search functionality
document.addEventListener('DOMContentLoaded', () => {
    initNavSearch();
    initPageSearch();
});

// Navbar Search
function initNavSearch() {
    const navSearchInput = document.getElementById('navSearchInput');
    const navSearchSuggestions = document.getElementById('navSearchSuggestions');

    if (!navSearchInput) return;

    navSearchInput.addEventListener('input', (e) => {
        const query = e.target.value.trim();

        clearTimeout(searchTimeout);

        if (query.length < 2) {
            navSearchSuggestions.innerHTML = '';
            navSearchSuggestions.style.display = 'none';
            return;
        }

        searchTimeout = setTimeout(() => {
            performSearch(query, navSearchSuggestions, true);
        }, SEARCH_DELAY);
    });

    // Handle Enter key
    navSearchInput.addEventListener('keydown', (e) => {
        if (e.key === 'Enter') {
            const query = e.target.value.trim();
            if (query.length >= 2) {
                window.location.href = `search.php?q=${encodeURIComponent(query)}`;
            }
        }
    });
}

// Page Search (on search.php)
function initPageSearch() {
    const pageSearchInput = document.getElementById('searchInput');
    const searchResults = document.getElementById('searchResults');

    if (!pageSearchInput) return;

    pageSearchInput.addEventListener('input', (e) => {
        const query = e.target.value.trim();

        clearTimeout(searchTimeout);

        if (query.length < 2) {
            searchResults.innerHTML = '<p class="text-center text-gray">Enter at least 2 characters to search</p>';
            return;
        }

        // Show loading skeleton
        showLoadingSkeleton(searchResults);

        searchTimeout = setTimeout(() => {
            performSearch(query, searchResults, false);
        }, SEARCH_DELAY);
    });
}

// Perform Search via API
async function performSearch(query, container, isSuggestion = false) {
    try {
        const response = await fetch(`api/search.php?q=${encodeURIComponent(query)}`);
        const data = await response.json();

        if (data.success && data.results) {
            if (isSuggestion) {
                displaySuggestions(data.results, container);
            } else {
                displaySearchResults(data.results, container);
            }
        } else {
            container.innerHTML = '<p class="text-center text-gray">No results found</p>';
        }
    } catch (error) {
        console.error('Search error:', error);
        container.innerHTML = '<p class="text-center text-gray">Error loading results</p>';
    }
}

// Display Suggestions (Autocomplete)
function displaySuggestions(results, container) {
    if (!results || results.length === 0) {
        container.innerHTML = '<p class="suggestion-item">No results found</p>';
        container.style.display = 'block';
        return;
    }

    const suggestions = results.slice(0, 5).map(item => {
        const title = item.title || item.name || 'Untitled';
        const year = item.release_date || item.first_air_date || '';
        const posterPath = item.poster_path
            ? `https://image.tmdb.org/t/p/w92${item.poster_path}`
            : 'assets/images/placeholder.jpg';

        return `
            <a href="details.php?id=${item.id}&type=${item.media_type || 'movie'}" class="suggestion-item">
                <img src="${posterPath}" alt="${title}" class="suggestion-image">
                <div class="suggestion-info">
                    <div class="suggestion-title">${truncateText(title, 40)}</div>
                    <div class="suggestion-meta">
                        ${year ? new Date(year).getFullYear() : ''} 
                        ${item.media_type ? `• ${capitalizeFirst(item.media_type)}` : ''}
                    </div>
                </div>
            </a>
        `;
    }).join('');

    container.innerHTML = suggestions;
    container.style.display = 'block';
}

// Display Full Search Results
function displaySearchResults(results, container) {
    if (!results || results.length === 0) {
        container.innerHTML = '<p class="text-center text-gray">No results found</p>';
        return;
    }

    const cards = results.map(item => createMediaCard(item)).join('');
    container.innerHTML = `<div class="grid grid-5">${cards}</div>`;

    // Reinitialize animations
    initScrollReveal();
}

// Create Media Card
function createMediaCard(item) {
    const title = item.title || item.name || 'Untitled';
    const year = item.release_date || item.first_air_date;
    const posterPath = item.poster_path
        ? `https://image.tmdb.org/t/p/w500${item.poster_path}`
        : 'assets/images/placeholder.jpg';
    const rating = item.vote_average ? item.vote_average.toFixed(1) : 'N/A';
    const type = item.media_type || 'movie';

    return `
        <div class="card card-entrance">
            <a href="details.php?id=${item.id}&type=${type}">
                <img src="${posterPath}" alt="${title}" class="card-image" loading="lazy">
            </a>
            <div class="card-content">
                <h3 class="card-title">${title}</h3>
                <div class="card-meta">
                    <span class="rating">
                        <i class="fas fa-star"></i> ${rating}
                    </span>
                    ${year ? `<span>${new Date(year).getFullYear()}</span>` : ''}
                </div>
            </div>
        </div>
    `;
}

// Show Loading Skeleton
function showLoadingSkeleton(container) {
    const skeletons = Array(10).fill(0).map(() => `
        <div class="card-skeleton">
            <div class="skeleton-image"></div>
            <div class="skeleton-text"></div>
            <div class="skeleton-text" style="width: 60%"></div>
        </div>
    `).join('');

    container.innerHTML = `<div class="grid grid-5">${skeletons}</div>`;
}

// Utility Functions
function capitalizeFirst(str) {
    return str.charAt(0).toUpperCase() + str.slice(1);
}

function truncateText(text, maxLength) {
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
}

// Close suggestions when clicking outside
document.addEventListener('click', (e) => {
    const navSearchSuggestions = document.getElementById('navSearchSuggestions');
    const navSearchInput = document.getElementById('navSearchInput');

    if (navSearchSuggestions && !e.target.closest('.search-wrapper')) {
        navSearchSuggestions.style.display = 'none';
    }
});
