
<header>
<!-- Topbar -->
    <nav class="navbar navbar-expand navbar-light bg-white topbar mb-4 static-top shadow">

        <!-- Sidebar Toggle (Topbar) -->
        <button id="sidebarToggleTop" class="btn btn-link d-md-none rounded-circle mr-3">
            <i class="fa fa-bars"></i>
        </button>

        @can(['comunidad','amigos'])
        <!-- Topbar Search -->
        <div class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search position-relative">
            <div class="input-group">
                <input type="text" id="global-search" class="form-control bg-light border-0 small"
                       placeholder="Buscar personas..." autocomplete="off" style="min-width:220px">
                <div class="input-group-append">
                    <span class="btn btn-primary"><i class="fas fa-search fa-sm"></i></span>
                </div>
            </div>
            <div id="search-results" class="bg-white position-absolute d-none"
                 style="top:calc(100% + 6px); left:0; right:0; z-index:9999;
                        max-height:340px; overflow-y:auto;
                        border:1px solid rgba(0,0,0,.1); border-radius:8px;
                        box-shadow:0 8px 24px rgba(0,0,0,.12);
                        min-width:300px"></div>
        </div>

        @endcan
        <ul class="navbar-nav ml-auto">


            @can(['comunidad','amigos'])
            <!-- Nav Item - Search (XS) -->
            <li class="nav-item no-arrow d-sm-none position-relative">
                <a class="nav-link" href="#" id="mobile-search-toggle" role="button">
                    <i class="fas fa-search fa-fw"></i>
                </a>
                <div id="mobile-search-panel" class="d-none"
                     style="position:fixed; top:56px; left:0; right:0; z-index:9998;
                            background:#fff; padding:.75rem 1rem; box-shadow:0 4px 12px rgba(0,0,0,.15)">
                    <div class="input-group">
                        <input type="text" id="global-search-mobile"
                               class="form-control bg-light border-0"
                               placeholder="Buscar personas..." autocomplete="off">
                        <div class="input-group-append">
                            <span class="btn btn-primary"><i class="fas fa-search fa-sm"></i></span>
                        </div>
                    </div>
                    <div id="search-results-mobile" class="bg-white mt-1 d-none"
                         style="border:1px solid rgba(0,0,0,.1); border-radius:8px;
                                box-shadow:0 4px 16px rgba(0,0,0,.1);
                                max-height:280px; overflow-y:auto"></div>
                </div>
            </li>
            @endcan

            @can(['comunidad','amigos'])
            <!-- Nav Item - Notificaciones -->
            <li class="nav-item dropdown no-arrow mx-1">
                <a class="nav-link dropdown-toggle" href="#" id="alertsDropdown" role="button"
                    data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    <i class="fas fa-bell fa-fw"></i>
                    @if($headerUnreadNotificationsCount > 0)
                        <span class="badge badge-danger badge-counter" id="notif-badge">
                            {{ $headerUnreadNotificationsCount > 9 ? '9+' : $headerUnreadNotificationsCount }}
                        </span>
                    @else
                        <span class="badge badge-danger badge-counter d-none" id="notif-badge">0</span>
                    @endif
                </a>
                <div class="dropdown-list dropdown-menu dropdown-menu-right shadow animated--grow-in"
                    aria-labelledby="alertsDropdown">
                    <h6 class="dropdown-header">Notificaciones</h6>

                    @forelse($headerUnreadNotifications as $notif)
                        @php $data = $notif->data; @endphp
                        <a class="dropdown-item d-flex align-items-center"
                           href="{{ $data['url'] ?? '#' }}"
                           onclick="markNotifRead('{{ $notif->id }}')">
                            <div class="mr-3">
                                <div class="icon-circle bg-{{ $data['color'] ?? 'primary' }}">
                                    <i class="fas {{ $data['icon'] ?? 'fa-bell' }} text-white"></i>
                                </div>
                            </div>
                            <div>
                                <div class="small text-gray-500">{{ $notif->created_at->diffForHumans() }}</div>
                                <span class="font-weight-bold">{{ $data['title'] ?? '' }}</span>
                                @if(!empty($data['body']))
                                    <div class="small text-truncate" style="max-width:200px">{{ $data['body'] }}</div>
                                @endif
                            </div>
                        </a>
                    @empty
                        <div class="dropdown-item text-center text-muted py-3">
                            <i class="fas fa-check-circle text-success mr-1"></i> Sin notificaciones nuevas
                        </div>
                    @endforelse

                    <a class="dropdown-item text-center small text-gray-500"
                       href="#" onclick="markAllNotifsRead(); return false;">
                        Marcar todas como leídas
                    </a>
                </div>
            </li>

            @endcan

            @can('mensajes')
            <!-- Nav Item - Mensajes -->
            <li class="nav-item dropdown no-arrow mx-1">
                <a class="nav-link dropdown-toggle" href="{{ route('chat.index') }}" id="messagesDropdown"
                    role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    <i class="fas fa-envelope fa-fw"></i>
                    @if($headerUnreadMessagesCount > 0)
                        <span class="badge badge-danger badge-counter" id="msg-badge">
                            {{ $headerUnreadMessagesCount > 9 ? '9+' : $headerUnreadMessagesCount }}
                        </span>
                    @else
                        <span class="badge badge-danger badge-counter d-none" id="msg-badge">0</span>
                    @endif
                </a>
                <div class="dropdown-list dropdown-menu dropdown-menu-right shadow animated--grow-in"
                    aria-labelledby="messagesDropdown">
                    <h6 class="dropdown-header">Mensajes</h6>

                    @forelse($headerUnreadConversations as $msg)
                        <a class="dropdown-item d-flex align-items-center"
                           href="{{ route('chat.show', $msg->sender) }}"
                           data-sender-id="{{ $msg->sender->id }}">
                            <div class="dropdown-list-image mr-3">
                                <img class="rounded-circle" width="40" height="40"
                                     style="object-fit:cover"
                                     src="{{ $msg->sender->profile_photo_url }}" alt="">
                                <div class="status-indicator bg-success"></div>
                            </div>
                            <div class="font-weight-bold overflow-hidden">
                                <div class="text-truncate">{{ $msg->body ?? '📎 Archivo adjunto' }}</div>
                                <div class="small text-gray-500">
                                    {{ $msg->sender->name }} · {{ $msg->created_at->diffForHumans() }}
                                </div>
                            </div>
                        </a>
                    @empty
                        <div class="dropdown-item text-center text-muted py-3">
                            <i class="fas fa-check-circle text-success mr-1"></i> Sin mensajes nuevos
                        </div>
                    @endforelse

                    <a class="dropdown-item text-center small text-gray-500" href="{{ route('chat.index') }}">
                        Ver todos los mensajes
                    </a>
                </div>
            </li>
            @endcan

            <div class="topbar-divider d-none d-sm-block"></div>

            <!-- Nav Item - Usuario -->
            <!-- Nav Item - Usuario -->
            <!-- Nav Item - Usuario -->
            <li class="nav-item dropdown no-arrow">
                <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button"
                    data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                    <span class="mr-2 d-none d-lg-inline text-gray-600 small">{{ Auth::user()->name }}</span>

                    <img class="img-profile rounded-circle" src="{{ Auth::user()->profile_photo_url }}">
                        {{-- <img class="img-profile rounded-circle"
                            src="{{ Auth::user()->profile_photo_url }}"
                            alt="{{ Auth::user()->name }}"> --}}
                </a>
                <div class="dropdown-menu dropdown-menu-right shadow animated--grow-in"
                    aria-labelledby="userDropdown">
                    <a class="dropdown-item" href="{{ route('perfil') }}">
                        <i class="fas fa-user fa-sm fa-fw mr-2 text-gray-400"></i> Mi perfil
                    </a>
                    <div class="dropdown-divider"></div>
                    <form id="logout-form" action="{{ route('logout') }}" method="POST" style="display:none">
                        @csrf
                    </form>
                    <a class="dropdown-item" href="{{ route('logout') }}"
                       onclick="event.preventDefault(); document.getElementById('logout-form').submit();">
                        <i class="fas fa-sign-out-alt fa-sm fa-fw mr-2" style="color:rgb(252,32,32)"></i>
                        Salir
                    </a>
                </div>
            </li>

        </ul>
    </nav>
