
// Componentes disponibles globalmente (cargados desde archivos externos)
const TenantsPage = window.TenantsPage;
const AddTenantPage = window.AddTenantPage;
const AnalyticsDashboard = window.AnalyticsDashboard;
const ReportsSystem = window.ReportsSystem;

const parseJWT = (token) => {
  try {
    if (!token) {
      return null;
    }
    
    const base64Url = token.split('.')[1];
    if (!base64Url) {
      return null;
    }
    

    let base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    while (base64.length % 4) {
      base64 += '=';
    }
    

    const jsonPayload = atob(base64);
    
    const parsed = JSON.parse(jsonPayload);
    
    return parsed;
  } catch (error) {
    return null;
  }
};

const getJWTFromStorage = () => {

  const sessionAuthToken = sessionStorage.getItem('authToken');
  const authToken = localStorage.getItem('authToken');
  const sessionJWT = sessionStorage.getItem('jwt');
  const jwt = localStorage.getItem('jwt');

  const token = sessionAuthToken || sessionJWT || authToken || jwt;
  return token;
};

const fixUTF8String = (str) => {
  if (typeof str !== 'string') return str;
  try {
    const map = {
      'Ã±': 'ñ', 'Ã¡': 'á', 'Ã©': 'é', 'Ã­': 'í', 'Ã³': 'ó', 'Ãº': 'ú',
      'Ã ': 'à', 'Ã¨': 'è', 'Ã¬': 'ì', 'Ã²': 'ò', 'Ã¹': 'ù',
      'Ã¢': 'â', 'Ãª': 'ê', 'Ã®': 'î', 'Ã´': 'ô', 'Ã»': 'û',
      'Ã¤': 'ä', 'Ã«': 'ë', 'Ã¯': 'ï', 'Ã¶': 'ö', 'Ã¼': 'ü',
      'Ã§': 'ç', 'Ã	1': 'Ñ'
    };
    let out = str;
    Object.keys(map).forEach(k => {
      out = out.split(k).join(map[k]);
    });
    return out;
  } catch (e) {
    return str;
  }
};

const isValidJWT = (token) => {
  if (!token) return false;
  try {
    const payload = parseJWT(token);
    if (!payload) return false;
    if (payload.exp) {
      const now = Math.floor(Date.now() / 1000);
      if (payload.exp < now) return false;
    }
    return true;
  } catch (e) {
    return false;
  }
};

const clearAuthData = () => {
  try {
    localStorage.removeItem('authToken');
    sessionStorage.removeItem('authToken');
    localStorage.removeItem('jwt');
    sessionStorage.removeItem('jwt');
    localStorage.removeItem('organizationName');
    localStorage.removeItem('organizationId');
    localStorage.removeItem('organizationUuid');
  } catch (e) {
    // ignore
  }
};

const hasValidOrganization = () => {
  try {
    const jwt = getJWTFromStorage();
    if (!jwt || !isValidJWT(jwt)) return false;
    const payload = parseJWT(jwt);
    if (!payload) return false;
    return !!(payload.organizationId || localStorage.getItem('organizationId'));
  } catch (e) {
    return false;
  }
};

const getOrganizationNameById = async (organizationId) => {
  try {
    if (!organizationId) return '';
    if (!DATABASE_API) return '';
    const response = await makeAuthenticatedRequest(`${DATABASE_API}/api/org-name/${organizationId}`);
    if (response && response.ok) {
      const data = await response.json();
      if (data && data.success && data.data) {
        return data.data.displayName || data.data.name || '';
      }
    }
    return '';
  } catch (e) {
    return '';
  }
};

const getOrganizationInfo = async (orgId, orgCode) => {
  try {
    if (!orgId || !orgCode) return null;
    
    // Construir la URL de la API
    const apiUrl = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' 
      ? 'http://localhost:3001' 
      : 'https://api.esperiency.com';
    
    const response = await fetch(`${apiUrl}/api/org-info`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        orgId: orgId,
        orgCode: orgCode
      })
    });
    
    if (response && response.ok) {
      const data = await response.json();
      if (data && data.success) {
        return data.organization;
      }
    }
    return null;
  } catch (e) {
    console.error('Error obteniendo información de organización:', e);
    return null;
  }
};

// Nueva función para obtener orgId desde Firestore y actualizar URL
const getOrgIdFromFirestore = async (jwt) => {
  try {
    const payload = parseJWT(jwt);
    if (!payload || !payload.organizationCode) {
      console.log('❌ No hay código de organización en el JWT');
      return null;
    }

    console.log('🔍 Obteniendo orgId desde Firestore para código:', payload.organizationCode);
    
    // Construir la URL de la API
    const apiUrl = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' 
      ? 'http://localhost:3001' 
      : 'https://api.esperiency.com';
    
    const response = await fetch(`${apiUrl}/api/get-org-id-by-code`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        organizationCode: payload.organizationCode
      })
    });
    
    if (response && response.ok) {
      const data = await response.json();
      if (data && data.success && data.orgId) {
        console.log('✅ OrgId encontrado en Firestore:', data.orgId);
        
        // Actualizar la URL con el orgId encontrado
        const currentUrl = new URL(window.location);
        currentUrl.searchParams.set(data.orgId, ''); // Agregar el orgId como parámetro
        
        // Actualizar la URL sin recargar la página
        window.history.replaceState({}, '', currentUrl);
        
        console.log('🔄 URL actualizada con orgId:', currentUrl.href);
        
        return data.orgId;
      }
    }
    
    console.log('❌ No se pudo obtener orgId desde Firestore');
    return null;
  } catch (error) {
    console.error('❌ Error obteniendo orgId desde Firestore:', error);
    return null;
  }
};

const getOrganizationNameByCode = async (orgCode) => {
  try {
    if (!orgCode) return { name: '', id: '' };
    
    // Construir la URL de la API
    const apiUrl = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' 
      ? 'http://localhost:3001' 
      : 'https://api.esperiency.com';
    
    const response = await fetch(`${apiUrl}/api/org-name-by-code/${orgCode}`);
    
    if (response && response.ok) {
      const data = await response.json();
      if (data && data.success) {
        return {
          name: data.organizationName || '',
          id: data.organizationId || ''
        };
      }
    }
    return { name: '', id: '' };
  } catch (e) {
    console.error('Error obteniendo nombre de organización por código:', e);
    return { name: '', id: '' };
  }
};

const getOrgIdFromUrl = () => {
  // Extraer orgId de la URL tipo /App/index.html?orgId
  const urlParams = new URLSearchParams(window.location.search);
  
  // Primero buscar en query parameters normales
  const orgIdParam = urlParams.get('orgId');
  if (orgIdParam) {
    return decodeURIComponent(orgIdParam);
  }
  
  // Si no hay parámetro orgId, usar el primer parámetro sin nombre (query string simple)
  const queryString = window.location.search;
  if (queryString && queryString.startsWith('?')) {
    const rawQuery = queryString.substring(1); // Quitar el ?
    // Si no contiene = entonces es solo el orgId
    if (!rawQuery.includes('=')) {
      return decodeURIComponent(rawQuery);
    }
  }
  
  return null;
};

const loadDashboardData = async () => {
  const cacheKey = 'dashboard';
  const cachedData = getCachedData(cacheKey);
  if (cachedData) {
    return cachedData;
  }

  try {
    const response = await makeAuthenticatedRequest(`${DATABASE_API}/api/dashboard`);
    if (response && response.ok) {
      const data = await response.json();
      setCachedData(cacheKey, data);
      return data;
    }
  } catch (error) {
  }
  return null;
};

const loadPaymentsData = async () => {
  
  const cacheKey = 'payments';
  const cachedData = getCachedData(cacheKey);
  if (cachedData) {
    return cachedData;
  }
  
  try {
    const response = await makeAuthenticatedRequest(`${DATABASE_API}/api/payments`);
    if (response && response.ok) {
      const data = await response.json();
      setCachedData(cacheKey, data);
      return data;
    }
  } catch (error) {
  }
  return null;
};

const loadNotificationsData = async () => {
  const cacheKey = 'notifications';
  const cachedData = getCachedData(cacheKey);
  if (cachedData) {
    return cachedData;
  }
  
  try {
    const response = await makeAuthenticatedRequest(`${DATABASE_API}/api/notifications`);
    if (response && response.ok) {
      const data = await response.json();
      setCachedData(cacheKey, data);
      return data;
    }
  } catch (error) {
  }
  return null;
};

const loadApartmentsData = async () => {
  const cacheKey = 'apartments';
  const cachedData = getCachedData(cacheKey);
  if (cachedData) {
    return cachedData;
  }
  
  try {
    const response = await makeAuthenticatedRequest(`${DATABASE_API}/api/apartments`);
    if (response && response.ok) {
      const data = await response.json();
      setCachedData(cacheKey, data);
      return data;
    }
  } catch (error) {
  }
  return null;
};

