<?php
if (!function_exists('avatar_url')) {
    function avatar_url($v){
        $v = (string)$v;
        $v = str_replace('\\','/',$v);
        if (preg_match('~^https?://~i',$v)) return $v;
        $file = basename($v);
        if ($file === '' || $file === '.' || $file === '..') return asset_url('uploads/avatars/default.png');
        $file = preg_replace('~[^A-Za-z0-9._-]~','',$file);
        return asset_url('uploads/avatars/'.$file);
    }
}
?>
<h2>Buscar amigos</h2>

<div class="search-container">
    <div class="search-card">
        <div class="search-header">
            <h3>Encuentra nuevos amigos</h3>
            <p>Busca por nombre, apellido o nickname</p>
        </div>
        
        <form method="get" action="<?php echo htmlspecialchars(base_url('/friends/search')); ?>" class="search-form" id="search-form">
            <div class="search-input-container">
                <div class="search-icon">🔍</div>
                <input type="text" 
                       name="q" 
                       id="search-input"
                       value="<?php echo htmlspecialchars($q); ?>" 
                       placeholder="Ej: maria, juan, pepe..."
                       autocomplete="off"
                       class="search-input">
                <button type="submit" class="btn btn-primary">Buscar</button>
            </div>
            <div id="search-suggestions" class="suggestions-container" style="display: none;"></div>
        </form>
    </div>

    <?php if($q !== ''): ?>
    <section class="results-section">
        <div class="results-header">
            <h3>Resultados para "<?php echo htmlspecialchars($q); ?>"</h3>
            <span class="results-count"><?php echo count($results); ?> resultado<?php echo count($results) !== 1 ? 's' : ''; ?></span>
        </div>
        
        <?php if(empty($results)): ?>
            <div class="no-results">
                <div class="no-results-icon">😕</div>
                <h4>No se encontraron resultados</h4>
                <p>Intenta con otros términos de búsqueda</p>
            </div>
        <?php else: ?>
            <div class="results-grid">
                <?php foreach($results as $r): ?>
                <div class="result-card">
                    <div class="result-avatar">
                        <a href="<?php echo htmlspecialchars(base_url('/profile?nick='.$r['nick'])); ?>">
                            <?php if(!empty($r['avatar'])): ?>
                                <img src="<?php echo htmlspecialchars(base_url('/uploads/avatars/'.$r['avatar'])); ?>" alt="<?php echo htmlspecialchars($r['first_name']); ?>">
                            <?php else: ?>
                                <div class="avatar-placeholder"><?php echo strtoupper(substr($r['first_name'], 0, 1) . substr($r['last_name'], 0, 1)); ?></div>
                            <?php endif; ?>
                        </a>
                    </div>
                    
                    <div class="result-info">
                        <a href="<?php echo htmlspecialchars(base_url('/profile?nick='.$r['nick'])); ?>" class="result-link">
                            <h4 class="result-name"><?php echo htmlspecialchars($r['first_name'].' '.$r['last_name']); ?></h4>
                            <p class="result-nick">@<?php echo htmlspecialchars($r['nick']); ?></p>
                        </a>
                    </div>
                    
                    <div class="result-action">
                        <?php if($r['state'] === 'friend'): ?>
                            <span class="status-badge status-friend">
                                <span class="status-icon">✓</span>
                                Amigos
                            </span>
                        <?php elseif($r['state'] === 'incoming'): ?>
                            <span class="status-badge status-incoming">
                                <span class="status-icon">📩</span>
                                Solicitud recibida
                            </span>
                        <?php elseif($r['state'] === 'outgoing'): ?>
                            <span class="status-badge status-outgoing">
                                <span class="status-icon">⏳</span>
                                Solicitud enviada
                            </span>
                        <?php else: ?>
                            <form method="post" action="<?php echo htmlspecialchars(base_url('/friends/request')); ?>" class="inline-form">
                                <input type="hidden" name="_csrf" value="<?php echo htmlspecialchars(csrf_token()); ?>">
                                <input type="hidden" name="user_id" value="<?php echo (int)$r['id']; ?>">
                                <button type="submit" class="btn btn-primary btn-sm">
                                    <span class="btn-icon">👋</span>
                                    Agregar
                                </button>
                            </form>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>
    </section>
    <?php endif; ?>
</div>

<style>
.search-container {
    max-width: 800px;
    margin: 0 auto;
}

.search-card {
    background: #1a1d23;
    border: 1px solid #2b3138;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    margin-bottom: 1.5rem;
}

.search-header {
    text-align: center;
    margin-bottom: 1.5rem;
}

.search-header h3 {
    margin: 0 0 0.5rem 0;
    color: #f8fafc;
    font-size: 1.5rem;
    font-weight: 600;
}

.search-header p {
    margin: 0;
    color: #94a3b8;
    font-size: 1rem;
}

