/* =============================================
   CONFIGURACION DE API
   ============================================= */
var API_URL = (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1')
    ? 'http://localhost:3000/api/auth'
    : 'https://api.sabha.pe/api/auth';

/* =============================================
   SISTEMA DE PARTICULAS - Canvas
   ============================================= */
(function initParticles() {
    var canvas = document.getElementById('particles-canvas');
    if (!canvas) return;
    var ctx = canvas.getContext('2d');
    var particles = [];
    var mouse = { x: null, y: null };
    var PARTICLE_COUNT = 60;
    var CONNECTION_DIST = 140;

    function resize() {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
    }
    resize();
    window.addEventListener('resize', resize);

    document.addEventListener('mousemove', function(e) {
        mouse.x = e.clientX;
        mouse.y = e.clientY;
    });

    function Particle() {
        this.x = Math.random() * canvas.width;
        this.y = Math.random() * canvas.height;
        this.vx = (Math.random() - 0.5) * 0.4;
        this.vy = (Math.random() - 0.5) * 0.4;
        this.radius = Math.random() * 1.8 + 0.5;
        this.baseAlpha = Math.random() * 0.4 + 0.1;
        this.alpha = this.baseAlpha;
    }

    Particle.prototype.update = function() {
        this.x += this.vx;
        this.y += this.vy;

        if (this.x < 0 || this.x > canvas.width) this.vx *= -1;
        if (this.y < 0 || this.y > canvas.height) this.vy *= -1;

        if (mouse.x !== null) {
            var dx = this.x - mouse.x;
            var dy = this.y - mouse.y;
            var dist = Math.sqrt(dx * dx + dy * dy);
            if (dist < 180) {
                var force = (180 - dist) / 180;
                this.alpha = this.baseAlpha + force * 0.5;
            } else {
                this.alpha += (this.baseAlpha - this.alpha) * 0.05;
            }
        }
    };

    Particle.prototype.draw = function() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, Math.max(0.1, this.radius), 0, Math.PI * 2);
        ctx.fillStyle = 'rgba(0, 212, 170, ' + this.alpha + ')';
        ctx.fill();
    };

    for (var i = 0; i < PARTICLE_COUNT; i++) {
        particles.push(new Particle());
    }

    function animate() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);

        for (var i = 0; i < particles.length; i++) {
            for (var j = i + 1; j < particles.length; j++) {
                var dx = particles[i].x - particles[j].x;
                var dy = particles[i].y - particles[j].y;
                var dist = Math.sqrt(dx * dx + dy * dy);

                if (dist < CONNECTION_DIST) {
                    var alpha = (1 - dist / CONNECTION_DIST) * 0.12;
                    ctx.beginPath();
                    ctx.moveTo(particles[i].x, particles[i].y);
                    ctx.lineTo(particles[j].x, particles[j].y);
                    ctx.strokeStyle = 'rgba(37, 99, 160, ' + alpha + ')';
                    ctx.lineWidth = 0.6;
                    ctx.stroke();
                }
            }
        }

        for (var k = 0; k < particles.length; k++) {
            particles[k].update();
            particles[k].draw();
        }

        requestAnimationFrame(animate);
    }

    animate();
})();

/* =============================================
   SISTEMA DE TOASTS
   ============================================= */
var Toast = {
    container: document.getElementById('toastContainer'),

    show: function(type, title, message, duration) {
        if (!this.container) return;
        duration = duration || 4000;

        var iconMap = {
            error: 'fas fa-times-circle',
            success: 'fas fa-check-circle',
            warning: 'fas fa-exclamation-triangle'
        };

        var toast = document.createElement('div');
        toast.className = 'toast ' + type;
        toast.innerHTML =
            '<i class="toast-icon ' + iconMap[type] + '"></i>' +
            '<div class="toast-body">' +
                '<div class="toast-title">' + title + '</div>' +
                '<div class="toast-msg">' + message + '</div>' +
            '</div>' +
            '<button class="toast-close" aria-label="Cerrar notificacion"><i class="fas fa-times"></i></button>' +
            '<div class="toast-progress" style="animation-duration:' + duration + 'ms"></div>';

        this.container.appendChild(toast);
        toast.offsetHeight; // forzar reflow
        toast.classList.add('show');

        var self = this;
        var closeBtn = toast.querySelector('.toast-close');
        closeBtn.addEventListener('click', function() {
            self.dismiss(toast);
        });

        var timer = setTimeout(function() {
            self.dismiss(toast);
        }, duration);
        toast._timer = timer;
    },

    dismiss: function(toast) {
        if (toast._dismissed) return;
        toast._dismissed = true;
        clearTimeout(toast._timer);
        toast.classList.remove('show');
        toast.classList.add('hide');
        setTimeout(function() {
            if (toast.parentNode) toast.parentNode.removeChild(toast);
        }, 400);
    }
};

