// ─── Layout: Sidebar, Topbar, App shell ─────────────────────────────────────

// ── Current-user context (rol-based permissions) ─────────────────────────
// Persiste en localStorage para que recargues y conserves el rol activo.
const LS_USER_KEY = 'lanven.user.email';

function loadCurrentUser() {
  try {
    const email = localStorage.getItem(LS_USER_KEY);
    const u = USUARIOS.find(x => x.email === email);
    if (u) return u;
  } catch (e) {}
  return USUARIOS[0]; // default: admin
}

// Helper: ¿el rol actual puede ver esta ruta?
function canSeeRoute(user, routeId) {
  if (!user) return true;
  const rol = ROLES[user.rol];
  if (!rol) return true;
  return rol.rutas.includes(routeId);
}

// ── Nodexis branding marks (discretos) ───────────────────────────────────
// Wordmark de Nodexis recreado tipográficamente — verde lima como acento solamente,
// para mantener la paleta cálida de Lanven sin que el verde domine.
const NODEXIS_GREEN = '#9FD13F';

function NodexisMark({ inverted = false, size = 'sm' }) {
  const fg = inverted ? '#FFFFFF' : '#3D4F5C';
  const sizes = {
    xs: { letter: 8.5, gap: 0.16, dotR: 1.2 },
    sm: { letter: 10,  gap: 0.18, dotR: 1.5 },
    md: { letter: 13,  gap: 0.22, dotR: 2.0 },
  };
  const s = sizes[size];
  return (
    <span className="inline-flex items-center gap-1.5" style={{ letterSpacing: '0.22em' }}>
      <svg width={s.letter * 1.1} height={s.letter * 1.1} viewBox="0 0 16 16" className="flex-shrink-0">
        {/* "N" mark inspirada en el logo — dos trazos en L + dot lime */}
        <path d="M 3 13 L 3 3 L 5 3 L 11 11 L 11 3" fill="none" stroke={fg} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" />
        <path d="M 13 3 L 13 13 L 11 13 L 5 5 L 5 13" fill="none" stroke={NODEXIS_GREEN} strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" opacity="0.85" />
        <circle cx="13" cy="3" r={s.dotR} fill={NODEXIS_GREEN} />
        <circle cx="3" cy="13" r={s.dotR} fill={fg} opacity="0.7" />
      </svg>
      <span className="font-mono font-medium" style={{ fontSize: s.letter, color: fg, opacity: inverted ? 0.7 : 0.55 }}>
        NODEXIS
      </span>
    </span>
  );
}

function LanvenLogo({ collapsed = false, brandRef }) {
  if (collapsed) {
    return (
      <div className="flex flex-col items-center justify-center">
        <span className="font-serif text-2xl text-white leading-none tracking-tight">L</span>
        <span className="mt-1 w-1 h-1 rounded-full bg-gold" />
      </div>
    );
  }
  return (
    <div>
      <div className="flex items-baseline gap-1">
        <span ref={brandRef} className="font-serif text-[26px] leading-none text-white tracking-[0.02em] font-medium">LANVEN</span>
        <span className="font-serif text-[10px] uppercase tracking-[0.18em] text-gold mb-0.5">s.a.</span>
      </div>
      {/* Marca Nodexis sutil debajo de Lanven */}
      <div className="mt-2 pl-px flex items-center gap-1.5 text-[8.5px] font-mono tracking-[0.18em] text-white/40">
        <span>by</span>
        <span className="inline-flex items-center gap-1">
          <span className="w-1 h-1 rounded-full" style={{ background: NODEXIS_GREEN }} />
          <span className="text-white/60 font-medium">NODEXIS</span>
        </span>
      </div>
    </div>
  );
}

// LVN monogram lockup — appears at sidebar foot + as a corner mark
function LVNMark({ size = 36, dark = false }) {
  const fg = dark ? '#1F2A33' : '#FFFFFF';
  const ac = '#C9A961';
  return (
    <svg width={size} height={size} viewBox="0 0 64 64">
      <circle cx="32" cy="32" r="31" fill="none" stroke={fg} strokeOpacity="0.22" />
      <text x="32" y="40" textAnchor="middle" fontFamily="Cormorant Garamond, serif" fontSize="22" fontWeight="600" fill={fg} letterSpacing="0.5">LVN</text>
      <circle cx="32" cy="50" r="1.2" fill={ac} />
    </svg>
  );
}

