/**
 * NEXUS IT - Notificaciones Header v1
 * Agrega campana de notificaciones al top-bar automáticamente
 */
(function(){
    // Wait for DOM
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initNotifs);
    } else {
        initNotifs();
    }

    function initNotifs() {
        var topRight = document.querySelector('.top-bar-right');
        if (!topRight) {
            var topBar = document.querySelector('.top-bar');
            if (!topBar) return;
            topRight = document.createElement('div');
            topRight.className = 'top-bar-right';
            topBar.appendChild(topRight);
        }

        // Insert notification bell at the beginning of top-bar-right
        var bellWrap = document.createElement('div');
        bellWrap.className = 'notif-bell-wrap';
        bellWrap.innerHTML =
            '<button class="notif-bell" onclick="NexusNotifs.toggle()" title="Notificaciones">' +
            '<span class="bell-icon">\uD83D\uDD14</span>' +
            '<span class="notif-badge" id="notifBadge" style="display:none">0</span>' +
            '</button>' +
            '<div class="notif-dropdown" id="notifDropdown">' +
            '<div class="notif-header">' +
            '<strong>Notificaciones</strong>' +
            '<button class="notif-mark-all" onclick="NexusNotifs.marcarTodas()">Marcar todas</button>' +
            '</div>' +
            '<div class="notif-list" id="notifList"><div style="padding:20px;text-align:center;color:var(--text-muted,#64748b)">Cargando...</div></div>' +
            '</div>';

        topRight.insertBefore(bellWrap, topRight.firstChild);

        // Add styles
        var style = document.createElement('style');
        style.textContent =
            '.notif-bell-wrap{position:relative;margin-right:8px}' +
            '.notif-bell{background:none;border:none;cursor:pointer;font-size:20px;position:relative;padding:4px 8px;border-radius:8px;transition:background 0.15s}' +
            '.notif-bell:hover{background:rgba(255,255,255,0.08)}' +
            '.notif-badge{position:absolute;top:-2px;right:0;background:#ef4444;color:#fff;font-size:10px;font-weight:700;min-width:16px;height:16px;border-radius:8px;display:flex;align-items:center;justify-content:center;padding:0 4px;font-family:system-ui}' +
            '.notif-dropdown{display:none;position:absolute;top:100%;right:0;width:360px;max-height:420px;background:var(--bg-card,#1e293b);border:1px solid var(--border-color,#334155);border-radius:12px;box-shadow:0 8px 32px rgba(0,0,0,0.4);z-index:1000;overflow:hidden;margin-top:8px}' +
            '.notif-dropdown.open{display:block}' +
            '.notif-header{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;border-bottom:1px solid var(--border-color,#334155);font-size:14px;color:var(--text-primary,#e2e8f0)}' +
            '.notif-mark-all{background:none;border:none;color:var(--primary,#3b82f6);cursor:pointer;font-size:12px;font-family:inherit}' +
            '.notif-mark-all:hover{text-decoration:underline}' +
            '.notif-list{max-height:350px;overflow-y:auto}' +
            '.notif-item{display:block;padding:12px 16px;border-bottom:1px solid rgba(255,255,255,0.04);cursor:pointer;transition:background 0.1s;text-decoration:none;color:inherit}' +
            '.notif-item:hover{background:rgba(255,255,255,0.04)}' +
            '.notif-item.unread{background:rgba(59,130,246,0.06);border-left:3px solid var(--primary,#3b82f6)}' +
            '.notif-item .notif-title{font-size:13px;font-weight:500;color:var(--text-primary,#e2e8f0);margin-bottom:2px}' +
            '.notif-item .notif-msg{font-size:12px;color:var(--text-muted,#64748b);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}' +
            '.notif-item .notif-time{font-size:11px;color:var(--text-muted,#64748b);margin-top:3px}' +
            '.notif-empty{padding:32px;text-align:center;color:var(--text-muted,#64748b);font-size:13px}' +
            '@media(max-width:480px){.notif-dropdown{width:calc(100vw - 20px);right:-60px}}';
        document.head.appendChild(style);

        // Close on outside click
        document.addEventListener('click', function(e) {
            if (!bellWrap.contains(e.target)) {
                document.getElementById('notifDropdown').classList.remove('open');
            }
        });

        // Load count
        NexusNotifs.cargarConteo();
        // Refresh every 60s
        setInterval(function(){ NexusNotifs.cargarConteo(); }, 60000);
    }
})();

window.NexusNotifs = {
    toggle: function() {
        var dd = document.getElementById('notifDropdown');
        dd.classList.toggle('open');
        if (dd.classList.contains('open')) this.cargarLista();
    },

    cargarConteo: async function() {
        try {
            var data = await NexusAPI.get('/notificaciones/no-leidas');
            if (data && data.success) {
                var badge = document.getElementById('notifBadge');
                var count = data.data.count || 0;
                if (count > 0) {
                    badge.textContent = count > 99 ? '99+' : count;
                    badge.style.display = 'flex';
                } else {
                    badge.style.display = 'none';
                }
            }
        } catch(e) {}
    },

    cargarLista: async function() {
        var list = document.getElementById('notifList');
        try {
            var data = await NexusAPI.get('/notificaciones');
            if (!data || !data.success) { list.innerHTML = '<div class="notif-empty">Error al cargar</div>'; return; }
            var items = data.data || [];
            if (items.length === 0) { list.innerHTML = '<div class="notif-empty">\uD83D\uDD14 Sin notificaciones</div>'; return; }

            list.innerHTML = items.slice(0, 20).map(function(n) {
                var cls = n.leida == 0 ? 'unread' : '';
                var ago = NexusNotifs.timeAgo(n.created_at);
                var href = n.url_accion || '#';
                return '<a class="notif-item ' + cls + '" href="' + href + '" onclick="NexusNotifs.marcar(' + n.id + ')">' +
                    '<div class="notif-title">' + (n.titulo || '') + '</div>' +
                    '<div class="notif-msg">' + (n.mensaje || '') + '</div>' +
                    '<div class="notif-time">' + ago + '</div></a>';
            }).join('');
        } catch(e) {
            list.innerHTML = '<div class="notif-empty">Error de conexi\u00f3n</div>';
        }
    },

    marcar: async function(id) {
        try { await NexusAPI.put('/notificaciones/' + id + '/leer', {}); this.cargarConteo(); } catch(e) {}
    },

    marcarTodas: async function() {
        try {
            await NexusAPI.put('/notificaciones/leer-todas', {});
            this.cargarConteo();
            this.cargarLista();
        } catch(e) {}
    },

    timeAgo: function(d) {
        if (!d) return '';
        var s = Math.floor((new Date() - new Date(d)) / 1000);
        if (s < 60) return 'ahora';
        if (s < 3600) return Math.floor(s/60) + ' min';
        if (s < 86400) return Math.floor(s/3600) + 'h';
        if (s < 604800) return Math.floor(s/86400) + 'd';
        return new Date(d).toLocaleDateString('es-CO', {day:'2-digit',month:'short'});
    }
};