/* =============================================
   REFERENCIAS A ELEMENTOS DEL DOM
   ============================================= */
var empresaSelect = document.getElementById('empresa');
var sucursalSelect = document.getElementById('sucursal');
var usuarioInput = document.getElementById('usuario');
var passwordInput = document.getElementById('password');
var btnLogin = document.getElementById('btnLogin');
var loginForm = document.getElementById('loginForm');
var togglePasswordBtn = document.getElementById('togglePassword');
var forgotLink = document.getElementById('forgotLink');
var forgotModal = document.getElementById('forgotModal');
var cancelRecoverBtn = document.getElementById('cancelRecover');
var sendRecoverBtn = document.getElementById('sendRecover');
var emailRecoverInput = document.getElementById('emailRecover');

/* =============================================
   FUNCIONES DE VALIDACION DE CAMPOS
   ============================================= */
function setFieldError(fieldId, message) {
    var wrapper = document.getElementById(fieldId + 'Wrapper');
    var errorMsg = document.getElementById(fieldId + 'Error');
    if (!wrapper || !errorMsg) return;
    wrapper.classList.add('error');
    if (message) errorMsg.querySelector('span').textContent = message;
    errorMsg.classList.add('visible');
}

function clearFieldError(fieldId) {
    var wrapper = document.getElementById(fieldId + 'Wrapper');
    var errorMsg = document.getElementById(fieldId + 'Error');
    if (!wrapper || !errorMsg) return;
    wrapper.classList.remove('error');
    errorMsg.classList.remove('visible');
}

function clearAllErrors() {
    clearFieldError('empresa');
    clearFieldError('sucursal');
    clearFieldError('usuario');
    clearFieldError('password');
}

/* =============================================
   CARGAR EMPRESAS DESDE EL SERVIDOR
   ============================================= */
function cargarEmpresas() {
    if (!empresaSelect) return;

    empresaSelect.innerHTML = '<option value="">Cargando empresas...</option>';
    empresaSelect.disabled = true;

    fetch(API_URL + '/empresas-disponibles')
        .then(function(res) {
            if (!res.ok) throw new Error('Error HTTP ' + res.status);
            return res.json();
        })
        .then(function(response) {
            if (response.ok) {
                var html = '<option value="">Selecciona una empresa</option>';

                if (response.data.length === 0) {
                    html += '<option value="" disabled>No hay empresas registradas</option>';
                } else {
                    response.data.forEach(function(emp) {
                        var texto = emp.razon_social;
                        if (emp.ruc) texto += ' \u2014 ' + emp.ruc;
                        html += '<option value="' + emp.id_empresa + '">' + texto + '</option>';
                    });
                }

                empresaSelect.innerHTML = html;
                empresaSelect.disabled = false;

                // Restaurar seleccion si habia sesion recordada
                var saved = localStorage.getItem('erp_session');
                if (saved) {
                    try {
                        var session = JSON.parse(saved);
                        if (session.id_empresa) {
                            empresaSelect.value = session.id_empresa;
                            cargarSucursales(session.id_empresa);
                        }
                    } catch(e) {
                        localStorage.removeItem('erp_session');
                    }
                }
            } else {
                empresaSelect.innerHTML = '<option value="">Error al cargar</option>';
                Toast.show('error', 'Error', response.mensaje || 'No se pudieron cargar las empresas');
            }
        })
        .catch(function(err) {
            console.error('[EMPRESAS] Error de conexion:', err);
            empresaSelect.innerHTML = '<option value="">Sin conexion al servidor</option>';
            Toast.show('error', 'Sin conexion', 'No se pudo conectar al servidor. Verifica que el backend este ejecutandose.');
        });
}

/* =============================================
   CARGAR SUCURSALES DE LA EMPRESA SELECCIONADA
   ============================================= */
