// Universidad CIES — Navbar con dropdowns (fixed)

// Dropdown item with hover highlight
const DropItem = ({ item, active, onNav }) => {
  const [hover, setHover] = React.useState(false);
  return (
    <button
      style={{
        ...navS.dropItem,
        ...(active ? navS.dropItemActive : {}),
        ...(hover && !active ? navS.dropItemHover : {}),
      }}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      onClick={() => onNav(item.page)}
    >
      {item.label}
    </button>
  );
};

// Main Nav component
const Nav = ({ currentPage, onNavigate }) => {
  const [menuOpen, setMenuOpen] = React.useState(false);
  const [dropdown, setDropdown] = React.useState(null);
  const [scrolled, setScrolled] = React.useState(false);
  const [hoveredLink, setHoveredLink] = React.useState(null);
  const closeTimer = React.useRef(null);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 10);
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const navGroups = [
    { id: 'nosotros', label: 'Nosotros', page: 'nosotros' },
    {
      id: 'licenciaturas', label: 'Licenciaturas',
      children: [
        { label: 'Derecho', page: 'lic-derecho' },
        { label: 'Comercio Exterior', page: 'lic-comercio' },
        { label: 'Administración de Empresas', page: 'lic-administracion' },
        { label: 'Ciencias de la Educación', page: 'lic-educacion' },
      ]
    },
    {
      id: 'ingenierias', label: 'Ingenierías',
      children: [
        { label: 'Ing. en Robótica', page: 'ing-robotica' },
        { label: 'Inteligencia Artificial', page: 'ing-ia' },
        { label: 'Mecatrónica', page: 'ing-mecatronica' },
        { label: 'Ing. Industrial', page: 'ing-industrial' },
      ]
    },
    {
      id: 'maestrias', label: 'Maestrías',
      children: [
        { label: 'MBA', page: 'mba' },
        { label: 'Maestría en Innovación Educativa', page: 'mie' },
      ]
    },
    { id: 'preparatoria', label: 'Preparatoria', page: 'preparatoria' },
    { id: 'admisiones', label: 'Admisiones', page: 'admisiones' },
  ];

  const openDropdown = (id) => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    setDropdown(id);
  };

  const scheduleClose = () => {
    closeTimer.current = setTimeout(() => setDropdown(null), 120);
  };

  const handleNav = (page) => {
    setMenuOpen(false);
    setDropdown(null);
    if (closeTimer.current) clearTimeout(closeTimer.current);
    onNavigate(page);
  };

  const isActive = (group) => {
    if (group.page) return currentPage === group.page;
    if (group.children) return group.children.some(c => c.page === currentPage);
    return false;
  };

  return (
    <header style={{
      ...navS.header,
      boxShadow: scrolled ? '0 2px 16px rgba(0,0,0,0.13)' : '0 1px 0 rgba(0,0,0,0.07)',
    }}>
      <div style={navS.inner}>
        <img
          src="assets/LOGO_CIES_HORIZONTAL_OFICIAL.png"
          alt="Universidad CIES"
          style={navS.logo}
          onClick={() => handleNav('home')}
        />

        {/* Desktop nav */}
        <nav style={navS.nav} className="nav-desktop">
          {navGroups.map(group => (
            <div key={group.id} style={navS.navItem}
              onMouseEnter={() => group.children ? openDropdown(group.id) : null}
              onMouseLeave={() => group.children ? scheduleClose() : null}
            >
              <button
                style={{ ...navS.navLink, ...(hoveredLink === group.id ? navS.navLinkHover : {}), ...(isActive(group) ? navS.navLinkActive : {}) }}
                onMouseEnter={() => setHoveredLink(group.id)}
                onMouseLeave={() => setHoveredLink(null)}
                onClick={() => group.page ? handleNav(group.page) : openDropdown(dropdown === group.id ? null : group.id)}
              >
                {group.label}
                {group.children && (
                  <svg style={{ ...navS.chevron, transform: dropdown === group.id ? 'rotate(180deg)' : 'none', transition: 'transform 0.15s' }} viewBox="0 0 10 6" fill="none" width="10" height="6">
                    <path d="M1 1l4 4 4-4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                  </svg>
                )}
              </button>

              {group.children && dropdown === group.id && (
                <div style={navS.dropdown}
                  onMouseEnter={() => openDropdown(group.id)}
                  onMouseLeave={() => scheduleClose()}
                >
                  {group.children.map(c => (
                    <DropItem key={c.page} item={c} active={currentPage === c.page} onNav={handleNav} />
                  ))}
                </div>
              )}
            </div>
          ))}
        </nav>

        <button style={navS.cta} className="nav-cta-desktop" onClick={() => handleNav('admisiones')}>Inscríbete</button>

        {/* Burger */}
        <button style={navS.burger} className="nav-burger" onClick={() => setMenuOpen(!menuOpen)}>
          <svg width="22" height="22" viewBox="0 0 22 22" fill="none">
            {menuOpen
              ? <><line x1="4" y1="4" x2="18" y2="18" stroke="#1A1A1A" strokeWidth="2" strokeLinecap="round"/><line x1="18" y1="4" x2="4" y2="18" stroke="#1A1A1A" strokeWidth="2" strokeLinecap="round"/></>
              : <><line x1="3" y1="6" x2="19" y2="6" stroke="#1A1A1A" strokeWidth="2" strokeLinecap="round"/><line x1="3" y1="11" x2="19" y2="11" stroke="#1A1A1A" strokeWidth="2" strokeLinecap="round"/><line x1="3" y1="16" x2="19" y2="16" stroke="#1A1A1A" strokeWidth="2" strokeLinecap="round"/></>
            }
          </svg>
        </button>
      </div>

      {/* Mobile menu */}
      {menuOpen && (
        <div style={navS.mobile}>
          {navGroups.map(group => (
            <div key={group.id}>
              {group.page ? (
                <button style={navS.mobileLink} onClick={() => handleNav(group.page)}>{group.label}</button>
              ) : (
                <>
                  <div style={navS.mobileGroup}>{group.label}</div>
                  {group.children.map(c => (
                    <button key={c.page} style={navS.mobileChild} onClick={() => handleNav(c.page)}>{c.label}</button>
                  ))}
                </>
              )}
            </div>
          ))}
          <button style={navS.mobileCta} onClick={() => handleNav('admisiones')}>Inscríbete</button>
        </div>
      )}
    </header>
  );
};