function NavItem({ id, label, icon: Ico, active, badge, collapsed, onClick, disabled }) {
  return (
    <button onClick={disabled ? undefined : onClick}
      disabled={disabled}
      title={disabled ? 'Sin permiso para esta sección' : label}
      className={`relative w-full flex items-center gap-3 px-4 py-2.5 text-[13px] transition-colors text-left ${
        disabled ? 'text-slate-500/40 cursor-not-allowed' :
        active   ? 'text-white nav-rail' :
                   'text-slate-300 hover:text-white hover:bg-white/[0.04]'
      }`}>
      <Ico size={17} sw={1.6} className={active ? 'text-gold' : ''} />
      {!collapsed && <span className="flex-1 truncate">{label}</span>}
      {!collapsed && badge != null && (
        <span className={`text-[10px] font-medium px-1.5 py-0.5 rounded ${active ? 'bg-gold text-slate-900' : 'bg-white/10 text-slate-200'}`}>{badge}</span>
      )}
      {!collapsed && disabled && <I.Lock size={11} className="text-slate-500/60" />}
    </button>
  );
}

const NAV_OPERACION = [
  { id: 'dashboard',    label: 'Dashboard',    icon: I.Dashboard },
  { id: 'operaciones',  label: 'Operaciones',  icon: I.Ops,     badgeKey: 'operaciones' },
  { id: 'propiedades',  label: 'Propiedades',  icon: I.Home,    badgeKey: 'propiedades' },
  { id: 'leads',        label: 'Leads',        icon: I.Users,   badgeKey: 'leads' },
  { id: 'rankings',     label: 'Rankings',     icon: I.Trophy },
];

const NAV_FINANZAS = [
  { id: 'finanzas-dashboard', label: 'Dashboard',         icon: I.Dashboard },
  { id: 'ingresos',     label: 'Ingresos',     icon: I.Up },
  { id: 'gastos',       label: 'Gastos',       icon: I.Dn },
  { id: 'cajas',        label: 'Cajas',        icon: I.Cash },
  { id: 'movimientos',  label: 'Movimientos',  icon: I.Wallet },
  { id: 'reservas',     label: 'Reservas',     icon: I.Bookmark, badgeKey: 'reservas' },
  { id: 'sueldos',      label: 'Sueldos',      icon: I.Users },
];

const NAV_ADMIN = [
  { id: 'usuarios', label: 'Usuarios', icon: I.Settings },
];

// Badges dinámicos por rol — cada número refleja sólo lo que el usuario tiene permiso de ver
function navBadges(user) {
  const ops    = filterOpsForUser(user, OPERACIONES);
  const leads  = filterLeadsForUser(user, LEADS);
  return {
    operaciones: ops.length,
    propiedades: PROPIEDADES.length,
    leads:       leads.length,
    reservas:    RESERVAS.length,
  };
}