function cargarSucursales(idEmpresa) {
    if (!sucursalSelect) return;

    if (!idEmpresa) {
        sucursalSelect.innerHTML = '<option value="">Selecciona una empresa primero</option>';
        sucursalSelect.disabled = true;
        return;
    }

    sucursalSelect.innerHTML = '<option value="">Cargando sucursales...</option>';
    sucursalSelect.disabled = true;

    fetch(API_URL + '/sucursales-empresa?id_empresa=' + idEmpresa)
        .then(function(res) {
            if (!res.ok) throw new Error('Error HTTP ' + res.status);
            return res.json();
        })
        .then(function(response) {
            if (response.ok) {
                var html = '<option value="">Selecciona una sucursal</option>';

                if (response.data.length === 0) {
                    html += '<option value="" disabled>No hay sucursales registradas</option>';
                } else {
                    response.data.forEach(function(suc) {
                        html += '<option value="' + suc.id_sucursal + '">' + suc.nombre + '</option>';
                    });
                }

                sucursalSelect.innerHTML = html;
                sucursalSelect.disabled = response.data.length === 0;

                // Restaurar sesion recordada
                var saved = localStorage.getItem('erp_session');
                if (saved) {
                    try {
                        var session = JSON.parse(saved);
                        if (session.id_sucursal) {
                            sucursalSelect.value = session.id_sucursal;
                        }
                    } catch(e) {}
                }
            } else {
                sucursalSelect.innerHTML = '<option value="">Error al cargar</option>';
            }
        })
        .catch(function(err) {
            console.error('[SUCURSALES] Error de conexion:', err);
            sucursalSelect.innerHTML = '<option value="">Sin conexion al servidor</option>';
        });
}

/* =============================================
   EVENTOS DE LIMPIEZA DE ERRORES
   ============================================= */
if (empresaSelect) {
    empresaSelect.addEventListener('change', function() {
        clearFieldError('empresa');
        cargarSucursales(this.value);
    });
}

if (sucursalSelect) {
    sucursalSelect.addEventListener('change', function() {
        clearFieldError('sucursal');
    });
}

if (usuarioInput) {
    usuarioInput.addEventListener('input', function() {
        clearFieldError('usuario');
    });
}

if (passwordInput) {
    passwordInput.addEventListener('input', function() {
        clearFieldError('password');
    });
}

/* =============================================
   ENVIO DEL FORMULARIO DE LOGIN
   ============================================= */
if (loginForm) {
    loginForm.addEventListener('submit', function(e) {
        e.preventDefault();
        clearAllErrors();

        var empresaVal = empresaSelect.value;
        var usuarioVal = usuarioInput.value.trim();
        var passwordVal = passwordInput.value;
        var hasError = false;

        // Validar empresa
        if (!empresaVal) {
            setFieldError('empresa', 'Debes seleccionar una empresa');
            hasError = true;
        }

        // Validar sucursal
        var sucursalVal = sucursalSelect ? sucursalSelect.value : '';
        if (!sucursalVal && sucursalSelect && !sucursalSelect.disabled) {
            setFieldError('sucursal', 'Debes seleccionar una sucursal');
            hasError = true;
        }

        // Validar usuario
        if (!usuarioVal) {
            setFieldError('usuario', 'El usuario es obligatorio');
            hasError = true;
        } else if (usuarioVal.length < 3) {
            setFieldError('usuario', 'Minimo 3 caracteres');
            hasError = true;
        }

        // Validar contrasena
        if (!passwordVal) {
            setFieldError('password', 'La contrasena es obligatoria');
            hasError = true;
        } else if (passwordVal.length < 4) {
            setFieldError('password', 'Minimo 4 caracteres');
            hasError = true;
        }

        if (hasError) return;

        // ---- Enviar al backend ----
        btnLogin.classList.add('loading');

        fetch(API_URL + '/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                id_empresa: parseInt(empresaVal),
                id_sucursal: sucursalVal ? parseInt(sucursalVal) : null,
                usuario: usuarioVal,
                password: passwordVal
            })
        })
        .then(function(res) {
            return res.json();
        })
        .then(function(response) {
            btnLogin.classList.remove('loading');

            if (response.ok) {
                // ---- LOGIN EXITOSO ----
                var sessionData = response.data;
                sessionData.timestamp = new Date().toISOString();
                sessionData.id_sucursal = sucursalVal ? parseInt(sucursalVal) : null;

                var sucursales = sessionData.sucursales || [];
                var sucursalSeleccionada = sucursales.find(function(s) { return s.id_sucursal == sessionData.id_sucursal; });
                if (sucursalSeleccionada) {
                    sessionData.id_rol = sucursalSeleccionada.id_rol || sessionData.id_rol;
                    sessionData.nombre_rol = sucursalSeleccionada.rol || sessionData.nombre_rol;
                }

                finalizarLogin(sessionData);

            } else {
                // ---- LOGIN FALLIDO ----
                manejarErrorLogin(response);
            }
        })
        .catch(function(err) {
            btnLogin.classList.remove('loading');
            console.error('[LOGIN] Error de conexion:', err);
            Toast.show('error', 'Sin conexion', 'No se pudo conectar al servidor. Verifica que el backend este ejecutandose en el puerto 3000.');
        });
    });
}

