<!DOCTYPE html>
<html lang="es">
<head>
  <script>/*pos_theme_early*/(function(){var t=localStorage.getItem("pos_theme")||"industrial";document.documentElement.setAttribute("data-theme",t);})()</script>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Nexus Autoparts — Iniciar Sesión</title>
  <link rel="stylesheet" href="/pos/static/css/tokens.css" />
  <link rel="stylesheet" href="/pos/static/css/pos-glass.css" />
  <link rel="manifest" href="/pos/static/pwa/manifest.json" />
  <meta name="theme-color" content="#F5A623" />
  <link rel="stylesheet" href="/pos/static/css/login.css">
</head>
<body>

  <!-- =====================================================================
       THEME SWITCHER BAR
       ===================================================================== -->
  <div class="theme-bar" role="toolbar" aria-label="Selector de tema">
    <span class="theme-bar__label">Tema</span>
    <button
      class="theme-btn active"
      data-theme-target="industrial"
      aria-pressed="true"
      title="Tema Industrial (oscuro)"
    >
      <span class="theme-btn__dot" aria-hidden="true"></span>
      Industrial
    </button>
    <button
      class="theme-btn"
      data-theme-target="modern"
      aria-pressed="false"
      title="Tema Moderno (claro)"
    >
      <span class="theme-btn__dot" aria-hidden="true"></span>
      Moderno
    </button>
  </div>

  <!-- =====================================================================
       LOGIN SCREEN
       ===================================================================== -->
  <main class="login-screen" role="main">
    <div class="login-card" role="region" aria-label="Inicio de sesión">

      <!-- CARD HEADER — Brand -->
      <header class="card-header">
        <div class="brand">
          <div class="brand-logo" aria-hidden="true">N</div>
          <div class="brand-text">
            <div class="brand-name">Nexus Autoparts</div>
            <div class="brand-sub">Sistema de Punto de Venta</div>
          </div>
        </div>
      </header>

      <!-- CARD BODY -->
      <div class="card-body">

        <!-- USER SELECTION -->
        <section class="users-section" aria-labelledby="users-label">
          <div class="section-label" id="users-label">Seleccionar usuario</div>
          <div class="users-grid" id="usersGrid" role="radiogroup" aria-label="Usuarios disponibles">
            <!-- Employees loaded dynamically from API -->
            <div style="text-align:center;padding:var(--space-4);color:var(--color-text-muted);">Cargando empleados...</div>
          </div>
        </section>

        <!-- PIN ENTRY -->
        <section class="pin-section" aria-labelledby="pin-label">
          <div class="section-label" id="pin-label">Ingresa tu PIN</div>

          <!-- PIN Display dots -->
          <div
            class="pin-display"
            role="status"
            aria-live="polite"
            aria-label="PIN ingresado"
            id="pin-display"
          >
            <span class="pin-placeholder" id="pin-placeholder">Selecciona un usuario</span>
            <span class="pin-dot" data-index="0" style="display:none;" aria-hidden="true"></span>
            <span class="pin-dot" data-index="1" style="display:none;" aria-hidden="true"></span>
            <span class="pin-dot" data-index="2" style="display:none;" aria-hidden="true"></span>
            <span class="pin-dot" data-index="3" style="display:none;" aria-hidden="true"></span>
            <span class="pin-dot" data-index="4" style="display:none;" aria-hidden="true"></span>
            <span class="pin-dot" data-index="5" style="display:none;" aria-hidden="true"></span>
          </div>

          <!-- PIN Pad 3x4 -->
          <div
            class="pin-pad"
            role="group"
            aria-label="Teclado numérico"
            id="pin-pad"
          >
            <!-- Row 1: 1 2 3 -->
            <button class="pin-key" data-digit="1" aria-label="1" disabled>1</button>
            <button class="pin-key" data-digit="2" aria-label="2" disabled>2</button>
            <button class="pin-key" data-digit="3" aria-label="3" disabled>3</button>

            <!-- Row 2: 4 5 6 -->
            <button class="pin-key" data-digit="4" aria-label="4" disabled>4</button>
            <button class="pin-key" data-digit="5" aria-label="5" disabled>5</button>
            <button class="pin-key" data-digit="6" aria-label="6" disabled>6</button>

            <!-- Row 3: 7 8 9 -->
            <button class="pin-key" data-digit="7" aria-label="7" disabled>7</button>
            <button class="pin-key" data-digit="8" aria-label="8" disabled>8</button>
            <button class="pin-key" data-digit="9" aria-label="9" disabled>9</button>

            <!-- Row 4: Backspace 0 Enter -->
            <button class="pin-key pin-key--backspace" data-action="backspace" aria-label="Borrar último dígito" disabled>
              ⌫
            </button>
            <button class="pin-key" data-digit="0" aria-label="0" disabled>0</button>
            <button class="pin-key pin-key--enter" data-action="enter" aria-label="Confirmar PIN" disabled>
              ↵
            </button>
          </div>
        </section>

        <!-- SUBMIT BUTTON -->
        <button class="btn-login" id="btn-login" disabled aria-label="Iniciar sesión">
          <span class="btn-login__icon" aria-hidden="true">→</span>
          Iniciar Sesión
        </button>

      </div><!-- /card-body -->

      <!-- CARD FOOTER -->
      <footer class="card-footer">
        <span class="footer-version">v2.4.1 — 2026</span>
        <span class="footer-status" aria-label="Sistema en línea">
          <span class="status-dot" aria-hidden="true"></span>
          Sistema en línea
        </span>
      </footer>

    </div><!-- /login-card -->
  </main>

  <!-- Toast notification -->
  <div class="toast" id="toast" role="alert" aria-live="assertive"></div>

  <!-- =====================================================================
       JAVASCRIPT
       ===================================================================== -->
  <script>
    'use strict';

    /* ------------------------------------------------------------------
       STATE
       ------------------------------------------------------------------ */
    const state = {
      selectedUser: null,
      selectedUserId: null,
      pin: [],
      maxPinLength: 6,
    };

    /* ------------------------------------------------------------------
       DOM REFS
       ------------------------------------------------------------------ */
    const html           = document.documentElement;
    const themeBtns      = document.querySelectorAll('.theme-btn');
    const userBtns       = document.querySelectorAll('.user-avatar-btn');
    const pinDisplay     = document.getElementById('pin-display');
    const pinPlaceholder = document.getElementById('pin-placeholder');
    const pinDots        = document.querySelectorAll('.pin-dot');
    const pinKeys        = document.querySelectorAll('.pin-key');
    const btnLogin       = document.getElementById('btn-login');
    const toast          = document.getElementById('toast');

    /* ------------------------------------------------------------------
       THEME SWITCHER
       ------------------------------------------------------------------ */
    themeBtns.forEach(btn => {
      btn.addEventListener('click', () => {
        const target = btn.dataset.themeTarget;
        html.dataset.theme = target;

        // Update button states
        themeBtns.forEach(b => {
          const isActive = b.dataset.themeTarget === target;
          b.classList.toggle('active', isActive);
          b.setAttribute('aria-pressed', isActive.toString());
        });

        // Body background for modern dot-grid
        // Handled by [data-theme="modern"] body CSS rule
      });
    });

    /* ------------------------------------------------------------------
       USER SELECTION — handled dynamically in loadEmployees()
       ------------------------------------------------------------------ */

    /* ------------------------------------------------------------------
       PIN PAD LOGIC
       ------------------------------------------------------------------ */
    function enablePinPad() {
      pinKeys.forEach(k => {
        k.disabled = false;
      });
    }

    function disablePinPad() {
      pinKeys.forEach(k => {
        k.disabled = true;
      });
    }

    pinKeys.forEach(key => {
      key.addEventListener('click', () => {
        if (!state.selectedUser) return;

        const digit  = key.dataset.digit;
        const action = key.dataset.action;

        if (digit !== undefined) {
          handleDigit(digit, key);
        } else if (action === 'backspace') {
          handleBackspace();
        } else if (action === 'enter') {
          handleEnter();
        }
      });
    });

    function handleDigit(digit, keyEl) {
      if (state.pin.length >= state.maxPinLength) return;

      state.pin.push(digit);
      triggerRipple(keyEl);
      updatePinDisplay();
      updateLoginButton();
    }

    function handleBackspace() {
      if (state.pin.length === 0) return;
      state.pin.pop();
      updatePinDisplay();
      updateLoginButton();
    }

    function handleEnter() {
      if (state.pin.length === 0) {
        showToast('Ingresa tu PIN para continuar');
        shakePinDisplay();
        return;
      }
      if (state.pin.length < 4) {
        showToast('El PIN debe tener al menos 4 dígitos');
        shakePinDisplay();
        return;
      }
      triggerLogin();
    }

    /* ------------------------------------------------------------------
       UPDATE PIN DISPLAY DOTS
       ------------------------------------------------------------------ */
    function updatePinDisplay() {
      const hasUser   = !!state.selectedUser;
      const pinLength = state.pin.length;

      if (!hasUser) {
        // Show placeholder, hide dots
        pinPlaceholder.style.display = '';
        pinDots.forEach(d => { d.style.display = 'none'; });
        pinDisplay.classList.remove('has-digits', 'error');
        return;
      }

      // Hide placeholder, show dots
      pinPlaceholder.style.display = 'none';
      pinDots.forEach((dot, i) => {
        dot.style.display = '';
        dot.classList.toggle('filled', i < pinLength);
      });

      pinDisplay.classList.toggle('has-digits', pinLength > 0);
    }

    /* ------------------------------------------------------------------
       LOGIN BUTTON STATE
       ------------------------------------------------------------------ */
    function updateLoginButton() {
      const canLogin = state.selectedUser && state.pin.length >= 4;
      btnLogin.disabled = !canLogin;
    }

    /* ------------------------------------------------------------------
       LOGIN BUTTON CLICK
       ------------------------------------------------------------------ */
    btnLogin.addEventListener('click', function() {
      triggerLogin();
    });

    /* ------------------------------------------------------------------
       TRIGGER LOGIN (demo)
       ------------------------------------------------------------------ */
    // Tenant resolution: subdomain (server-side) > URL param > localStorage
    var _serverTenantId = {{ tenant_id | default('null') | tojson }};
    var _serverTenantName = {{ tenant_name | default('null') | tojson }};
    var _serverSubdomain = {{ tenant_subdomain | default('null') | tojson }};

    var tenantId = _serverTenantId
                   || new URLSearchParams(window.location.search).get('tenant')
                   || localStorage.getItem('pos_tenant_id')
                   || '11';  // Default tenant — remove in production when multi-tenant selector exists

    // Show business name from subdomain if available
    if (_serverTenantName) {
      var brandNameEl = document.querySelector('.brand-name');
      var brandSubEl = document.querySelector('.brand-sub');
      if (brandNameEl) brandNameEl.textContent = _serverTenantName;
      if (brandSubEl) brandSubEl.textContent = 'Punto de Venta';
    }
    // 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);
    }

    // Auto-redirect if already logged in with valid token
    (function checkExistingSession() {
      var token = localStorage.getItem('pos_token');
      if (token && tenantId) {
        try {
          var payload = JSON.parse(atob(token.split('.')[1]));
          if (payload.exp * 1000 > Date.now() + 30000) {
            window.location.href = '/pos/catalog';
            return;
          }
        } catch(e) {}
        localStorage.removeItem('pos_token');
      }
    })();

    function triggerLogin() {
      btnLogin.disabled = true;
      btnLogin.innerHTML = '<span class="btn-login__icon" aria-hidden="true">⟳</span> Verificando…';

      var enteredPin = state.pin.join('');

      fetch('/pos/api/auth/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          tenant_id: parseInt(tenantId),
          employee_id: state.selectedUserId,
          pin: enteredPin,
          device_id: deviceId
        })
      })
      .then(function(res) { return res.json().then(function(d) { return { ok: res.ok, data: d }; }); })
      .then(function(result) {
        if (!result.ok) {
          btnLogin.innerHTML = '<span class="btn-login__icon" aria-hidden="true">→</span> Iniciar Sesión';
          btnLogin.disabled = false;
          btnLogin.style.background = '';
          showToast(result.data.error || 'PIN incorrecto');
          shakePinDisplay();
          setTimeout(function() {
            state.pin = [];
            updatePinDisplay();
            updateLoginButton();
          }, 600);
          return;
        }
        // Success
        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';

        btnLogin.innerHTML = '<span class="btn-login__icon" aria-hidden="true">✓</span> Bienvenido, ' + result.data.employee.name;
        btnLogin.style.background = 'var(--color-success)';
        showToast('¡Acceso concedido! Redirigiendo…');

        setTimeout(function() {
          window.location.href = '/pos/catalog';
        }, 1000);
      })
      .catch(function() {
        btnLogin.innerHTML = '<span class="btn-login__icon" aria-hidden="true">→</span> Iniciar Sesión';
        btnLogin.disabled = false;
        showToast('Error de conexión');
        shakePinDisplay();
        setTimeout(function() {
          state.pin = [];
          updatePinDisplay();
          updateLoginButton();
        }, 600);
      });
    }

    function resetLoginState() {
      state.selectedUser = null;
      state.selectedUserId = null;
      state.pin = [];

      userBtns.forEach(b => {
        b.classList.remove('selected');
        b.setAttribute('aria-checked', 'false');
      });

      disablePinPad();
      updatePinDisplay();
      updateLoginButton();

      btnLogin.innerHTML = '<span class="btn-login__icon" aria-hidden="true">→</span> Iniciar Sesión';
      btnLogin.style.background = '';
    }

    /* ------------------------------------------------------------------
       EFFECTS — shake, ripple, toast
       ------------------------------------------------------------------ */
    function shakePinDisplay() {
      pinDisplay.classList.remove('error');
      // Force reflow for re-trigger
      void pinDisplay.offsetWidth;
      pinDisplay.classList.add('error');
      pinDisplay.addEventListener('animationend', () => {
        pinDisplay.classList.remove('error');
      }, { once: true });
    }

    function triggerRipple(el) {
      el.classList.remove('ripple');
      void el.offsetWidth;
      el.classList.add('ripple');
      el.addEventListener('transitionend', () => {
        el.classList.remove('ripple');
      }, { once: true });
    }

    let toastTimer = null;
    function showToast(message, duration = 2800) {
      toast.textContent = message;
      toast.classList.add('show');
      clearTimeout(toastTimer);
      toastTimer = setTimeout(() => {
        toast.classList.remove('show');
      }, duration);
    }

    /* ------------------------------------------------------------------
       KEYBOARD SUPPORT
       ------------------------------------------------------------------ */
    document.addEventListener('keydown', e => {
      if (!state.selectedUser) return;

      const digit = e.key;
      if (/^[0-9]$/.test(digit)) {
        const keyEl = document.querySelector(`.pin-key[data-digit="${digit}"]`);
        handleDigit(digit, keyEl);
      } else if (e.key === 'Backspace') {
        handleBackspace();
      } else if (e.key === 'Enter') {
        handleEnter();
      }
    });

    /* ------------------------------------------------------------------
       LOAD REAL EMPLOYEES FROM API
       ------------------------------------------------------------------ */
    function loadEmployees() {
      if (!tenantId) {
        document.getElementById('usersGrid').innerHTML = '<div style="text-align:center;padding:var(--space-4);color:var(--color-error);">No se especificó tenant. Agrega ?tenant=ID a la URL o usa un subdominio.</div>';
        return;
      }
      // If subdomain is set, the server already knows the tenant — use /employees endpoint
      var empUrl = _serverSubdomain
          ? '/pos/api/auth/employees'
          : '/pos/api/auth/employees/' + tenantId;
      fetch(empUrl)
        .then(function(r) { return r.json(); })
        .then(function(data) {
          var grid = document.getElementById('usersGrid');
          var employees = data.data || [];
          if (!employees.length) {
            grid.innerHTML = '<div style="text-align:center;padding:var(--space-4);color:var(--color-text-muted);">No hay empleados registrados.</div>';
            return;
          }
          grid.innerHTML = '';
          employees.forEach(function(emp) {
            var btn = document.createElement('button');
            btn.className = 'user-avatar-btn';
            btn.setAttribute('data-id', emp.id);
            btn.setAttribute('data-user', emp.initials);
            btn.setAttribute('data-name', emp.name);
            btn.setAttribute('data-role', emp.role_label);
            btn.setAttribute('role', 'radio');
            btn.setAttribute('aria-checked', 'false');
            btn.setAttribute('aria-label', emp.name + ', ' + emp.role_label);
            btn.innerHTML = '<div class="user-initials" aria-hidden="true">' + emp.initials + '</div>'
              + '<div class="user-name">' + emp.name + '</div>'
              + '<div class="user-role">' + emp.role_label + '</div>';
            btn.addEventListener('click', function() {
              // Deselect all
              grid.querySelectorAll('.user-avatar-btn').forEach(function(b) {
                b.classList.remove('selected');
                b.setAttribute('aria-checked', 'false');
              });
              // Select this one
              btn.classList.add('selected');
              btn.setAttribute('aria-checked', 'true');
              state.selectedUser = emp.initials;
              state.selectedUserId = emp.id;
              state.pin = [];
              enablePinPad();
              updatePinDisplay();
              updateLoginButton();
            });
            grid.appendChild(btn);
          });

          // If only 1 employee, auto-select
          if (employees.length === 1) {
            grid.querySelector('.user-avatar-btn').click();
          }
        })
        .catch(function() {
          document.getElementById('usersGrid').innerHTML = '<div style="text-align:center;padding:var(--space-4);color:var(--color-error);">Error al cargar empleados.</div>';
        });
    }

    /* ------------------------------------------------------------------
       INIT
       ------------------------------------------------------------------ */
    // Initial state: pin pad disabled, dots hidden
    disablePinPad();
    updatePinDisplay();
    updateLoginButton();
    // Load real employees
    loadEmployees();

  </script>

  <script src="/pos/static/js/kiosk.js" defer></script>
  <script src="/pos/static/js/sync-engine.js" defer></script>
  <script>if('serviceWorker' in navigator){navigator.serviceWorker.register('/pos/sw.js',{scope:'/pos/'});}</script>
  <script src="/pos/static/js/pwa-install.js" defer></script>

</body>
</html>