const getMenuItems1 = (isCollapsed, setCurrentPage, currentPage) => [
  {
    title: "Reportes",
    Icon: () => React.createElement('i', { className: `fas fa-chart-bar ${isCollapsed ? 'size-6' : 'size-5'} ${currentPage === 'reportes' ? 'text-white' : 'text-[#626367]'}` }),
    count: 0,
    page: 'reportes'
  },
  {
    title: "Inquilinos",
    Icon: () => React.createElement('i', { className: `fas fa-users ${isCollapsed ? 'size-6' : 'size-5'} ${currentPage === 'inquilinos' ? 'text-white' : 'text-[#626367]'}` }),
    page: 'inquilinos'
  },
  {
    title: "Administrar",
    Icon: () => React.createElement('i', { className: `fas fa-cogs ${isCollapsed ? 'size-6' : 'size-5'} ${currentPage === 'administrar' ? 'text-white' : 'text-[#626367]'}` }),
    page: 'administrar'
  },
  {
    title: "Analitica",
    Icon: () => React.createElement('i', { className: `fas fa-chart-line ${isCollapsed ? 'size-6' : 'size-5'} ${currentPage === 'analitica' ? 'text-white' : 'text-[#626367]'}` }),
    page: 'analitica'
  },
    {
    title: "Tareas",
    Icon: () => React.createElement('i', { className: `fas fa-tasks ${isCollapsed ? 'size-6' : 'size-5'} ${currentPage === 'tareas' ? 'text-white' : 'text-[#626367]'}` }),
    page: 'tareas'
  },
      {
    title: "Departamentos",
    Icon: () => React.createElement('i', { className: `fas fa-building ${isCollapsed ? 'size-6' : 'size-5'} ${currentPage === 'departamentos' ? 'text-white' : 'text-[#626367]'}` }),
    page: 'departamentos'
  },
      {
    title: "Mantenimiento",
    Icon: () => React.createElement('i', { className: `fas fa-wrench ${isCollapsed ? 'size-6' : 'size-5'} ${currentPage === 'mantenimiento' ? 'text-white' : 'text-[#626367]'}` }),
    page: 'mantenimiento'
  },
  
];

const getMenuItems2 = (isCollapsed, setCurrentPage, currentPage) => [
  {
    title: "Soporte",
    Icon: () => React.createElement('i', { className: `fas fa-headset ${isCollapsed ? 'size-6' : 'size-5'} ${currentPage === 'soporte' ? 'text-white' : 'text-[#626367]'}` }),
    page: 'soporte'
  },
  {
    title: "Chat Inteligente",
    Icon: () => React.createElement('i', { className: `fas fa-robot ${isCollapsed ? 'size-6' : 'size-5'} ${currentPage === 'chat' ? 'text-white' : 'text-[#626367]'}` }),
    page: 'chat'
  },
  {
    title: "Configuracion",
    Icon: () => React.createElement('i', { className: `fas fa-cog ${isCollapsed ? 'size-6' : 'size-5'} ${currentPage === 'configuracion' ? 'text-white' : 'text-[#626367]'}` }),
    page: 'configuracion'
  },
];


const dashboardItems = [];


const rightSidebarItems = [];

const notifications = [];

const statusItems = [];