const navS = {
  header: { position:'sticky', top:0, zIndex:200, background:'#fff', transition:'box-shadow 0.2s ease' },
  inner: { maxWidth:1200, margin:'0 auto', padding:'0 24px', height:72, display:'flex', alignItems:'center', gap:0 },
  logo: { height:36, objectFit:'contain', flexShrink:0, cursor:'pointer', marginRight:32 },
  nav: { display:'flex', gap:2, flex:1, alignItems:'center' },
  navItem: { position:'relative' },
  navLink: { fontFamily:"'Figtree',sans-serif", fontSize:14, fontWeight:500, color:'#3D3D3D', background:'none', border:'none', cursor:'pointer', padding:'8px 12px', borderRadius:4, display:'flex', alignItems:'center', gap:4, transition:'color 0.15s,background 0.15s', whiteSpace:'nowrap' },
  navLinkHover: { background:'#F0F3FA', color:'#2B4DA8' },
  navLinkActive: { color:'#2B4DA8', fontWeight:600, background:'#E8EDF8' },
  chevron: { opacity:0.6 },
  dropdown: { position:'absolute', top:'calc(100% + 2px)', left:0, background:'#fff', borderRadius:8, boxShadow:'0 8px 32px rgba(0,0,0,0.14)', padding:'8px', minWidth:220, zIndex:300 },
  dropItem: { display:'block', width:'100%', textAlign:'left', fontFamily:"'Figtree',sans-serif", fontSize:14, fontWeight:400, color:'#3D3D3D', background:'none', border:'none', cursor:'pointer', padding:'10px 14px', borderRadius:4, transition:'background 0.12s,color 0.12s' },
  dropItemHover: { background:'#F0F3FA', color:'#2B4DA8' },
  dropItemActive: { background:'#E8EDF8', color:'#2B4DA8', fontWeight:600 },
  cta: { background:'#C23535', color:'#fff', fontFamily:"'Figtree',sans-serif", fontWeight:600, fontSize:14, padding:'9px 22px', borderRadius:4, border:'none', cursor:'pointer', flexShrink:0, marginLeft:16, transition:'background 0.2s' },
  burger: { display:'none', background:'none', border:'none', cursor:'pointer', padding:4, marginLeft:'auto' },
  mobile: { background:'#fff', borderTop:'1px solid #E8E8E8', padding:'12px 24px 20px', display:'flex', flexDirection:'column' },
  mobileLink: { background:'none', border:'none', textAlign:'left', width:'100%', fontFamily:"'Figtree',sans-serif", fontSize:15, fontWeight:500, color:'#1A1A1A', padding:'12px 0', borderBottom:'1px solid #F0F0F0', cursor:'pointer' },
  mobileGroup: { fontFamily:"'Figtree',sans-serif", fontSize:11, fontWeight:700, color:'#8A8A8A', letterSpacing:'0.08em', textTransform:'uppercase', padding:'14px 0 4px' },
  mobileChild: { background:'none', border:'none', textAlign:'left', width:'100%', fontFamily:"'Figtree',sans-serif", fontSize:14, fontWeight:400, color:'#3D3D3D', padding:'10px 14px', cursor:'pointer', borderBottom:'1px solid #F5F5F5' },
  mobileCta: { background:'#C23535', color:'#fff', fontFamily:"'Figtree',sans-serif", fontWeight:600, fontSize:15, padding:'13px 20px', borderRadius:4, border:'none', cursor:'pointer', marginTop:16, textAlign:'center' },
};

Object.assign(window, { Nav });