/* =============================================
   MANEJO DE ERRORES DE LOGIN SEGUN CODIGO
   ============================================= */
function manejarErrorLogin(response) {
    var codigo = response.codigo || '';

    switch (codigo) {
        case 'CAMPOS_VACIOS':
            Toast.show('warning', 'Campos incompletos', response.mensaje);
            break;

        case 'USUARIO_NO_EXISTE':
            setFieldError('usuario', 'Usuario no encontrado');
            Toast.show('error', 'Acceso denegado', response.mensaje);
            break;

        case 'USUARIO_INACTIVO':
            Toast.show('error', 'Cuenta desactivada', response.mensaje);
            break;

        case 'CUENTA_BLOQUEADA':
            Toast.show('error', 'Cuenta bloqueada', response.mensaje);
            break;

        case 'EMPRESA_INCORRECTA':
            setFieldError('empresa', 'Este usuario no pertenece a esta empresa');
            Toast.show('warning', 'Empresa incorrecta', response.mensaje);
            break;

        case 'SUCURSAL_NO_ASIGNADA':
            setFieldError('sucursal', 'No tiene acceso a esta sucursal');
            Toast.show('warning', 'Sucursal incorrecta', response.mensaje);
            break;

        case 'PASSWORD_INCORRECTO':
            setFieldError('password', 'Contrasena incorrecta');
            Toast.show('error', 'Acceso denegado', response.mensaje);
            break;

        default:
            Toast.show('error', 'Error', response.mensaje || 'No se pudo completar el inicio de sesion');
    }

    // Shake visual en el boton
    if (btnLogin) {
        btnLogin.style.animation = 'shake 0.5s ease';
        setTimeout(function() {
            btnLogin.style.animation = '';
        }, 500);
    }
}

/* =============================================
   TOGGLE DE VISIBILIDAD DE CONTRASENA
   ============================================= */
if (togglePasswordBtn && passwordInput) {
    togglePasswordBtn.addEventListener('click', function() {
        var icon = this.querySelector('i');
        if (passwordInput.type === 'password') {
            passwordInput.type = 'text';
            icon.classList.remove('fa-eye');
            icon.classList.add('fa-eye-slash');
        } else {
            passwordInput.type = 'password';
            icon.classList.remove('fa-eye-slash');
            icon.classList.add('fa-eye');
        }
        passwordInput.focus();
    });
}

/* =============================================
   MODAL DE RECUPERACION DE ACCESO
   ============================================= */
if (forgotLink && forgotModal) {
    forgotLink.addEventListener('click', function(e) {
        e.preventDefault();
        forgotModal.classList.add('active');
        setTimeout(function() {
            if (emailRecoverInput) emailRecoverInput.focus();
        }, 300);
    });
}

if (cancelRecoverBtn && forgotModal) {
    cancelRecoverBtn.addEventListener('click', function() {
        forgotModal.classList.remove('active');
        if (emailRecoverInput) emailRecoverInput.value = '';
        clearFieldError('emailRecover');
    });
}

if (forgotModal) {
    forgotModal.addEventListener('click', function(e) {
        if (e.target === forgotModal) {
            forgotModal.classList.remove('active');
            if (emailRecoverInput) emailRecoverInput.value = '';
            clearFieldError('emailRecover');
        }
    });
}

// Cerrar modal con Escape
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape' && forgotModal && forgotModal.classList.contains('active')) {
        forgotModal.classList.remove('active');
        if (emailRecoverInput) emailRecoverInput.value = '';
        clearFieldError('emailRecover');
    }
});

// Enviar recuperacion
if (sendRecoverBtn) {
    sendRecoverBtn.addEventListener('click', function() {
        var email = emailRecoverInput.value.trim();
        var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        clearFieldError('emailRecover');

        if (!email) {
            setFieldError('emailRecover', 'Ingresa tu correo electronico');
            return;
        }

        if (!emailRegex.test(email)) {
            setFieldError('emailRecover', 'Formato de correo no valido');
            return;
        }

        sendRecoverBtn.textContent = 'Enviando...';
        sendRecoverBtn.disabled = true;

        setTimeout(function() {
            sendRecoverBtn.textContent = 'Enviar enlace';
            sendRecoverBtn.disabled = false;
            forgotModal.classList.remove('active');
            emailRecoverInput.value = '';
            Toast.show('success', 'Enlace enviado', 'Si el correo esta registrado, recibiras un enlace de recuperacion en breve.');
        }, 2000);
    });
}

