/* eslint-disable react/prop-types */
/**
 * Header · Navegación principal del sitio.
 * Brief 0.1 §5 + Brief 1 §2. Refinamiento estilo gehlpeople.com:
 *  - Underline cobre animado scale-x desde la izquierda
 *  - Megamenú fade + translateY con entry escalonada de sub-items
 *  - Sticky shrink suave (transform + height)
 *  - data-cursor="link" en items para el cursor custom
 */

const { useState: uS_H, useEffect: uE_H, useRef: uR_H } = React;

const NAV_ITEMS = [
  { label: 'INICIO', href: '/home/Home.html' },
  {
    label: 'NUESTRO TRABAJO',
    href: '/distritos/Distritos.html',
    children: [
      { label: 'Distritos',       href: '/distritos/Distritos.html',                   desc: '40+ distritos co-creados a lo largo de 18 años.' },
      { label: 'Servicios',       href: '/servicios/Servicios.html',                   desc: 'Originación, Co-Desarrollo y Dataria.' },
      { label: 'Originación',     href: '/servicios/Servicios.html#originacion',       desc: 'De la lectura del polígono al diseño del negocio.' },
      { label: 'Co-Desarrollo',   href: '/servicios/Servicios.html#co-desarrollo',     desc: 'Acompañamos la operación con riesgo compartido.' },
      { label: 'Dataria',         href: '/servicios/Servicios.html#digo',              desc: 'La plataforma que pone DIGO® en operación.' },
      { label: 'Nuestro Enfoque', href: '/enfoque/NuestroEnfoque.html', desc: 'Por qué empezar por la persona y terminar por el negocio.' },
    ],
  },
  {
    label: 'SOBRE NOSOTROS',
    href: '/sobre-nosotros/Equipo.html',
    children: [
      { label: 'Equipo',          href: '/sobre-nosotros/Equipo.html',          desc: '35 personas haciéndose la misma pregunta.' },
      { label: 'Historia',        href: '/sobre-nosotros/Historia.html',        desc: '18 años originando lo que la industria no veía.' },
      { label: 'Responsabilidad', href: '/sobre-nosotros/Responsabilidad.html', desc: 'Cinco compromisos con la ciudad.' },
    ],
  },
  {
    label: 'CONOCIMIENTO',
    href: '/conocimiento/Blog.html',
    children: [
      { label: 'Blog',          href: '/conocimiento/Blog.html',          desc: 'Cómo pensamos, lo que aprendemos.' },
      { label: 'Casos',         href: '/conocimiento/Casos.html',         desc: 'Las historias detrás de los distritos.' },
      { label: 'Publicaciones', href: '/conocimiento/Publicaciones.html', desc: 'Reportes, whitepapers e índices.' },
      { label: 'Eventos',       href: '/conocimiento/Eventos.html',       desc: 'Dónde estamos hablando.' },
      { label: 'Prensa',        href: '/conocimiento/Prensa.html',        desc: 'En los medios.' },
      { label: 'Podcast',       href: '/conocimiento/Podcast.html',       desc: 'Creamos lo Extraordinario.' },
    ],
  },
  { label: 'BOLSA DE TRABAJO', href: '/bolsa-de-trabajo/BolsaDeTrabajo.html' },
  { label: 'CONTACTO',         href: '/home/Home.html#contacto' },
];

