/**
 * NEXUS IT — Autenticación Frontend
 */
const NexusAuth = {
    getToken() { return localStorage.getItem('nexus_token'); },
    
    getUser() {
        try { return JSON.parse(localStorage.getItem('nexus_user')); }
        catch(e) { return null; }
    },

    getInitials() {
        const u = this.getUser();
        if (!u || !u.nombre_completo) return '??';
        return u.nombre_completo.split(' ').map(n=>n[0]).join('').substring(0,2).toUpperCase();
    },

    setAuth(token, user) {
        localStorage.setItem('nexus_token', token);
        localStorage.setItem('nexus_user', JSON.stringify(user));
    },

    clearAuth() {
        localStorage.removeItem('nexus_token');
        localStorage.removeItem('nexus_user');
    },

    async login(email, password) {
        try {
            const res = await fetch('/api/v1/auth/login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ email, password })
            });
            const data = await res.json();
            if (data.success && data.data) {
                this.setAuth(data.data.token, data.data.usuario);
                return { success: true, user: data.data.usuario };
            }
            return { success: false, message: data.message || 'Credenciales incorrectas' };
        } catch(e) {
            return { success: false, message: 'Error de conexión' };
        }
    },

    logout() { this.clearAuth(); window.location.href = '/app/'; },

    requireAuth(allowedRoles) {
        const token = this.getToken();
        const user = this.getUser();
        const path = window.location.pathname;

        if (!token || !user) {
            if (path === '/app/' || path === '/app/index.html') return false;
            window.location.href = '/app/';
            return false;
        }

        try {
            const payload = JSON.parse(atob(token.split('.')[1]));
            if (payload.exp && payload.exp < Date.now()/1000) {
                this.clearAuth(); window.location.href = '/app/'; return false;
            }
        } catch(e) {}

        if (allowedRoles && !allowedRoles.includes(user.rol)) {
            window.location.href = user.rol === 'usuario' ? '/app/portal/' : '/app/admin/';
            return false;
        }
        return true;
    },

    isAdmin() { const u=this.getUser(); return u && u.rol==='admin'; }
};

window.NexusAuth = NexusAuth;
