<?php $__env->startSection('title', 'Search Results - SocialLink'); ?>

<?php $__env->startPush('styles'); ?>
<link rel="stylesheet" href="<?php echo e(asset('assets/css/search.css')); ?>">
<style>
.search-header {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 0.5rem;
    padding: 2rem;
    margin-bottom: 2rem;
}

.search-empty-state {
    text-align: center;
    padding: 4rem 2rem;
}

.search-empty-state i {
    font-size: 4rem;
    color: #6c757d;
    margin-bottom: 1rem;
}

.btn-search-filter {
    border-radius: 20px;
    margin: 0.25rem;
    transition: all 0.3s ease;
}

.btn-search-filter:hover {
    transform: translateY(-2px);
}

.search-result-card {
    border: none;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    margin-bottom: 1.5rem;
    border-radius: 15px;
    transition: all 0.3s ease;
}

.search-result-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 20px rgba(0,0,0,0.15);
}

.user-avatar {
    width: 60px;
    height: 60px;
    border-radius: 50%;
    object-fit: cover;
    border: 3px solid #fff;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.search-stats-badge {
    background: rgba(255,255,255,0.2);
    color: white;
    border-radius: 20px;
    padding: 0.5rem 1rem;
    font-size: 0.9rem;
    margin: 0.25rem;
}

.filter-card {
    background: #f8f9fa;
    border-radius: 15px;
    padding: 1.5rem;
    border: none;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}

.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255,255,255,0.9);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 9999;
    backdrop-filter: blur(5px);
}