if (emailRecoverInput) {
    emailRecoverInput.addEventListener('input', function() {
        clearFieldError('emailRecover');
    });
}

/* =============================================
   RESTAURAR SESION RECORDADA (solo usuario,
   las empresas se cargan desde la API)
   ============================================= */
(function checkRememberedSession() {
    var saved = localStorage.getItem('erp_session');
    if (saved) {
        try {
            var session = JSON.parse(saved);
            if (session.usuario && usuarioInput) {
                usuarioInput.value = session.usuario;
            }
            if (document.getElementById('remember')) {
                document.getElementById('remember').checked = true;
            }
        } catch(e) {
            localStorage.removeItem('erp_session');
        }
    }
})();

/* =============================================
   CARGAR EMPRESAS AL INICIAR LA PAGINA
   ============================================= */
cargarEmpresas();

/* =============================================
   FUNCIONES DE SELECCION DE SUCURSAL
   ============================================= */
function finalizarLogin(sessionData) {
    Toast.show('success', 'Bienvenido', sessionData.nombre_completo + ' \u2014 ' + sessionData.nombre_rol);

    if (document.getElementById('remember').checked) {
        localStorage.setItem('erp_session', JSON.stringify(sessionData));
    } else {
        sessionStorage.setItem('erp_session', JSON.stringify(sessionData));
    }

    setTimeout(function() {
        window.location.href = 'dashboard.html';
    }, 800);
}

function mostrarSelectorSucursal(sessionData) {
    var sucursales = sessionData.sucursales || [];
    var overlay = document.createElement('div');
    overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:9999;display:flex;align-items:center;justify-content:center';

    var modal = document.createElement('div');
    modal.style.cssText = 'background:#fff;border-radius:12px;padding:24px;width:420px;max-width:90vw;box-shadow:0 20px 60px rgba(0,0,0,0.3)';

    var html = '<div style="text-align:center;margin-bottom:16px">';
    html += '<i class="fas fa-building" style="font-size:2rem;color:#1A4480;margin-bottom:8px"></i>';
    html += '<h3 style="margin:0;color:#1E293B;font-size:1rem">Seleccione Sucursal</h3>';
    html += '<p style="margin:4px 0 0;color:#64748B;font-size:0.75rem">' + sessionData.nombre_completo + '</p>';
    html += '</div>';
    html += '<div style="display:grid;gap:8px;margin-bottom:16px">';

    for (var i = 0; i < sucursales.length; i++) {
        var s = sucursales[i];
        html += '<button onclick="seleccionarSucursal(' + i + ')" style="display:flex;align-items:center;gap:12px;padding:12px 16px;border:2px solid #E2E8F0;border-radius:8px;background:#fff;cursor:pointer;text-align:left;transition:all 0.2s" onmouseover="this.style.borderColor=\'#1A4480\';this.style.background=\'#F0F7FF\'" onmouseout="this.style.borderColor=\'#E2E8F0\';this.style.background=\'#fff\'">';
        html += '<i class="fas fa-store" style="color:#1A4480;font-size:1.1rem"></i>';
        html += '<div><div style="font-weight:600;color:#1E293B;font-size:0.85rem">' + (s.nombre || 'Sin nombre') + '</div>';
        html += '<div style="color:#64748B;font-size:0.72rem">' + (s.rol || '') + '</div></div>';
        html += '<i class="fas fa-chevron-right" style="margin-left:auto;color:#94A3B8;font-size:0.7rem"></i>';
        html += '</button>';
    }
    html += '</div>';

    modal.innerHTML = html;
    overlay.appendChild(modal);
    document.body.appendChild(overlay);

    window._sessionDataSelector = sessionData;

    window.seleccionarSucursal = function(index) {
        var s = sucursales[index];
        sessionData.id_sucursal = s.id_sucursal;
        sessionData.id_rol = s.id_rol || sessionData.id_rol;
        sessionData.nombre_rol = s.rol || sessionData.nombre_rol;
        document.body.removeChild(overlay);
        finalizarLogin(sessionData);
    };
}