/* ============================================================
   app.js — Main app shell: auth check, routing, nav
   ============================================================ */

var APP = {
  currentView: null,

  views: {
    dashboard:   { title: 'Dashboard',         fn: renderDashboard },
    network:     { title: 'Mi Red',            fn: renderNetwork },
    catalog:     { title: 'Catálogo',           fn: renderCatalog },
    newpurchase: { title: 'Nueva Compra',       fn: renderNewPurchase },
    purchases:   { title: 'Mis Compras',        fn: renderPurchases },
    earnings:    { title: 'Ganancias',          fn: renderEarnings },
    vouchers:    { title: 'Vouchers',           fn: renderVouchers },
    kyc:         { title: 'Verificación KYC',  fn: renderKyc },
    avisos:      { title: 'Avisos',             fn: renderAvisos },
    profile:     { title: 'Mi Perfil',          fn: renderProfile },
  },

  init: function() {
    if (!requireAuth()) return;
    this.loadUser();
    this.wireNav();
    this.navigate('dashboard');
  },

  loadUser: function() {
    var u = getUser();
    var nombre = u.nombre || '';
    var appat  = u.appat  || '';
    var full   = (nombre + ' ' + appat).trim() || u.nombre_usuario || 'Distribuidor';
    document.getElementById('sidebarName').textContent = full;
    document.getElementById('sidebarRef').textContent  = 'Ref: ' + (u.referencia || '—');
  },

  navigate: function(view) {
    if (!this.views[view]) view = 'dashboard';
    this.currentView = view;

    // Update sidebar
    var navItems = document.querySelectorAll('#sidebarNav .nav-item');
    for (var i = 0; i < navItems.length; i++) {
      navItems[i].classList.toggle('active', navItems[i].dataset.view === view);
    }
    // Update bottom nav
    var bnItems = document.querySelectorAll('#bottomNav .bottom-nav-item');
    for (var j = 0; j < bnItems.length; j++) {
      bnItems[j].classList.toggle('active', bnItems[j].dataset.view === view);
    }

    // Update topbar title
    document.getElementById('topbarTitle').textContent = this.views[view].title;

    // Close sidebar on mobile
    document.getElementById('sidebar').classList.remove('open');
    document.getElementById('sidebarOverlay').classList.remove('show');

    // Hide topbar badge
    var badge = document.getElementById('topbarBadge');
    badge.style.display = 'none';

    // Render view
    var area = document.getElementById('contentArea');
    setLoading(area, true);
    this.views[view].fn(area);
  },

  wireNav: function() {
    var self = this;

    // Sidebar nav items
    document.getElementById('sidebarNav').addEventListener('click', function(e) {
      var item = e.target.closest('.nav-item');
      if (item && item.dataset.view) self.navigate(item.dataset.view);
    });

    // Bottom nav items
    document.getElementById('bottomNav').addEventListener('click', function(e) {
      var item = e.target.closest('.bottom-nav-item');
      if (item && item.dataset.view) self.navigate(item.dataset.view);
    });

    // Hamburger menu
    document.getElementById('menuBtn').addEventListener('click', function() {
      document.getElementById('sidebar').classList.toggle('open');
      document.getElementById('sidebarOverlay').classList.toggle('show');
    });

    // Overlay click — close sidebar
    document.getElementById('sidebarOverlay').addEventListener('click', function() {
      document.getElementById('sidebar').classList.remove('open');
      document.getElementById('sidebarOverlay').classList.remove('show');
    });

    // Logout
    document.getElementById('logoutBtn').addEventListener('click', function() {
      confirmModal('Cerrar sesión', '¿Estás seguro de que quieres salir?', logout, 'Salir', 'btn-danger');
    });
  },
};

// Global navigate shortcut
function goTo(view) { APP.navigate(view); }

document.addEventListener('DOMContentLoaded', function() { APP.init(); });