.spinner {
    width: 50px;
    height: 50px;
    border: 5px solid #f3f3f3;
    border-top: 5px solid #667eea;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
</style>
<?php $__env->stopPush(); ?>

<?php
    // Disable sidebars for search page
    $showLeftSidebar = false;
    $showRightSidebar = false;
?>

<?php $__env->startSection('content'); ?>
<!-- Loading Overlay -->
<div id="loadingOverlay" class="loading-overlay" style="display: none;">
    <div class="text-center">
        <div class="spinner"></div>
        <p class="mt-3">Searching...</p>
    </div>
</div>

<!-- Search Header -->
<div class="search-header">
    <div class="row align-items-center">
        <div class="col-md-8">
            <h2 class="mb-2">Search Results</h2>
            <p class="mb-0" id="searchSummary">
                <span id="queryText">Enter a search term to get started</span>
            </p>
        </div>
        <div class="col-md-4 text-end">
            <div class="d-flex flex-wrap justify-content-end">
                <span class="search-stats-badge" id="totalResults">0 Results</span>
                <span class="search-stats-badge" id="searchTime">0ms</span>
            </div>
        </div>
    </div>
</div>

<div class="row">
    <!-- Filters Sidebar -->
    <div class="col-lg-3 mb-4">
        <div class="filter-card">
            <h5 class="mb-3">
                <i class="bi bi-funnel me-2"></i>Filters
            </h5>
            
            <!-- Search Type -->
            <div class="mb-4">
                <h6 class="text-muted mb-2">Search In</h6>
                <div class="btn-group-vertical w-100" role="group">
                    <input type="radio" class="btn-check" name="searchType" id="typeAll" value="all" checked>
                    <label class="btn btn-outline-primary btn-sm" for="typeAll">
                        <i class="bi bi-search me-2"></i>All Results
                    </label>
                    <input type="radio" class="btn-check" name="searchType" id="typeUsers" value="users">
                    <label class="btn btn-outline-primary btn-sm" for="typeUsers">
                        <i class="bi bi-people me-2"></i>People
                    </label>
                    <input type="radio" class="btn-check" name="searchType" id="typePosts" value="posts">
                    <label class="btn btn-outline-primary btn-sm" for="typePosts">
                        <i class="bi bi-file-post me-2"></i>Posts
                    </label>
                    <input type="radio" class="btn-check" name="searchType" id="typeGroups" value="groups">
                    <label class="btn btn-outline-primary btn-sm" for="typeGroups">
                        <i class="bi bi-people-fill me-2"></i>Groups
                    </label>
                </div>
            </div>

            <!-- Sort Options -->
            <div class="mb-4">
                <h6 class="text-muted mb-2">Sort By</h6>
                <select class="form-select" id="sortBy">
                    <option value="relevance">Most Relevant</option>
                    <option value="date">Most Recent</option>
                    <option value="popularity">Most Popular</option>
                    <option value="alphabetical">A to Z</option>
                </select>
            </div>

            <!-- Additional Filters -->
            <div class="mb-4">
                <h6 class="text-muted mb-2">Additional Filters</h6>
                <div class="form-check mb-2">
                    <input class="form-check-input" type="checkbox" id="verifiedOnly">
                    <label class="form-check-label" for="verifiedOnly">
                        Verified users only
                    </label>
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="friendsOnly">
                    <label class="form-check-label" for="friendsOnly">
                        Friends only
                    </label>
                </div>
            </div>

            <!-- Action Buttons -->
            <button class="btn btn-primary w-100 mb-2" onclick="applyFilters()">
                <i class="bi bi-check-circle me-2"></i>Apply Filters
            </button>
            <button class="btn btn-outline-secondary w-100" onclick="clearFilters()">
                <i class="bi bi-x-circle me-2"></i>Clear All
            </button>
        </div>
    </div>

    <!-- Results Content -->
    <div class="col-lg-9">
        <!-- Search Input for This Page -->
        <div class="card search-result-card mb-4">
            <div class="card-body">
                <form onsubmit="performNewSearch(event)" class="d-flex gap-2">
                    <input type="text" id="newSearchInput" class="form-control" placeholder="Search people, posts, groups..." value="">
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-search"></i>
                    </button>
                </form>
            </div>
        </div>

        <!-- No Search Query State -->
        <div id="noSearchState" class="search-empty-state">
            <i class="bi bi-search"></i>
            <h4>Start Your Search</h4>
            <p class="text-muted">Enter a search term above to find people, posts, and groups.</p>
        </div>

        <!-- No Results State -->
        <div id="noResultsState" class="search-empty-state" style="display: none;">
            <i class="bi bi-search"></i>
            <h4>No Results Found</h4>
            <p class="text-muted">Try different keywords or clear your filters.</p>
            <button class="btn btn-outline-primary" onclick="clearFilters()">Clear Filters</button>
        </div>

        <!-- Search Results -->
        <div id="searchResults" style="display: none;">
            <!-- Users Section -->
            <div id="usersSection" class="mb-4">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5><i class="bi bi-people me-2 text-primary"></i>People</h5>
                    <button class="btn btn-outline-primary btn-sm" onclick="showMore('users')">
                        See All <span id="usersCount">0</span>
                    </button>
                </div>
                <div id="usersList"></div>
            </div>

            <!-- Posts Section -->
            <div id="postsSection" class="mb-4">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5><i class="bi bi-file-post me-2 text-success"></i>Posts</h5>
                    <button class="btn btn-outline-success btn-sm" onclick="showMore('posts')">
                        See All <span id="postsCount">0</span>
                    </button>
                </div>
                <div id="postsList"></div>
            </div>

            <!-- Groups Section -->
            <div id="groupsSection" class="mb-4">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <h5><i class="bi bi-people-fill me-2 text-info"></i>Groups</h5>
                    <button class="btn btn-outline-info btn-sm" onclick="showMore('groups')">
                        See All <span id="groupsCount">0</span>
                    </button>
                </div>
                <div id="groupsList"></div>
            </div>

            <!-- Pagination -->
            <div id="paginationContainer" class="d-flex justify-content-center mt-4"></div>
        </div>
    </div>
</div>

<?php $__env->startPush('scripts'); ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
    console.log('Search page loaded');
    
    // Get URL parameters
    const urlParams = new URLSearchParams(window.location.search);
    const searchQuery = urlParams.get('query') || '';
    const searchType = urlParams.get('type') || 'all';
    
    console.log('Search query:', searchQuery);
    console.log('Search type:', searchType);
    
    // Update search input
    const newSearchInput = document.getElementById('newSearchInput');
    if (newSearchInput) {
        newSearchInput.value = searchQuery;
    }
    
    // Set search type filter
    const typeRadio = document.querySelector(`input[name="searchType"][value="${searchType}"]`);
    if (typeRadio) {
        typeRadio.checked = true;
    }
    
    // Perform initial search if query exists
    if (searchQuery && searchQuery.trim() !== '') {
        performSearch(searchQuery, searchType);
    } else {
        showNoSearchState();
    }
    
    // Setup filter listeners
    setupFilterListeners();
});

let currentQuery = '';
let currentType = 'all';
let currentPage = 1;
let searchResults = {};

