// /home/Autopartes/pos/static/js/login.js
(function() {
    'use strict';

    var pin = '';
    var dots = document.querySelectorAll('#pinDots .pin-dot');
    var errorEl = document.getElementById('loginError');

    // Get tenant_id from URL param or localStorage
    var tenantId = new URLSearchParams(window.location.search).get('tenant')
                   || localStorage.getItem('pos_tenant_id');

    // Device ID (persistent)
    var deviceId = localStorage.getItem('pos_device_id');
    if (!deviceId) {
        deviceId = 'dev-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
        localStorage.setItem('pos_device_id', deviceId);
    }

    /**
     * Check if a JWT token is expired by decoding its payload.
     * Returns true if the token is valid (not expired), false otherwise.
     */
    function isTokenValid(token) {
        try {
            var parts = token.split('.');
            if (parts.length !== 3) return false;
            // Base64url decode the payload (index 1)
            var payload = parts[1].replace(/-/g, '+').replace(/_/g, '/');
            var decoded = JSON.parse(atob(payload));
            // exp is in seconds, Date.now() is in milliseconds
            if (!decoded.exp) return false;
            // Add 30-second buffer to avoid edge cases
            return (decoded.exp * 1000) > (Date.now() + 30000);
        } catch (e) {
            return false;
        }
    }

    function updateDots() {
        dots.forEach(function(dot, i) {
            dot.classList.toggle('filled', i < pin.length);
        });
    }

    window.addDigit = function(d) {
        if (pin.length >= 4) return;
        pin += d;
        updateDots();
        errorEl.textContent = '';
        if (pin.length === 4) {
            submitPin();
        }
    };

    window.clearPin = function() {
        pin = '';
        updateDots();
        errorEl.textContent = '';
    };

    window.submitPin = function() {
        if (pin.length !== 4) return;
        errorEl.textContent = '';

        fetch('/pos/api/auth/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                tenant_id: parseInt(tenantId),
                pin: pin,
                device_id: deviceId
            })
        })
        .then(function(res) { return res.json().then(function(d) { return { ok: res.ok, data: d }; }); })
        .then(function(result) {
            if (!result.ok) {
                errorEl.textContent = result.data.error || 'Error de autenticacion';
                clearPin();
                return;
            }
            localStorage.setItem('pos_token', result.data.token);
            localStorage.setItem('pos_employee', JSON.stringify(result.data.employee));
            localStorage.setItem('pos_tenant_id', tenantId);
            document.cookie = 'pos_role=' + (result.data.employee.role || '') + '; path=/pos; SameSite=Lax';
            window.location.href = '/pos/catalog';
        })
        .catch(function() {
            errorEl.textContent = 'Error de conexion';
            clearPin();
        });
    };

    // Keyboard support
    document.addEventListener('keydown', function(e) {
        if (e.key >= '0' && e.key <= '9') addDigit(e.key);
        else if (e.key === 'Backspace') clearPin();
        else if (e.key === 'Enter') submitPin();
    });

    // Auto-redirect if already logged in AND token is not expired
    var token = localStorage.getItem('pos_token');
    if (token && tenantId) {
        if (isTokenValid(token)) {
            window.location.href = '/pos/catalog';
        } else {
            // Token expired — clean up and stay on login page
            localStorage.removeItem('pos_token');
            localStorage.removeItem('pos_employee');
        }
    }
})();