function Sidebar({ route, setRoute, collapsed, setCollapsed, user, sidebarBrandRef }) {
  const badges = navBadges(user);
  return (
    <aside className={`bg-slate-700 text-white flex flex-col h-screen sticky top-0 transition-[width] duration-200 ${collapsed ? 'w-[68px]' : 'w-[232px]'}`}
      style={{ background: 'linear-gradient(180deg, #3D4F5C 0%, #344452 100%)' }}>
      {/* Brand */}
      <div className={`px-5 pt-6 pb-5 border-b border-white/10 ${collapsed ? 'flex justify-center px-0' : ''}`}>
        <LanvenLogo collapsed={collapsed} brandRef={sidebarBrandRef} />
        {!collapsed && <div className="mt-3 text-[9px] uppercase tracking-[0.22em] text-slate-300/50">Gestión interna</div>}
      </div>

      {/* Nav */}
      <nav className="flex-1 py-4 overflow-y-auto no-scrollbar">
        {!collapsed && <div className="px-5 pb-2 text-[10px] uppercase tracking-[0.16em] text-slate-300/60">Operación</div>}
        {NAV_OPERACION.map((n, idx) => {
          const allowed = canSeeRoute(user, n.id);
          const badge = n.badgeKey ? badges[n.badgeKey] : n.badge;
          return (
            <div key={n.id} className="lv-nav-enter" style={{ animationDelay: (0.30 + idx * 0.06) + 's' }}>
              <NavItem {...n} badge={badge} active={route === n.id} collapsed={collapsed} disabled={!allowed} onClick={() => setRoute(n.id)} />
            </div>
          );
        })}
        {!collapsed && <div className="px-5 pt-5 pb-2 text-[10px] uppercase tracking-[0.16em] text-slate-300/60">Finanzas</div>}
        {collapsed && <div className="my-2 mx-4 border-t border-white/10" />}
        {NAV_FINANZAS.map((n, idx) => {
          const allowed = canSeeRoute(user, n.id);
          const badge = n.badgeKey ? badges[n.badgeKey] : n.badge;
          return (
            <div key={n.id} className="lv-nav-enter" style={{ animationDelay: (0.30 + NAV_OPERACION.length * 0.06 + idx * 0.06) + 's' }}>
              <NavItem {...n} badge={badge} active={route === n.id} collapsed={collapsed} disabled={!allowed} onClick={() => setRoute(n.id)} />
            </div>
          );
        })}
        {user.rawRol === 'ADMIN' && (
          <>
            {!collapsed && <div className="px-5 pt-5 pb-2 text-[10px] uppercase tracking-[0.16em] text-slate-300/60">Administración</div>}
            {collapsed && <div className="my-2 mx-4 border-t border-white/10" />}
            {NAV_ADMIN.map((n, idx) => (
              <div key={n.id} className="lv-nav-enter" style={{ animationDelay: (0.30 + (NAV_OPERACION.length + NAV_FINANZAS.length) * 0.06 + idx * 0.06) + 's' }}>
                <NavItem {...n} active={route === n.id} collapsed={collapsed} disabled={false} onClick={() => setRoute(n.id)} />
              </div>
            ))}
          </>
        )}
      </nav>

      {/* Foot: collapse + LVN + Nodexis */}
      <div className={`border-t border-white/10 ${collapsed ? 'flex flex-col items-center py-4 gap-3' : 'px-5 py-4 flex flex-col gap-3'}`}>
        {!collapsed && (
          <div className="flex items-center justify-between">
            <LVNMark size={32} />
            <button onClick={() => setCollapsed(!collapsed)}
              className="text-slate-300 hover:text-white text-[11px] flex items-center gap-1.5">
              <span>Ocultar</span>
              <I.Chevron size={14} className="rotate-180" />
            </button>
          </div>
        )}
        {collapsed && (
          <>
            <LVNMark size={28} />
            <button onClick={() => setCollapsed(!collapsed)}
              className="text-slate-300 hover:text-white">
              <I.Chevron size={14} />
            </button>
          </>
        )}
        {!collapsed && (
          <div className="-mx-5 -mb-4 px-5 py-2.5 border-t border-white/5 bg-black/10 flex items-center justify-center">
            <NodexisMark inverted size="xs" />
          </div>
        )}
      </div>
    </aside>
  );
}

// ── User switcher (modal) ─────────────────────────────────────────────────
function UserSwitcher({ open, current, onPick, onClose }) {
  if (!open) return null;
  return (
    <div className="absolute right-0 top-[52px] w-[360px] bg-white border border-slate-100 rounded-md shadow-pop fade-in z-40">
      <div className="px-4 pt-4 pb-2 border-b border-slate-100">
        <div className="text-[10px] uppercase tracking-[0.14em] text-slate-400 font-medium">Cambiar usuario · demo</div>
        <h3 className="font-serif text-[18px] text-ink leading-tight mt-1">Permisos por rol</h3>
        <p className="text-[11px] text-slate-500 mt-1 leading-snug">
          Cada rol habilita distintas secciones. Pasame los emails reales del equipo y los mapeamos 1 a 1.
        </p>
      </div>
      <ul className="max-h-[360px] overflow-y-auto py-1">
        {USUARIOS.map(u => {
          const rol = ROLES[u.rol];
          const isCur = current.email === u.email;
          return (
            <li key={u.email}>
              <button onClick={() => onPick(u)}
                className={`w-full text-left px-4 py-2.5 flex items-start gap-3 hover:bg-canvas transition-colors ${isCur ? 'bg-slate-50/60' : ''}`}>
                <div className="w-9 h-9 rounded-full flex items-center justify-center text-white font-semibold text-[12px] flex-shrink-0"
                  style={{ background: rol.badge }}>{u.initials}</div>
                <div className="flex-1 min-w-0">
                  <div className="flex items-center gap-2">
                    <span className="text-[13px] text-ink font-medium truncate">{u.nombre}</span>
                    {isCur && <I.Check size={13} className="text-emerald-700" sw={2.5} />}
                  </div>
                  <div className="text-[11px] text-slate-500 font-mono truncate">{u.email}</div>
                  <div className="mt-1 flex items-center gap-1.5">
                    <span className="text-[10px] uppercase tracking-[0.1em] px-1.5 py-0.5 rounded font-medium" style={{ background: rol.badge + '18', color: rol.badge }}>{rol.label}</span>
                    <span className="text-[10px] text-slate-400 truncate">{rol.rutas.length} secciones · {rol.canEdit ? 'edita' : 'sólo lectura'}</span>
                  </div>
                </div>
              </button>
            </li>
          );
        })}
      </ul>
      <div className="px-4 py-3 border-t border-slate-100 bg-canvas flex items-center justify-between">
        <span className="text-[10.5px] text-slate-500 font-mono">{USUARIOS.length} usuarios cargados</span>
        <button onClick={onClose} className="text-[11px] text-slate-600 hover:text-ink">Cerrar</button>
      </div>
    </div>
  );
}