</header>

<style>
.search-result-item { transition: background .15s; }
.search-result-item:hover { background: #f8f9fc; }
#search-results > div:first-child { border-radius: 8px 8px 0 0; }
#search-results > div:last-child  { border-radius: 0 0 8px 8px; }
</style>

<script>
// ── Mensajes en tiempo real ──────────────────────────────
function updateBadge(id, increment) {
    const badge = document.getElementById(id);
    if (!badge) return;
    const current = parseInt(badge.textContent) || 0;
    const next = current + increment;
    if (next <= 0) {
        badge.classList.add('d-none');
        badge.textContent = '0';
    } else {
        badge.classList.remove('d-none');
        badge.textContent = next > 9 ? '9+' : next;
    }
}

function waitForEcho(cb) {
    if (window.Echo) cb(); else setTimeout(() => waitForEcho(cb), 100);
}

waitForEcho(() => {
    const authId = {{ auth()->id() }};

    // Badge + dropdown de mensajes
    window.Echo.channel(`chat.${authId}`)
        .listen('MessageSent', (e) => {
            const list = document.querySelector('#messagesDropdown + .dropdown-list');
            if (!list) return;

            // Quitar el "sin mensajes nuevos" si existe
            const empty = list.querySelector('.text-muted.py-3');
            if (empty) empty.remove();

            // Si ya había una entrada de este remitente, quitarla (actualizar con el nuevo)
            const existing = list.querySelector(`[data-sender-id="${e.sender.id}"]`);
            if (!existing) {
                // Solo incrementar badge si es una conversación nueva en el dropdown
                updateBadge('msg-badge', 1);
            } else {
                existing.remove();
            }

            // Insertar nueva entrada al tope (después del header)
            const preview = e.body ? e.body : '📎 Archivo adjunto';
            const item = document.createElement('a');
            item.className = 'dropdown-item d-flex align-items-center';
            item.href = `/chat/${e.sender.id}`;
            item.dataset.senderId = e.sender.id;
            item.innerHTML = `
                <div class="dropdown-list-image mr-3">
                    <img class="rounded-circle" width="40" height="40"
                         style="object-fit:cover"
                         src="${e.sender.avatar}" alt="">
                    <div class="status-indicator bg-success"></div>
                </div>
                <div class="font-weight-bold overflow-hidden">
                    <div class="text-truncate">${preview}</div>
                    <div class="small text-gray-500">${e.sender.name} · ahora</div>
                </div>`;
            list.querySelector('.dropdown-header').insertAdjacentElement('afterend', item);
        });

    // Cuando el usuario responde desde el chat, quitar esa conversación del dropdown
    window.addEventListener('chat:replied', (ev) => {
        const receiverId = ev.detail.receiverId;
        const list = document.querySelector('#messagesDropdown + .dropdown-list');
        if (!list) return;
        const entry = list.querySelector(`[data-sender-id="${receiverId}"]`);
        if (entry) {
            entry.remove();
            updateBadge('msg-badge', -1);
            // Si ya no quedan conversaciones, mostrar el mensaje vacío
            const remaining = list.querySelectorAll('.dropdown-item[data-sender-id]');
            if (remaining.length === 0) {
                const empty = document.createElement('div');
                empty.className = 'dropdown-item text-center text-muted py-3';
                empty.innerHTML = '<i class="fas fa-check-circle text-success mr-1"></i> Sin mensajes nuevos';
                list.querySelector('.dropdown-header').insertAdjacentElement('afterend', empty);
            }
        }
    });

    // Badge de notificaciones
    window.Echo.channel(`notifications.${authId}`)
        .listen('NewNotification', (e) => {
            updateBadge('notif-badge', 1);
            // Agregar al dropdown sin recargar
            const list = document.querySelector('#alertsDropdown + .dropdown-list');
            const empty = list.querySelector('.text-muted.py-3');
            if (empty) empty.remove();
            const item = document.createElement('a');
            item.className = 'dropdown-item d-flex align-items-center';
            item.href = e.url ?? '#';
            item.innerHTML = `
                <div class="mr-3">
                    <div class="icon-circle bg-${e.color}">
                        <i class="fas ${e.icon} text-white"></i>
                    </div>
                </div>
                <div>
                    <div class="small text-gray-500">${e.time}</div>
                    <span class="font-weight-bold">${e.title}</span>
                    ${e.body ? `<div class="small text-truncate" style="max-width:200px">${e.body}</div>` : ''}
                </div>`;
            list.querySelector('.dropdown-header').insertAdjacentElement('afterend', item);
        });
});

// ── Marcar notificaciones como leídas ───────────────────
function markNotifRead(id) {
    axios.post('/notifications/' + id + '/read').catch(() => {});
}

function markAllNotifsRead() {
    axios.post('/notifications/read-all').then(() => {
        document.getElementById('notif-badge').classList.add('d-none');
        document.querySelectorAll('#alertsDropdown + .dropdown-list .dropdown-item[onclick]')
            .forEach(el => el.classList.remove('font-weight-bold'));
    }).catch(() => {});
}

// ── Búsqueda de usuarios ─────────────────────────────────
function friendshipLabel(f) {
    if (f.status === 'accepted')                  return { label: 'Amigos',           cls: 'btn-outline-secondary', icon: 'fa-user-check' };
    if (f.status === 'pending' && !f.is_receiver) return { label: 'Solicitud enviada', cls: 'btn-outline-secondary', icon: 'fa-user-clock'  };
    if (f.status === 'pending' &&  f.is_receiver) return { label: 'Aceptar',           cls: 'btn-success',           icon: 'fa-user-plus'   };
    return                                               { label: 'Agregar',            cls: 'btn-primary',           icon: 'fa-user-plus'   };
}

function initSearchWidget(inputEl, resultsEl) {
    if (!inputEl || !resultsEl) return;
    let timer;

    function renderResults(users) {
        if (!users.length) {
            resultsEl.innerHTML = `
                <div class="px-4 py-3 text-center">
                    <i class="fas fa-search text-muted mb-2 d-block" style="font-size:1.4rem"></i>
                    <span class="text-muted small">Sin resultados</span>
                </div>`;
            resultsEl.classList.remove('d-none');
            return;
        }
        resultsEl.innerHTML =
            `<div class="px-3 pt-2 pb-1" style="font-size:.7rem;font-weight:600;letter-spacing:.05em;color:#aaa;text-transform:uppercase">Personas</div>` +
            users.map((u, i) => {
                const btn    = friendshipLabel(u.friendship);
                const isLast = i === users.length - 1;
                return `
                <div class="d-flex align-items-center px-3 py-2 search-result-item"
                     style="${!isLast ? 'border-bottom:1px solid #f1f1f1' : ''}">
                    <a href="${u.profile_url}"
                       class="d-flex align-items-center flex-grow-1 text-dark text-decoration-none"
                       style="min-width:0">
                        <img src="${u.avatar}" class="rounded-circle flex-shrink-0 mr-3"
                             width="38" height="38" style="object-fit:cover">
                        <span class="font-weight-bold small text-truncate">${u.name}</span>
                    </a>
                    <div class="d-flex align-items-center flex-shrink-0 ml-2" style="gap:.35rem">
                        <button class="btn btn-sm ${btn.cls} friend-toggle-btn rounded-pill"
                                style="font-size:.72rem;padding:.2rem .65rem"
                                data-user-id="${u.id}"
                                data-status="${u.friendship.status}"
                                data-is-receiver="${u.friendship.is_receiver}">
                            <i class="fas ${btn.icon} mr-1"></i>${btn.label}
                        </button>
                        ${u.friendship.status === 'accepted'
                            ? `<a href="${u.chat_url}"
                                  class="btn btn-sm btn-outline-primary rounded-pill"
                                  style="font-size:.72rem;padding:.2rem .55rem"
                                  title="Enviar mensaje">
                                   <i class="fas fa-comment"></i>
                               </a>`
                            : ''}
                    </div>
                </div>`;
            }).join('');
        resultsEl.classList.remove('d-none');

        resultsEl.querySelectorAll('.friend-toggle-btn').forEach(btn => {
            btn.addEventListener('click', function (e) {
                e.stopPropagation();
                axios.post(`/friends/${this.dataset.userId}/toggle`)
                    .then(() => doSearch(inputEl.value));
            });
        });
    }

    function doSearch(q) {
        if (q.length < 2) { resultsEl.classList.add('d-none'); return; }
        axios.get('/search', { params: { q } }).then(res => renderResults(res.data));
    }

    inputEl.addEventListener('input', function () {
        clearTimeout(timer);
        timer = setTimeout(() => doSearch(this.value.trim()), 300);
    });

    inputEl.addEventListener('focus', function () {
        if (this.value.trim().length >= 2) resultsEl.classList.remove('d-none');
    });

    // Evita cierre al interactuar con el dropdown
    let busy = false;
    resultsEl.addEventListener('mousedown', () => { busy = true; });
    document.addEventListener('mouseup',   () => { busy = false; });
    document.addEventListener('click', function (e) {
        if (busy) return;
        if (!inputEl.contains(e.target) && !resultsEl.contains(e.target)) {
            resultsEl.classList.add('d-none');
        }
    });
}

// Desktop
initSearchWidget(
    document.getElementById('global-search'),
    document.getElementById('search-results')
);

// Móvil: toggle del panel y widget de búsqueda
(function () {
    const toggle  = document.getElementById('mobile-search-toggle');
    const panel   = document.getElementById('mobile-search-panel');
    const mInput  = document.getElementById('global-search-mobile');
    const mResult = document.getElementById('search-results-mobile');
    if (!toggle) return;

    toggle.addEventListener('click', function (e) {
        e.preventDefault();
        const isHidden = panel.classList.contains('d-none');
        panel.classList.toggle('d-none', !isHidden);
        if (!isHidden) { mInput.focus(); }
    });

    // Cerrar panel al tocar fuera
    document.addEventListener('click', function (e) {
        if (!panel.contains(e.target) && !toggle.contains(e.target)) {
            panel.classList.add('d-none');
        }
    });

    initSearchWidget(mInput, mResult);
})();
</script>