.search-input-container {
    position: relative;
    display: flex;
    align-items: center;
    background: #2b3138;
    border: 2px solid #3f4752;
    border-radius: 8px;
    padding: 0.5rem;
    transition: all 0.3s ease;
}

.search-input-container:focus-within {
    border-color: #6366f1;
    background: #374151;
    box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.search-icon {
    padding: 0 1rem;
    font-size: 1.1rem;
    color: #94a3b8;
}

.search-input {
    flex: 1;
    border: none;
    background: none;
    padding: 0.75rem 0;
    font-size: 1rem;
    color: #f8fafc;
    outline: none;
}

.search-input::placeholder {
    color: #64748b;
}

/* BOTONES CONSISTENTES CON EL RESTO DE LA APLICACIÓN */
.btn {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 12px 20px;
    border-radius: 8px;
    font-weight: 500;
    text-decoration: none;
    border: none;
    cursor: pointer;
    transition: all 0.2s ease;
    font-size: 0.9rem;
    min-width: 120px;
    justify-content: center;
}

.btn-primary {
    background: #6366f1;
    color: white;
}

.btn-primary:hover:not(:disabled) {
    background: #4f46e5;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
}

.btn-sm {
    padding: 8px 16px;
    font-size: 0.8rem;
    min-width: auto;
}

.btn-icon {
    font-size: 1rem;
}

.suggestions-container {
    position: absolute;
    top: 100%;
    left: 0;
    right: 0;
    background: #1a1d23;
    border: 1px solid #2b3138;
    border-radius: 8px;
    box-shadow: 0 10px 25px -8px rgba(0, 0, 0, 0.3);
    z-index: 1000;
    max-height: 300px;
    overflow-y: auto;
    margin-top: 0.5rem;
}

.suggestion-item {
    padding: 1rem;
    cursor: pointer;
    border-bottom: 1px solid #2b3138;
    display: flex;
    align-items: center;
    gap: 1rem;
    transition: background-color 0.2s ease;
}

.suggestion-item:hover {
    background-color: #2b3138;
}

.suggestion-item:last-child {
    border-bottom: none;
}

.suggestion-avatar {
    flex-shrink: 0;
}

.suggestion-avatar img {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #3f4752;
}

.suggestion-info {
    flex: 1;
    min-width: 0;
}

.suggestion-name {
    font-weight: 600;
    color: #f8fafc;
    margin: 0 0 0.25rem 0;
    font-size: 0.9rem;
}

.suggestion-nick {
    color: #94a3b8;
    font-size: 0.8rem;
    margin: 0;
}

.suggestion-action {
    flex-shrink: 0;
}

.results-section {
    background: #1a1d23;
    border: 1px solid #2b3138;
    border-radius: 12px;
    padding: 24px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.results-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1.5rem;
    padding-bottom: 1rem;
    border-bottom: 1px solid #2b3138;
}

.results-header h3 {
    margin: 0;
    color: #f8fafc;
    font-size: 1.25rem;
    font-weight: 600;
}

.results-count {
    background: #6366f1;
    color: white;
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
}

.results-grid {
    display: grid;
    gap: 1rem;
}

.result-card {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem;
    background: #2b3138;
    border: 1px solid #3f4752;
    border-radius: 8px;
    transition: all 0.3s ease;
}

.result-card:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 25px -8px rgba(0, 0, 0, 0.4);
    border-color: #6366f1;
}

.result-avatar img {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    object-fit: cover;
    border: 2px solid #3f4752;
}