function setupFilterListeners() {
    // Search type radio buttons
    document.querySelectorAll('input[name="searchType"]').forEach(radio => {
        radio.addEventListener('change', function() {
            if (this.checked && currentQuery) {
                currentType = this.value;
                currentPage = 1;
                performSearch(currentQuery, currentType);
            }
        });
    });
    
    // Sort dropdown
    document.getElementById('sortBy').addEventListener('change', function() {
        if (currentQuery) {
            currentPage = 1;
            performSearch(currentQuery, currentType);
        }
    });
}

function performNewSearch(event) {
    event.preventDefault();
    const query = document.getElementById('newSearchInput').value.trim();
    if (query) {
        // Update URL
        const newUrl = new URL(window.location);
        newUrl.searchParams.set('query', query);
        newUrl.searchParams.set('type', currentType);
        window.history.pushState({}, '', newUrl);
        
        // Perform search
        performSearch(query, currentType);
    }
}

async function performSearch(query, type = 'all') {
    currentQuery = query;
    currentType = type;
    
    console.log('Performing search for:', query, 'type:', type);
    
    // Update UI
    updateSearchHeader(query);
    showLoading();
    hideStates();
    
    try {
        const params = new URLSearchParams({
            query: query,
            type: type,
            limit: 20,
            offset: (currentPage - 1) * 20,
            sort_by: document.getElementById('sortBy').value,
        });
        
        // Add filters
        if (document.getElementById('verifiedOnly').checked) {
            params.append('filters[verified_only]', '1');
        }
        if (document.getElementById('friendsOnly').checked) {
            params.append('filters[friends_only]', '1');
        }
        
        const response = await fetch(`/api/search?${params.toString()}`, {
            headers: {
                'Accept': 'application/json',
                'X-Requested-With': 'XMLHttpRequest',
                'Authorization': `Bearer <?php echo e(Auth::user()?->createToken("search")->plainTextToken ?? ""); ?>`,
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
            }
        });
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        const data = await response.json();
        console.log('Search response:', data);
        
        hideLoading();
        
        if (data.status === 200 && data.data) {
            searchResults = data.data;
            displayResults(data.data);
        } else {
            showNoResults();
        }
        
    } catch (error) {
        console.error('Search error:', error);
        hideLoading();
        showError('An error occurred while searching. Please try again.');
    }
}

function displayResults(data) {
    const totalResults = (data.meta?.total_results || 0);
    
    if (totalResults === 0) {
        showNoResults();
        return;
    }
    
    // Update counts
    document.getElementById('usersCount').textContent = data.meta?.total_users || 0;
    document.getElementById('postsCount').textContent = data.meta?.total_posts || 0;
    document.getElementById('groupsCount').textContent = data.meta?.total_groups || 0;
    document.getElementById('totalResults').textContent = `${totalResults} Results`;
    
    // Display results by type
    displayUsers(data.results?.users || []);
    displayPosts(data.results?.posts || []);
    displayGroups(data.results?.groups || []);
    
    // Show results container
    document.getElementById('searchResults').style.display = 'block';
}

function displayUsers(users) {
    const container = document.getElementById('usersList');
    const section = document.getElementById('usersSection');
    
    if (!users || users.length === 0) {
        section.style.display = 'none';
        return;
    }
    
    section.style.display = 'block';
    container.innerHTML = '';
    
    users.slice(0, currentType === 'users' ? users.length : 3).forEach(user => {
        const userCard = document.createElement('div');
        userCard.className = 'card search-result-card';
        userCard.innerHTML = `
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-auto">
                        <img src="${user.avatar || '/assets/images/avatar/default.jpg'}" 
                             class="user-avatar" alt="${user.first_name} ${user.last_name}">
                    </div>
                    <div class="col">
                        <h6 class="mb-1">${user.first_name} ${user.last_name}</h6>
                        <p class="text-muted mb-1">@${user.username}</p>
                        ${user.bio ? `<p class="small mb-0">${user.bio.substring(0, 100)}...</p>` : ''}
                    </div>
                    <div class="col-auto">
                        <a href="/profile/${user.username}" class="btn btn-primary btn-sm">View Profile</a>
                    </div>
                </div>
            </div>
        `;
        container.appendChild(userCard);
    });
}

