// CNV Work — Mega-menu Navbar with 3-level dropdowns + dark mode + responsive

const MegaNav = ({ current, dark = false, theme = 'blue' }) => {
  const [openIdx, setOpenIdx] = React.useState(null);
  const [scrolled, setScrolled] = React.useState(false);
  const [isMobile, setIsMobile] = React.useState(typeof window !== 'undefined' && window.innerWidth < 900);
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const [mobileExpanded, setMobileExpanded] = React.useState(null); // index của item đang mở submenu trong drawer
  const [activeModuleIdx, setActiveModuleIdx] = React.useState(0); // module đang chọn trong dropdown Sản phẩm
  const timeoutRef = React.useRef(null);

  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 4);
    const onResize = () => setIsMobile(window.innerWidth < 900);
    onScroll(); onResize();
    window.addEventListener('scroll', onScroll);
    window.addEventListener('resize', onResize);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onResize);
    };
  }, []);

  // Lock body scroll when drawer open
  React.useEffect(() => {
    if (drawerOpen) {
      document.body.style.overflow = 'hidden';
    } else {
      document.body.style.overflow = '';
    }
    return () => { document.body.style.overflow = ''; };
  }, [drawerOpen]);

  const open = (i) => {
    if (timeoutRef.current) clearTimeout(timeoutRef.current);
    setOpenIdx(i);
  };
  const scheduleClose = () => {
    if (timeoutRef.current) clearTimeout(timeoutRef.current);
    timeoutRef.current = setTimeout(() => setOpenIdx(null), 300);
  };

  // Pink theme tokens
  const isPink = theme === 'pink';
  const PINK_C = window.PINK?.[400] || '#FF688E';
  const PINK_500 = window.PINK?.[500] || '#FF4978';
  const accent = isPink ? PINK_C : BLUE[600];
  const accentEyebrow = isPink ? PINK_C : BLUE[600];

  // Top bar
  const bg = dark ? '#000' : (scrolled ? 'rgba(255,255,255,0.95)' : 'rgba(255,255,255,0.85)');
  const border = dark ? 'rgba(255,255,255,0.08)' : 'rgba(12,26,52,0.08)';
  const linkColor = dark ? 'rgba(255,255,255,0.82)' : 'rgba(12,26,52,0.82)';
  const linkActive = dark ? '#fff' : INK;

  // Dropdown panel theme — pink dark khi dark=true
  const panelBg = dark ? '#0A0E1A' : '#fff';
  const panelBorder = dark ? `${PINK_C}26` : LINE;
  const panelShadow = dark ? `0 24px 60px rgba(0,0,0,0.6), 0 0 0 1px ${PINK_C}1A` : '0 20px 50px rgba(12,26,52,0.12)';
  const colHeadColor = dark ? PINK_C : accentEyebrow;
  const colDescColor = dark ? 'rgba(255,255,255,0.55)' : INK_SOFT;
  const featTitleColor = dark ? '#fff' : INK;
  const featDescColor = dark ? 'rgba(255,255,255,0.55)' : INK_SOFT;
  const hoverBg = dark ? `${PINK_C}1A` : (isPink ? `${PINK_C}15` : BLUE[50]);
  const promoBg = dark
    ? `linear-gradient(135deg, ${PINK_C}26, ${PINK_500}10)`
    : (isPink ? `linear-gradient(135deg, ${PINK_C}20, ${window.CYAN?.[500] || '#00D9FF'}10)` : GRADIENT_SOFT);
  const promoBorder = dark ? `${PINK_C}40` : (isPink ? 'rgba(255,104,142,0.18)' : LINE);
  const promoTitleColor = dark ? '#fff' : INK;
  const promoDescColor = dark ? 'rgba(255,255,255,0.6)' : INK_SOFT;
  const promoBadgeBg = dark ? `${PINK_C}26` : (isPink ? `${PINK_C}1F` : GREEN[50]);
  const promoBadgeColor = dark ? PINK_C : (isPink ? PINK_C : GREEN[700]);

  // ════ MOBILE NAV (drawer) ════
  if (isMobile) {
    return (
      <>
        <div style={{
          position: 'sticky', top: 0, zIndex: 80,
          background: bg, backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
          borderBottom: `1px solid ${border}`,
        }}>
          <div style={{ height: 60, padding: '0 16px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <a href="/" style={{ textDecoration: 'none' }}>
              {isPink && window.PinkLogo ? <window.PinkLogo size={26} dark={dark}/> : <CNVLogo size={26} dark={dark}/>}
            </a>
            <button onClick={() => setDrawerOpen(true)} aria-label="Mở menu"
              style={{ background: 'transparent', border: 'none', padding: 8, cursor: 'pointer', color: dark ? '#fff' : INK }}>
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                <line x1="3" y1="6" x2="21" y2="6"/>
                <line x1="3" y1="12" x2="21" y2="12"/>
                <line x1="3" y1="18" x2="21" y2="18"/>
              </svg>
            </button>
          </div>
        </div>

        {drawerOpen && (
          <div style={{ position: 'fixed', inset: 0, zIndex: 100 }}>
            <div onClick={() => setDrawerOpen(false)}
              style={{ position: 'absolute', inset: 0, background: 'rgba(0,0,0,0.5)', animation: 'mmFade .15s ease' }}/>
            <div style={{
              position: 'absolute', top: 0, right: 0, bottom: 0, width: 'min(360px, 90vw)',
              background: panelBg, color: featTitleColor,
              boxShadow: '-20px 0 50px rgba(0,0,0,0.4)',
              animation: 'mmSlideRight .22s ease',
              display: 'flex', flexDirection: 'column',
            }}>
              <style>{`
                @keyframes mmFade { from{opacity:0} to{opacity:1} }
                @keyframes mmSlideRight { from{transform:translateX(100%)} to{transform:translateX(0)} }
              `}</style>

              <div style={{ padding: '16px 20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between', borderBottom: `1px solid ${panelBorder}` }}>
                {isPink && window.PinkLogo ? <window.PinkLogo size={26} dark={dark}/> : <CNVLogo size={26} dark={dark}/>}
                <button onClick={() => setDrawerOpen(false)} aria-label="Đóng"
                  style={{ background: 'transparent', border: 'none', padding: 4, cursor: 'pointer', color: featTitleColor }}>
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                    <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
                  </svg>
                </button>
              </div>

              <div style={{ flex: 1, overflowY: 'auto', padding: '8px 0' }}>
                {MENU.map((item, i) => {
                  const hasDropdown = !!item.modules || !!item.integrations;
                  const expanded = mobileExpanded === i;
                  return (
                    <div key={item.label} style={{ borderBottom: `1px solid ${panelBorder}` }}>
                      {hasDropdown ? (
                        <button onClick={() => setMobileExpanded(expanded ? null : i)}
                          style={{
                            width: '100%', textAlign: 'left',
                            background: 'transparent', border: 'none', cursor: 'pointer',
                            padding: '14px 20px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                            fontFamily: 'Inter, sans-serif', fontSize: 15, fontWeight: 600,
                            color: featTitleColor,
                          }}>
                          {item.label}
                          <svg width="14" height="14" viewBox="0 0 12 12" style={{ transition: 'transform .15s', transform: expanded ? 'rotate(180deg)' : 'none' }}>
                            <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                          </svg>
                        </button>
                      ) : (
                        <a href={item.href}
                          target={item.external ? '_blank' : undefined}
                          rel={item.external ? 'noopener noreferrer' : undefined}
                          onClick={() => setDrawerOpen(false)}
                          style={{
                            display: 'block', padding: '14px 20px',
                            fontFamily: 'Inter, sans-serif', fontSize: 15, fontWeight: 600,
                            color: featTitleColor, textDecoration: 'none',
                          }}>{item.label}</a>
                      )}

                      {/* Sub items — modules cho dropdown Sản phẩm */}
                      {expanded && item.modules && (
                        <div style={{ padding: '0 20px 16px', background: hoverBg }}>
                          {item.modules.map((mod, mi) => (
                            <div key={mi} style={{ marginTop: 14, paddingBottom: 8, borderBottom: mi === item.modules.length - 1 ? 'none' : `1px solid ${panelBorder}` }}>
                              <a href={mod.href || '#'} onClick={() => setDrawerOpen(false)} style={{ display: 'flex', alignItems: 'center', gap: 8, fontFamily: 'Inter, sans-serif', fontSize: 12.5, fontWeight: 700, letterSpacing: '0.06em', color: featTitleColor, marginBottom: 8, textDecoration: 'none' }}>
                                {window.Icon && <window.Icon name={mod.icon} size={14}/>}
                                {mod.title} <span style={{ color: accent, marginLeft: 'auto' }}>→</span>
                              </a>
                              {mod.features.map((f, fi) => (
                                <a key={fi} href={f.href || mod.href || '#'} onClick={() => setDrawerOpen(false)}
                                  style={{ display: 'block', padding: '5px 0 5px 22px', fontFamily: 'Inter, sans-serif', fontSize: 12.5, color: featDescColor, textDecoration: 'none' }}>
                                  {f.name}
                                </a>
                              ))}
                            </div>
                          ))}
                        </div>
                      )}
                      {expanded && item.integrations && window.INTEGRATIONS && (
                        <div style={{ padding: '0 20px 16px', background: hoverBg }}>
                          {window.INTEGRATIONS.map(it => {
                            const Logo = it.Logo;
                            return (
                              <a key={it.id} href="/integrations" onClick={() => setDrawerOpen(false)}
                                style={{ display: 'flex', gap: 10, alignItems: 'center', padding: '8px 0', textDecoration: 'none' }}>
                                <Logo size={24}/>
                                <span style={{ fontFamily: 'Inter, sans-serif', fontSize: 13, fontWeight: 600, color: featTitleColor }}>{it.name}</span>
                              </a>
                            );
                          })}
                        </div>
                      )}
                    </div>
                  );
                })}
              </div>

              <div style={{ padding: 20, borderTop: `1px solid ${panelBorder}`, display: 'flex', flexDirection: 'column', gap: 10 }}>
                <a href="#" style={{ padding: '10px 14px', borderRadius: 10, textAlign: 'center', textDecoration: 'none', fontFamily: 'Inter, sans-serif', fontSize: 14, fontWeight: 600, color: featTitleColor, border: `1px solid ${panelBorder}` }}>Đăng nhập</a>
                <window.PinkBtn size="md">Đặt lịch demo</window.PinkBtn>
              </div>
            </div>
          </div>
        )}
      </>
    );
  }

  // ════ DESKTOP NAV ════
  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 80,
      background: bg, backdropFilter: 'blur(16px)', WebkitBackdropFilter: 'blur(16px)',
      borderBottom: `1px solid ${border}`,
      transition: 'background .2s',
    }}>
      <div style={{
        maxWidth: 1440, margin: '0 auto', height: 68,
        padding: '0 48px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      }}>
        <a href="/" style={{ textDecoration: 'none' }}>
          {isPink && window.PinkLogo ? <window.PinkLogo size={30} dark={dark}/> : <CNVLogo size={30} dark={dark}/>}
        </a>

        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }} onMouseLeave={scheduleClose}>
          {MENU.map((item, i) => {
            const hasDropdown = !!item.modules || !!item.integrations;
            const isOpen = openIdx === i;
            const isActive = current === item.href || current === item.label;
            return (
              <div key={item.label} style={{ position: 'relative' }}
                onMouseEnter={() => hasDropdown ? open(i) : open(null)}>
                {hasDropdown ? (
                  <button style={{
                    background: 'transparent', border: 'none',
                    padding: '10px 14px', borderRadius: 8,
                    fontFamily: 'Inter, sans-serif', fontSize: 14, fontWeight: 500,
                    color: isActive ? linkActive : linkColor, cursor: 'pointer',
                    display: 'flex', alignItems: 'center', gap: 4,
                    letterSpacing: '-0.005em',
                  }}>
                    {item.label}
                    <svg width="12" height="12" viewBox="0 0 12 12" style={{ transition: 'transform .15s', transform: isOpen ? 'rotate(180deg)' : 'none' }}>
                      <path d="M3 4.5L6 7.5L9 4.5" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                    </svg>
                  </button>
                ) : (
                  <a href={item.href}
                    target={item.external ? '_blank' : undefined}
                    rel={item.external ? 'noopener noreferrer' : undefined}
                    style={{
                      display: 'inline-block',
                      padding: '10px 14px', borderRadius: 8,
                      fontFamily: 'Inter, sans-serif', fontSize: 14, fontWeight: 500,
                      color: isActive ? linkActive : linkColor, textDecoration: 'none',
                      letterSpacing: '-0.005em',
                    }}>{item.label}</a>
                )}
              </div>
            );
          })}
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <GhostBtn dark={dark}>Đăng nhập</GhostBtn>
          <window.PinkBtn size="sm">Đặt lịch demo</window.PinkBtn>
        </div>
      </div>

      {/* Mega panel — Sản phẩm: sidebar trái + feature grid phải */}
      {openIdx !== null && MENU[openIdx]?.modules && (
        <div onMouseEnter={() => open(openIdx)} onMouseLeave={scheduleClose}
          style={{
            position: 'absolute', top: '100%', left: 0, right: 0,
            background: panelBg,
            borderTop: `1px solid ${panelBorder}`,
            boxShadow: panelShadow,
            animation: 'mmSlide .18s ease',
          }}>
          <style>{`@keyframes mmSlide { from { opacity: 0; transform: translateY(-6px); } to { opacity: 1; transform: translateY(0); } }`}</style>
          <div style={{ maxWidth: 1280, margin: '0 auto', padding: '28px 48px',
            display: 'grid', gridTemplateColumns: '260px 1fr', gap: 32 }}>
            {/* LEFT — module sidebar */}
            <div style={{ borderRight: `1px solid ${panelBorder}`, paddingRight: 16 }}>
              <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 11, fontWeight: 700, letterSpacing: '0.14em', textTransform: 'uppercase', color: colHeadColor, marginBottom: 12, padding: '0 10px' }}>PHÂN HỆ</div>
              {MENU[openIdx].modules.map((m, mi) => {
                const active = activeModuleIdx === mi;
                return (
                  <div key={mi}
                    onMouseEnter={() => setActiveModuleIdx(mi)}
                    style={{
                      display: 'flex', alignItems: 'center', gap: 10,
                      padding: '10px 12px', borderRadius: 10,
                      background: active ? `${accent}15` : 'transparent',
                      borderLeft: active ? `2px solid ${accent}` : '2px solid transparent',
                      cursor: 'pointer', marginBottom: 2,
                      transition: 'background .12s',
                    }}>
                    <div style={{
                      width: 30, height: 30, borderRadius: 8,
                      background: active ? `${accent}25` : hoverBg,
                      color: active ? accent : featDescColor,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      flexShrink: 0,
                    }}>
                      {window.Icon && <window.Icon name={m.icon} size={16}/>}
                    </div>
                    <span style={{
                      fontFamily: 'Inter, sans-serif', fontSize: 13.5,
                      fontWeight: active ? 700 : 600,
                      color: active ? featTitleColor : featDescColor,
                      letterSpacing: '-0.005em',
                    }}>{m.title}</span>
                  </div>
                );
              })}
            </div>

            {/* RIGHT — module title + desc + feature grid */}
            {(() => {
              const m = MENU[openIdx].modules[activeModuleIdx] || MENU[openIdx].modules[0];
              return (
                <div>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 16, marginBottom: 16 }}>
                    <div>
                      <a href={m.href || '#'} style={{
                        fontFamily: 'Inter, sans-serif', fontSize: 18, fontWeight: 800,
                        color: featTitleColor, letterSpacing: '-0.015em', textDecoration: 'none',
                        display: 'inline-flex', alignItems: 'center', gap: 6,
                      }}>{m.title} <span style={{ color: accent, fontSize: 14 }}>→</span></a>
                      <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 13.5, color: featDescColor, marginTop: 4, lineHeight: 1.5 }}>{m.desc}</div>
                    </div>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6 }}>
                    {m.features.map((f, fi) => (
                      <a key={fi} href={f.href || m.href || '#'} style={{
                        display: 'flex', alignItems: 'flex-start', gap: 10,
                        padding: '12px 12px', borderRadius: 10,
                        textDecoration: 'none', transition: 'background .12s',
                      }}
                      onMouseEnter={e => e.currentTarget.style.background = hoverBg}
                      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                        <div style={{
                          width: 32, height: 32, borderRadius: 8,
                          background: `${accent}18`, color: accent,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          flexShrink: 0,
                        }}>
                          {window.Icon && <window.Icon name={f.icon} size={16}/>}
                        </div>
                        <div style={{ minWidth: 0 }}>
                          <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 13.5, fontWeight: 700, color: featTitleColor, letterSpacing: '-0.005em', marginBottom: 2 }}>{f.name}</div>
                          <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 12, color: featDescColor, lineHeight: 1.45 }}>{f.desc}</div>
                        </div>
                      </a>
                    ))}
                  </div>
                </div>
              );
            })()}
          </div>
        </div>
      )}

      {/* Integrations mega panel */}
      {openIdx !== null && MENU[openIdx]?.integrations && window.INTEGRATIONS && (
        <div onMouseEnter={() => open(openIdx)} onMouseLeave={scheduleClose}
          style={{
            position: 'absolute', top: '100%', left: 0, right: 0,
            background: panelBg,
            borderTop: `1px solid ${panelBorder}`,
            boxShadow: panelShadow,
            animation: 'mmSlide .18s ease',
          }}>
          <div style={{ maxWidth: 1440, margin: '0 auto', padding: '32px 48px',
            display: 'grid', gridTemplateColumns: '1fr 240px', gap: 32 }}>
            <div>
              <div style={{
                fontFamily: 'Inter, sans-serif', fontSize: 12, fontWeight: 700,
                letterSpacing: '0.14em', textTransform: 'uppercase',
                color: colHeadColor, marginBottom: 6,
              }}>10 tích hợp sẵn sàng</div>
              <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 13, color: colDescColor, marginBottom: 18, lineHeight: 1.5 }}>
                Kết nối các công cụ phổ biến doanh nghiệp Việt đang dùng — không cần code.
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 4 }}>
                {window.INTEGRATIONS.map((it) => {
                  const Logo = it.Logo;
                  return (
                    <a key={it.id} href="/integrations" style={{
                      display: 'grid', gridTemplateColumns: '32px 1fr', gap: 12,
                      padding: '10px 12px', borderRadius: 8,
                      textDecoration: 'none', transition: 'background .12s',
                      alignItems: 'center',
                    }}
                    onMouseEnter={e => e.currentTarget.style.background = hoverBg}
                    onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                      <Logo size={32}/>
                      <div>
                        <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 14, fontWeight: 600, color: featTitleColor, letterSpacing: '-0.005em', marginBottom: 2 }}>{it.name}</div>
                        <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 12, color: featDescColor, lineHeight: 1.4, overflow: 'hidden', textOverflow: 'ellipsis', display: '-webkit-box', WebkitLineClamp: 1, WebkitBoxOrient: 'vertical' }}>{it.desc}</div>
                      </div>
                    </a>
                  );
                })}
              </div>
            </div>

            {/* Promo tile */}
            <div style={{
              background: promoBg, border: `1px solid ${promoBorder}`,
              borderRadius: 16, padding: 24, display: 'flex', flexDirection: 'column', gap: 10,
            }}>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px', background: promoBadgeBg, color: promoBadgeColor, borderRadius: 99, fontSize: 11, fontWeight: 700, letterSpacing: '0.08em', width: 'fit-content' }}>
                <span style={{ width: 6, height: 6, borderRadius: 99, background: accent }}/>API
              </div>
              <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 16, fontWeight: 700, color: promoTitleColor, letterSpacing: '-0.01em', lineHeight: 1.3 }}>
                Cần tích hợp khác? Open API + Webhook
              </div>
              <div style={{ fontFamily: 'Inter, sans-serif', fontSize: 13, color: promoDescColor, lineHeight: 1.5, flex: 1 }}>
                Kết nối ERP, kế toán, e-commerce — đội kỹ thuật CNV hỗ trợ triển khai.
              </div>
              <div style={{ marginTop: 4 }}>
                <a href="/integrations" style={{
                  fontFamily: 'Inter, sans-serif', fontSize: 13, fontWeight: 600,
                  color: PINK_C, textDecoration: 'none',
                }}>Xem tất cả tích hợp →</a>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { MegaNav });