.avatar-placeholder {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background: linear-gradient(135deg, #1f2937 0%, #374151 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-weight: bold;
    font-size: 1rem;
    border: 2px solid #3f4752;
}

.result-info {
    flex: 1;
}

.result-link {
    text-decoration: none;
    color: inherit;
}

.result-link:hover .result-name {
    color: #6366f1;
}

.result-name {
    margin: 0 0 0.25rem 0;
    font-size: 1rem;
    font-weight: 600;
    color: #f8fafc;
    transition: color 0.2s ease;
}

.result-nick {
    margin: 0;
    color: #94a3b8;
    font-size: 0.85rem;
}

.result-action {
    flex-shrink: 0;
}

.status-badge {
    display: inline-flex;
    align-items: center;
    gap: 0.5rem;
    padding: 0.5rem 1rem;
    border-radius: 20px;
    font-weight: 600;
    font-size: 0.8rem;
}

.status-friend {
    background: #065f46;
    color: #d1fae5;
}

.status-incoming {
    background: #92400e;
    color: #fef3c7;
}

.status-outgoing {
    background: #1e40af;
    color: #dbeafe;
}

.status-icon {
    font-size: 0.9rem;
}

.no-results {
    text-align: center;
    padding: 2rem 1rem;
    color: #94a3b8;
}

.no-results-icon {
    font-size: 3rem;
    margin-bottom: 1rem;
    opacity: 0.5;
}

.no-results h4 {
    margin: 0 0 0.5rem 0;
    font-size: 1.25rem;
    color: #f8fafc;
}

.no-results p {
    margin: 0;
    font-size: 1rem;
}

@media (max-width: 768px) {
    .search-card, .results-section {
        padding: 20px;
        border-radius: 10px;
    }
    
    .search-input-container {
        flex-direction: column;
        gap: 0.75rem;
    }
    
    .search-input {
        width: 100%;
        text-align: center;
    }
    
    .btn {
        width: 100%;
    }
    
    .results-header {
        flex-direction: column;
        gap: 0.75rem;
        text-align: center;
    }
    
    .result-card {
        flex-direction: column;
        text-align: center;
        gap: 0.75rem;
    }
    
    .result-info {
        text-align: center;
    }
}

@media (max-width: 480px) {
    .search-card, .results-section {
        padding: 16px;
    }
}
</style>

<script>
// El mismo JavaScript que antes, no cambia
document.addEventListener('DOMContentLoaded', function() {
    const searchInput = document.getElementById('search-input');
    const suggestionsContainer = document.getElementById('search-suggestions');
    let debounceTimer;

    searchInput.addEventListener('input', function(e) {
        clearTimeout(debounceTimer);
        const query = e.target.value.trim();
        
        if (query.length < 2) {
            suggestionsContainer.style.display = 'none';
            return;
        }

        debounceTimer = setTimeout(() => {
            fetchSuggestions(query);
        }, 300);
    });

    searchInput.addEventListener('blur', function() {
        setTimeout(() => {
            suggestionsContainer.style.display = 'none';
        }, 200);
    });

    searchInput.addEventListener('focus', function() {
        const query = this.value.trim();
        if (query.length >= 2 && suggestionsContainer.innerHTML !== '') {
            suggestionsContainer.style.display = 'block';
        }
    });

    function fetchSuggestions(query) {
        fetch(`<?php echo base_url('/friends/search-suggestions'); ?>?q=${encodeURIComponent(query)}`)
            .then(response => response.json())
            .then(data => {
                displaySuggestions(data);
            })
            .catch(error => {
                console.error('Error fetching suggestions:', error);
            });
    }

    function displaySuggestions(users) {
        if (users.length === 0) {
            suggestionsContainer.style.display = 'none';
            return;
        }

        suggestionsContainer.innerHTML = '';
        users.forEach(user => {
            const item = document.createElement('div');
            item.className = 'suggestion-item';
            
            const avatarHtml = user.avatar ? 
                `<img src="<?php echo base_url('/uploads/avatars/'); ?>${escapeHtml(user.avatar)}" alt="${escapeHtml(user.first_name)}">` :
                `<div class="avatar-placeholder" style="width: 40px; height: 40px; font-size: 0.9rem;">${escapeHtml(user.first_name.charAt(0) + user.last_name.charAt(0))}</div>`;
            
            item.innerHTML = `
                <div class="suggestion-avatar">
                    ${avatarHtml}
                </div>
                <div class="suggestion-info">
                    <div class="suggestion-name">${escapeHtml(user.first_name + ' ' + user.last_name)}</div>
                    <div class="suggestion-nick">@${escapeHtml(user.nick)}</div>
                </div>
                <div class="suggestion-action">
                    ${getSuggestionAction(user)}
                </div>
            `;
            
            item.addEventListener('click', function() {
                searchInput.value = user.nick;
                suggestionsContainer.style.display = 'none';
                document.getElementById('search-form').submit();
            });
            
            suggestionsContainer.appendChild(item);
        });
        
        suggestionsContainer.style.display = 'block';
    }

    function getSuggestionAction(user) {
        switch(user.state) {
            case 'friend':
                return '<span class="status-badge status-friend" style="padding: 0.4rem 0.8rem; font-size: 0.75rem;">Amigo</span>';
            case 'incoming':
                return '<span class="status-badge status-incoming" style="padding: 0.4rem 0.8rem; font-size: 0.75rem;">Recibida</span>';
            case 'outgoing':
                return '<span class="status-badge status-outgoing" style="padding: 0.4rem 0.8rem; font-size: 0.75rem;">Enviada</span>';
            default:
                return `<form method="post" action="<?php echo base_url('/friends/request'); ?>" class="inline-form" onclick="event.stopPropagation();">
                    <input type="hidden" name="_csrf" value="<?php echo csrf_token(); ?>">
                    <input type="hidden" name="user_id" value="${user.id}">
                    <button type="submit" class="btn btn-primary btn-sm" style="padding: 0.4rem 0.8rem; font-size: 0.75rem;">
                        <span class="btn-icon">👋</span>
                        Agregar
                    </button>
                </form>`;
        }
    }

    function escapeHtml(unsafe) {
        return unsafe
            .replace(/&/g, "&amp;")
            .replace(/</g, "&lt;")
            .replace(/>/g, "&gt;")
            .replace(/"/g, "&quot;")
            .replace(/'/g, "&#039;");
    }
});
</script>