function displayPosts(posts) {
    const container = document.getElementById('postsList');
    const section = document.getElementById('postsSection');
    
    if (!posts || posts.length === 0) {
        section.style.display = 'none';
        return;
    }
    
    section.style.display = 'block';
    container.innerHTML = '';
    
    posts.slice(0, currentType === 'posts' ? posts.length : 3).forEach(post => {
        const postCard = document.createElement('div');
        postCard.className = 'card search-result-card';
        postCard.innerHTML = `
            <div class="card-body">
                <div class="d-flex align-items-center mb-3">
                    <img src="${post.user?.avatar || '/assets/images/avatar/default.jpg'}" 
                         class="rounded-circle me-3" style="width: 40px; height: 40px;">
                    <div>
                        <h6 class="mb-0">${post.user?.first_name || ''} ${post.user?.last_name || ''}</h6>
                        <small class="text-muted">@${post.user?.username || ''} • ${formatDate(post.created_at)}</small>
                    </div>
                </div>
                <p class="mb-3">${post.post_text}</p>
                <div class="d-flex justify-content-between align-items-center">
                    <div class="d-flex gap-3">
                        <span class="text-muted"><i class="bi bi-heart"></i> ${post.likes_count || 0}</span>
                        <span class="text-muted"><i class="bi bi-chat"></i> ${post.comments_count || 0}</span>
                        <span class="text-muted"><i class="bi bi-share"></i> ${post.shares_count || 0}</span>
                    </div>
                    <a href="/post/${post.id}" class="btn btn-outline-primary btn-sm">View Post</a>
                </div>
            </div>
        `;
        container.appendChild(postCard);
    });
}

function displayGroups(groups) {
    const container = document.getElementById('groupsList');
    const section = document.getElementById('groupsSection');
    
    if (!groups || groups.length === 0) {
        section.style.display = 'none';
        return;
    }
    
    section.style.display = 'block';
    container.innerHTML = '';
    
    groups.slice(0, currentType === 'groups' ? groups.length : 3).forEach(group => {
        const groupCard = document.createElement('div');
        groupCard.className = 'card search-result-card';
        groupCard.innerHTML = `
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col-auto">
                        <img src="${group.cover_image || '/assets/images/group/default.jpg'}" 
                             class="rounded" style="width: 60px; height: 60px; object-fit: cover;">
                    </div>
                    <div class="col">
                        <h6 class="mb-1">${group.name}</h6>
                        <p class="text-muted mb-1">${group.members_count || 0} members • ${group.privacy}</p>
                        ${group.description ? `<p class="small mb-0">${group.description.substring(0, 100)}...</p>` : ''}
                    </div>
                    <div class="col-auto">
                        <a href="/group/${group.id}" class="btn btn-primary btn-sm">View Group</a>
                    </div>
                </div>
            </div>
        `;
        container.appendChild(groupCard);
    });
}

function showMore(type) {
    currentType = type;
    currentPage = 1;
    
    // Update radio button
    const radio = document.querySelector(`input[name="searchType"][value="${type}"]`);
    if (radio) radio.checked = true;
    
    performSearch(currentQuery, type);
}

function applyFilters() {
    if (currentQuery) {
        currentPage = 1;
        performSearch(currentQuery, currentType);
    }
}

function clearFilters() {
    // Reset form elements
    document.getElementById('sortBy').value = 'relevance';
    document.getElementById('verifiedOnly').checked = false;
    document.getElementById('friendsOnly').checked = false;
    document.querySelector('input[name="searchType"][value="all"]').checked = true;
    
    currentType = 'all';
    
    if (currentQuery) {
        currentPage = 1;
        performSearch(currentQuery, currentType);
    }
}

function updateSearchHeader(query) {
    document.getElementById('queryText').textContent = `Results for "${query}"`;
}

function showLoading() {
    document.getElementById('loadingOverlay').style.display = 'flex';
}

function hideLoading() {
    document.getElementById('loadingOverlay').style.display = 'none';
}

function hideStates() {
    document.getElementById('noSearchState').style.display = 'none';
    document.getElementById('noResultsState').style.display = 'none';
    document.getElementById('searchResults').style.display = 'none';
}

function showNoSearchState() {
    hideLoading();
    hideStates();
    document.getElementById('noSearchState').style.display = 'block';
    document.getElementById('queryText').textContent = 'Enter a search term to get started';
}

function showNoResults() {
    hideLoading();
    hideStates();
    document.getElementById('noResultsState').style.display = 'block';
}

function showError(message) {
    hideLoading();
    alert(message); // You can replace with a better error display
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString();
}
</script>
<?php $__env->stopPush(); ?>
<?php $__env->stopSection(); ?> 
<?php echo $__env->make('front_end.layouts.home', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH /Applications/MAMP/htdocs/socialink_backend/resources/views/front_end/search.blade.php ENDPATH**/ ?>