function Topbar({ user, onLogout }) {
  const rol = ROLES[user.rol] || ROLES['broker'];

  return (
    <header className="lv-topbar-enter h-[64px] bg-white/70 backdrop-blur-md border-b border-slate-100 px-8 flex items-center sticky top-0 z-20">
      <div className="flex-1">
        <div className="relative max-w-[420px]">
          <I.Search size={15} className="absolute left-3 top-1/2 -translate-y-1/2 text-slate-400" />
          <input placeholder="Buscar propiedades, leads, operaciones, gastos…"
            className="w-full pl-9 pr-4 py-2 text-[13px] bg-slate-50 border border-transparent rounded text-ink placeholder-slate-400 focus:outline-none focus:bg-white focus:border-slate-200" />
          <span className="absolute right-3 top-1/2 -translate-y-1/2 text-[10px] text-slate-400 font-mono">⌘K</span>
        </div>
      </div>

      <div className="flex items-center gap-5 text-slate-600">
        <div className="hidden xl:flex items-center gap-2 text-[12px] text-slate-500">
          <I.Calendar size={14} />
          <span>23 de mayo, 2026</span>
        </div>
        <div className="hidden lg:flex items-center gap-2 text-[12px] border border-slate-200 rounded px-2.5 py-1 bg-white">
          <span className="text-slate-400">USD oficial</span>
          <span className="font-mono text-ink">$1.180,50</span>
          <span className="text-emerald-700 font-medium">+0.4%</span>
        </div>
        <button className="relative p-1.5 rounded hover:bg-slate-100">
          <I.Bell size={18} />
          <span className="absolute top-1 right-1 w-1.5 h-1.5 rounded-full bg-gold" />
        </button>

        {/* User chip + logout */}
        <div className="flex items-center gap-2.5 pl-5 border-l border-slate-200">
          <div className="w-8 h-8 rounded-full flex items-center justify-center text-white font-semibold text-[12px]"
            style={{ background: rol?.badge || '#3D4F5C' }}>
            {user.nombre?.slice(0,2).toUpperCase()}
          </div>
          <div className="hidden md:block text-left">
            <div className="text-[12px] font-medium text-ink leading-none">{user.nombre}</div>
            <div className="text-[10px] leading-none mt-1 font-medium" style={{ color: rol?.badge }}>{rol?.label}</div>
          </div>
          <button onClick={onLogout} title="Cerrar sesión"
            className="ml-1 p-1.5 rounded hover:bg-slate-100 text-slate-400 hover:text-bad transition-colors">
            <I.Lock size={15} />
          </button>
        </div>
      </div>
    </header>
  );
}

window.Sidebar     = Sidebar;
window.Topbar      = Topbar;
window.LanvenLogo  = LanvenLogo;
window.LVNMark     = LVNMark;
window.NodexisMark = NodexisMark;
window.canSeeRoute = canSeeRoute;
window.loadCurrentUser = loadCurrentUser;
window.LS_USER_KEY = LS_USER_KEY;