function Header() {
  const [shrunk, setShrunk]       = uS_H(false);
  const [hovered, setHovered]     = uS_H(null);
  const [mobileOpen, setMobileOpen] = uS_H(false);
  const [mobileExpanded, setMobileExpanded] = uS_H(null);
  const closeTimer = uR_H(null);

  uE_H(() => {
    const onScroll = () => setShrunk(window.scrollY > 100);
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  uE_H(() => {
    document.body.style.overflow = mobileOpen ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [mobileOpen]);

  uE_H(() => {
    const onKey = (e) => { if (e.key === 'Escape') { setHovered(null); setMobileOpen(false); } };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  const openMenu = (label) => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    setHovered(label);
  };
  const closeMenuSoon = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => setHovered(null), 160);
  };

  return (
    <div style={{
      position: 'fixed', top: 0, left: 0, right: 0,
      zIndex: 1000,
    }}>
      {window.NotificationBar && <window.NotificationBar />}
      <header style={{
        ...headerStyles.header,
        paddingTop:    shrunk ? '10px' : '18px',
        paddingBottom: shrunk ? '10px' : '18px',
      }}>
      <div style={headerStyles.inner}>
        <a href="#top" style={headerStyles.logoLink} aria-label="Prosperia · Inicio" data-cursor="link">
          <img
            src="assets/logo/prosperia-vertical.png"
            alt="Prosperia"
            style={{
              ...headerStyles.logoImg,
              height: shrunk ? '46px' : '60px',
            }}
          />
        </a>

        {/* Nav desktop */}
        <nav style={headerStyles.navDesktop} aria-label="Menú principal">
          {NAV_ITEMS.map((item) => {
            const isHover = hovered === item.label;
            return (
              <div
                key={item.label}
                style={headerStyles.navItemWrap}
                onMouseEnter={() => item.children && openMenu(item.label)}
                onMouseLeave={() => item.children && closeMenuSoon()}
              >
                <a
                  href={item.href}
                  data-cursor="link"
                  style={{
                    ...headerStyles.navLink,
                    color: isHover ? 'var(--color-copper-fallback)' : 'var(--color-navy-deep)',
                  }}
                  aria-haspopup={item.children ? 'true' : undefined}
                  aria-expanded={item.children ? isHover : undefined}
                >
                  {item.label}
                  {item.children && (
                    <span style={{
                      marginLeft: 6,
                      display: 'inline-flex',
                      transition: 'transform 280ms cubic-bezier(0.16, 1, 0.3, 1)',
                      transform: isHover ? 'rotate(180deg)' : 'rotate(0)',
                    }}>
                      <window.Icon name="chevron-down" size={12} stroke={2} />
                    </span>
                  )}
                  <span aria-hidden="true" style={{
                    ...headerStyles.underline,
                    transform: isHover ? 'scaleX(1)' : 'scaleX(0)',
                  }} />
                </a>
              </div>
            );
          })}

          {/* WhatsApp directo · solo desktop */}
          <a
            href={`https://wa.me/528136050471?text=${encodeURIComponent('Hola, encontré Prosperia en su sitio. Me gustaría conversar sobre un proyecto.')}`}
            target="_blank"
            rel="noopener noreferrer"
            data-cursor="link"
            aria-label="Conversar por WhatsApp"
            style={headerStyles.waLink}
            title="Conversar por WhatsApp"
          >
            <svg width="18" height="18" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" style={headerStyles.waIcon}>
              <path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.768.967-.941 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413Z"/>
            </svg>
            <span style={headerStyles.waLabel}>WhatsApp</span>
          </a>
        </nav>

        {/* Hamburger */}
        <button
          onClick={() => setMobileOpen(true)}
          style={headerStyles.hamburger}
          aria-label="Abrir menú"
          aria-expanded={mobileOpen}
          data-cursor="link"
        >
          <window.Icon name="menu" size={24} stroke={1.8} />
        </button>
      </div>

      {/* Megamenú */}
      {hovered && NAV_ITEMS.find(i => i.label === hovered)?.children && (
        <div
          style={headerStyles.megamenu}
          onMouseEnter={() => openMenu(hovered)}
          onMouseLeave={closeMenuSoon}
        >
          <div style={headerStyles.megaInner}>
            <div style={headerStyles.megaCol}>
              {NAV_ITEMS.find(i => i.label === hovered).children.map((sub, i) => (
                <a key={sub.href} href={sub.href} data-cursor="link"
                   style={{
                     ...headerStyles.megaLink,
                     animation: `megaIn 500ms cubic-bezier(0.16,1,0.3,1) ${i * 60}ms backwards`,
                   }}>
                  <span style={headerStyles.megaLinkInner}>
                    <span>{sub.label}</span>
                    <span style={headerStyles.megaArrow}>
                      <window.Icon name="arrow-right" size={16} stroke={1.6} />
                    </span>
                  </span>
                </a>
              ))}
            </div>
            <div style={headerStyles.megaCol}>
              {NAV_ITEMS.find(i => i.label === hovered).children.map((sub, i) => (
                <p key={sub.href + '-desc'}
                   style={{
                     ...headerStyles.megaDesc,
                     animation: `megaIn 500ms cubic-bezier(0.16,1,0.3,1) ${i * 60 + 80}ms backwards`,
                   }}>
                  {sub.desc}
                </p>
              ))}
            </div>
          </div>
        </div>
      )}

      {/* Overlay mobile */}
      {mobileOpen && (
        <div style={headerStyles.overlay} role="dialog" aria-modal="true">
          <div style={headerStyles.overlayTop}>
            <img src="assets/logo/prosperia-vertical.png" alt="Prosperia" style={{ height: 50 }} />
            <button onClick={() => setMobileOpen(false)} style={headerStyles.closeBtn} aria-label="Cerrar menú">
              <window.Icon name="close" size={24} stroke={1.8} />
            </button>
          </div>
          <nav style={headerStyles.overlayNav} aria-label="Menú móvil">
            {NAV_ITEMS.map((item, i) => (
              <div key={item.label} style={{
                width: '100%',
                animation: `megaIn 500ms cubic-bezier(0.16,1,0.3,1) ${i * 60}ms backwards`,
              }}>
                {item.children ? (
                  <React.Fragment>
                    <button
                      onClick={() => setMobileExpanded(mobileExpanded === item.label ? null : item.label)}
                      style={headerStyles.overlayBtn}
                      aria-expanded={mobileExpanded === item.label}
                    >
                      <span>{item.label}</span>
                      <span style={{
                        transition: 'transform 280ms cubic-bezier(0.16, 1, 0.3, 1)',
                        transform: mobileExpanded === item.label ? 'rotate(180deg)' : 'rotate(0)',
                        display: 'inline-flex',
                      }}>
                        <window.Icon name="chevron-down" size={18} stroke={2} />
                      </span>
                    </button>
                    {mobileExpanded === item.label && (
                      <div style={headerStyles.overlaySubs}>
                        {item.children.map((sub, j) => (
                          <a key={sub.href} href={sub.href}
                             style={{
                               ...headerStyles.overlaySub,
                               animation: `megaIn 400ms cubic-bezier(0.16,1,0.3,1) ${j * 50}ms backwards`,
                             }}>
                            {sub.label}
                            <window.Icon name="arrow-right" size={14} stroke={1.6} style={{ opacity: 0.4 }} />
                          </a>
                        ))}
                      </div>
                    )}
                  </React.Fragment>
                ) : (
                  <a href={item.href} style={headerStyles.overlayLink} onClick={() => setMobileOpen(false)}>
                    {item.label}
                  </a>
                )}
              </div>
            ))}
          </nav>
        </div>
      )}
    </header>
    </div>
  );
}

const headerStyles = {
  header: {
    position: 'relative',
    background: 'rgba(250, 249, 244, 0.92)',
    backdropFilter: 'blur(12px) saturate(140%)',
    WebkitBackdropFilter: 'blur(12px) saturate(140%)',
    boxShadow: '0 1px 0 rgba(33, 52, 64, 0.08)',
    transition: 'padding 320ms cubic-bezier(0.16, 1, 0.3, 1), background 320ms ease',
  },
  inner: {
    maxWidth: 1280, margin: '0 auto',
    padding: '0 var(--container-padding-mobile)',
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    gap: 24,
  },
  logoLink: { display: 'flex', alignItems: 'center' },
  logoImg: { transition: 'height 320ms cubic-bezier(0.16, 1, 0.3, 1)', width: 'auto' },
  navDesktop: {
    display: 'none',
    alignItems: 'center',
    gap: 28,
  },
  navItemWrap: {
    position: 'relative',
    display: 'inline-flex',
    alignItems: 'center',
  },
  navLink: {
    position: 'relative',
    fontSize: 12,
    fontWeight: 700,
    letterSpacing: '0.14em',
    textTransform: 'uppercase',
    color: 'var(--color-navy-deep)',
    transition: 'color 240ms cubic-bezier(0.16, 1, 0.3, 1)',
    display: 'inline-flex', alignItems: 'center',
    padding: '12px 0',
    whiteSpace: 'nowrap',
    lineHeight: 1,
  },
  underline: {
    position: 'absolute',
    left: 0, right: 0, bottom: 6,
    height: 2,
    background: 'var(--color-copper-fallback)',
    transformOrigin: 'left center',
    transition: 'transform 360ms cubic-bezier(0.16, 1, 0.3, 1)',
  },
  waLink: {
    display: 'inline-flex',
    alignItems: 'center',
    gap: 8,
    paddingInline: 14,
    paddingBlock: 9,
    background: '#25D366',
    color: '#fff',
    fontWeight: 700,
    fontSize: 12,
    letterSpacing: '0.10em',
    textTransform: 'uppercase',
    borderRadius: 999,
    textDecoration: 'none',
    whiteSpace: 'nowrap',
    lineHeight: 1,
    transition: 'background 240ms ease, transform 240ms cubic-bezier(0.16,1,0.3,1), box-shadow 240ms ease',
    boxShadow: '0 2px 8px rgba(37, 211, 102, 0.25)',
  },
  waIcon: {
    display: 'block',
  },
  waLabel: {
    color: '#fff',
    fontWeight: 700,
  },
  hamburger: {
    background: 'transparent', border: 0,
    padding: 0,
    width: 44, height: 44,  /* tamaño táctil iOS HIG */
    display: 'flex', alignItems: 'center', justifyContent: 'center',
    color: 'var(--color-navy-deep)',
    cursor: 'pointer',
  },
  hamburgerIcon: {
    /* override del bug de Icon.jsx — fuerza stroke visible */
    stroke: 'var(--color-navy-deep)',
    strokeWidth: 1.8,
    fill: 'none',
  },
  megamenu: {
    position: 'absolute', top: '100%', left: 0, right: 0,
    background: 'rgba(255,255,255,0.98)',
    backdropFilter: 'blur(8px)',
    WebkitBackdropFilter: 'blur(8px)',
    borderTop: '1px solid rgba(33, 52, 64, 0.06)',
    boxShadow: '0 18px 36px rgba(33, 52, 64, 0.08)',
    padding: '40px 80px 48px',
    animation: 'megaFadeIn 320ms cubic-bezier(0.16,1,0.3,1)',
  },
  megaInner: {
    maxWidth: 1280, margin: '0 auto',
    display: 'grid', gridTemplateColumns: 'minmax(220px, 0.8fr) 1.6fr', gap: 64,
  },
  megaCol: { display: 'flex', flexDirection: 'column', gap: 18 },
  megaLink: {
    fontSize: 22, fontWeight: 800,
    color: 'var(--color-navy-deep)',
    paddingBlock: 6,
    letterSpacing: '-0.005em',
  },
  megaLinkInner: {
    display: 'inline-flex',
    alignItems: 'center',
    gap: 12,
    transition: 'color 240ms ease, gap 360ms cubic-bezier(0.16,1,0.3,1)',
  },
  megaArrow: {
    color: 'var(--color-copper-fallback)',
    display: 'inline-flex',
    opacity: 0,
    transform: 'translateX(-8px)',
    transition: 'opacity 280ms ease, transform 360ms cubic-bezier(0.16,1,0.3,1)',
  },
  megaDesc: {
    margin: 0,
    fontSize: 15,
    color: 'var(--color-navy-medium)',
    lineHeight: 1.7,
    paddingBlock: 6,
  },
  overlay: {
    position: 'fixed',
    top: 0, left: 0, right: 0, bottom: 0,
    width: '100%',
    height: '100vh',
    /* dvh = dynamic viewport height en navegadores modernos, mejor para mobile */
    minHeight: '100dvh',
    background: 'var(--color-cream)',
    zIndex: 1100,
    display: 'flex', flexDirection: 'column',
    animation: 'slideDown 320ms cubic-bezier(0.16, 1, 0.3, 1)',
    overflowY: 'auto',
  },
  overlayTop: {
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    padding: '20px 24px',
    borderBottom: '1px solid rgba(33, 52, 64, 0.08)',
  },
  closeBtn: { background: 'transparent', border: 0, padding: 8, color: 'var(--color-navy-deep)' },
  overlayNav: {
    flex: 1, overflowY: 'auto',
    display: 'flex', flexDirection: 'column',
    padding: '40px 24px 80px',
    gap: 28,
  },
  overlayLink: {
    display: 'block',
    fontSize: 30, fontWeight: 800, color: 'var(--color-navy-deep)',
    letterSpacing: '-0.01em',
  },
  overlayBtn: {
    width: '100%',
    display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    background: 'transparent', border: 0, padding: 0,
    fontSize: 30, fontWeight: 800, color: 'var(--color-navy-deep)',
    textAlign: 'left', letterSpacing: '-0.01em',
  },
  overlaySubs: {
    paddingLeft: 4, paddingTop: 16,
    display: 'flex', flexDirection: 'column', gap: 12,
  },
  overlaySub: {
    fontSize: 17, fontWeight: 700, color: 'var(--color-navy-medium)',
    display: 'flex', alignItems: 'center', gap: 12,
  },
};

const headerMQ = document.createElement('style');
headerMQ.textContent = `
  /* Bug fix: Icon.jsx renderiza stroke="<numero>" en vez de stroke="currentColor".
     Forzamos visualización correcta del SVG dentro de TODOS los íconos del header. */
  header button[aria-label="Abrir menú"] svg,
  header button[aria-label="Abrir menú"] svg *,
  div[role="dialog"] button svg,
  div[role="dialog"] button svg *,
  div[role="dialog"] a svg,
  div[role="dialog"] a svg * {
    stroke: var(--color-navy-deep) !important;
    fill: none !important;
  }
  header button[aria-label="Abrir menú"]:hover svg,
  header button[aria-label="Abrir menú"]:hover svg * {
    stroke: var(--color-copper-fallback) !important;
  }

  header a[aria-label="Conversar por WhatsApp"]:hover {
    background: #1ebe5d !important;
    transform: translateY(-1px);
    box-shadow: 0 6px 16px rgba(37, 211, 102, 0.35) !important;
  }

  @media (min-width: 1024px) {
    header nav[aria-label="Menú principal"] { display: flex !important; }
    header button[aria-label="Abrir menú"]  { display: none !important; }
  }
  @media (min-width: 1280px) {
    header nav[aria-label="Menú principal"] { gap: 40px !important; }
  }
  /* Megamenu link hover state */
  header div[style*="background: rgba(255,255,255,0.98)"] a:hover > span:first-child {
    color: var(--color-copper-fallback) !important;
    gap: 18px !important;
  }
  header div[style*="background: rgba(255,255,255,0.98)"] a:hover > span:first-child > span:last-child {
    opacity: 1 !important;
    transform: translateX(0) !important;
  }
  @keyframes slideDown {
    from { transform: translateY(-12px); opacity: 0; }
    to   { transform: translateY(0);     opacity: 1; }
  }
  @keyframes megaFadeIn {
    from { opacity: 0; transform: translateY(-6px); }
    to   { opacity: 1; transform: translateY(0); }
  }
  @keyframes megaIn {
    from { opacity: 0; transform: translateY(8px); }
    to   { opacity: 1; transform: translateY(0); }
  }
`;
document.head.appendChild(headerMQ);

window.Header = Header;