function SidebarLeft({ isCollapsed, setIsCollapsed, currentPage, setCurrentPage }) {

  const [organizationName, setOrganizationName] = React.useState('Cargando...');
  const [userInfo, setUserInfo] = React.useState({
    fullName: 'Cargando...',
    firstName: '',
    lastName: '',
    role: 'user',
    email: '',
    organizationRole: 'member'
  });
  
  const [userMenuOpen, setUserMenuOpen] = React.useState(false);
  

  const organizationLoaded = React.useRef(false);

  // Función para asociar usuario con organización (actualizar JWT)
  const updateUserOrganization = async (organizationId, organizationName, organizationCode) => {
    try {
      console.log('🔄 Asociando usuario con organización:', {
        organizationId,
        organizationName,
        organizationCode
      });
      
      const apiUrl = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' 
        ? 'http://localhost:3001' 
        : 'https://api.esperiency.com';
      
      const token = getJWTFromStorage();
      if (!token) {
        console.error(' No hay token JWT para actualizar');
        return;
      }
      
      const response = await fetch(`${apiUrl}/api/update-user-organization`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          organizationId: organizationId,
          organizationName: organizationName,
          organizationCode: organizationCode,
          organizationRole: 'usuario'
        })
      });
      
      if (response.ok) {
        const result = await response.json();
        if (result.success && result.token) {
          // Actualizar el token en localStorage
          localStorage.setItem('authToken', result.token);
          console.log(' Usuario asociado con organización y JWT actualizado');
        } else {
          console.error(' Error en respuesta del servidor:', result);
        }
      } else {
        const errorText = await response.text();
        console.error(' Error asociando usuario con organización:', response.status, errorText);
      }
    } catch (error) {
      console.error(' Error en updateUserOrganization:', error);
    }
  };
  
  const supportContainerRef = React.useRef(null);
  const bubble1Ref = React.useRef(null);
  const bubble2Ref = React.useRef(null);
  const bubble3Ref = React.useRef(null);
  const contentRef = React.useRef(null);
  const iconRef = React.useRef(null);
  const titleRef = React.useRef(null);
  const descriptionRef = React.useRef(null);
  const buttonRef = React.useRef(null);

  const getUserInitials = (firstName, lastName) => {
    const first = firstName?.charAt(0)?.toUpperCase() || '';
    const last = lastName?.charAt(0)?.toUpperCase() || '';
    return first + last || 'U';
  };

  const getRoleDisplayName = (role, organizationRole) => {
    if (organizationRole === 'admin') return 'Administrador';
    if (role === 'admin') return 'Administrador';
    if (role === 'user') return 'Usuario';
    return 'Miembro';
  };

  const toggleUserMenu = (e) => {
    e.stopPropagation();
    setUserMenuOpen(!userMenuOpen);
  };

  const toggleSidebar = () => {
    setIsCollapsed(!isCollapsed);
    setUserMenuOpen(false);
  };

  const handleMenuItemClick = (action) => {
    setUserMenuOpen(false);
    switch (action) {
      case 'personalizar':
        break;
      case 'configuracion':
        break;
      case 'cerrar-sesion':
        localStorage.removeItem('authToken');
        sessionStorage.removeItem('authToken');
        localStorage.removeItem('jwt');
        sessionStorage.removeItem('jwt');
        localStorage.removeItem('organizationName');
        localStorage.removeItem('organizationId');
        localStorage.removeItem('organizationUuid');
        window.location.href = './Login/index.html';
        break;
    }
  };

  React.useEffect(() => {
    const handleClickOutside = () => {
      if (userMenuOpen) {
        setUserMenuOpen(false);
      }
    };

    if (userMenuOpen) {
      document.addEventListener('click', handleClickOutside);
    }

    return () => {
      document.removeEventListener('click', handleClickOutside);
    };
  }, [userMenuOpen]);

  React.useEffect(() => {
    const jwtToken = getJWTFromStorage();
    const host = window.location.hostname || '';
    const params = new URLSearchParams(window.location.search || '');
    const wantsTutorial = params.has('tutorial') || localStorage.getItem('esperiency_open_tutorial') === '1';
    const isCloudDemo =
      host.endsWith('.pages.dev') ||
      host.endsWith('.workers.dev') ||
      localStorage.getItem('esperiency_tutorial_demo') === '1';

    // En preview/producción Cloudflare sin sesión: modo demo para poder usar el tutorial
    if ((!jwtToken || !isValidJWT(jwtToken)) && (isCloudDemo || wantsTutorial)) {
      localStorage.setItem('esperiency_tutorial_demo', '1');
      setOrganizationName('Demo Esperiency');
      setUserInfo({
        fullName: 'Usuario demo',
        firstName: 'Demo',
        lastName: '',
        role: 'demo',
        email: 'demo@esperiency.pages.dev',
        organizationRole: 'member'
      });
      return;
    }

    if (!jwtToken || !isValidJWT(jwtToken)) {
      clearAuthData();
      window.location.href = './Login/index.html';
      setOrganizationName('Sin autenticación válida');
      setUserInfo({
        fullName: 'Usuario no autenticado',
        firstName: '',
        lastName: '',
        role: 'guest',
        email: '',
        organizationRole: 'none'
      });
      return;
    }
    
    const payload = parseJWT(jwtToken);
    
    if (payload) {
      const firstName = fixUTF8String(payload?.firstName || '');
      const lastName = fixUTF8String(payload?.lastName || '');
      const fullName = fixUTF8String(payload?.fullName) || `${firstName} ${lastName}`.trim() || 'Usuario';
      
      setUserInfo({
        fullName: fullName,
        firstName: firstName,
        lastName: lastName,
        role: payload?.role || 'user',
        email: payload?.email || '',
        organizationRole: payload?.organizationRole || 'member'
      });
      const orgName = localStorage.getItem('organizationName') || payload?.organizationName || null;
      if (orgName) {
        setOrganizationName(orgName);
      }
    }
    if (!hasValidOrganization()) {
      setOrganizationName('Sin organización configurada');
    }
    
    // Intentar obtener el orgId de la URL primero (formato ?orgId)
    let orgIdFromUrl = getOrgIdFromUrl();
    
    // Intentar obtener el código de organización de otros parámetros de la URL
    const urlParams = new URLSearchParams(window.location.search);
    const orgCodeFromUrl = urlParams.get('orgCode') || urlParams.get('code');
    
    let organizationId = null;
    let organizationCode = null;
    
    if (payload) {
      organizationId = payload?.organizationId;
      organizationCode = payload?.organizationCode;
    }
    
    // También verificar localStorage para el código
    const storedOrgCode = localStorage.getItem('organizationCode');
    
    // Si no hay orgId en la URL, intentar obtenerlo desde Firestore
    const loadOrgIdFromFirestore = async () => {
      const jwt = getJWTFromStorage(); // Fix: Properly define jwt variable
      if (!orgIdFromUrl && jwt) {
        console.log('🔄 No hay orgId en URL, consultando Firestore...');
        const orgIdFromFirestore = await getOrgIdFromFirestore(jwt);
        if (orgIdFromFirestore) {
          // Actualizar el orgId y continuar con el proceso
          orgIdFromUrl = orgIdFromFirestore;
          processOrganizationInfo(orgIdFromFirestore, orgCodeFromUrl, organizationCode, storedOrgCode);
        }
      }
    };
    
    // Función para procesar la información de organización
    const processOrganizationInfo = (orgId, orgCodeUrl, orgCodePayload, orgCodeStored) => {
      const finalOrgCode = orgCodeUrl || orgCodePayload || orgCodeStored;
      
      console.log('🔍 Datos de organización detectados:', {
        orgId,
        finalOrgCode,
        url: window.location.href
      });
      
      if (orgId && finalOrgCode && !organizationLoaded.current) {
        organizationLoaded.current = true;
        
        console.log('📡 Obteniendo información completa de organización...');
        getOrganizationInfo(orgId, finalOrgCode).then(orgInfo => {
          if (orgInfo && orgInfo.name) {
            setOrganizationName(orgInfo.name);
            localStorage.setItem('organizationId', orgInfo.id);
            localStorage.setItem('organizationName', orgInfo.name);
            localStorage.setItem('organizationCode', orgInfo.code);
            localStorage.setItem('organizationUuid', orgInfo.uuid);
            
            // 🌐 Crear variables globales para otros componentes
            window.currentOrganizationId = orgInfo.id;
            window.currentOrganizationCode = orgInfo.code;
            window.currentOrganizationName = orgInfo.name;
            window.currentOrganizationUuid = orgInfo.uuid;
            
            console.log('✅ Información de organización cargada:', orgInfo);
            console.log('🌐 Variables globales creadas:', {
              orgId: window.currentOrganizationId,
              orgCode: window.currentOrganizationCode,
              orgName: window.currentOrganizationName
            });
            
            // 🔄 Asociar usuario con la organización (actualizar JWT)
            updateUserOrganization(orgInfo.id, orgInfo.name, orgInfo.code);
          } else {
            setOrganizationName('Organización no encontrada');
          }
        }).catch(error => {
          console.error('Error obteniendo información de organización:', error);
          setOrganizationName('Error de conexión');
        });
      }
    };
    
    const finalOrgId = orgIdFromUrl || organizationId;
    const finalOrgCode = orgCodeFromUrl || organizationCode || storedOrgCode;
    
    // Procesar inmediatamente si ya tenemos orgId
    if (orgIdFromUrl) {
      processOrganizationInfo(finalOrgId, orgCodeFromUrl, organizationCode, storedOrgCode);
    } else {
      // Si no hay orgId, intentar obtenerlo desde Firestore
      loadOrgIdFromFirestore();
    }
    
    console.log('🔍 Datos de organización detectados:', {
      orgIdFromUrl,
      finalOrgId,
      finalOrgCode,
      url: window.location.href
    });
    
    if (finalOrgId && finalOrgCode && !organizationLoaded.current) {
      organizationLoaded.current = true;
      
      console.log('📡 Obteniendo información completa de organización...');
      // Usar tanto el ID como el código para obtener la información completa de la organización
      getOrganizationInfo(finalOrgId, finalOrgCode).then(orgInfo => {
        if (orgInfo && orgInfo.name) {
          setOrganizationName(orgInfo.name);
          // Guardar información adicional en localStorage
          localStorage.setItem('organizationId', orgInfo.id);
          localStorage.setItem('organizationName', orgInfo.name);
          localStorage.setItem('organizationCode', orgInfo.code);
          localStorage.setItem('organizationUuid', orgInfo.uuid);
          console.log('✅ Información de organización cargada:', orgInfo);
        } else {
          setOrganizationName('Organización no encontrada');
        }
      }).catch(error => {
        console.error('Error obteniendo información de organización:', error);
        setOrganizationName('Error cargando organización');
      });
    } else if (finalOrgCode && !organizationLoaded.current && !finalOrgId) {
      // Fallback al método anterior si solo hay código pero no ID
      organizationLoaded.current = true;
      
      console.log('📡 Obteniendo organización solo por código...');
      getOrganizationNameByCode(finalOrgCode).then(result => {
        if (result.name) {
          setOrganizationName(result.name);
          // Guardar el ID para futuras referencias
          if (result.id) {
            localStorage.setItem('organizationId', result.id);
          }
        } else {
          setOrganizationName('Organización no encontrada');
        }
      }).catch(error => {
        console.error('Error obteniendo organización por código:', error);
        setOrganizationName('Error cargando organización');
      });
    } else if (organizationId && !organizationLoaded.current && !finalOrgCode && !finalOrgId) {
      // Fallback al método más antiguo si solo hay ID pero no código
      organizationLoaded.current = true;
      
      console.log('📡 Obteniendo organización solo por ID (método legacy)...');
      getOrganizationNameById(organizationId).then(orgName => {
        if (orgName) {
          setOrganizationName(orgName);
        } else {
          setOrganizationName('Organización no encontrada');
        }
      }).catch(error => {
        setOrganizationName('Error cargando organización');
      });
    }
    if (typeof gsap !== 'undefined') {
      const tl = gsap.timeline();
      gsap.set([supportContainerRef.current, bubble1Ref.current, bubble2Ref.current, bubble3Ref.current, iconRef.current, titleRef.current, descriptionRef.current, buttonRef.current], {
        opacity: 0,
        scale: 0.8,
        y: 30
      });
      tl.to(supportContainerRef.current, {
        opacity: 1,
        scale: 1,
        y: 0,
        duration: 0.8,
        ease: "back.out(1.7)"
      })
      .to([bubble1Ref.current, bubble2Ref.current, bubble3Ref.current], {
        opacity: 1,
        scale: 1,
        y: 0,
        duration: 0.6,
        stagger: 0.1,
        ease: "elastic.out(1, 0.3)"
      }, "-=0.4")
      .to(iconRef.current, {
        opacity: 1,
        scale: 1,
        y: 0,
        duration: 0.5,
        ease: "back.out(2)"
      }, "-=0.3")
      .to([titleRef.current, descriptionRef.current], {
        opacity: 1,
        scale: 1,
        y: 0,
        duration: 0.4,
        stagger: 0.1,
        ease: "power2.out"
      }, "-=0.3")
      .to(buttonRef.current, {
        scale: 1,
        y: 0,
        duration: 0.3,
        ease: "back.out(1.5)"
      }, "-=0.1");
    }

    
  }, []);
  
  return (
    <div className={`fixed left-0 inset-y-0 flex-col p-4 hidden xl:flex overflow-x-hidden overflow-y-auto transition-all duration-300 ease-in-out ${isCollapsed ? 'w-16' : 'w-64'}`}>
      <div className="shrink-0 flex items-center justify-between">
        {!isCollapsed && <div className="text-white font-semibold text-lg truncate">{organizationName}</div>}
        <div 
          className="size-8 rounded-full grid place-items-center border-2 border-[#252628] text-white cursor-pointer hover:bg-[#252628] transition-colors"
          onClick={toggleSidebar}
        >
          <svg className={`size-5 transition-transform duration-300 ${isCollapsed ? 'rotate-180' : ''}`} strokeWidth={3} viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path d="m15 18-6-6 6-6"/>
          </svg>
        </div>
      </div>
      
      <div className="shrink-0 relative">
        <div 
          className={`flex items-center p-2 mt-3 transition-colors ${
            isCollapsed 
              ? 'justify-center' 
              : 'bg-[#1b1c20] rounded-md hover:bg-[#252628] cursor-pointer'
          }`}
          onClick={isCollapsed ? undefined : toggleUserMenu}
        >
          <div 
            className={`size-9 rounded-full flex items-center justify-center text-white font-semibold text-sm transition-all duration-300 flex-shrink-0 ${
              isCollapsed ? 'cursor-pointer' : ''
            }`}
            style={{
              background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)'
            }}
          >
            {getUserInitials(userInfo.firstName, userInfo.lastName)}
          </div>
          {!isCollapsed && (
            <>
              <div className="ml-2">
                <div className="font-semibold text-white cursor-pointer select-none">{userInfo.fullName}</div>
                <div className="text-[#7a7d82] cursor-pointer select-none">{getRoleDisplayName(userInfo.role, userInfo.organizationRole)}</div>
              </div>
              <svg className="size-4 ml-auto text-[#7a7d82] cursor-pointer" strokeWidth={3} viewBox="0 0 24 24" fill="none" stroke="currentColor">
                <circle cx="12" cy="12" r="1"/>
                <circle cx="12" cy="5" r="1"/>
                <circle cx="12" cy="19" r="1"/>
              </svg>
            </>
          )}
        </div>


        {userMenuOpen && !isCollapsed && (
          <div 
            className="absolute top-full left-0 w-full mt-2 bg-[#1b1c20] rounded-md shadow-lg border border-[#252628] py-1 z-50 animate-slideDown"
            style={{
              animation: 'slideDown 0.2s ease-out forwards',
              transformOrigin: 'top'
            }}
          >
            <button
              onClick={() => handleMenuItemClick('personalizar')}
              className="w-full flex items-center px-3 py-2 text-sm text-white hover:bg-gray-600 hover:text-white transition-colors"
            >
              <i className="fas fa-palette w-4 mr-3"></i>
              Personalizar
            </button>
            <button
              onClick={() => handleMenuItemClick('configuracion')}
              className="w-full flex items-center px-3 py-2 text-sm text-white hover:bg-gray-600 hover:text-white transition-colors"
            >
              <i className="fas fa-cog w-4 mr-3"></i>
              Configuración de usuario
            </button>
            <button
              onClick={() => handleMenuItemClick('cerrar-sesion')}
              className="w-full flex items-center px-3 py-2 text-sm text-white hover:bg-red-500 hover:text-white transition-colors"
            >
              <i className="fas fa-sign-out-alt w-4 mr-3"></i>
              Cerrar sesión
            </button>
          </div>
        )}
      </div>

      <div data-tutorial="nav-primary">
        <div className="shrink-0 py-2 mt-3 border-t-2 border-t-zinc-800">
          <button 
            data-tutorial="dashboard"
            onClick={() => setCurrentPage('dashboard')}
            className={`w-full flex items-center p-1.5 rounded-md hover:bg-[#1e1e1e] transition-all duration-300 ${isCollapsed ? 'justify-center px-0 py-2' : ''} ${
              currentPage === 'dashboard' ? 'bg-[#35383d]' : ''
            }`}
          >
            <div className={`${isCollapsed ? 'flex items-center justify-center w-full' : ''}`}>
              <svg className={`${isCollapsed ? 'size-6' : 'size-5'} shrink-0 transition-all duration-300 ${currentPage === 'dashboard' ? 'text-white' : 'text-[#626367]'}`} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <rect width="7" height="9" x="3" y="3" rx="1"/>
                <rect width="7" height="5" x="14" y="3" rx="1"/>
                <rect width="7" height="9" x="14" y="12" rx="1"/>
                <rect width="7" height="5" x="3" y="16" rx="1"/>
              </svg>
            </div>
            {!isCollapsed && <div className={`ml-2 ${currentPage === 'dashboard' ? 'text-white font-semibold' : 'text-[#c0c4cd]'}`}>Dashboard</div>}
          </button>
          <button
            type="button"
            data-tutorial="nav-tutorial"
            onClick={() => {
              if (typeof window.tutorial === 'function') window.tutorial('tour');
              else window.dispatchEvent(new CustomEvent('esperiency-tutorial-open', { detail: { mode: 'tour' } }));
            }}
            className={`w-full flex items-center p-1.5 rounded-md hover:bg-[#1e1e1e] transition-all duration-300 mt-1 ${isCollapsed ? 'justify-center px-0 py-2' : ''}`}
            title="Abrir tutorial"
          >
            <div className={`${isCollapsed ? 'flex items-center justify-center w-full' : ''}`}>
              <i className={`fas fa-graduation-cap ${isCollapsed ? 'size-6' : 'size-5'} text-[#fae0d1]`} aria-hidden="true"></i>
            </div>
            {!isCollapsed && <div className="ml-2 text-[#fae0d1] font-semibold">Tutorial</div>}
          </button>
        </div>

        <div className="shrink-0 flex flex-col py-1 border-t-2 border-t-zinc-800">
          {getMenuItems1(isCollapsed, setCurrentPage, currentPage).map(({ title, Icon, count, page }, idx) => (
            <button
              data-tutorial={`nav-${page}`}
              onClick={() => setCurrentPage(page)}
              className={`flex items-center p-1.5 rounded-md hover:bg-[#1e1e1e] transition-all duration-300 ${isCollapsed ? 'justify-center px-0 py-2' : ''} ${
                currentPage === page ? 'bg-[#35383d]' : ''
              }`}
              key={idx}
            >
              <div className={`${isCollapsed ? 'flex items-center justify-center w-full' : ''}`}>
                <Icon />
              </div>
              {!isCollapsed && (
                <>
                  <div className={`ml-2 ${currentPage === page ? 'text-white font-semibold' : 'text-[#c0c4cd]'}`}>{title}</div>
                  {count > 0 && (
                    <div className="grid place-items-center size-6 bg-[#fae0d1] text-black rounded-md ml-auto text-sm font-semibold">
                      {count}
                    </div>
                  )}
                </>
              )}
            </button>
          ))}
        </div>
      </div>

      <div className="grow flex flex-col py-1 mt-1 border-t-2 border-t-zinc-800">
        {getMenuItems2(isCollapsed, setCurrentPage, currentPage).map(({ title, Icon, page }, idx) => (
          <button
            onClick={() => setCurrentPage(page)}
            className={`flex items-center p-1.5 rounded-md hover:bg-[#1e1e1e] transition-all duration-300 ${isCollapsed ? 'justify-center px-0 py-2' : ''} ${
              currentPage === page ? 'bg-[#35383d]' : ''
            }`}
            key={idx}
          >
            <div className={`${isCollapsed ? 'flex items-center justify-center w-full' : ''}`}>
              <Icon />
            </div>
            {!isCollapsed && <div className={`ml-2 ${currentPage === page ? 'text-white font-semibold' : 'text-[#c0c4cd]'}`}>{title}</div>}
          </button>
        ))}
      </div>

      {!isCollapsed && (
        <div
          ref={supportContainerRef}
          className="shrink-0 aspect-[4/3] mt-4 rounded-lg overflow-hidden relative group cursor-pointer hover-parent transition-all duration-300"
          style={{ background: 'linear-gradient(45deg, #ff006e, #8338ec, #3a86ff, #06ffa5)' }}
        >

        <div className="absolute inset-0 opacity-60">
          <div 
            ref={bubble1Ref}
            className="absolute w-20 h-20 bg-gradient-to-r from-purple-400 to-pink-400 rounded-full blur-xl animate-pulse transition-transform duration-1000 group-hover:scale-105 group-hover:translate-x-2"
            style={{
              top: '15%',
              left: '15%',
              animationDelay: '0s'
            }}
          ></div>
          <div 
            ref={bubble2Ref}
            className="absolute w-16 h-16 bg-gradient-to-r from-blue-400 to-cyan-400 rounded-full blur-lg animate-pulse transition-transform duration-1200 group-hover:scale-103 group-hover:-translate-y-1"
            style={{
              top: '50%',
              right: '20%',
              animationDelay: '0.5s'
            }}
          ></div>
          <div 
            ref={bubble3Ref}
            className="absolute w-14 h-14 bg-gradient-to-r from-green-400 to-yellow-400 rounded-full blur-lg animate-pulse transition-transform duration-1100 group-hover:scale-102 group-hover:translate-x-1"
            style={{
              bottom: '25%',
              left: '40%',
              animationDelay: '1s'
            }}
          ></div>
        </div>
        

        <div ref={contentRef} className="relative z-20 flex flex-col items-center justify-center h-full text-center px-4">

          <div ref={iconRef} className="mb-2 transition-transform duration-500 group-hover:scale-102">
            <i className="fas fa-rocket text-lg text-white"></i>
          </div>
          
          <div ref={titleRef} className="text-sm font-semibold text-white drop-shadow-lg">
            Bienvenido a la Versión Release 1.0
          </div>
          <div ref={descriptionRef} className="text-xs text-white/90 mt-1 mb-3 drop-shadow">
            Bienvenido a la primera versión de Esperiency Management
          </div>
          

          <button ref={buttonRef} className="hover-button relative z-30 px-4 py-1.5 bg-white/20 backdrop-blur-md hover:bg-white/30 text-white text-xs font-medium rounded-full border border-white/30 transition-all duration-400 opacity-0">
            Ver más
          </button>
        </div>
        </div>
      )}
    </div>
  );
}

