import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Icon } from '../../Atoms/Icon/Icon';
import { Avatar } from '../../Atoms/Avatar/Avatar';
import { Typography } from '../../Atoms/Typography/Typography';
import { Badge } from '../../Atoms/Badge/Badge';
import { SidebarCoreMobile } from '../Sidebar/SidebarCore';
import { DesplegablePerfil } from '../DesplegablePerfil/DesplegablePerfil';
import { FONT_FAMILY_SANS } from '../../../designTokens';

const getFirstNonEmptyValue = (...values) => {
  for (const value of values) {
    if (value === null || value === undefined) continue;
    const stringValue = String(value).trim();
    if (stringValue) return stringValue;
  }
  return '';
};

const getPersonaSearchResultData = (item) => {
  if (!item || typeof item !== 'object') {
    const label = getFirstNonEmptyValue(item);
    return {
      id: label,
      name: label,
      email: '',
      document: '',
      status: '',
      avatar: '',
    };
  }

  return {
    id: getFirstNonEmptyValue(item.id, item.personId),
    name: getFirstNonEmptyValue(item.nombre, item.name, item.fullName, item.label),
    email: getFirstNonEmptyValue(item.email),
    document: getFirstNonEmptyValue(item.documento, item.document),
    status: getFirstNonEmptyValue(item.estado, item.statusLabel, item.status),
    avatar: getFirstNonEmptyValue(item.foto, item.avatar, item.image, item.userAvatar),
  };
};

const getPersonaInitials = (name) => {
  const parts = String(name || '')
    .trim()
    .split(/\s+/)
    .filter(Boolean);
  if (parts.length === 0) return '';
  if (parts.length === 1) return parts[0].slice(0, 1).toUpperCase();
  return `${parts[0].slice(0, 1)}${parts[1].slice(0, 1)}`.toUpperCase();
};

const getPersonaBadgeVariant = (status) => {
  const normalizedStatus = String(status || '').trim().toLowerCase();
  if (normalizedStatus === 'activa' || normalizedStatus === 'active') return 'success';
  return 'inactive';
};

