import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Icon } from '../../Atoms/Icon/Icon';
import { Typography } from '../../Atoms/Typography/Typography';
import { LogoHexa } from '../../Atoms/LogoHexa/LogoHexa';
import { FONT_FAMILY_SANS } from '../../../designTokens';

// Mock data con 2 títulos y 2 secciones
const MOCK_SECTIONS = [
  {
    title: 'PERSONAS',
    items: [
      { id: 'empleados', label: 'Empleados', icon: 'UserGroupIcon' },
      { id: 'organizacion', label: 'Organización', icon: 'BuildingOfficeIcon' },
    ],
  },
  {
    title: 'TALENTO',
    items: [
      { id: 'reclutamiento', label: 'Reclutamiento', icon: 'UserPlusIcon' },
      { id: 'desarrollo', label: 'Desarrollo', icon: 'AcademicCapIcon' },
    ],
  },
];

// Componente SidebarCore Mobile
const SidebarCoreMobile = ({
  sections = MOCK_SECTIONS,
  activeItem,
  onItemClick,
  companyName = 'HEXA Core',
  companyLogo,
  onCompanyClick,
  itemBadges = {},
  footerText, // Texto del footer: puede ser string "v1.0 | Powered by Nucleus" o objeto { version: "v1.0", poweredBy: "Powered by", brand: "Nucleus" }
  footerCollapsedContent, // Contenido a mostrar en el footer cuando está colapsado (puede ser string, ReactNode, o objeto con icon y text)
  coreContainerStyle, // Estilos personalizados para el contenedor de LogoHexa y "Core"
  coreTextStyle, // Estilos personalizados para el texto "Core"
  transitionDurationMs = 300,
  transitionEasing = 'ease-in-out',
  // UX: permitir que el item se pinte inmediatamente aunque el padre tarde en actualizar activeItem
  enableOptimisticActiveItem = true,
  closeOnItemClickAnimationFrame = true,
  // Mobile: labels de items
  mobileItemLabelFontSize = '1rem',
  mobileItemLabelWeightInactive = 'regular',
  mobileItemLabelWeightActive = 'semibold',
  // Mobile: íconos
  mobileIconSize = 24,
  mobileIconStyle,
  inicioLabel,
  // Sección de Configuración
  configSectionLabel,
  configSectionIcon = 'Cog6ToothIcon',
  configSectionId = 'configapp',
  onConfigClick,
  configBadge,
  isOpen: controlledIsOpen,
  onClose: controlledOnClose,
  // Breakpoints (resolución): ancho del sidebar mobile (entre min y max usa 412px)
  breakpointSidebarMobileWidthMinPx = 640,
  breakpointSidebarMobileWidthMaxPx = 1024,
  className = '',
  ...props
}) => {
  const { t } = useTranslation();
  const [internalIsOpen, setInternalIsOpen] = useState(false);
  const [optimisticActiveItem, setOptimisticActiveItem] = useState(null);
  const resolvedInicioLabel = inicioLabel ?? t('sidebar.homeLabel', { defaultValue: 'Inicio' });
  const resolvedConfigSectionLabel =
    configSectionLabel ?? t('sidebar.settingsLabel', { defaultValue: 'Configuración' });
  
  // Si se proporciona control externo, usarlo; si no, usar estado interno
  const isMobileMenuOpen = controlledIsOpen !== undefined ? controlledIsOpen : internalIsOpen;
  const setIsMobileMenuOpen = controlledOnClose ? controlledOnClose : setInternalIsOpen;

  const effectiveActiveItem =
    enableOptimisticActiveItem && optimisticActiveItem != null ? optimisticActiveItem : activeItem;

  useEffect(() => {
    if (!enableOptimisticActiveItem) return;
    if (optimisticActiveItem != null && optimisticActiveItem === activeItem) {
      setOptimisticActiveItem(null);
    }
  }, [activeItem, optimisticActiveItem, enableOptimisticActiveItem]);

  useEffect(() => {
    if (!enableOptimisticActiveItem) return;
    if (!isMobileMenuOpen && optimisticActiveItem != null) {
      setOptimisticActiveItem(null);
    }
  }, [isMobileMenuOpen, optimisticActiveItem, enableOptimisticActiveItem]);

  const toggleMobileMenu = () => {
    if (controlledOnClose) {
      controlledOnClose();
    } else {
      setInternalIsOpen(!internalIsOpen);
    }
  };

  // Generar footerCollapsedContent automáticamente si no se proporciona pero sí hay footerText
  const getFooterCollapsedContent = () => {
    if (footerCollapsedContent) {
      return footerCollapsedContent;
    }
    
    // Si hay footerText pero no footerCollapsedContent, generar uno automáticamente
    if (footerText && !footerCollapsedContent) {
      if (typeof footerText === 'string') {
        // Extraer la versión (parte antes del |) o usar todo el texto si no hay |
        const parts = footerText.split('|');
        return parts[0].trim() || footerText.trim();
      } else if (typeof footerText === 'object' && footerText.version) {
        return footerText.version;
      }
    }
    
    return null;
  };

  const effectiveFooterCollapsedContent = getFooterCollapsedContent();

  return (
    <>
      <style>{`
        .sidebar-core-mobile {
          width: 100%;
          transform: ${isMobileMenuOpen ? 'translateX(0)' : 'translateX(-100%)'};
          position: fixed;
          left: 0;
          top: 0;
          height: 100vh;
          z-index: 50;
          transition: transform ${transitionDurationMs}ms ${transitionEasing};
        }
        .sidebar-core-mobile-overlay {
          background-color: rgba(0, 0, 0, 0.5);
        }
        @media (min-width: ${breakpointSidebarMobileWidthMinPx}px) and (max-width: ${breakpointSidebarMobileWidthMaxPx}px) {
          .sidebar-core-mobile {
            width: 412px;
          }
          .sidebar-core-mobile-overlay {
            background-color: #00000040;
          }
        }
      `}</style>
      {/* Botón hamburguesa - solo visible cuando el menú está cerrado y no hay control externo */}
      {!isMobileMenuOpen && controlledIsOpen === undefined && (
        <button
          onClick={toggleMobileMenu}
          className="fixed top-4 left-4 z-50 p-2 bg-white rounded-lg 
                   hover:bg-gray-50 transition-colors"
          style={{ border: '1px solid #C4C4C4' }}
          aria-label="Toggle menu"
        >
          <Icon
            name="Bars3Icon"
            variant="24-outline"
            size={mobileIconSize}
            className="color-gray-700"
            style={{
              width: `${mobileIconSize}px`,
              height: `${mobileIconSize}px`,
              opacity: 1,
              transform: 'rotate(0deg)',
              ...(mobileIconStyle || {}),
            }}
          />
        </button>
      )}
      {/* Overlay para cerrar el menú */}
      <div
        className="fixed inset-0 sidebar-core-mobile-overlay z-40"
        style={{
          opacity: isMobileMenuOpen ? 1 : 0,
          pointerEvents: isMobileMenuOpen ? 'auto' : 'none',
          transition: `opacity ${transitionDurationMs}ms ${transitionEasing}`
        }}
        onClick={() => {
          if (controlledOnClose) {
            controlledOnClose();
          } else {
            toggleMobileMenu();
          }
        }}
      />
      <aside
        className={`bg-white sidebar-core-mobile ${className}`}
        style={{ border: '1px solid #C4C4C4', borderRadius: '16px' }}
        {...props}
      >
        <nav className="h-full flex flex-col">
          {/* Header con LogoHexa, "Core" y botón X */}
          <div className="bg-white px-4 py-4 flex items-center justify-between border-b border-gray-200">
            {/* Lado izquierdo: LogoHexa y "Core" */}
            <div 
              className="flex items-center space-x-2 min-w-0 flex-1"
              style={coreContainerStyle}
            >
              {/* Logo Hexa */}
              <LogoHexa
                width={36}
                height={40}
                className="flex-shrink-0"
              />
              
              {/* Texto "Core" */}
              <Typography
                variant="h6"
                style={{
                  color: '#2D5C63',
                  fontSize: '24px',
                  fontFamily: FONT_FAMILY_SANS,
                  fontWeight: 600,
                  lineHeight: '1.2',
                  margin: 0,
                  marginLeft: '8px',
                  display: 'flex',
                  alignItems: 'center',
                  minWidth: 0,
                  flex: 1,
                  ...coreTextStyle
                }}
              >
                Core
              </Typography>
            </div>
            
            {/* Lado derecho: Botón X */}
            <button
              onClick={() => {
                if (controlledOnClose) {
                  controlledOnClose();
                } else {
                  toggleMobileMenu();
                }
              }}
              className="p-1 hover:bg-gray-100 rounded transition-colors flex-shrink-0"
              aria-label="Cerrar menú"
            >
              <Icon
                name="XMarkIcon"
                variant="24-outline"
                size={mobileIconSize}
                className="color-gray-700"
                style={{
                  width: `${mobileIconSize}px`,
                  height: `${mobileIconSize}px`,
                  opacity: 1,
                  transform: 'rotate(0deg)',
                  ...(mobileIconStyle || {}),
                }}
              />
            </button>
          </div>
          {/* Contenido del sidebar mobile */}
          <div className="flex-1 overflow-y-auto py-4">
            {/* Item "Inicio" destacado */}
            <div className="px-4 mb-4">
              <button
                onClick={() => {
                  onItemClick && onItemClick('inicio');
                  if (controlledOnClose) {
                    controlledOnClose();
                  } else {
                    toggleMobileMenu();
                  }
                }}
                className={`w-full flex items-center cursor-pointer px-4 justify-between py-2.5 rounded-lg transition-all duration-200 ${
                  effectiveActiveItem === 'inicio'
                    ? ''
                    : 'color-gray-700 hover:bg-gray-100'
                }`}
                style={
                  effectiveActiveItem === 'inicio'
                    ? { backgroundColor: '#2D5C63' }
                    : {}
                }
              >
                <div className="flex items-center">
                  <Icon
                    name="HomeIcon"
                    variant="24-outline"
                    size={mobileIconSize}
                    className={`mr-3 ${
                      effectiveActiveItem === 'inicio' ? 'color-white' : 'color-gray-700'
                    }`}
                    style={{
                      width: `${mobileIconSize}px`,
                      height: `${mobileIconSize}px`,
                      opacity: 1,
                      transform: 'rotate(0deg)',
                      ...(mobileIconStyle || {}),
                    }}
                  />
                  <Typography
                    variant="body-md"
                    weight={effectiveActiveItem === 'inicio' ? mobileItemLabelWeightActive : mobileItemLabelWeightInactive}
                    className={effectiveActiveItem === 'inicio' ? 'color-white' : 'color-gray-700'}
                    style={{ fontSize: mobileItemLabelFontSize }}
                  >
                    {resolvedInicioLabel}
                  </Typography>
                </div>
                {itemBadges['inicio'] !== undefined && itemBadges['inicio'] > 0 && (
                  <span
                    className="px-2 py-0.5 min-w-[20px] h-5 
                             rounded-full flex items-center justify-center
                             text-body-sm-14 font-medium flex-shrink-0"
                    style={{ 
                      backgroundColor: effectiveActiveItem === 'inicio' ? '#ffffff' : '#6D3856',
                      color: effectiveActiveItem === 'inicio' ? '#6D3856' : '#ffffff',
                      borderRadius: '12px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      lineHeight: '1'
                    }}
                  >
                    {itemBadges['inicio'] > 9 ? '9+' : itemBadges['inicio']}
                  </span>
                )}
              </button>
            </div>

            {/* Secciones */}
            {sections.map((section, sectionIndex) => (
              <div key={sectionIndex} className="mb-6">
                {/* Título de la sección */}
                <div className="px-4 mb-2">
                  <Typography
                    className="text-sidebar-core color-gray-500 uppercase font-medium tracking-wider"
                  >
                    {section.title}
                  </Typography>
                </div>

                {/* Items de la sección */}
                <div>
                  {section.items.map((item) => (
                    <div key={item.id} className="px-4">
                      <button
                        onClick={() => {
                          if (enableOptimisticActiveItem) {
                            setOptimisticActiveItem(item.id);
                          }
                          onItemClick && onItemClick(item.id);
                          if (controlledOnClose) {
                            if (closeOnItemClickAnimationFrame) {
                              requestAnimationFrame(() => controlledOnClose());
                            } else {
                            controlledOnClose();
                            }
                          } else {
                            toggleMobileMenu();
                          }
                        }}
                        className={`w-full flex items-center cursor-pointer px-4 justify-between py-2.5 rounded-lg transition-all duration-200 ${
                          effectiveActiveItem === item.id
                            ? ''
                            : 'color-gray-700 hover:bg-gray-100'
                        }`}
                        style={
                          effectiveActiveItem === item.id
                            ? { backgroundColor: '#2D5C63' }
                            : {}
                        }
                      >
                        <div className="flex items-center">
                          <Icon
                            name={item.icon}
                            variant="24-outline"
                            size={mobileIconSize}
                            className={`mr-3 ${
                              effectiveActiveItem === item.id ? 'color-white' : 'color-gray-700'
                            }`}
                            style={{
                              width: `${mobileIconSize}px`,
                              height: `${mobileIconSize}px`,
                              opacity: 1,
                              transform: 'rotate(0deg)',
                              ...(mobileIconStyle || {}),
                            }}
                          />
                          <Typography
                            variant="body-md"
                            weight={effectiveActiveItem === item.id ? mobileItemLabelWeightActive : mobileItemLabelWeightInactive}
                            className={effectiveActiveItem === item.id ? 'color-white' : 'color-gray-700'}
                            style={{ fontSize: mobileItemLabelFontSize }}
                          >
                            {item.label}
                          </Typography>
                        </div>
                        {((itemBadges[item.id] !== undefined && itemBadges[item.id] > 0) || (item.id === 'empleados' && 2)) && (
                          <span
                            className="px-2 py-0.5 min-w-[20px] h-5 
                                     rounded-full flex items-center justify-center
                                     text-body-sm-14 font-medium flex-shrink-0"
                            style={{ 
                              backgroundColor: effectiveActiveItem === item.id ? '#ffffff' : '#6D3856',
                              color: effectiveActiveItem === item.id ? '#6D3856' : '#ffffff',
                              borderRadius: '12px',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              lineHeight: '1'
                            }}
                          >
                            {item.id === 'empleados' ? 2 : (itemBadges[item.id] > 9 ? '9+' : itemBadges[item.id])}
                          </span>
                        )}
                      </button>
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>

          {/* Sección de Configuración */}
          <div 
            className="flex-shrink-0 px-4"
            style={{
              paddingTop: '24px',
              paddingBottom: '40px',
              position: 'relative',
            }}
          >
            {/* Borde superior centrado */}
            <div
              style={{
                position: 'absolute',
                top: '0px',
                left: '16px',
                right: '16px',
                height: '1px',
                backgroundColor: '#E5E5E5',
              }}
            />
            <button
              onClick={() => {
                if (enableOptimisticActiveItem) {
                  setOptimisticActiveItem(configSectionId);
                }
                onItemClick && onItemClick(configSectionId);
                onConfigClick && onConfigClick(configSectionId);
                if (controlledOnClose) {
                  if (closeOnItemClickAnimationFrame) {
                    requestAnimationFrame(() => controlledOnClose());
                  } else {
                    controlledOnClose();
                  }
                } else {
                  toggleMobileMenu();
                }
              }}
              className={`w-full flex items-center cursor-pointer px-4 justify-between py-2.5 rounded-lg transition-all duration-200 ${
                effectiveActiveItem === configSectionId
                  ? ''
                  : 'color-gray-700 hover:bg-gray-100'
              }`}
              style={
                effectiveActiveItem === configSectionId
                  ? { backgroundColor: '#2D5C63' }
                  : {}
              }
            >
              <div className="flex items-center">
                <Icon
                  name={configSectionIcon}
                  variant="24-outline"
                  size={mobileIconSize}
                  className={`mr-3 ${
                    effectiveActiveItem === configSectionId ? 'color-white' : 'color-gray-700'
                  }`}
                  style={{
                    width: `${mobileIconSize}px`,
                    height: `${mobileIconSize}px`,
                    opacity: 1,
                    transform: 'rotate(0deg)',
                    ...(mobileIconStyle || {}),
                  }}
                />
                <Typography
                  variant="body-md"
                  weight={effectiveActiveItem === configSectionId ? mobileItemLabelWeightActive : mobileItemLabelWeightInactive}
                  className={effectiveActiveItem === configSectionId ? 'color-white' : 'color-gray-700'}
                  style={{ fontSize: mobileItemLabelFontSize }}
                >
                  {resolvedConfigSectionLabel}
                </Typography>
              </div>
              {configBadge !== undefined && configBadge > 0 && (
                <span
                  className="px-2 py-0.5 min-w-[20px] h-5 
                           rounded-full flex items-center justify-center
                           text-body-sm-14 font-medium flex-shrink-0"
                  style={{ 
                    backgroundColor: effectiveActiveItem === configSectionId ? '#ffffff' : '#6D3856',
                    color: effectiveActiveItem === configSectionId ? '#6D3856' : '#ffffff',
                    borderRadius: '12px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    lineHeight: '1'
                  }}
                >
                  {configBadge > 9 ? '9+' : configBadge}
                </span>
              )}
            </button>
          </div>

          {/* Footer con texto configurable */}
          {footerText && (
            <div className="px-4 pb-4 flex-shrink-0">
              <div 
                className="bg-white border rounded-lg px-3 py-2 flex items-center justify-center"
                style={{ 
                  borderColor: '#2D5C63',
                  borderRadius: '8px'
                }}
              >
                {typeof footerText === 'string' ? (
                  <Typography
                    variant="body-sm"
                    style={{ color: '#2D5C63', fontSize: '14px', lineHeight: '20px' }}
                    className="text-center"
                  >
                    {(() => {
                      const parts = footerText.split('|');
                      if (parts.length === 2) {
                        const leftPart = parts[0].trim();
                        const rightPart = parts[1].trim();
                        // Si contiene "Powered by", separar y poner la marca en bold
                        if (rightPart.includes('Powered by')) {
                          const poweredByMatch = rightPart.match(/Powered by (.+)/);
                          if (poweredByMatch) {
                            return (
                              <>
                                {leftPart} | Powered by <span className="font-bold">{poweredByMatch[1]}</span>
                              </>
                            );
                          }
                        }
                        return `${leftPart} | ${rightPart}`;
                      }
                      return footerText;
                    })()}
                  </Typography>
                ) : (
                  <Typography
                    variant="body-sm"
                    style={{ color: '#2D5C63', fontSize: '14px', lineHeight: '20px' }}
                    className="text-center"
                  >
                    {footerText.version && `${footerText.version}`}
                    {footerText.version && (footerText.poweredBy || footerText.brand) && ' | '}
                    {footerText.poweredBy && `${footerText.poweredBy} `}
                    {footerText.brand && <span className="font-bold">{footerText.brand}</span>}
                  </Typography>
                )}
              </div>
            </div>
          )}
        </nav>
      </aside>
    </>
  );
};

export const SidebarCore = ({
  sections = MOCK_SECTIONS,
  activeItem,
  onItemClick,
  defaultCollapsed = false,
  companyName = 'HEXA Core',
  companyLogo,
  onCompanyClick,
  // Overrides desktop para el header "HEXA Core"
  desktopCompanyButtonClassName = '',
  desktopCompanyButtonStyle,
  desktopCompanyNameClassName = '',
  desktopCompanyNameStyle,
  // Desktop: overrides para el control de colapsar (solo cuando NO está colapsado)
  desktopCollapseControlWrapperClassName = '',
  desktopCollapseControlWrapperStyle,
  desktopCollapseButtonClassName = '',
  desktopCollapseButtonStyle,
  desktopCollapseIconSize = 20,
  desktopCollapseIconStrokeWidth = 1.5,
  desktopCollapseIconColor = '#0F172A',
  desktopCollapseIconClassName = '',
  desktopCollapseIconStyle,
  // Desktop: overrides para el control de expandir (solo cuando está colapsado)
  desktopExpandButtonClassName = '',
  desktopExpandButtonStyle,
  desktopExpandIconSize = 20,
  desktopExpandIconStrokeWidth = 1.5,
  desktopExpandIconColor = '#0F172A',
  desktopExpandIconClassName = '',
  desktopExpandIconStyle,
  // Desktop: labels de items (solo cuando NO está colapsado)
  desktopItemLabelFontSize = '1rem',
  desktopItemLabelWeightInactive = 'regular',
  desktopItemLabelWeightActive = 'semibold',
  // Desktop: íconos de navegación (items)
  desktopExpandedIconSize = 24,
  desktopCollapsedIconSize = 32,
  // Desktop colapsado: wrapper interno del ícono (hijo del 32x32)
  desktopCollapsedIconInnerSize = 24,
  desktopCollapsedIconInnerStyle,
  desktopCollapsedIconWrapperStyle,
  // Desktop colapsado: solapamiento icono + badge (mínimo)
  desktopCollapsedOverlapEnabled = true,
  desktopCollapsedOverlapIconMarginLeftPx = 3,
  desktopCollapsedOverlapBadgeMarginLeftPx = -6,
  desktopCollapsedOverlapColumnGapPx = 0,
  desktopNavIconStyle,
  // Desktop colapsado: wrapper de cada item (Inicio + opciones)
  desktopCollapsedItemWrapperClassName = '',
  desktopCollapsedItemWrapperStyle,
  desktopCollapsedItemActiveBackgroundColor = '#2D5C63',
  // Desktop colapsado: badge (globito) de notificaciones
  desktopCollapsedBadgeClassName = '',
  desktopCollapsedBadgeStyle,
  desktopCollapsedBadgeWidth = '21px',
  desktopCollapsedBadgeHeight = '20px',
  // Desktop colapsado: ancho del sidebar (fijo 84px en desktop)
  desktopCollapsedWidth = '84px',
  // Desktop colapsado: footer
  desktopCollapsedFooterContainerClassName = '',
  desktopCollapsedFooterContainerStyle,
  desktopCollapsedFooterTextClassName = '',
  desktopCollapsedFooterTextStyle,
  // Desktop colapsado: separador entre secciones
  desktopCollapsedSectionSeparatorClassName = '',
  desktopCollapsedSectionSeparatorStyle,
  desktopCollapsedSectionSeparatorWrapperClassName = '',
  desktopCollapsedSectionSeparatorWrapperStyle,
  // Desktop colapsado: ajustes de spacing (para evitar “aire” extra)
  desktopCollapsedInicioContainerClassName = '',
  desktopCollapsedSectionContainerClassName = '',
  desktopCollapsedSeparatorContainerClassName = '',
  inicioLabel,
  nucleusName = 'Nucleus AR',
  nucleusLogo,
  onNucleusClick,
  itemBadges = {}, // Objeto con { itemId: number } para los badges
  footerText, // Texto del footer: puede ser string "v1.0 | Powered by Nucleus" o objeto { version: "v1.0", poweredBy: "Powered by", brand: "Nucleus" }
  footerCollapsedContent, // Contenido a mostrar en el footer cuando está colapsado (puede ser string, ReactNode, o objeto con icon y text)
  coreContainerStyle, // Estilos personalizados para el contenedor de LogoHexa y "Core" (solo mobile)
  coreTextStyle, // Estilos personalizados para el texto "Core" (solo mobile)
  fluidWidth = false, // Si es true, el root respeta el ancho del contenedor (grid/flex) en lugar de usar anchos fijos
  // Sección de Configuración
  configSectionLabel,
  configSectionIcon = 'Cog6ToothIcon',
  configSectionId = 'configapp',
  onConfigClick,
  configBadge,
  // Breakpoints (resolución): el consumidor puede override; por defecto los valores actuales
  breakpointMobileMaxPx = 1024,
  breakpointCollapsedMaxPx = 1440,
  breakpointSidebarMobileWidthMinPx = 640,
  breakpointSidebarMobileWidthMaxPx = 1024,
  className = '',
  ...props
}) => {
  const { t } = useTranslation();
  const [isCollapsed, setIsCollapsed] = useState(() => {
    if (typeof window === 'undefined') return defaultCollapsed;
    const w = window.innerWidth;
    if (w < breakpointMobileMaxPx) return defaultCollapsed;
    return w < breakpointCollapsedMaxPx;
  });
  const [isMobile, setIsMobile] = useState(false);
  const desktopNavIconSize = isCollapsed ? desktopCollapsedIconSize : desktopExpandedIconSize;
  const desktopNavIconGlyphSize = isCollapsed ? desktopCollapsedIconInnerSize : desktopExpandedIconSize;
  const collapsedItemWrapperDefaults = {
    width: '100%',
    height: '48px',
    paddingTop: '8px',
    paddingRight: '12px',
    paddingBottom: '8px',
    paddingLeft: '12px',
    gap: '12px',
    opacity: 1,
    transform: 'rotate(0deg)',
    borderRadius: '8px',
    boxSizing: 'border-box',
  };

  // Detectar tamaño de pantalla y sincronizar estado colapsado (desktop: hasta breakpointCollapsedMaxPx colapsado, desde ahí expandido)
  useEffect(() => {
    const checkMobile = () => {
      const w = window.innerWidth;
      setIsMobile(w < breakpointMobileMaxPx);
      if (w >= breakpointMobileMaxPx) {
        setIsCollapsed(w < breakpointCollapsedMaxPx);
      }
    };

    // Verificar al montar
    checkMobile();

    // Escuchar cambios de tamaño
    window.addEventListener('resize', checkMobile);

    return () => {
      window.removeEventListener('resize', checkMobile);
    };
  }, [breakpointMobileMaxPx, breakpointCollapsedMaxPx]);

  const toggleCollapse = () => {
    setIsCollapsed(!isCollapsed);
  };

  // Generar footerCollapsedContent automáticamente si no se proporciona pero sí hay footerText
  const getFooterCollapsedContent = () => {
    if (footerCollapsedContent) {
      return footerCollapsedContent;
    }
    
    // Si hay footerText pero no footerCollapsedContent, generar uno automáticamente
    if (footerText && !footerCollapsedContent) {
      if (typeof footerText === 'string') {
        // Extraer la versión (parte antes del |) o usar todo el texto si no hay |
        const parts = footerText.split('|');
        return parts[0].trim() || footerText.trim();
      } else if (typeof footerText === 'object' && footerText.version) {
        return footerText.version;
      }
    }
    
    return null;
  };

  const effectiveFooterCollapsedContent = getFooterCollapsedContent();
  const resolvedInicioLabel = inicioLabel ?? t('sidebar.homeLabel', { defaultValue: 'Inicio' });
  const resolvedConfigSectionLabel =
    configSectionLabel ?? t('sidebar.settingsLabel', { defaultValue: 'Configuración' });

  // Si es mobile, renderizar SidebarCoreMobile
  if (isMobile) {
    return (
      <SidebarCoreMobile
        sections={sections}
        activeItem={activeItem}
        onItemClick={onItemClick}
        companyName={companyName}
        companyLogo={companyLogo}
        onCompanyClick={onCompanyClick}
        itemBadges={itemBadges}
        footerText={footerText}
        footerCollapsedContent={footerCollapsedContent}
        coreContainerStyle={coreContainerStyle}
        coreTextStyle={coreTextStyle}
        inicioLabel={inicioLabel}
        configSectionLabel={configSectionLabel}
        configSectionIcon={configSectionIcon}
        configSectionId={configSectionId}
        onConfigClick={onConfigClick}
        configBadge={configBadge}
        className={className}
        breakpointSidebarMobileWidthMinPx={breakpointSidebarMobileWidthMinPx}
        breakpointSidebarMobileWidthMaxPx={breakpointSidebarMobileWidthMaxPx}
        {...props}
      />
    );
  }

  // Determinar estilos del root según fluidWidth (anchos fijos: 84px colapsado, 280px expandido)
  const rootWidthStyles = fluidWidth
    ? {
        width: '100%',
        maxWidth: '100%',
        minWidth: 0,
        boxSizing: 'border-box',
      }
    : isCollapsed
      ? { width: '84px' }
      : { width: '280px' };

  const rootClassName = fluidWidth
    ? `bg-white transition-all duration-300 ease-in-out h-full ${className}`
    : `bg-white transition-all duration-300 ease-in-out h-full ${className}`;

  return (
    <aside
      className={rootClassName}
      style={{
        border: '1px solid #C4C4C4',
        borderRadius: '16px',
        ...rootWidthStyles,
      }}
      {...props}
    >
      <nav className="h-full flex flex-col" style={{ overflow: 'hidden' }}>
        {/* Barra superior con HEXA Core */}
        {!isCollapsed && (
          <div className="p-4 border-b border-gray-200 flex-shrink-0">
            <button
              onClick={onCompanyClick}
              className={`w-full bg-white rounded-lg pl-0 pr-3 py-0 h-10 
                       flex items-center justify-between hover:bg-gray-50 transition-colors ${desktopCompanyButtonClassName}`}
              style={desktopCompanyButtonStyle}
            >
              <div className="flex items-center space-x-3 min-w-0 flex-1">
                {/* Logo hexagonal */}
                {companyLogo ? (
                  <img
                    src={companyLogo}
                    alt={companyName}
                    className="w-8 h-8 rounded flex-shrink-0"
                  />
                ) : (
                  <LogoHexa width={36} height={40} className="flex-shrink-0" />
                )}
                {/* Nombre de la empresa */}
                <Typography
                  variant="body-md"
                  className={`${desktopCompanyNameClassName} min-w-0`}
                  style={{
                    color: 'var(--color-cyan-19)',
                    fontFamily: FONT_FAMILY_SANS,
                    fontWeight: 600,
                    fontStyle: 'normal',
                    fontSize: '18px',
                    lineHeight: '28px',
                    letterSpacing: '0px',
                    opacity: 1,
                    transform: 'rotate(0deg)',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap',
                    ...(desktopCompanyNameStyle || {}),
                  }}
                >
                  {companyName}
                </Typography>
              </div>
            </button>
          </div>
        )}

        {/* Botón de colapsar/expandir - Solo visible cuando está expandido */}
        {!isCollapsed && (
          <div className="px-4 pt-2 flex justify-end flex-shrink-0">
            {/* Wrapper con medidas Figma (overrideable por props) */}
            <div
              className={`flex justify-end ${desktopCollapseControlWrapperClassName}`}
              style={{
                width: '228px',
                height: '36px',
                opacity: 1,
                transform: 'rotate(0deg)',
                paddingBottom: '16px',
                boxSizing: 'border-box',
                borderTopRightRadius: '8px',
                borderBottomRightRadius: '8px',
                ...(desktopCollapseControlWrapperStyle || {}),
              }}
            >
            <button
              onClick={toggleCollapse}
                className={`hover:bg-gray-100 transition-colors rounded-lg ${desktopCollapseButtonClassName}`}
              aria-label="Colapsar sidebar"
                style={{
                  width: '36px',
                  height: '36px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  opacity: 1,
                  transform: 'rotate(0deg)',
                  ...(desktopCollapseButtonStyle || {}),
                }}
            >
              <Icon
                name="ChevronDoubleLeftIcon"
                variant="24-outline"
                  size={desktopCollapseIconSize}
                  strokeWidth={desktopCollapseIconStrokeWidth}
                  className={desktopCollapseIconClassName}
                  style={{
                    width: `${desktopCollapseIconSize}px`,
                    height: `${desktopCollapseIconSize}px`,
                    opacity: 1,
                    transform: 'rotate(0deg)',
                    color: desktopCollapseIconColor,
                    ...(desktopCollapseIconStyle || {}),
                  }}
              />
            </button>
            </div>
          </div>
        )}

        {/* Logo cuando está colapsado */}
        {isCollapsed && (
          <div className="p-4 border-b border-gray-200 flex justify-center flex-shrink-0">
            {companyLogo ? (
              <img
                src={companyLogo}
                alt={companyName}
                className="w-8 h-8 rounded"
              />
            ) : (
              <LogoHexa width={36} height={40} />
            )}
          </div>
        )}

        {/* Botón para expandir - Solo visible cuando está colapsado */}
        {isCollapsed && (
          <div className="px-4 pt-2 pb-2 flex justify-center flex-shrink-0">
            <button
              onClick={toggleCollapse}
              className={`p-1.5 hover:bg-gray-100 rounded-lg transition-colors ${desktopExpandButtonClassName}`}
              aria-label="Expandir sidebar"
              style={desktopExpandButtonStyle}
            >
              <Icon
                name="ChevronDoubleRightIcon"
                variant="24-outline"
                size={desktopExpandIconSize}
                strokeWidth={desktopExpandIconStrokeWidth}
                className={desktopExpandIconClassName}
                style={{
                  color: desktopExpandIconColor,
                  width: `${desktopExpandIconSize}px`,
                  height: `${desktopExpandIconSize}px`,
                  opacity: 1,
                  transform: 'rotate(0deg)',
                  ...(desktopExpandIconStyle || {}),
                }}
              />
            </button>
          </div>
        )}

        {/* Contenido del sidebar - Wrapper para controlar el espacio */}
        <div className="flex-1 min-h-0 flex flex-col overflow-hidden">
          <div className={`flex-1 overflow-y-auto ${isCollapsed ? 'py-2' : 'py-4'}`} style={{ overflowX: 'hidden' }}>
          {/* Item "Inicio" destacado */}
          <div
            className={`${isCollapsed ? 'px-2' : 'px-4'} ${isCollapsed ? 'mb-0' : 'mb-4'} ${desktopCollapsedInicioContainerClassName}`}
          >
            {isCollapsed ? (
              <div
                className={desktopCollapsedItemWrapperClassName}
                style={{
                  ...collapsedItemWrapperDefaults,
                  backgroundColor:
                    activeItem === 'inicio' ? desktopCollapsedItemActiveBackgroundColor : 'transparent',
                  ...(desktopCollapsedItemWrapperStyle || {}),
                }}
                title={resolvedInicioLabel}
              >
                <button
                  onClick={() => onItemClick && onItemClick('inicio')}
                  className="flex items-center justify-center transition-all duration-200"
                  style={{
                    width: '100%',
                    height: '100%',
                    backgroundColor: 'transparent',
                    borderRadius: '8px',
                  }}
                  title={resolvedInicioLabel}
                >
                  <div
                    className="flex items-center"
                    style={{
                      justifyContent: 'center',
                      columnGap: `${desktopCollapsedOverlapColumnGapPx}px`,
                      width: '100%',
                    }}
                  >
                    <div
                      style={{
                        width: `${desktopNavIconSize}px`,
                        height: `${desktopNavIconSize}px`,
                        opacity: 1,
                        transform: 'rotate(0deg)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        marginLeft:
                          desktopCollapsedOverlapEnabled &&
                          itemBadges['inicio'] !== undefined &&
                          itemBadges['inicio'] > 0
                            ? `${desktopCollapsedOverlapIconMarginLeftPx}px`
                            : undefined,
                        ...(desktopCollapsedIconWrapperStyle || {}),
                      }}
                    >
                      <div
                        style={{
                          width: '24px',
                          height: '24px',
                          opacity: 1,
                          transform: 'rotate(0deg)',
                          display: 'flex',
                          alignItems: 'center',
                          justifyContent: 'center',
                          ...(desktopCollapsedIconInnerStyle || {}),
                        }}
                      >
                        <Icon
                          name="HomeIcon"
                          variant="24-outline"
                          size={desktopNavIconGlyphSize}
                          className={activeItem === 'inicio' ? 'color-white' : 'color-gray-700'}
                          style={{
                            width: `${desktopNavIconGlyphSize}px`,
                            height: `${desktopNavIconGlyphSize}px`,
                            opacity: 1,
                            transform: 'rotate(0deg)',
                            ...(desktopNavIconStyle || {}),
                          }}
                        />
                      </div>
                    </div>
                    {itemBadges['inicio'] !== undefined && itemBadges['inicio'] > 0 && (
                      <span
                        className={`flex items-center justify-center text-body-sm-14 font-medium ${desktopCollapsedBadgeClassName}`}
                        style={{
                          backgroundColor: activeItem === 'inicio' ? '#ffffff' : '#6D3856',
                          color: activeItem === 'inicio' ? '#6D3856' : '#ffffff',
                          width: desktopCollapsedBadgeWidth,
                          height: desktopCollapsedBadgeHeight,
                          paddingTop: '4px',
                          paddingRight: '6px',
                          paddingBottom: '4px',
                          paddingLeft: '6px',
                          borderRadius: '16px',
                          opacity: 1,
                          transform: 'rotate(0deg)',
                          marginLeft: desktopCollapsedOverlapEnabled
                            ? `${desktopCollapsedOverlapBadgeMarginLeftPx}px`
                            : undefined,
                          boxSizing: 'border-box',
                          ...(desktopCollapsedBadgeStyle || {}),
                        }}
                      >
                        {itemBadges['inicio'] > 9 ? '9+' : itemBadges['inicio']}
                      </span>
                    )}
                  </div>
                </button>
              </div>
            ) : (
              <button
                onClick={() => onItemClick && onItemClick('inicio')}
                className={`w-full flex items-center cursor-pointer px-4 justify-between py-2.5 rounded-lg transition-all duration-200 ${
                  activeItem === 'inicio'
                    ? ''
                    : 'color-gray-700 hover:bg-gray-100'
                }`}
                style={
                  activeItem === 'inicio'
                    ? { backgroundColor: '#2D5C63' }
                    : {}
                }
              >
                <div className="flex items-center">
                  <Icon
                    name="HomeIcon"
                    variant="24-outline"
                    size={desktopNavIconGlyphSize}
                    className={`mr-3 ${
                      activeItem === 'inicio' ? 'color-white' : 'color-gray-700'
                    }`}
                  />
                  <Typography
                    variant="body-lg"
                    weight={activeItem === 'inicio' ? desktopItemLabelWeightActive : desktopItemLabelWeightInactive}
                    className={`${
                      activeItem === 'inicio' ? 'color-white' : 'color-gray-700'
                    } min-w-0`}
                    style={{
                      fontSize: desktopItemLabelFontSize,
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      whiteSpace: 'nowrap',
                    }}
                  >
                    {resolvedInicioLabel}
                  </Typography>
                </div>
                {itemBadges['inicio'] !== undefined && itemBadges['inicio'] > 0 && (
                  <span
                    className="px-2 py-0.5 min-w-[20px] h-5 
                             rounded-full flex items-center justify-center
                             text-body-sm-14 font-medium flex-shrink-0"
                    style={{ 
                      backgroundColor: activeItem === 'inicio' ? '#ffffff' : '#6D3856',
                      color: activeItem === 'inicio' ? '#6D3856' : '#ffffff',
                      borderRadius: '12px',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      lineHeight: '1'
                    }}
                  >
                    {itemBadges['inicio'] > 9 ? '9+' : itemBadges['inicio']}
                  </span>
                )}
              </button>
            )}
          </div>

          {/* Secciones */}
          {sections.map((section, sectionIndex) => (
            <div
              key={sectionIndex}
              className={`${isCollapsed ? 'mb-0' : 'mb-6'} ${desktopCollapsedSectionContainerClassName}`}
            >
              {/* Línea separadora cuando está colapsado - antes de cada sección */}
              {isCollapsed && (
                <div className={`px-2 mb-0 ${desktopCollapsedSeparatorContainerClassName}`}>
                  <div
                    className={desktopCollapsedSectionSeparatorWrapperClassName}
                    style={{
                      width: '100%',
                      height: '32px',
                      paddingTop: '16px',
                      paddingRight: '8px',
                      paddingBottom: '16px',
                      paddingLeft: '8px',
                      opacity: 1,
                      transform: 'rotate(0deg)',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      boxSizing: 'border-box',
                      ...(desktopCollapsedSectionSeparatorWrapperStyle || {}),
                    }}
                  >
                    <div
                      className={desktopCollapsedSectionSeparatorClassName}
                      style={{
                        width: '42px',
                        height: '0px',
                        opacity: 1,
                        transform: 'rotate(0deg)',
                        borderTopWidth: '1px',
                        borderTopStyle: 'solid',
                        borderTopColor: '#2D5C63',
                        marginLeft: 'auto',
                        marginRight: 'auto',
                        ...(desktopCollapsedSectionSeparatorStyle || {}),
                      }}
                    />
                  </div>
                </div>
              )}
              
              {/* Título de la sección - solo visible cuando NO está colapsado */}
              {!isCollapsed && (
                <div className="px-4 mb-2">
                  <Typography
                    className="text-sidebar-core color-gray-500 uppercase font-medium tracking-wider"
                  >
                    {section.title}
                  </Typography>
                </div>
              )}

              {/* Items de la sección */}
              <div>
                {section.items.map((item) => (
                  <div key={item.id} className={isCollapsed ? 'px-2' : 'px-4'}>
                    {isCollapsed ? (
                      <div
                        className={desktopCollapsedItemWrapperClassName}
                        style={{
                          ...collapsedItemWrapperDefaults,
                          backgroundColor:
                            activeItem === item.id ? desktopCollapsedItemActiveBackgroundColor : 'transparent',
                          ...(desktopCollapsedItemWrapperStyle || {}),
                        }}
                        title={item.label}
                      >
                        <button
                          onClick={() => onItemClick && onItemClick(item.id)}
                          className="flex items-center justify-center transition-all duration-200"
                          style={{
                            width: '100%',
                            height: '100%',
                            backgroundColor: 'transparent',
                            borderRadius: '8px',
                          }}
                          title={item.label}
                        >
                          <div
                            className="flex items-center"
                            style={{
                              justifyContent: 'center',
                              columnGap: `${desktopCollapsedOverlapColumnGapPx}px`,
                              width: '100%',
                            }}
                          >
                            <div
                              style={{
                                width: `${desktopNavIconSize}px`,
                                height: `${desktopNavIconSize}px`,
                                opacity: 1,
                                transform: 'rotate(0deg)',
                                display: 'flex',
                                alignItems: 'center',
                                justifyContent: 'center',
                                marginLeft:
                                  desktopCollapsedOverlapEnabled &&
                                  ((itemBadges[item.id] !== undefined && itemBadges[item.id] > 0) ||
                                    (item.id === 'empleados' && 2))
                                    ? `${desktopCollapsedOverlapIconMarginLeftPx}px`
                                    : undefined,
                                ...(desktopCollapsedIconWrapperStyle || {}),
                              }}
                            >
                              <div
                                style={{
                                  width: '24px',
                                  height: '24px',
                                  opacity: 1,
                                  transform: 'rotate(0deg)',
                                  display: 'flex',
                                  alignItems: 'center',
                                  justifyContent: 'center',
                                  ...(desktopCollapsedIconInnerStyle || {}),
                                }}
                              >
                                <Icon
                                  name={item.icon}
                                  variant="24-outline"
                                  size={desktopNavIconGlyphSize}
                                  className={activeItem === item.id ? 'color-white' : 'color-gray-700'}
                                  style={{
                                    width: `${desktopNavIconGlyphSize}px`,
                                    height: `${desktopNavIconGlyphSize}px`,
                                    opacity: 1,
                                    transform: 'rotate(0deg)',
                                    ...(desktopNavIconStyle || {}),
                                  }}
                                />
                              </div>
                            </div>
                            {((itemBadges[item.id] !== undefined && itemBadges[item.id] > 0) || (item.id === 'empleados' && 2)) && (
                              <span
                                className={`flex items-center justify-center text-body-sm-14 font-medium ${desktopCollapsedBadgeClassName}`}
                                style={{
                                  backgroundColor: activeItem === item.id ? '#ffffff' : '#6D3856',
                                  color: activeItem === item.id ? '#6D3856' : '#ffffff',
                                  width: desktopCollapsedBadgeWidth,
                                  height: desktopCollapsedBadgeHeight,
                                  paddingTop: '4px',
                                  paddingRight: '6px',
                                  paddingBottom: '4px',
                                  paddingLeft: '6px',
                                  borderRadius: '16px',
                                  opacity: 1,
                                  transform: 'rotate(0deg)',
                                  marginLeft: desktopCollapsedOverlapEnabled
                                    ? `${desktopCollapsedOverlapBadgeMarginLeftPx}px`
                                    : undefined,
                                  boxSizing: 'border-box',
                                  ...(desktopCollapsedBadgeStyle || {}),
                                }}
                              >
                                {item.id === 'empleados' ? 2 : (itemBadges[item.id] > 9 ? '9+' : itemBadges[item.id])}
                              </span>
                            )}
                          </div>
                        </button>
                      </div>
                    ) : (
                      <button
                        onClick={() => onItemClick && onItemClick(item.id)}
                        className={`w-full flex items-center cursor-pointer px-4 justify-between py-2.5 rounded-lg transition-all duration-200 ${
                          activeItem === item.id
                            ? ''
                            : 'color-gray-700 hover:bg-gray-100'
                        }`}
                        style={
                          activeItem === item.id
                            ? { backgroundColor: '#2D5C63' }
                            : {}
                        }
                      >
                        <div className="flex items-center">
                          <Icon
                            name={item.icon}
                            variant="24-outline"
                            size={desktopNavIconGlyphSize}
                            className={`mr-3 ${
                              activeItem === item.id ? 'color-white' : 'color-gray-700'
                            }`}
                          />
                          <Typography
                            variant="body-lg"
                            weight={activeItem === item.id ? desktopItemLabelWeightActive : desktopItemLabelWeightInactive}
                            className={`${
                              activeItem === item.id ? 'color-white' : 'color-gray-700'
                            } min-w-0`}
                            style={{
                              fontSize: desktopItemLabelFontSize,
                              overflow: 'hidden',
                              textOverflow: 'ellipsis',
                              whiteSpace: 'nowrap',
                            }}
                          >
                            {item.label}
                          </Typography>
                        </div>
                        {((itemBadges[item.id] !== undefined && itemBadges[item.id] > 0) || (item.id === 'empleados' && 2)) && (
                          <span
                            className="px-2 py-0.5 min-w-[20px] h-5 
                                     rounded-full flex items-center justify-center
                                     text-body-sm-14 font-medium flex-shrink-0"
                            style={{ 
                              backgroundColor: activeItem === item.id ? '#ffffff' : '#6D3856',
                              color: activeItem === item.id ? '#6D3856' : '#ffffff',
                              borderRadius: '12px',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              lineHeight: '1'
                            }}
                          >
                            {item.id === 'empleados' ? 2 : (itemBadges[item.id] > 9 ? '9+' : itemBadges[item.id])}
                          </span>
                        )}
                      </button>
                    )}
                  </div>
                ))}
              </div>
            </div>
          ))}
          </div>
        </div>

        {/* Sección de Configuración - Desktop expandido */}
        {!isCollapsed && (
          <div 
            className="flex-shrink-0 px-4"
            style={{
              paddingTop: '24px',
              paddingBottom: '40px',
              position: 'relative',
            }}
          >
            {/* Borde superior centrado */}
            <div
              style={{
                position: 'absolute',
                top: '0px',
                left: '16px',
                right: '16px',
                height: '1px',
                backgroundColor: '#E5E5E5',
              }}
            />
            <button
              onClick={() => {
                onItemClick && onItemClick(configSectionId);
                onConfigClick && onConfigClick(configSectionId);
              }}
              className={`w-full flex items-center cursor-pointer px-4 justify-between py-2.5 rounded-lg transition-all duration-200 ${
                activeItem === configSectionId
                  ? ''
                  : 'color-gray-700 hover:bg-gray-100'
              }`}
              style={
                activeItem === configSectionId
                  ? { backgroundColor: '#2D5C63' }
                  : {}
              }
            >
              <div className="flex items-center">
                <Icon
                  name={configSectionIcon}
                  variant="24-outline"
                  size={desktopNavIconGlyphSize}
                  className={`mr-3 ${
                    activeItem === configSectionId ? 'color-white' : 'color-gray-700'
                  }`}
                />
                <Typography
                  variant="body-lg"
                  weight={activeItem === configSectionId ? desktopItemLabelWeightActive : desktopItemLabelWeightInactive}
                  className={`${
                    activeItem === configSectionId ? 'color-white' : 'color-gray-700'
                  } min-w-0`}
                  style={{
                    fontSize: desktopItemLabelFontSize,
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap',
                  }}
                >
                  {resolvedConfigSectionLabel}
                </Typography>
              </div>
              {configBadge !== undefined && configBadge > 0 && (
                <span
                  className="px-2 py-0.5 min-w-[20px] h-5 
                           rounded-full flex items-center justify-center
                           text-body-sm-14 font-medium flex-shrink-0"
                  style={{ 
                    backgroundColor: activeItem === configSectionId ? '#ffffff' : '#6D3856',
                    color: activeItem === configSectionId ? '#6D3856' : '#ffffff',
                    borderRadius: '12px',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    lineHeight: '1'
                  }}
                >
                  {configBadge > 9 ? '9+' : configBadge}
                </span>
              )}
            </button>
          </div>
        )}

        {/* Sección de Configuración - Desktop colapsado */}
        {isCollapsed && (
          <div 
            className="flex-shrink-0 px-2"
            style={{
              paddingTop: '24px',
              paddingBottom: '40px',
              position: 'relative',
            }}
          >
            {/* Borde superior centrado */}
            <div
              style={{
                position: 'absolute',
                top: '0px',
                left: '8px',
                right: '8px',
                height: '1px',
                backgroundColor: '#E5E5E5',
              }}
            />
            <div
              className={desktopCollapsedItemWrapperClassName}
              style={{
                ...collapsedItemWrapperDefaults,
                backgroundColor:
                  activeItem === configSectionId ? desktopCollapsedItemActiveBackgroundColor : 'transparent',
                ...(desktopCollapsedItemWrapperStyle || {}),
              }}
              title={resolvedConfigSectionLabel}
            >
              <button
                onClick={() => {
                  onItemClick && onItemClick(configSectionId);
                  onConfigClick && onConfigClick(configSectionId);
                }}
                className="flex items-center justify-center transition-all duration-200"
                style={{
                  width: '100%',
                  height: '100%',
                  backgroundColor: 'transparent',
                  borderRadius: '8px',
                }}
                title={resolvedConfigSectionLabel}
              >
                <div
                  className="flex items-center"
                  style={{
                    justifyContent: 'center',
                    columnGap: `${desktopCollapsedOverlapColumnGapPx}px`,
                    width: '100%',
                  }}
                >
                  <div
                    style={{
                      width: `${desktopNavIconSize}px`,
                      height: `${desktopNavIconSize}px`,
                      opacity: 1,
                      transform: 'rotate(0deg)',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      marginLeft:
                        desktopCollapsedOverlapEnabled &&
                        configBadge !== undefined &&
                        configBadge > 0
                          ? `${desktopCollapsedOverlapIconMarginLeftPx}px`
                          : undefined,
                      ...(desktopCollapsedIconWrapperStyle || {}),
                    }}
                  >
                    <div
                      style={{
                        width: '24px',
                        height: '24px',
                        opacity: 1,
                        transform: 'rotate(0deg)',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        ...(desktopCollapsedIconInnerStyle || {}),
                      }}
                    >
                      <Icon
                        name={configSectionIcon}
                        variant="24-outline"
                        size={desktopNavIconGlyphSize}
                        className={activeItem === configSectionId ? 'color-white' : 'color-gray-700'}
                        style={{
                          width: `${desktopNavIconGlyphSize}px`,
                          height: `${desktopNavIconGlyphSize}px`,
                          opacity: 1,
                          transform: 'rotate(0deg)',
                          ...(desktopNavIconStyle || {}),
                        }}
                      />
                    </div>
                  </div>
                  {configBadge !== undefined && configBadge > 0 && (
                    <span
                      className={`flex items-center justify-center text-body-sm-14 font-medium ${desktopCollapsedBadgeClassName}`}
                      style={{
                        backgroundColor: activeItem === configSectionId ? '#ffffff' : '#6D3856',
                        color: activeItem === configSectionId ? '#6D3856' : '#ffffff',
                        width: desktopCollapsedBadgeWidth,
                        height: desktopCollapsedBadgeHeight,
                        paddingTop: '4px',
                        paddingRight: '6px',
                        paddingBottom: '4px',
                        paddingLeft: '6px',
                        borderRadius: '16px',
                        opacity: 1,
                        transform: 'rotate(0deg)',
                        marginLeft: desktopCollapsedOverlapEnabled
                          ? `${desktopCollapsedOverlapBadgeMarginLeftPx}px`
                          : undefined,
                        boxSizing: 'border-box',
                        ...(desktopCollapsedBadgeStyle || {}),
                      }}
                    >
                      {configBadge > 9 ? '9+' : configBadge}
                    </span>
                  )}
                </div>
              </button>
            </div>
          </div>
        )}

        {/* Footer con texto configurable - cuando está expandido */}
        {footerText && !isCollapsed && (
          <div className="px-4 pb-4 flex-shrink-0">
            <div 
              className="bg-white border rounded-lg px-3 py-2 flex items-center justify-center"
              style={{ 
                borderColor: '#2D5C63',
                borderRadius: '8px'
              }}
            >
              {typeof footerText === 'string' ? (
                <Typography
                  variant="body-sm"
                  style={{ color: '#2D5C63', fontSize: '14px', lineHeight: '20px' }}
                  className="text-center"
                >
                  {(() => {
                    const parts = footerText.split('|');
                    if (parts.length === 2) {
                      const leftPart = parts[0].trim();
                      const rightPart = parts[1].trim();
                      // Si contiene "Powered by", separar y poner la marca en bold
                      if (rightPart.includes('Powered by')) {
                        const poweredByMatch = rightPart.match(/Powered by (.+)/);
                        if (poweredByMatch) {
                          return (
                            <>
                              {leftPart} | Powered by <span className="font-bold">{poweredByMatch[1]}</span>
                            </>
                          );
                        }
                      }
                      return `${leftPart} | ${rightPart}`;
                    }
                    return footerText;
                  })()}
                </Typography>
              ) : (
                <Typography
                  variant="body-sm"
                  style={{ color: '#2D5C63', fontSize: '14px', lineHeight: '20px' }}
                  className="text-center"
                >
                  {footerText.version && `${footerText.version}`}
                  {footerText.version && (footerText.poweredBy || footerText.brand) && ' | '}
                  {footerText.poweredBy && `${footerText.poweredBy} `}
                  {footerText.brand && <span className="font-bold">{footerText.brand}</span>}
                </Typography>
              )}
            </div>
          </div>
        )}

        {/* Footer cuando está colapsado */}
        {effectiveFooterCollapsedContent && isCollapsed && (
          <div className="px-2 pt-2 pb-2 flex justify-center flex-shrink-0" style={{ zIndex: 10 }}>
            <div 
              className={`bg-white flex items-center justify-center ${desktopCollapsedFooterContainerClassName}`}
              style={{ 
                width: '100%',
                height: '32px',
                borderRadius: '8px',
                border: '1px solid var(--color-main-800)',
                paddingTop: '8px',
                paddingRight: '12px',
                paddingBottom: '8px',
                paddingLeft: '12px',
                gap: '10px',
                opacity: 1,
                transform: 'rotate(0deg)',
                boxSizing: 'border-box',
                ...(desktopCollapsedFooterContainerStyle || {})
              }}
            >
              {typeof effectiveFooterCollapsedContent === 'string' ? (
                <span
                  className={desktopCollapsedFooterTextClassName}
                  style={{ 
                    color: 'var(--color-cyan-19)',
                    fontFamily: FONT_FAMILY_SANS,
                    fontWeight: 400,
                    fontStyle: 'normal',
                    fontSize: '12px',
                    lineHeight: '100%',
                    letterSpacing: '0%',
                    textAlign: 'center',
                    whiteSpace: 'nowrap',
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    maxWidth: '100%',
                    ...(desktopCollapsedFooterTextStyle || {})
                  }}
                >
                  {effectiveFooterCollapsedContent}
                </span>
              ) : typeof effectiveFooterCollapsedContent === 'object' && effectiveFooterCollapsedContent.icon ? (
                <div className="flex items-center justify-center">
                  {effectiveFooterCollapsedContent.icon && (
                    <Icon
                      name={effectiveFooterCollapsedContent.icon}
                      variant="24-outline"
                      size={14}
                      style={{ color: '#2D5C63' }}
                    />
                  )}
                  {effectiveFooterCollapsedContent.text && (
                    <span
                      className={desktopCollapsedFooterTextClassName}
                      style={{ 
                        color: 'var(--color-cyan-19)',
                        fontFamily: FONT_FAMILY_SANS,
                        fontWeight: 400,
                        fontStyle: 'normal',
                        fontSize: '12px',
                        lineHeight: '100%',
                        letterSpacing: '0%',
                        textAlign: 'center',
                        marginLeft: effectiveFooterCollapsedContent.icon ? '4px' : '0',
                        ...(desktopCollapsedFooterTextStyle || {})
                      }}
                    >
                      {effectiveFooterCollapsedContent.text}
                    </span>
                  )}
                </div>
              ) : (
                effectiveFooterCollapsedContent
              )}
            </div>
          </div>
        )}
      </nav>
    </aside>
  );
};

// Exportar ambos componentes
export { SidebarCoreMobile };
export default SidebarCore;