function Dashboard() {
  return (
    <>
      <div className="px-4">
        <div className="text-lg font-semibold text-white">Dashboard</div>
        <div className="p-1 bg-[#000000] rounded-md mt-1">
          <div className="grid grid-cols-3 gap-2">
            {dashboardItems.map(({ title, Icon }, idx) => (
              <div
                className={`py-2 rounded-md flex items-center justify-center space-x-2 ${
                  idx === 0 ? "bg-[#35383d] text-white" : "text-[#575757] hover:bg-[#1a1a1a]"
                }`}
                key={idx}
              >
                <Icon />
                <div className="text-sm">{title}</div>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="flex items-center mt-2 px-4">
        <svg className="size-5 text-[#6e7176]" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
          <circle cx="9" cy="7" r="4"/>
          <path d="M22 21v-2a4 4 0 0 0-3-3.87"/>
          <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
        </svg>
        <div className="ml-2 text-base font-semibold text-white">Deudores</div>
        <div className="inline-flex items-center ml-auto space-x-3">
          <div className="bg-[#35383d] px-2 py-0.5 rounded-md text-white text-sm">All</div>
          <div className="bg-[#35383d] px-2 py-0.5 rounded-md text-white text-sm">Todos los deudores</div>
        </div>
      </div>
      <CampaignSlider />
    </>
  );
}

function CampaignSlider() {
  React.useEffect(() => {
    if (typeof Swiper !== 'undefined') {
      new Swiper(".mySwiper", {
        slidesPerView: "auto",
        spaceBetween: 16,
        slidesOffsetBefore: 16,
        slidesOffsetAfter: 40,
      });
    }
  }, []);

  return (
    <div className="mt-3 relative">
      <div className="swiper mySwiper">
        <div className="swiper-wrapper">
          {campaigns.map(({ title, redemptions, remaining, color }, idx) => (
            <div
              className="swiper-slide rounded-md p-3 select-none cursor-pointer"
              key={idx}
              style={{ background: color, height: '105px', width: '220px' }}
            >
              <div className="flex items-center border-b-2 border-b-[#6464648c] pb-2">
                <div className="size-3 rounded-full bg-[#37363e]"></div>
                <div className="ml-2 font-semibold text-[#37363e]">{title}</div>
                <svg className="size-5 ml-auto text-[#555]" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <circle cx="12" cy="12" r="1"/>
                  <circle cx="19" cy="12" r="1"/>
                  <circle cx="5" cy="12" r="1"/>
                </svg>
              </div>

              <div className="grid grid-cols-2 mt-3">
                <div>
                  <div className="text-[#555]">Remaining</div>
                  <div className="flex items-center space-x-2">
                    <svg className="size-4 text-[#555]" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <circle cx="12" cy="12" r="10"/>
                      <polyline points="12,6 12,12 16,14"/>
                    </svg>
                    <div className="text-[#37363e] font-semibold">{remaining}</div>
                  </div>
                </div>

                <div>
                  <div className="text-[#555]">Reportes</div>
                  <div className="flex items-center space-x-2">
                    <svg className="size-4 text-[#555]" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                      <path d="M3 3v18h18" />
                      <path d="M18.7 8l-5.1 5.2-2.8-2.7L7 14.3" />
                    </svg>
                    <div className="text-[#37363e] font-semibold">{redemptions}</div>
                  </div>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      <div
        className="absolute inset-y-0 w-4 z-10"
        style={{
          background: "linear-gradient(90deg, #18181B 0%, rgba(24, 24, 27, 0) 100%)",
          left: "0px",
        }}
      ></div>
      <div
        className="absolute inset-y-0 w-20 z-10"
        style={{
          background: "linear-gradient(90deg, rgba(24, 24, 27, 0) 0%, #18181B 100%)",
          right: "0px",
        }}
      ></div>

      <button
        className="size-9 absolute rounded-full z-20 bg-white grid place-items-center"
        style={{ right: "8px", top: "32px" }}
      >
        <svg className="size-5 text-zinc-900" strokeWidth={3} viewBox="0 0 24 24" fill="none" stroke="currentColor">
          <path d="m9 18 6-6-6-6"/>
        </svg>
      </button>
    </div>
  );
}
const paymentData = [];

const ingresosData = [];

const recentPayments = [];

function GlobalSearchBar({ onNavigate }) {
  const [query, setQuery] = React.useState('');
  const shortcuts = [
    { label: 'Dashboard', page: 'dashboard' },
    { label: 'Inquilinos', page: 'inquilinos' },
    { label: 'Analítica', page: 'analitica' },
    { label: 'Tareas', page: 'tareas' },
    { label: 'Departamentos', page: 'departamentos' },
    { label: 'Configuración', page: 'configuracion' },
  ];
  const filtered = query.trim()
    ? shortcuts.filter((s) => s.label.toLowerCase().includes(query.trim().toLowerCase()))
    : [];

  return (
    <div className="relative mb-6" data-tutorial="search">
      <div className="flex items-center gap-3 rounded-xl px-4 py-3 bg-[#1b1c20] border border-white/10">
        <i className="fas fa-search text-[#8b8f97]" aria-hidden="true"></i>
        <input
          type="search"
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          placeholder="Buscar módulos… (inquilinos, tareas, analítica)"
          className="w-full bg-transparent outline-none text-white placeholder:text-[#6e7176]"
          aria-label="Búsqueda rápida"
        />
      </div>
      {filtered.length > 0 && (
        <div className="absolute left-0 right-0 mt-2 rounded-xl bg-[#1b1c20] border border-white/10 shadow-2xl z-30 overflow-hidden">
          {filtered.map((item) => (
            <button
              key={item.page}
              type="button"
              className="w-full text-left px-4 py-3 text-sm text-gray-200 hover:bg-white/5"
              onClick={() => {
                setQuery('');
                if (typeof onNavigate === 'function') onNavigate(item.page);
                else if (typeof window.setCurrentPage === 'function') window.setCurrentPage(item.page);
              }}
            >
              {item.label}
            </button>
          ))}
        </div>
      )}
    </div>
  );
}

function PaymentGraph() {
  const drawn = React.useRef(false);

  React.useEffect(() => {
    if (!drawn.current) {
      drawn.current = true;
      drawPaymentGraph();
    }
  }, []);

  return (
    <div className="bg-[#1b1c20] rounded-lg p-6" data-tutorial="dashboard-widgets">
      <div className="flex items-center justify-between mb-4">
        <div>
          <div className="flex items-center">
            <svg className="size-5 text-[#606165] mr-2" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/>
              <path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/>
            </svg>
            <div className="text-lg font-semibold text-white">Pagos de Inquilinos</div>
          </div>
          <div className="text-sm text-gray-400 mt-1">Seguimiento mensual de pagos 2025</div>
        </div>
        <div className="inline-flex items-center space-x-2 p-1 rounded-md bg-[#35383d]">
          <button className="px-3 py-1 bg-[#fae0d1] text-[#1b1c20] rounded-md text-sm font-semibold">
            2025
          </button>
          <button className="px-3 py-1 rounded-md text-white text-sm hover:bg-[#4a4d52]">
            2024
          </button>
        </div>
      </div>
      <div className="h-[300px]" id="payment-graph-container"></div>
    </div>
  );
}
function IngresosGraph() {
  const drawn = React.useRef(false);

  React.useEffect(() => {
    if (!drawn.current) {
      drawn.current = true;
      drawIngresosGraph();
    }
  }, []);

  return (
    <div className="bg-[#1b1c20] rounded-lg p-6">
      <div className="flex items-center justify-between mb-4">
        <div>
          <div className="flex items-center">
            <svg className="size-5 text-[#606165] mr-2" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
              <path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/>
            </svg>
            <div className="text-lg font-semibold text-white">Ingresos por Departamento</div>
          </div>
          <div className="text-sm text-gray-400 mt-1">Departamentos con mayores ingresos</div>
        </div>
        <div className="inline-flex items-center space-x-2 p-1 rounded-md bg-[#35383d]">
          <button className="px-3 py-1 bg-[#fae0d1] text-[#1b1c20] rounded-md text-sm font-semibold">
            Este mes
          </button>
          <button className="px-3 py-1 rounded-md text-white text-sm hover:bg-[#4a4d52]">
            Año
          </button>
        </div>
      </div>
      <div className="h-[300px]" id="ingresos-graph-container"></div>
    </div>
  );
}

function PaymentWidget() {
  const totalRevenue = recentPayments.reduce((sum, payment) => sum + (payment.amount || 0), 0);
  const totalPaidThisMonth = (paymentData && paymentData.length)
    ? (paymentData.find(d => d.current)?.paid || 0)
    : 0;
  const totalApartments = (paymentData && paymentData.length)
    ? (paymentData.find(d => d.current)?.total || paymentData[0].total || 0)
    : 0;
  
  return (
    <div className="bg-[#1b1c20] rounded-lg p-8 mt-8">
      <div className="flex items-center mb-8">
        <svg className="size-6 text-[#606165] mr-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <rect width="20" height="14" x="2" y="5" rx="2"/>
          <line x1="2" y1="10" x2="22" y2="10"/>
        </svg>
        <div className="text-xl font-semibold text-white">Resumen de Ingresos</div>
      </div>
      
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-8">
        <div className="bg-[#35383d] rounded-lg p-6">
          <div className="flex items-center justify-between mb-3">
            <div className="text-sm text-gray-400">Total Ingresos</div>
            <div className="size-10 bg-green-500 rounded-full grid place-items-center">
              <svg className="size-5 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/>
              </svg>
            </div>
          </div>
          <div className="text-3xl font-bold text-white mb-2">${totalRevenue.toLocaleString()}</div>
          <div className="text-sm text-gray-400">Sin datos</div>
        </div>
        
        <div className="bg-[#35383d] rounded-lg p-6">
          <div className="flex items-center justify-between mb-3">
            <div className="text-sm text-gray-400">Inquilinos Pagaron</div>
            <div className="size-10 bg-blue-500 rounded-full grid place-items-center">
              <svg className="size-5 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/>
                <circle cx="9" cy="7" r="4"/>
                <path d="M22 21v-2a4 4 0 0 0-3-3.87"/>
                <path d="M16 3.13a4 4 0 0 1 0 7.75"/>
              </svg>
            </div>
          </div>
          <div className="text-3xl font-bold text-white mb-2">{totalPaidThisMonth}/{totalApartments}</div>
          <div className="text-sm text-gray-400">
            {totalApartments > 0 ? `${((totalPaidThisMonth/totalApartments)*100).toFixed(1)}% del total` : 'Sin datos'}
          </div>
        </div>
        
        <div className="bg-[#35383d] rounded-lg p-6">
          <div className="flex items-center justify-between mb-3">
            <div className="text-sm text-gray-400">Pendientes</div>
            <div className="size-10 bg-orange-500 rounded-full grid place-items-center">
              <svg className="size-5 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <circle cx="12" cy="12" r="10"/>
                <polyline points="12,6 12,12 16,14"/>
              </svg>
            </div>
          </div>
          <div className="text-3xl font-bold text-white mb-2">{Math.max(0, totalApartments - totalPaidThisMonth)}</div>
          <div className="text-sm text-gray-400">Sin datos</div>
        </div>
      </div>
      
      <div className="mt-8">
        <div className="text-xl font-semibold text-white mb-6">Pagos Recientes</div>
        <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-4">
          {recentPayments.slice(0, 6).map((payment, idx) => (
            <div key={idx} className="flex items-center justify-between bg-[#35383d] rounded-lg p-4 hover:bg-[#404349] transition-colors">
              <div className="flex items-center min-w-0 flex-1">
                <div className="size-10 bg-[#fae0d1] rounded-full grid place-items-center mr-3 flex-shrink-0">
                  <svg className="size-5 text-[#1b1c20]" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                    <circle cx="12" cy="7" r="4"/>
                  </svg>
                </div>
                <div className="min-w-0 flex-1">
                  <div className="text-white font-medium truncate">{payment.tenant}</div>
                  <div className="text-sm text-gray-400 truncate">{payment.apartment}</div>
                </div>
              </div>
              <div className="text-right flex-shrink-0 ml-4">
                <div className="text-white font-semibold">${payment.amount}</div>
                <div className="text-sm text-gray-400">{payment.date}</div>
              </div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function ViewMoreSection() {
  const [expanded, setExpanded] = React.useState(false);

  return (
    <div className="flex flex-col items-center mt-8 mb-6">
      <button
        onClick={() => setExpanded(!expanded)}
        className="group flex items-center space-x-3 bg-[#1b1c20] hover:bg-[#35383d] px-6 py-3 rounded-lg transition-all duration-300 border border-[#35383d] hover:border-[#fae0d1]"
      >
        <svg 
          className={`size-5 text-[#fae0d1] transform transition-transform duration-300 ${expanded ? 'rotate-180' : ''}`} 
          viewBox="0 0 24 24" 
          fill="none" 
          stroke="currentColor" 
          strokeWidth="2"
        >
          <path d="M12 5v14"/>
          <path d="M5 12l7 7 7-7"/>
        </svg>
        <span className="text-white font-medium">
          {expanded ? 'Ver menos detalles' : 'Ver más detalles'}
        </span>
        <div className="size-6 bg-[#fae0d1] rounded-full grid place-items-center">
          <span className="text-[#1b1c20] text-sm font-bold">+</span>
        </div>
      </button>
      
      {expanded && (
        <div className="mt-8 w-full">
          <div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
            <DetailedPaymentHistory />
            <DetailedIngresosAnalytics />
          </div>
        </div>
      )}
    </div>
  );
}

function DetailedPaymentHistory() {
  const allPayments = [];

  return (
    <div className="bg-[#1b1c20] rounded-lg p-6 w-full">
      <div className="flex items-center mb-6">
        <svg className="size-5 text-[#fae0d1] mr-2" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="M21 12V7H5a2 2 0 0 1 0-4h14v4"/>
          <path d="M3 5v14a2 2 0 0 0 2 2h16v-5"/>
        </svg>
        <h3 className="text-lg font-semibold text-white">Historial Completo de Pagos</h3>
      </div>
      
      <div className="space-y-3 max-h-96 overflow-y-auto overflow-x-hidden pr-2">
        {allPayments.map((payment, idx) => (
          <div key={idx} className="flex items-center justify-between bg-[#35383d] rounded-lg p-4 hover:bg-[#404349] transition-colors min-w-0">
            <div className="flex items-center min-w-0 flex-1">
              <div className={`size-10 rounded-full grid place-items-center mr-4 flex-shrink-0 ${
                payment.status === 'paid' ? 'bg-green-500' : 'bg-orange-500'
              }`}>
                {payment.status === 'paid' ? (
                  <svg className="size-5 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                    <circle cx="12" cy="7" r="4"/>
                  </svg>
                ) : (
                  <svg className="size-5 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                    <circle cx="12" cy="12" r="10"/>
                    <polyline points="12,6 12,12 16,14"/>
                  </svg>
                )}
              </div>
              <div className="min-w-0 flex-1">
                <div className="text-white font-medium truncate">{payment.tenant}</div>
                <div className="text-sm text-gray-400 truncate">{payment.apartment}</div>
              </div>
            </div>
            <div className="text-right flex-shrink-0 ml-4">
              <div className="text-white font-semibold">${payment.amount}</div>
              <div className={`text-sm ${payment.status === 'paid' ? 'text-green-400' : 'text-orange-400'}`}>
                {payment.date}
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function DetailedIngresosAnalytics() {
  const detailedViews = [];

  return (
    <div className="bg-[#1b1c20] rounded-lg p-6 w-full">
      <div className="flex items-center mb-6">
        <svg className="size-5 text-[#fae0d1] mr-2" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="M12 2v20M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/>
        </svg>
        <h3 className="text-lg font-semibold text-white">Análisis detallado de ingresos</h3>
      </div>
      
      <div className="space-y-3 max-h-96 overflow-y-auto overflow-x-hidden pr-2">
        {detailedViews.map((item, idx) => (
          <div key={idx} className="bg-[#35383d] rounded-lg p-4 hover:bg-[#404349] transition-colors">
            <div className="flex items-center justify-between mb-3">
              <span className="text-white font-medium text-lg">{item.apartment}</span>
              <span className="text-[#fae0d1] text-sm font-semibold bg-[#1b1c20] px-2 py-1 rounded-md">${item.amount}</span>
            </div>
            <div className="grid grid-cols-3 gap-4 text-sm">
              <div className="text-center">
                <div className="text-gray-400 mb-1">Estado</div>
                <div className="text-white font-semibold text-lg">{item.engagement}</div>
              </div>
              <div className="text-center">
                <div className="text-gray-400 mb-1">Reportes</div>
                <div className="text-white font-semibold text-lg">{item.clicks}</div>
              </div>
              <div className="text-center">
                <div className="text-gray-400 mb-1">Mantenim.</div>
                <div className="text-white font-semibold text-lg">{item.leads}</div>
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function SidebarRight({ setSidebarExpanded, isCollapsed, setIsCollapsed }) {
  const [selectedIcon, setSelectedIcon] = React.useState(0); 
  const [currentPage, setCurrentPage] = React.useState(0);
  const [selectedTask, setSelectedTask] = React.useState(null);
  const [isModalOpen, setIsModalOpen] = React.useState(false);

  const toggleSidebar = () => {
    setIsCollapsed(!isCollapsed);
  };
  
  const extendedNotifications = [];

  const regularNotifications = [];

  const itemsPerPage = 4;
  const currentData = selectedIcon === 0 ? extendedNotifications : regularNotifications;
  const totalPages = Math.ceil(currentData.length / itemsPerPage);
  const startIndex = currentPage * itemsPerPage;
  const currentItems = currentData.slice(startIndex, startIndex + itemsPerPage);

  React.useEffect(() => {
    if (setSidebarExpanded) {
      setSidebarExpanded(true);
    }
  }, [setSidebarExpanded]);

  React.useEffect(() => {
    setCurrentPage(0);
  }, [selectedIcon]);

  return (
    <>
      <div className={`fixed inset-y-0 right-0 px-4 pb-4 pt-2 hidden xl:block flex flex-col transition-all duration-300 ease-in-out ${isCollapsed ? 'w-16' : 'w-64'}`}>

      <div className="flex items-center justify-end mb-4 flex-shrink-0">
        <div 
          className="size-8 rounded-full grid place-items-center border-2 border-[#252628] text-white cursor-pointer hover:bg-[#252628] transition-colors"
          onClick={toggleSidebar}
        >
          <svg className={`size-5 transition-transform duration-300 ${isCollapsed ? 'rotate-180' : ''}`} strokeWidth={3} viewBox="0 0 24 24" fill="none" stroke="currentColor">
            <path d="m9 18 6-6-6-6"/>
          </svg>
        </div>
      </div>

      {!isCollapsed ? (
        <>

          <div className="flex items-center justify-center pb-4 border-b-2 border-b-zinc-800 flex-shrink-0">
        {rightSidebarItems.map(({ Icon }, idx) => (
          <button
            onClick={() => {
              setSelectedIcon(idx);
            }}
            className={`mx-2 transition-all duration-200 hover:bg-opacity-90 ${
              selectedIcon === idx 
                ? "size-12 grid place-items-center rounded-lg bg-[#fae0d1] text-[#1b1c20] shadow-lg" 
                : "p-3 text-[#666] hover:text-white"
            }`}
            key={idx}
          >
            <Icon />
          </button>
        ))}
      </div>
      

      <div className="flex flex-col flex-1 mt-4 overflow-hidden h-full">

        <div className="text-white font-semibold mb-4 text-center flex-shrink-0">
          {selectedIcon === 0 ? "Tareas" : "Notificaciones"}
        </div>
        

        <div className="flex flex-col space-y-2 flex-1 overflow-hidden">
          {currentItems.map((item, idx) => {
            if (selectedIcon === 0) {
              const { title, time, category } = item;
              let borderClass = "";
              let timeColorClass = "";
              let categoryColorClass = "";
              
              if (time === "Muy alta") {
                borderClass = "border-2 border-red-600";
                timeColorClass = "text-red-500 font-bold";
                categoryColorClass = "text-red-300";
              } else if (time === "Alta") {
                borderClass = "border-2 border-orange-500";
                timeColorClass = "text-orange-400 font-semibold";
                categoryColorClass = "text-orange-300";
              } else {
                borderClass = "";
                timeColorClass = "text-[#70718e]";
                categoryColorClass = "text-[#5b5b5b]";
              }
              
              return (
                <div
                  className={`p-0.5 rounded-md transition-all duration-200 hover:bg-opacity-90 cursor-pointer ${borderClass}`}
                  key={idx}
                  onClick={() => {
                    setSelectedTask(item);
                    setIsModalOpen(true);
                  }}
                >
                  <div className="bg-zinc-950 p-3 rounded-md">
                    <div className={timeColorClass}>{time}</div>
                    <div className="mt-1 font-semibold text-white">{title}</div>
                    <div className={`mt-2 ${categoryColorClass}`}>{category}</div>
                  </div>
                </div>
              );
            } else {
              const { title, time, category, icon } = item;
              return (
                <div
                  className="p-0.5 rounded-md transition-all duration-200 hover:bg-opacity-90"
                  key={idx}
                >
                  <div className="bg-zinc-950 p-3 rounded-md">
                    <div className="flex items-center justify-between">
                      <div className="text-[#70718e] text-sm">{time}</div>
                      <div className="text-lg">{icon}</div>
                    </div>
                    <div className="mt-1 font-semibold text-white">{title}</div>
                    <div className="mt-2 text-[#5b5b5b] text-sm">{category}</div>
                  </div>
                </div>
              );
            }
          })}
        </div>
        

        {totalPages > 1 && (
          <div className="flex items-center justify-center mt-4 space-x-2 flex-shrink-0">
            <button
              onClick={() => setCurrentPage(Math.max(0, currentPage - 1))}
              disabled={currentPage === 0}
              className="size-8 grid place-items-center rounded-md bg-[#35383d] text-white hover:bg-[#4a4d52] disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
            >
              <svg className="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M15 18l-6-6 6-6"/>
              </svg>
            </button>
            
            <div className="flex space-x-1">
              {Array.from({ length: totalPages }, (_, i) => (
                <button
                  key={i}
                  onClick={() => setCurrentPage(i)}
                  className={`size-8 grid place-items-center rounded-md text-sm font-medium transition-all duration-200 ${
                    currentPage === i
                      ? "bg-[#fae0d1] text-[#1b1c20]"
                      : "bg-[#35383d] text-white hover:bg-[#4a4d52]"
                  }`}
                >
                  {i + 1}
                </button>
              ))}
            </div>
            
            <button
              onClick={() => setCurrentPage(Math.min(totalPages - 1, currentPage + 1))}
              disabled={currentPage === totalPages - 1}
              className="size-8 grid place-items-center rounded-md bg-[#35383d] text-white hover:bg-[#4a4d52] disabled:opacity-50 disabled:cursor-not-allowed transition-all duration-200"
            >
              <svg className="size-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                <path d="M9 18l6-6-6-6"/>
              </svg>
            </button>
          </div>
        )}
      </div>
        </>
      ) : (

        <div className="flex flex-col items-center space-y-4 pt-4">
          {rightSidebarItems.map(({ Icon }, idx) => (
            <button
              onClick={() => {
                setSelectedIcon(idx);
                setIsCollapsed(false); 
              }}
              className={`transition-all duration-200 hover:bg-opacity-90 ${
                selectedIcon === idx 
                  ? "size-10 grid place-items-center rounded-lg bg-[#fae0d1] text-[#1b1c20] shadow-lg" 
                  : "size-10 grid place-items-center text-[#666] hover:text-white hover:bg-[#252628] rounded-lg"
              }`}
              key={idx}
            >
              <Icon />
            </button>
          ))}
        </div>
      )}
    </div>

      {isModalOpen && selectedTask && (
        <div className="fixed inset-0 flex items-center justify-center z-50">

          <div 
            className="absolute inset-0 bg-black/20 backdrop-blur-md"
            onClick={() => setIsModalOpen(false)}
          />
          
          <div className="relative bg-[#1b1c20] border border-[#35383d] rounded-2xl shadow-2xl p-10 max-w-4xl w-full mx-4 text-white">
            <div className="flex justify-between items-start mb-8">
              <div className="flex items-center gap-4">
                <h3 className="text-3xl font-bold text-white">{selectedTask.title}</h3>
                <div className={`inline-block px-5 py-2 rounded-full text-base font-semibold ${
                  selectedTask.priority === 'Muy alta' ? 'bg-red-500/20 text-red-300 border border-red-500/30' :
                  selectedTask.priority === 'Alta' ? 'bg-orange-500/20 text-orange-300 border border-orange-500/30' :
                  selectedTask.priority === 'Media' ? 'bg-yellow-500/20 text-yellow-300 border border-yellow-500/30' :
                  'bg-gray-500/20 text-gray-300 border border-gray-500/30'
                }`}>
                  {selectedTask.priority}
                </div>
              </div>
              <button
                onClick={() => setIsModalOpen(false)}
                className="text-[#666] hover:text-white transition-colors p-2"
              >
                <svg className="size-8" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
            
            <div className="space-y-8">
              <div>
                <h4 className="font-semibold text-white mb-4 text-xl">Descripción</h4>
                <p className="text-[#b0b0b0] text-lg leading-relaxed">{selectedTask.description}</p>
              </div>
              
              <div className="grid grid-cols-2 gap-8">
                <div>
                  <h4 className="font-semibold text-white mb-3 text-lg">Creada por</h4>
                  <p className="text-[#b0b0b0] text-lg">{selectedTask.assignedTo}</p>
                </div>
                <div>
                  <h4 className="font-semibold text-white mb-3 text-lg">Estado</h4>
                  <p className="text-[#b0b0b0] text-lg">{selectedTask.status}</p>
                </div>
              </div>
              
              <div>
                <h4 className="font-semibold text-white mb-3 text-lg">Categoría</h4>
                <p className="text-[#b0b0b0] text-lg">{selectedTask.category}</p>
              </div>
            </div>
            <div className="flex justify-end mt-10">
              <button className="flex items-center gap-3 px-8 py-4 bg-green-800 hover:bg-green-700 text-white rounded-lg transition-colors font-medium text-lg">
                <i className="fas fa-check"></i>
                Marcar como completada
              </button>
            </div>
          </div>
        </div>
      )}
    </>
  );
}

function Graph() {
  const drawn = React.useRef(false);

  React.useEffect(() => {
    if (!drawn.current) {
      drawn.current = true;
      drawGraph();
    }
  }, []);

  return (
    <div className="px-4">
      <div className="flex items-center">
        <svg className="size-5 text-[#606165]" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <path d="M3 3v18h18" />
          <path d="M18.7 8l-5.1 5.2-2.8-2.7L7 14.3" />
        </svg>
        <div className="text-base font-semibold ml-2 text-white">Reportes</div>
        <div className="ml-auto inline-flex items-center space-x-2 p-1 rounded-md bg-[#1b1c20]">
          <button className="w-16 bg-white text-[#1b1c20] rounded-md py-0.5 cursor-pointer text-sm font-semibold">
            24h
          </button>
          <button className="w-16 rounded-md py-0.5 cursor-pointer text-white text-sm">
            7d
          </button>
          <button className="w-16 rounded-md py-0.5 cursor-pointer text-white text-sm">
            1m
          </button>
        </div>
      </div>
      <div
        className="min-h-[175px] mt-2 bg-[#1b1c20] rounded-md"
        id="graph-container"
      ></div>
    </div>
  );
}

function drawPaymentGraph() {
  const ctx = document.getElementById('payment-graph-container');
  if (ctx && typeof Chart !== 'undefined') {
    ctx.innerHTML = '';
    const canvas = document.createElement('canvas');
    canvas.style.width = '100%';
    canvas.style.height = '300px';
    ctx.appendChild(canvas);
    
    if (paymentData.length === 0) {
      new Chart(canvas, {
        type: 'line',
        data: {
          labels: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
          datasets: [
            {
              label: 'Inquilinos que Pagaron',
              data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              borderColor: '#fae0d1',
              backgroundColor: 'rgba(250, 224, 209, 0.1)',
              tension: 0.4,
              fill: true,
            },
            {
              label: 'Total Apartamentos',
              data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
              borderColor: '#666',
              backgroundColor: 'rgba(102, 102, 102, 0.05)',
              borderDash: [5, 5],
            }
          ]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: true,
              labels: {
                color: '#fff'
              }
            }
          },
          scales: {
            x: {
              grid: {
                display: false
              },
              ticks: {
                color: '#666'
              }
            },
            y: {
              grid: {
                color: '#333'
              },
              ticks: {
                color: '#666'
              },
              beginAtZero: true,
              max: 10
            }
          }
        }
      });
      return;
    }
    
    const currentMonthIndex = paymentData.findIndex(d => d.current);
    const pointColors = paymentData.map((_, index) => 
      index === currentMonthIndex ? '#ff6b6b' : '#fae0d1'
    );
    const pointSizes = paymentData.map((_, index) => 
      index === currentMonthIndex ? 8 : 4
    );
    
    new Chart(canvas, {
      type: 'line',
      data: {
        labels: paymentData.map(d => d.month),
        datasets: [
          {
            label: 'Inquilinos que Pagaron',
            data: paymentData.map(d => d.paid),
            borderColor: '#fae0d1',
            backgroundColor: 'rgba(250, 224, 209, 0.1)',
            tension: 0.4,
            fill: true,
            pointBackgroundColor: pointColors,
            pointBorderColor: pointColors,
            pointRadius: pointSizes,
            pointHoverRadius: pointSizes.map(size => size + 2),
          },
          {
            label: 'Total Apartamentos',
            data: paymentData.map(d => d.total),
            borderColor: '#666',
            backgroundColor: 'rgba(102, 102, 102, 0.05)',
            borderDash: [5, 5],
            pointBackgroundColor: '#666',
            pointBorderColor: '#666',
            pointRadius: 2,
          }
        ]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: true,
            labels: {
              color: '#fff'
            }
          },
          tooltip: {
            callbacks: {
              afterLabel: function(context) {
                const dataIndex = context.dataIndex;
                if (paymentData[dataIndex].current) {
                  return 'Mes Actual';
                }
                return '';
              }
            }
          }
        },
        scales: {
          x: {
            grid: {
              display: false
            },
            ticks: {
              color: function(context) {
                const index = context.index;
                return paymentData[index] && paymentData[index].current ? '#ff6b6b' : '#666';
              },
              font: function(context) {
                const index = context.index;
                return {
                  weight: paymentData[index] && paymentData[index].current ? 'bold' : 'normal'
                };
              }
            }
          },
          y: {
            grid: {
              color: '#333'
            },
            ticks: {
              color: '#666'
            },
            beginAtZero: true,
            max: 55
          }
        }
      }
    });
  }
}

function drawIngresosGraph() {
  const ctx = document.getElementById('ingresos-graph-container');
  if (ctx && typeof Chart !== 'undefined') {
    ctx.innerHTML = '';
    const canvas = document.createElement('canvas');
    canvas.style.width = '100%';
    canvas.style.height = '300px';
    ctx.appendChild(canvas);
    
    if (ingresosData.length === 0) {
      new Chart(canvas, {
        type: 'bar',
        data: {
          labels: ['Sin datos'],
          datasets: [{
            label: 'Ingresos',
            data: [0],
            backgroundColor: 'rgba(250, 224, 209, 0.3)',
            borderColor: '#fae0d1',
            borderWidth: 2,
            borderRadius: 4,
          }]
        },
        options: {
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: {
              display: false
            }
          },
          scales: {
            x: {
              grid: {
                display: false
              },
              ticks: {
                color: '#666'
              }
            },
            y: {
              grid: {
                color: '#333'
              },
              ticks: {
                color: '#666',
                callback: function(value) {
                  return '$' + value.toLocaleString();
                }
              },
              beginAtZero: true,
              max: 4000
            }
          }
        }
      });
      return;
    }
    
    new Chart(canvas, {
      type: 'bar',
      data: {
        labels: ingresosData.map(d => d.apartment),
        datasets: [{
          label: 'Ingresos',
          data: ingresosData.map(d => d.amount),
          backgroundColor: [
            'rgba(250, 224, 209, 0.8)',
            'rgba(196, 135, 126, 0.8)',
            'rgba(217, 193, 179, 0.8)',
            'rgba(172, 154, 198, 0.8)',
            'rgba(250, 224, 209, 0.6)',
            'rgba(196, 135, 126, 0.6)',
            'rgba(217, 193, 179, 0.6)',
            'rgba(172, 154, 198, 0.6)',
          ],
          borderColor: [
            '#fae0d1',
            '#c4877e',
            '#d9c1b3',
            '#ac9ac6',
            '#fae0d1',
            '#c4877e',
            '#d9c1b3',
            '#ac9ac6',
          ],
          borderWidth: 2,
          borderRadius: 4,
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          }
        },
        scales: {
          x: {
            grid: {
              display: false
            },
            ticks: {
              color: '#666'
            }
          },
          y: {
            grid: {
              color: '#333'
            },
            ticks: {
              color: '#666',
              callback: function(value) {
                return '$' + value.toLocaleString();
              }
            },
            beginAtZero: true
          }
        },
        plugins: {
          tooltip: {
            callbacks: {
              label: function(context) {
                return 'Ingresos: $' + context.parsed.y.toLocaleString();
              }
            }
          }
        }
      }
    });
  }
}

function drawGraph() {
  const ctx = document.getElementById('graph-container');
  if (ctx && typeof Chart !== 'undefined') {
    ctx.innerHTML = '';
    const canvas = document.createElement('canvas');
    canvas.style.width = '100%';
    canvas.style.height = '175px';
    ctx.appendChild(canvas);
    
    new Chart(canvas, {
      type: 'line',
      data: {
        labels: ['6AM', '9AM', '12PM', '3PM', '6PM', '9PM'],
        datasets: [{
          label: 'Reportes',
          data: [12, 19, 3, 5, 2, 3],
          borderColor: '#fae0d1',
          backgroundColor: 'rgba(250, 224, 209, 0.1)',
          tension: 0.4,
          fill: true
        }]
      },
      options: {
        responsive: true,
        maintainAspectRatio: false,
        plugins: {
          legend: {
            display: false
          }
        },
        scales: {
          x: {
            grid: {
              display: false
            },
            ticks: {
              color: '#666'
            }
          },
          y: {
            grid: {
              color: '#333'
            },
            ticks: {
              color: '#666'
            }
          }
        }
      }
    });
  }
}

function Status() {
  return (
    <div className="grid grid-cols-3 gap-3 mt-2 px-4">
      {statusItems.map(
        ({ title, count, percentage, color1, color2, Icon }, idx) => (
          <div className="p-3 rounded-md bg-[#1b1c20]" key={idx}>
            <div className="flex items-center space-x-2">
              <div className="font-semibold text-white">{title}</div>
              <div className="grid place-items-center size-5 bg-[#28292d] rounded-full text-[#65666b]">
                <svg className="size-3" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
                  <circle cx="12" cy="12" r="10"/>
                  <path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"/>
                  <path d="M12 17h.01"/>
                </svg>
              </div>
            </div>

            <div className="flex items-center space-x-3 mt-2">
              <div
                className="size-9 grid place-items-center rounded-full text-[#3c3c55]"
                style={{ background: color1 }}
              >
                <Icon />
              </div>
              <div className="text-lg text-white font-semibold">{count.toLocaleString()}</div>
              <div
                className="py-0.5 px-2 rounded-md text-white text-sm font-semibold"
                style={{ background: color2 }}
              >
                +{percentage}%
              </div>
            </div>
          </div>
        )
      )}
    </div>
  );
}

const App = () => {
  const [sidebarExpanded, setSidebarExpanded] = React.useState(true);
  const [sidebarLeftCollapsed, setSidebarLeftCollapsed] = React.useState(false);
  const [sidebarRightCollapsed, setSidebarRightCollapsed] = React.useState(false);
  const [currentPage, setCurrentPage] = React.useState('dashboard');
  const [appReady, setAppReady] = React.useState(false);

  // Hacer setCurrentPage disponible globalmente
  React.useEffect(() => {
    window.setCurrentPage = setCurrentPage;
  }, []);

  React.useEffect(() => {
    const t = setTimeout(() => setAppReady(true), 300);
    return () => clearTimeout(t);
  }, []);

  const PlaceholderModule = ({ title, icon, description }) => (
    <div className="rounded-2xl p-10 bg-[#1b1c20] border border-white/10 text-center">
      <div className="w-14 h-14 rounded-2xl mx-auto mb-4 grid place-items-center bg-[#fae0d1]/10 text-[#fae0d1]">
        <i className={`fas ${icon} text-xl`} aria-hidden="true"></i>
      </div>
      <h2 className="text-xl font-semibold text-white mb-2">{title}</h2>
      <p className="text-gray-400 text-sm max-w-md mx-auto">{description}</p>
    </div>
  );

  return (
    <>
      <SidebarLeft 
        isCollapsed={sidebarLeftCollapsed}
        setIsCollapsed={setSidebarLeftCollapsed}
        currentPage={currentPage}
        setCurrentPage={setCurrentPage}
      />
      <SidebarRight 
        setSidebarExpanded={setSidebarExpanded}
        isCollapsed={sidebarRightCollapsed}
        setIsCollapsed={setSidebarRightCollapsed}
      />
      <div className={`transition-all duration-500 pl-0 pr-0 ${
        sidebarLeftCollapsed ? 'xl:pl-16' : 'xl:pl-64'
      } ${
        sidebarRightCollapsed ? 'xl:pr-16' : (sidebarExpanded ? 'xl:pr-80' : 'xl:pr-64')
      }`}>
        <div className="max-w-none mx-auto py-6 px-6">
          <GlobalSearchBar onNavigate={setCurrentPage} />

          {currentPage === 'dashboard' && (
            <>
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
                <PaymentGraph />
                <IngresosGraph />
              </div>
              <PaymentWidget />
              <ViewMoreSection />
              <Status />
            </>
          )}
          
          {currentPage === 'inquilinos' && <TenantsPage />}
          {currentPage === 'add-tenant' && <AddTenantPage />}
          {currentPage === 'analitica' && window.AnalyticsDashboard && <AnalyticsDashboard />}
          {currentPage === 'reportes' && window.ReportsSystem && <ReportsSystem />}
          {currentPage === 'tareas' && (
            <PlaceholderModule
              title="Tareas"
              icon="fa-tasks"
              description="Organiza pendientes del equipo. Practica el flujo en el laboratorio de Tareas del tutorial."
            />
          )}
          {currentPage === 'departamentos' && (
            <PlaceholderModule
              title="Departamentos"
              icon="fa-building"
              description="Consulta y organiza tus unidades. Este módulo se enlaza con inquilinos y contratos."
            />
          )}
          {currentPage === 'configuracion' && window.SettingsPage && (
            React.createElement(window.SettingsPage, { setCurrentPage })
          )}
        </div>
      </div>

      {window.FirstRunTutorial && (
        React.createElement(window.FirstRunTutorial, { onNavigate: setCurrentPage })
      )}
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App />);