export const HeaderCore = ({
  searchValue: controlledSearchValue,
  searchPlaceholder,
  mobileSearchPlaceholder,
  userName,
  userAvatar,
  notificationCount = 0,
  onSearch,
  onNotificationClick,
  onUserClick,
  onProfileClick,
  onSettingsClick,
  onHelpClick,
  onLogoutClick,
  // Borde inferior (subrayado)
  showBottomBorder = false,
  bottomBorderClassName = 'border-b border-gray-200',
  // Sidebar mobile (animación/cierre controlado)
  mobileSidebarTransitionDurationMs = 300,
  mobileSidebarTransitionEasing = 'ease-in-out',
  // Mobile background
  mobileBackgroundColor = '#F3F3F3',
  mobileHeaderClassName = '',
  mobileHeaderStyle,
  // Overrides de estilo/clases para poder ajustar layout desde el proyecto consumidor
  desktopLayoutClassName = '',
  desktopLayoutStyle,
  desktopSearchContainerClassName = '',
  desktopSearchContainerStyle,
  desktopRightContainerClassName = '',
  desktopRightContainerStyle,
  notificationButtonClassName = '',
  notificationButtonStyle,
  notificationIconClassName = '',
  notificationIconStyle,
  notificationBadgeClassName = '',
  notificationBadgeStyle,
  // Overrides específicos de medidas/posiciones (Desktop / Mobile)
  notificationDesktopButtonStyle,
  notificationDesktopIconWrapperClassName = '',
  notificationDesktopIconWrapperStyle,
  notificationDesktopIconSize = 24,
  notificationDesktopIconStrokeWidth = 1.5,
  notificationDesktopIconStyle,
  notificationDesktopBadgeStyle,
  notificationMobileButtonClassName = '',
  notificationMobileButtonStyle,
  notificationMobileIconWrapperClassName = '',
  notificationMobileIconWrapperStyle,
  notificationMobileIconSize = 24,
  notificationMobileIconStrokeWidth = 1.5,
  notificationMobileIconStyle,
  showNotificationBadgeOnMobile = false,
  notificationMobileBadgeStyle,
  // Desktop avatar / nombre (overrides)
  desktopUserAvatarClassName = '',
  desktopUserAvatarStyle,
  desktopUserNameStyle,
  // Mobile avatar (overrides)
  mobileUserAvatarClassName = '',
  mobileUserAvatarStyle,
  searchResults = [],
  isSearchResultsOpen = false,
  searchResultsLoading = false,
  searchResultsEmptyText,
  searchResultsAriaLabel,
  maxVisibleSearchResults = 3,
  searchResultItemMinHeight = 96,
  searchResultsPanelClassName = '',
  searchResultsPanelStyle,
  searchResultsListClassName = '',
  searchResultsListStyle,
  searchResultsScrollbarInsetPx = 8,
  searchResultsContainerClassName = '',
  searchResultsContainerStyle,
  searchResultVariant = 'default',
  renderSearchResultItem,
  getSearchResultKey,
  onSearchResultClick,
  onSearchResultsClose,
  sidebarSections,
  sidebarActiveItem,
  onSidebarItemClick,
  // Mobile: permitir persistir el item activo aunque el consumidor no controle sidebarActiveItem
  enableInternalSidebarActiveItem = true,
  sidebarItemBadges,
  sidebarCompanyName,
  sidebarCompanyLogo,
  sidebarFooterText,
  sidebarFooterCollapsedContent,
  sidebarCoreContainerStyle,
  sidebarCoreTextStyle,
  // Breakpoints (resolución): el consumidor puede override; por defecto los valores actuales
  breakpointMobileMaxPx = 1024,
  breakpointDesktopUserNameMinPx = 1440,
  breakpointSidebarMobileWidthMinPx = 640,
  breakpointSidebarMobileWidthMaxPx = 1024,
  className = '',
  ...props
}) => {
  const { t } = useTranslation();
  const [internalSearchValue, setInternalSearchValue] = useState('');
  const [isSidebarOpen, setIsSidebarOpen] = useState(false);
  const [shouldRenderSidebarMobile, setShouldRenderSidebarMobile] = useState(false);
  const [internalSidebarActiveItem, setInternalSidebarActiveItem] = useState(undefined);
  const [isProfileDropdownOpen, setIsProfileDropdownOpen] = useState(false);
  const [isMobileViewport, setIsMobileViewport] = useState(() =>
    typeof window !== 'undefined' ? window.matchMedia(`(max-width: ${breakpointMobileMaxPx}px)`).matches : false
  );
  const closeTimeoutRef = useRef(null);
  const profileButtonRef = useRef(null);
  const profileButtonMobileRef = useRef(null);
  const desktopSearchContainerRef = useRef(null);
  const mobileSearchContainerRef = useRef(null);
  const searchResultsListRef = useRef(null);
  const searchResultsScrollRafRef = useRef(null);
  const [isDraggingSearchResultsScrollbar, setIsDraggingSearchResultsScrollbar] = useState(false);
  const bellIconName = notificationCount > 0 ? 'BellAlertIcon' : 'BellIcon';
  const hasSearchResults = Array.isArray(searchResults) && searchResults.length > 0;
  const shouldShowSearchResults = isSearchResultsOpen && (searchResultsLoading || hasSearchResults || !!searchResultsEmptyText);
  const resolvedSearchValue = controlledSearchValue !== undefined ? controlledSearchValue : internalSearchValue;
  const [searchResultsScrollState, setSearchResultsScrollState] = useState({
    scrollTop: 0,
    clientHeight: 0,
    scrollHeight: 0,
  });

  const openSidebarMobile = () => {
    if (closeTimeoutRef.current) {
      clearTimeout(closeTimeoutRef.current);
      closeTimeoutRef.current = null;
    }
    // Para que se vea la animación de apertura:
    // 1) montamos el sidebar en estado cerrado
    // 2) lo abrimos en el siguiente frame (después de pintar)
    setShouldRenderSidebarMobile(true);
    setIsSidebarOpen(false);
    requestAnimationFrame(() => setIsSidebarOpen(true));
  };

  const closeSidebarMobile = () => {
    setIsSidebarOpen(false);
  };

  const resolvedSidebarActiveItem =
    sidebarActiveItem !== undefined && sidebarActiveItem !== null
      ? sidebarActiveItem
      : enableInternalSidebarActiveItem
        ? internalSidebarActiveItem
        : sidebarActiveItem;

  useEffect(() => {
    if (typeof window === 'undefined') return undefined;
    const mql = window.matchMedia(`(max-width: ${breakpointMobileMaxPx}px)`);
    const handle = () => setIsMobileViewport(mql.matches);
    handle();
    mql.addEventListener('change', handle);
    return () => {
      mql.removeEventListener('change', handle);
    };
  }, [breakpointMobileMaxPx]);

  useEffect(() => {
    if (!isSidebarOpen && shouldRenderSidebarMobile) {
      closeTimeoutRef.current = setTimeout(() => {
        setShouldRenderSidebarMobile(false);
        closeTimeoutRef.current = null;
      }, mobileSidebarTransitionDurationMs);
    }
    return () => {
      if (closeTimeoutRef.current) {
        clearTimeout(closeTimeoutRef.current);
        closeTimeoutRef.current = null;
      }
    };
  }, [isSidebarOpen, shouldRenderSidebarMobile, mobileSidebarTransitionDurationMs]);

  const handleSearchChange = (e) => {
    const value = e.target.value;
    setInternalSearchValue(value);
    if (onSearch) {
      onSearch(value);
    }
  };

  const handleSearchSubmit = (e) => {
    e.preventDefault();
    if (onSearch) {
      onSearch(resolvedSearchValue);
    }
  };

  const handleToggleProfileDropdown = () => {
    setIsProfileDropdownOpen((prev) => {
      const newState = !prev;
      // Si hay un callback onUserClick, también lo ejecutamos para mantener compatibilidad
      if (onUserClick && !newState) {
        onUserClick();
      }
      return newState;
    });
  };

  const handleCloseProfileDropdown = () => {
    setIsProfileDropdownOpen(false);
  };

  useEffect(() => {
    if (!shouldShowSearchResults) return undefined;
    const handleClickOutsideSearchResults = (event) => {
      const target = event?.target;
      const clickedInsideDesktop = desktopSearchContainerRef.current?.contains?.(target);
      const clickedInsideMobile = mobileSearchContainerRef.current?.contains?.(target);
      if (clickedInsideDesktop || clickedInsideMobile) return;
      onSearchResultsClose?.();
    };
    document.addEventListener('mousedown', handleClickOutsideSearchResults);
    return () => {
      document.removeEventListener('mousedown', handleClickOutsideSearchResults);
    };
  }, [shouldShowSearchResults, onSearchResultsClose]);

  const syncSearchResultsScrollState = () => {
    const el = searchResultsListRef.current;
    if (!el) return;
    if (searchResultsScrollRafRef.current) return;
    searchResultsScrollRafRef.current = window.requestAnimationFrame(() => {
      searchResultsScrollRafRef.current = null;
      setSearchResultsScrollState((prev) => {
        const next = {
          scrollTop: el.scrollTop,
          clientHeight: el.clientHeight,
          scrollHeight: el.scrollHeight,
        };
        if (
          prev.scrollTop === next.scrollTop &&
          prev.clientHeight === next.clientHeight &&
          prev.scrollHeight === next.scrollHeight
        ) {
          return prev;
        }
        return next;
      });
    });
  };

  useEffect(() => {
    if (!shouldShowSearchResults) return undefined;
    const el = searchResultsListRef.current;
    if (!el) return undefined;
    const onScroll = () => syncSearchResultsScrollState();
    syncSearchResultsScrollState();
    el.addEventListener('scroll', onScroll, { passive: true });
    const timerId = window.setTimeout(() => syncSearchResultsScrollState(), 0);
    const onResize = () => syncSearchResultsScrollState();
    window.addEventListener('resize', onResize);
    return () => {
      window.clearTimeout(timerId);
      window.removeEventListener('resize', onResize);
      el.removeEventListener('scroll', onScroll);
      if (searchResultsScrollRafRef.current) {
        window.cancelAnimationFrame(searchResultsScrollRafRef.current);
        searchResultsScrollRafRef.current = null;
      }
    };
  }, [shouldShowSearchResults, searchResults, searchResultsLoading, maxVisibleSearchResults, searchResultItemMinHeight]);

  const handleSearchResultItemClick = (item, index, event) => {
    onSearchResultClick?.(item, index, event);
  };

  const renderDefaultSearchResult = (item) => {
    if (item == null) return '';
    if (typeof item === 'string' || typeof item === 'number') return String(item);
    if (typeof item === 'object') {
      return item.label ?? item.name ?? item.title ?? item.id ?? '';
    }
    return '';
  };

  const renderPersonaSearchResult = (item) => {
    const persona = getPersonaSearchResultData(item);
    const resolvedName = persona.name || t('header.searchResultPersonaUnnamed', { defaultValue: 'Sin nombre' });
    const statusLabel = persona.status;
    const secondaryDesktop = [persona.email, persona.document].filter(Boolean).join(' · ');
    const shouldShowStatus = !!statusLabel;

    return (
      <div
        style={{
          width: '100%',
          display: 'flex',
          alignItems: isMobileViewport ? 'flex-start' : 'center',
          justifyContent: 'space-between',
          gap: '12px',
          padding: '12px 16px',
          boxSizing: 'border-box',
        }}
      >
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: '12px', minWidth: 0, flex: 1 }}>
          {persona.avatar ? (
            <img
              src={persona.avatar}
              alt=""
              style={{ width: 40, height: 40, borderRadius: '999px', objectFit: 'cover', flexShrink: 0 }}
            />
          ) : (
            <div
              style={{
                width: 40,
                height: 40,
                borderRadius: '999px',
                border: '1px solid #38656D',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                color: '#38656D',
                fontFamily: FONT_FAMILY_SANS,
                fontWeight: 500,
                fontSize: '14px',
                flexShrink: 0,
              }}
            >
              {getPersonaInitials(resolvedName)}
            </div>
          )}
          <div style={{ minWidth: 0 }}>
            <Typography
              component="p"
              style={{
                margin: 0,
                fontFamily: FONT_FAMILY_SANS,
                fontSize: 16,
                lineHeight: '24px',
                color: '#29474C',
                fontWeight: 450,
                fontStyle: 'normal',
                letterSpacing: '0%',
                whiteSpace: 'nowrap',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
              }}
            >
              {resolvedName}
            </Typography>
            {(persona.email || (!isMobileViewport && persona.document)) && (
              <Typography
                component="p"
                style={{
                  margin: 0,
                  fontFamily: FONT_FAMILY_SANS,
                  fontSize: 14,
                  lineHeight: '21px',
                  color: '#29474C',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                }}
              >
                {isMobileViewport ? persona.email : secondaryDesktop}
              </Typography>
            )}
            {isMobileViewport && persona.document && (
              <Typography
                component="p"
                style={{
                  margin: 0,
                  fontFamily: FONT_FAMILY_SANS,
                  fontSize: 14,
                  lineHeight: '21px',
                  color: '#29474C',
                  whiteSpace: 'nowrap',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                }}
              >
                {persona.document}
              </Typography>
            )}
            {isMobileViewport && shouldShowStatus && (
              <div style={{ marginTop: 8 }}>
                <Badge variant={getPersonaBadgeVariant(statusLabel)} size="medium">
                  {statusLabel}
                </Badge>
              </div>
            )}
          </div>
        </div>
        {!isMobileViewport && shouldShowStatus && (
          <Badge variant={getPersonaBadgeVariant(statusLabel)} size="medium">
            {statusLabel}
          </Badge>
        )}
      </div>
    );
  };

  const renderResolvedSearchResult = (item, index) => {
    if (renderSearchResultItem) return renderSearchResultItem(item, index);
    if (searchResultVariant === 'persona') return renderPersonaSearchResult(item);
    return (
      <div
        className="px-4 py-3 text-sm color-gray-700"
        style={{ fontFamily: FONT_FAMILY_SANS }}
      >
        {renderDefaultSearchResult(item)}
      </div>
    );
  };

  const renderSearchResultsPanel = () => {
    if (!shouldShowSearchResults) return null;
    const resolvedEmptyText =
      searchResultsEmptyText ?? t('header.searchResultsEmpty', { defaultValue: 'Sin resultados' });
    const resolvedAria =
      searchResultsAriaLabel ?? t('header.searchResultsAria', { defaultValue: 'Resultados de búsqueda' });
    const SEARCH_RESULTS_SCROLLBAR_GUTTER_PX = 20;
    return (
      <div
        className={`absolute left-0 right-0 top-full mt-2 bg-white border border-gray-200 radius-12 shadow-lg z-[1000] ${searchResultsPanelClassName}`}
        style={{
          overflow: 'hidden',
          ...(searchResultsPanelStyle || {}),
        }}
        role="listbox"
        aria-label={resolvedAria}
      >
        <div
          style={{
            position: 'relative',
            paddingTop: 0,
            paddingRight: `${searchResultsScrollbarInsetPx}px`,
            paddingBottom: 0,
            paddingLeft: 0,
            boxSizing: 'border-box',
          }}
        >
          <div
            className={`header-core-search-results-list ${searchResultsListClassName}`}
            ref={searchResultsListRef}
            style={{
              maxHeight: `${Math.max(1, maxVisibleSearchResults) * Math.max(1, searchResultItemMinHeight)}px`,
              overflowY: hasSearchResults ? 'auto' : 'hidden',
              overflowX: 'hidden',
              paddingRight: hasSearchResults ? `${SEARCH_RESULTS_SCROLLBAR_GUTTER_PX}px` : 0,
              ...(searchResultsListStyle || {}),
            }}
          >
            {searchResultsLoading ? (
              <div
                className="px-4 py-3 text-sm color-gray-600"
                style={{ fontFamily: FONT_FAMILY_SANS }}
              >
                {t('common.loading', { defaultValue: 'Cargando...' })}
              </div>
            ) : hasSearchResults ? (
              searchResults.map((item, index) => (
                <button
                  key={getSearchResultKey ? getSearchResultKey(item, index) : `${index}`}
                  type="button"
                  className="header-core-search-result-item w-full text-left block bg-white transition-colors"
                  style={{
                    width: hasSearchResults
                      ? `calc(100% + ${SEARCH_RESULTS_SCROLLBAR_GUTTER_PX}px)`
                      : '100%',
                    marginRight: hasSearchResults ? `-${SEARCH_RESULTS_SCROLLBAR_GUTTER_PX}px` : 0,
                    borderBottom:
                      index < searchResults.length - 1 ? '1px solid var(--color-grey-100, #DDDDDD)' : 'none',
                  }}
                  onClick={(event) => handleSearchResultItemClick(item, index, event)}
                >
                  {renderResolvedSearchResult(item, index)}
                </button>
              ))
            ) : (
              <div
                className="px-4 py-3 text-sm color-gray-600"
                style={{ fontFamily: FONT_FAMILY_SANS }}
              >
                {resolvedEmptyText}
              </div>
            )}
          </div>
          {(() => {
            const TRACK_HEIGHT_PX = 215;
            const TRACK_WIDTH_PX = 8;
            const THUMB_HEIGHT_PX = 117;
            const THUMB_WIDTH_PX = 8;
            const BORDER_RADIUS_PX = 20;
            const hasMoreThanVisible = searchResults.length > Math.max(1, maxVisibleSearchResults);
            const canScroll =
              hasSearchResults &&
              searchResultsScrollState.scrollHeight > searchResultsScrollState.clientHeight + 1;
            const shouldShowCustomScrollbar = hasSearchResults && (canScroll || hasMoreThanVisible);
            if (!shouldShowCustomScrollbar) return null;
            const maxScrollTop = Math.max(
              1,
              searchResultsScrollState.scrollHeight - searchResultsScrollState.clientHeight
            );
            const travelPx = Math.max(0, TRACK_HEIGHT_PX - THUMB_HEIGHT_PX);
            const thumbTopPx = canScroll ? (searchResultsScrollState.scrollTop / maxScrollTop) * travelPx : 0;
            return (
              <div
                aria-hidden="true"
                style={{
                  position: 'absolute',
                  top: '50%',
                  right: `${searchResultsScrollbarInsetPx}px`,
                  transform: 'translateY(-50%)',
                  width: `${TRACK_WIDTH_PX}px`,
                  height: `${TRACK_HEIGHT_PX}px`,
                  opacity: 1,
                  zIndex: 2,
                  borderRadius: `${BORDER_RADIUS_PX}px`,
                  backgroundColor: '#D3DDE0',
                  overflow: 'hidden',
                  cursor: 'pointer',
                }}
                onMouseDown={(e) => {
                  if (e.button !== 0) return;
                  const el = searchResultsListRef.current;
                  if (!el || !canScroll) return;
                  const track = e.currentTarget;
                  const rect = track.getBoundingClientRect();
                  const y = Math.max(0, Math.min(e.clientY - rect.top, rect.height));
                  const ratio = rect.height > 0 ? y / rect.height : 0;
                  el.scrollTop = ratio * (searchResultsScrollState.scrollHeight - searchResultsScrollState.clientHeight);
                  syncSearchResultsScrollState();
                }}
              >
                <div
                  style={{
                    position: 'absolute',
                    top: `${thumbTopPx}px`,
                    left: 0,
                    width: `${THUMB_WIDTH_PX}px`,
                    height: `${THUMB_HEIGHT_PX}px`,
                    gap: '10px',
                    opacity: 1,
                    borderRadius: `${BORDER_RADIUS_PX}px`,
                    backgroundColor: '#3F6F75',
                    transition: isDraggingSearchResultsScrollbar ? 'none' : 'top 0.1s ease',
                    cursor: 'grab',
                  }}
                  onMouseDown={(e) => {
                    if (e.button !== 0) return;
                    e.stopPropagation();
                    const el = searchResultsListRef.current;
                    if (!el || !canScroll) return;
                    const track = e.currentTarget.parentElement;
                    if (!track) return;
                    const trackRect = track.getBoundingClientRect();
                    const trackHeight = trackRect.height;
                    const thumbHeightPx = THUMB_HEIGHT_PX;
                    const travelPx = Math.max(1, trackHeight - thumbHeightPx);
                    const startY = e.clientY;
                    const startTop = el.scrollTop;
                    const initialUserSelect = document.body.style.userSelect;
                    setIsDraggingSearchResultsScrollbar(true);
                    document.body.style.userSelect = 'none';
                    const onMove = (moveEvt) => {
                      const dy = moveEvt.clientY - startY;
                      const ratio = dy / travelPx;
                      const nextTop =
                        startTop + ratio * (searchResultsScrollState.scrollHeight - searchResultsScrollState.clientHeight);
                      el.scrollTop = Math.max(
                        0,
                        Math.min(
                          searchResultsScrollState.scrollHeight - searchResultsScrollState.clientHeight,
                          nextTop
                        )
                      );
                      syncSearchResultsScrollState();
                    };
                    const onUp = () => {
                      setIsDraggingSearchResultsScrollbar(false);
                      document.body.style.userSelect = initialUserSelect;
                      document.removeEventListener('mousemove', onMove);
                      document.removeEventListener('mouseup', onUp);
                    };
                    document.addEventListener('mousemove', onMove);
                    document.addEventListener('mouseup', onUp);
                  }}
                />
              </div>
            );
          })()}
        </div>
      </div>
    );
  };

  return (
    <header
      className={`bg-white ${showBottomBorder ? bottomBorderClassName : ''} ${className}`}
      {...props}
    >
      <style>{`
        .header-search-input {
          border-color: #9ca3af;
        }
        .header-search-input::placeholder {
          color: #9ca3af !important;
          opacity: 1 !important;
        }
        .header-search-icon-container {
          border-color: #9ca3af;
        }
        .header-search-form:focus-within .header-search-input {
          border-color: #3b82f6 !important;
          box-shadow: 0 0 0 1px #3b82f6;
        }
        .header-search-form:focus-within .header-search-icon-container {
          border-color: #3b82f6 !important;
          box-shadow: 0 0 0 1px #3b82f6;
        }
        .header-core-search-results-list {
          scrollbar-width: none;
          -ms-overflow-style: none;
        }
        .header-core-search-results-list::-webkit-scrollbar {
          display: none;
        }
        .header-core-search-result-item:hover {
          background: #DDDDDD !important;
        }
        /* Hasta breakpointMobileMaxPx: HeaderCore mobile. */
        @media (max-width: ${breakpointMobileMaxPx}px) {
          .header-mobile-layout {
            display: block;
          }
          .header-mobile-top-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 8px 4px;
            min-height: 48px;
          }
          .header-mobile-search-row {
            display: block;
            padding: 12px 0px 8px 0px;
          }
          .header-desktop-layout {
            display: none !important;
          }
          .header-mobile-layout .header-search-input {
            font-size: 12px !important;
            padding-left: 8px !important;
            padding-right: 8px !important;
          }
          .header-mobile-layout .header-search-icon-container {
            width: 36px !important;
          }
        }
        /* Desde breakpointMobileMaxPx: HeaderCore desktop (mismo valor para evitar hueco). */
        @media (min-width: ${breakpointMobileMaxPx}px) {
          .header-mobile-layout {
            display: none;
          }
          .header-desktop-layout {
            display: flex !important;
          }
        }
        /* breakpointMobileMaxPx – (breakpointDesktopUserNameMinPx-1): ocultar nombre de usuario en desktop. */
        @media (min-width: ${breakpointMobileMaxPx}px) and (max-width: ${breakpointDesktopUserNameMinPx - 1}px) {
          .header-desktop-user-name {
            display: none !important;
          }
        }
        /* breakpointDesktopUserNameMinPx en adelante: mostrar nombre de usuario en desktop. */
        @media (min-width: ${breakpointDesktopUserNameMinPx}px) {
          .header-desktop-user-name {
            display: block !important;
          }
        }
      `}</style>
      
      <div className="w-full">
        {/* Layout Desktop (1024px o más) */}
        <div
          className={`header-desktop-layout flex items-center justify-between h-16 ${desktopLayoutClassName}`}
          style={desktopLayoutStyle}
        >
          {/* Barra de búsqueda con icono a la derecha */}
          <div
            ref={desktopSearchContainerRef}
            className={`relative flex-1 mr-2 md:mr-4 ${desktopSearchContainerClassName} ${searchResultsContainerClassName}`}
            style={{ maxWidth: 'none', minWidth: '0', ...(desktopSearchContainerStyle || {}), ...(searchResultsContainerStyle || {}) }}
          >
            <form onSubmit={handleSearchSubmit} className="header-search-form flex items-center w-full">
              {/* Input de búsqueda */}
              <input
                type="text"
                value={resolvedSearchValue}
                onChange={handleSearchChange}
                placeholder={searchPlaceholder ?? t('header.searchPlaceholder', { defaultValue: 'Buscar empleados, reportes, configuraciones...' })}
                aria-label={searchPlaceholder ?? t('header.searchPlaceholder', { defaultValue: 'Buscar empleados, reportes, configuraciones...' })}
                className="header-search-input flex-1 pl-2 md:pl-4 pr-2 md:pr-4 py-2 md:py-2.5 bg-white border border-gray-400 rounded-l-lg 
                         focus:outline-none text-sm md:text-base"
                style={{ 
                  height: '40px', 
                  borderRight: 'none', 
                  borderTopRightRadius: '0', 
                  borderBottomRightRadius: '0',
                  color: '#374151',
                  fontFamily: FONT_FAMILY_SANS,
                  fontWeight: 400,
                  fontStyle: 'italic',
                  fontSize: '14px',
                  lineHeight: '20px',
                  letterSpacing: '0px'
                }}
              />
              
              {/* Recuadro con icono de buscar a la derecha */}
              <div 
                className="header-search-icon-container flex items-center justify-center border border-gray-400 rounded-r-lg bg-white"
                style={{
                  width: '40px',
                  height: '40px',
                  borderTopLeftRadius: '0',
                  borderBottomLeftRadius: '0'
                }}
              >
                <Icon 
                  name="MagnifyingGlassIcon" 
                  variant="24-outline" 
                  size={20} 
                  className="color-gray-600" 
                />
              </div>
            </form>
            {!isMobileViewport && renderSearchResultsPanel()}
          </div>

          {/* Notificaciones y Perfil */}
          <div
            className={`flex items-center space-x-3 md:space-x-6 flex-shrink-0 ${desktopRightContainerClassName}`}
            style={{ marginLeft: 'auto', paddingRight: '0px', ...(desktopRightContainerStyle || {}) }}
          >
            {/* Icono de notificaciones */}
            {notificationCount !== undefined && (
              <button
                onClick={onNotificationClick}
                className={`ml-3 p-2 hover:bg-gray-100 rounded-lg transition-colors flex items-center gap-2 ${notificationButtonClassName}`}
                aria-label={t('header.notificationsAria', { defaultValue: 'Notificaciones' })}
                style={{
                  // Nota: en desktop el contenedor derecho está anclado a la derecha (marginLeft: auto).
                  // Un ml-* en el primer hijo no “mueve” visualmente, porque ensancha el contenedor hacia la izquierda.
                  // Por eso usamos translateX por defecto (overrideable por props).
                  transform: 'translateX(12px)',
                  ...(notificationButtonStyle || {}),
                  ...(notificationDesktopButtonStyle || {}),
                }}
              >
                {/* Contenedor 24x24 + icono posicionado (Figma) */}
                <span
                  className={`relative inline-block ${notificationDesktopIconWrapperClassName}`}
                  style={{
                    width: '24px',
                    height: '24px',
                    opacity: 1,
                    ...(notificationDesktopIconWrapperStyle || {}),
                  }}
              >
                <Icon 
                    name={bellIconName} 
                  variant="24-outline" 
                    size={notificationDesktopIconSize}
                    strokeWidth={notificationDesktopIconStrokeWidth}
                    className={`color-gray-600 ${notificationIconClassName}`}
                    style={{
                      width: '24px',
                      height: '24px',
                      position: 'absolute',
                      top: '0px',
                      left: '0px',
                      opacity: 1,
                      transform: 'rotate(0deg)',
                      ...(notificationIconStyle || {}),
                      ...(notificationDesktopIconStyle || {}),
                    }}
                />
                </span>
                {notificationCount > 0 && (
                  <span
                    className={`h-5 text-white flex items-center justify-center text-body-sm-14 font-medium ${notificationBadgeClassName}`}
                    style={{ 
                      backgroundColor: '#6D3856',
                      minWidth: '24px',
                      width: 'fit-content',
                      height: '20px',
                      paddingTop: '2px',
                      paddingRight: '8px',
                      paddingBottom: '2px',
                      paddingLeft: '8px',
                      borderRadius: '16px',
                      opacity: 1,
                      transform: 'rotate(0deg)',
                      ...(notificationBadgeStyle || {}),
                      ...(notificationDesktopBadgeStyle || {}),
                    }}
                  >
                    {notificationCount > 9 ? '9+' : notificationCount}
                  </span>
                )}
              </button>
            )}

            {/* Perfil de usuario */}
            {userName && (
              <div className="relative">
                <button
                  ref={profileButtonRef}
                  onClick={handleToggleProfileDropdown}
                  className="flex items-center space-x-3 hover:bg-gray-50 
                           rounded-lg px-2 py-1.5 transition-colors cursor-pointer"
                  aria-label={t('header.profileAria', { defaultValue: 'Perfil de usuario' })}
                  aria-expanded={isProfileDropdownOpen}
                >
                  <Avatar
                    src={userAvatar}
                    name={userName}
                    size="medium"
                    variant="circle"
                    className={`cursor-pointer ${desktopUserAvatarClassName}`}
                    style={{
                      width: '36px',
                      height: '36px',
                      opacity: 1,
                      borderRadius: '16777200px',
                      transform: 'rotate(0deg)',
                      ...(desktopUserAvatarStyle || {}),
                    }}
                  />
                  <Typography
                    variant="body-lg"
                    className="header-desktop-user-name color-gray-700 hidden md:block cursor-pointer"
                    style={{
                      fontFamily: FONT_FAMILY_SANS,
                      fontWeight: 400,
                      fontStyle: 'normal',
                      fontSize: '16px',
                      lineHeight: '24px',
                      letterSpacing: '0%',
                      verticalAlign: 'middle'
                      ,...(desktopUserNameStyle || {})
                    }}
                  >
                    {userName}
                  </Typography>
                  <Icon
                    name="ChevronDownIcon"
                    variant="24-outline"
                    size={20}
                    className="color-gray-500 cursor-pointer transition-transform duration-200"
                    style={{
                      transform: isProfileDropdownOpen ? 'rotate(180deg)' : 'rotate(0deg)',
                    }}
                  />
                </button>
                <DesplegablePerfil
                  isOpen={isProfileDropdownOpen}
                  onClose={handleCloseProfileDropdown}
                  onProfileClick={onProfileClick}
                  onSettingsClick={onSettingsClick}
                  onHelpClick={onHelpClick}
                  onLogoutClick={onLogoutClick}
                  triggerRef={profileButtonRef}
                />
              </div>
            )}
          </div>
        </div>

        {/* Layout Mobile (menos de 1024px) */}
        <div
          className={`header-mobile-layout ${mobileHeaderClassName}`}
          style={{ background: mobileBackgroundColor, ...(mobileHeaderStyle || {}) }}
        >
          {/* Primera fila: Menú, Core, Notificaciones y Avatar */}
          <div className="header-mobile-top-row">
            {/* Lado izquierdo: Menú hamburguesa y Core */}
            <div className="flex items-center space-x-2">
              {/* Botón menú hamburguesa */}
              <button
                onClick={openSidebarMobile}
                className="p-2 hover:bg-gray-100 rounded-lg transition-colors"
                aria-label={t('header.menuAria', { defaultValue: 'Menú' })}
              >
                <Icon 
                  name="Bars3Icon" 
                  variant="24-outline" 
                  size={24} 
                  className="color-gray-700" 
                />
              </button>
              
              {/* Texto "Core" */}
              <Typography
                variant="h6"
                style={{
                  color: '#2D5C63',
                  fontSize: '24px',
                  fontFamily: FONT_FAMILY_SANS,
                  fontWeight: 600,
                  lineHeight: '1.2',
                  margin: 0
                }}
              >
                {t('header.coreLabel', { defaultValue: 'Core' })}
              </Typography>
            </div>

            {/* Lado derecho: Notificaciones y Avatar */}
            <div className="flex items-center space-x-3">
              {/* Icono de notificaciones */}
              {notificationCount !== undefined && (
                <button
                  onClick={onNotificationClick}
                  className={`ml-2 hover:bg-gray-100 transition-colors flex items-center justify-center ${notificationButtonClassName} ${notificationMobileButtonClassName}`}
                  aria-label={t('header.notificationsAria', { defaultValue: 'Notificaciones' })}
                  style={{
                    width: '48px',
                    height: '48px',
                    paddingRight: '0px',
                    borderRadius: '8px',
                    opacity: 1,
                    transform: 'rotate(0deg)',
                    ...(notificationButtonStyle || {}),
                    ...(notificationMobileButtonStyle || {}),
                  }}
                >
                  {/* Contenedor 32x32 implícito dentro del botón 48x48 + icono posicionado (Figma) */}
                  <span
                    className={`relative inline-block ${notificationMobileIconWrapperClassName}`}
                    style={{
                      width: '24px',
                      height: '24px',
                      opacity: 1,
                      ...(notificationMobileIconWrapperStyle || {}),
                    }}
                >
                  <Icon 
                      name={bellIconName} 
                    variant="24-outline" 
                      size={notificationMobileIconSize}
                      strokeWidth={notificationMobileIconStrokeWidth}
                      className={`color-gray-600 ${notificationIconClassName}`}
                      style={{
                        width: '24px',
                        height: '24px',
                        position: 'absolute',
                        top: '0px',
                        left: '0px',
                        opacity: 1,
                        transform: 'rotate(0deg)',
                        ...(notificationIconStyle || {}),
                        ...(notificationMobileIconStyle || {}),
                      }}
                    />
                  </span>
                  {showNotificationBadgeOnMobile && notificationCount > 0 && (
                    <span
                      className={`h-5 text-white flex items-center justify-center text-body-sm-14 font-medium ${notificationBadgeClassName}`}
                      style={{ 
                        backgroundColor: '#6D3856',
                        minWidth: '24px',
                        width: 'fit-content',
                        height: '20px',
                        paddingTop: '2px',
                        paddingRight: '8px',
                        paddingBottom: '2px',
                        paddingLeft: '8px',
                        borderRadius: '16px',
                        marginLeft: '6px',
                        opacity: 1,
                        transform: 'rotate(0deg)',
                        ...(notificationBadgeStyle || {}),
                        ...(notificationMobileBadgeStyle || {}),
                      }}
                    >
                      {notificationCount > 9 ? '9+' : notificationCount}
                    </span>
                  )}
                </button>
              )}

              {/* Avatar (sin nombre) */}
              {userAvatar && (
                <div className="relative">
                  <button
                    ref={profileButtonMobileRef}
                    onClick={handleToggleProfileDropdown}
                    className="hover:bg-gray-50 rounded-lg transition-colors cursor-pointer"
                    aria-label={t('header.profileAria', { defaultValue: 'Perfil de usuario' })}
                    aria-expanded={isProfileDropdownOpen}
                  >
                    <Avatar
                      src={userAvatar}
                      name={userName || ''}
                      size="medium"
                      variant="circle"
                      className={`cursor-pointer ${mobileUserAvatarClassName}`}
                      style={mobileUserAvatarStyle}
                    />
                  </button>
                  <DesplegablePerfil
                    isOpen={isProfileDropdownOpen}
                    onClose={handleCloseProfileDropdown}
                    onProfileClick={onProfileClick}
                    onSettingsClick={onSettingsClick}
                    onHelpClick={onHelpClick}
                    onLogoutClick={onLogoutClick}
                    triggerRef={profileButtonMobileRef}
                  />
                </div>
              )}
            </div>
          </div>

          {/* Segunda fila: Barra de búsqueda */}
          <div
            ref={mobileSearchContainerRef}
            className={`header-mobile-search-row relative ${searchResultsContainerClassName}`}
            style={{ ...(searchResultsContainerStyle || {}) }}
          >
            <form onSubmit={handleSearchSubmit} className="header-search-form flex items-center w-full">
              {/* Input de búsqueda */}
              <input
                type="text"
                value={resolvedSearchValue}
                onChange={handleSearchChange}
                placeholder={mobileSearchPlaceholder ?? t('header.mobileSearchPlaceholder', { defaultValue: 'Busca lo que necesites' })}
                aria-label={mobileSearchPlaceholder ?? t('header.mobileSearchPlaceholder', { defaultValue: 'Busca lo que necesites' })}
                className="header-search-input flex-1 pl-3 pr-3 py-2 bg-white border border-gray-400 rounded-l-lg 
                         focus:outline-none text-sm"
                style={{ 
                  height: '40px', 
                  borderRight: 'none', 
                  borderTopRightRadius: '0', 
                  borderBottomRightRadius: '0',
                  color: '#374151',
                  fontFamily: FONT_FAMILY_SANS,
                  fontWeight: 400,
                  fontStyle: 'italic',
                  fontSize: '14px',
                  lineHeight: '20px',
                  letterSpacing: '0px'
                }}
              />
              
              {/* Recuadro con icono de buscar a la derecha */}
              <div 
                className="header-search-icon-container flex items-center justify-center border border-gray-400 rounded-r-lg bg-white"
                style={{
                  width: '40px',
                  height: '40px',
                  borderTopLeftRadius: '0',
                  borderBottomLeftRadius: '0'
                }}
              >
                <Icon 
                  name="MagnifyingGlassIcon" 
                  variant="24-outline" 
                  size={20} 
                  className="color-gray-600" 
                />
              </div>
            </form>
            {isMobileViewport && renderSearchResultsPanel()}
          </div>
        </div>
      </div>

      {/* SidebarCoreMobile - mantener montado para animación de cierre */}
      {shouldRenderSidebarMobile && (
        <div className="header-core-mobile-sidebar-wrapper">
          <SidebarCoreMobile
            sections={sidebarSections}
            activeItem={resolvedSidebarActiveItem}
            onItemClick={(itemId) => {
              if (enableInternalSidebarActiveItem) {
                setInternalSidebarActiveItem(itemId);
              }
              if (onSidebarItemClick) {
                onSidebarItemClick(itemId);
              }
              // permitir que el item se "pinte" y luego cerrar con animación
              requestAnimationFrame(() => closeSidebarMobile());
            }}
            itemBadges={sidebarItemBadges}
            companyName={sidebarCompanyName}
            companyLogo={sidebarCompanyLogo}
            footerText={sidebarFooterText}
            footerCollapsedContent={sidebarFooterCollapsedContent}
            coreContainerStyle={sidebarCoreContainerStyle}
            coreTextStyle={sidebarCoreTextStyle}
            isOpen={isSidebarOpen}
            onClose={closeSidebarMobile}
            transitionDurationMs={mobileSidebarTransitionDurationMs}
            transitionEasing={mobileSidebarTransitionEasing}
            breakpointSidebarMobileWidthMinPx={breakpointSidebarMobileWidthMinPx}
            breakpointSidebarMobileWidthMaxPx={breakpointSidebarMobileWidthMaxPx}
          />
        </div>
      )}
    </header>
  );
};

export default HeaderCore;

