// header.jsx, Editorial header with mega-menu on hover
const { useState: useStateHd, useEffect: useEffectHd, useRef: useRefHd } = React;

const MEGA_PT = {
  services: {
    label: 'SOLUÇÕES',
    featured: {
      tag: 'TRIPÉ TEÓRICO-METODOLÓGICO',
      title: <>Fayol / Porter / <em>Damodaran</em></>,
      meta: 'DISCIPLINA / ESCOLHA / RIGOR FINANCEIRO'
    },
    columns: [
      {
        title: 'ESTRATÉGIA',
        items: [
          { label: 'Estratégia Competitiva', href: '#solucoes-estrategia-competitiva' },
          { label: 'Governança e Conselho', href: '#solucoes-governanca-e-conselho' },
          { label: 'Educação Executiva', href: '#solucoes-educacao-executiva' }
        ]
      },
      {
        title: 'FINANÇAS',
        items: [
          { label: 'Finanças Corporativas', href: '#solucoes-financas-corporativas' },
          { label: 'Valuation', href: '#solucoes-valuation' },
          { label: 'Gestão Baseada em Valor', href: '#solucoes-gestao-baseada-em-valor' }
        ]
      }
    ]
  },
  approach: {
    label: 'MÉTODO',
    featured: {
      tag: 'COMO TRABALHAMOS',
      title: <>Quatro movimentos até o <em>valor econômico</em></>,
      meta: 'DIAGNÓSTICO / DESENHO / EXECUÇÃO / PERENIDADE'
    },
    columns: [
      {
        title: 'ETAPAS',
        items: [
          { label: 'Diagnóstico', href: '#metodo-etapa-diagnostico' },
          { label: 'Desenho do plano', href: '#metodo-etapa-desenho-do-plano' },
          { label: 'Execução em campo', href: '#metodo-etapa-execucao-em-campo' },
          { label: 'Perenidade', href: '#metodo-etapa-perenidade' }
        ]
      },
      {
        title: 'PRINCÍPIOS',
        items: [
          { label: 'Fundador no campo', href: '#metodo-principio-fundador-no-campo' },
          { label: 'Decisão por dados', href: '#metodo-principio-decisao-por-dados' },
          { label: 'Execução até o caixa', href: '#metodo-principio-execucao-ate-o-caixa' }
        ]
      }
    ]
  },
  // 'insights' (Blog da SN&Cia) is a direct link, not a mega-menu — kept here
  // only for label lookup; columns/featured intentionally absent.
  insights: { label: 'BLOG DA SN&CIA' },
  about: {
    label: 'SOBRE NÓS',
    featured: {
      tag: 'SOBRE',
      title: <>Uma butique <em>por escolha</em>, não por escala</>,
      meta: 'BRASIL'
    },
    columns: [
      {
        title: 'SOBRE NÓS',
        items: [
          { label: 'Fundadores', href: '#socios' },
          { label: 'Setores', href: '#setores' }
        ]
      },
      {
        title: 'CARREIRA',
        items: [
          { label: 'Programa de associados', href: '#associados' }
        ]
      }
    ]
  }
};

const MEGA_EN = {
  services: {
    label: 'SOLUTIONS',
    featured: {
      tag: 'METHODOLOGICAL TRIPOD',
      title: <>Fayol / Porter / <em>Damodaran</em></>,
      meta: 'DISCIPLINE / CHOICE / FINANCIAL RIGOR'
    },
    columns: [
      {
        title: 'STRATEGY',
        items: [
          { label: 'Competitive Strategy', href: '#solucoes-estrategia-competitiva' },
          { label: 'Governance & Board', href: '#solucoes-governanca-e-conselho' },
          { label: 'Executive Education', href: '#solucoes-educacao-executiva' }
        ]
      },
      {
        title: 'FINANCE',
        items: [
          { label: 'Corporate Finance', href: '#solucoes-financas-corporativas' },
          { label: 'Valuation', href: '#solucoes-valuation' },
          { label: 'Value-Based Management', href: '#solucoes-gestao-baseada-em-valor' }
        ]
      }
    ]
  },
  approach: {
    label: 'METHOD',
    featured: {
      tag: 'HOW WE WORK',
      title: <>Four moves to <em>economic value</em></>,
      meta: 'DIAGNOSE / DESIGN / EXECUTE / PERMANENCE'
    },
    columns: [
      {
        title: 'STAGES',
        items: [
          { label: 'Diagnostic', href: '#metodo-etapa-diagnostico' },
          { label: 'Plan design', href: '#metodo-etapa-desenho-do-plano' },
          { label: 'Execution on site', href: '#metodo-etapa-execucao-em-campo' },
          { label: 'Permanence', href: '#metodo-etapa-perenidade' }
        ]
      },
      {
        title: 'PRINCIPLES',
        items: [
          { label: 'Founder on the field', href: '#metodo-principio-fundador-no-campo' },
          { label: 'Data-driven decisions', href: '#metodo-principio-decisao-por-dados' },
          { label: 'Execute until cash', href: '#metodo-principio-execucao-ate-o-caixa' }
        ]
      }
    ]
  },
  insights: { label: 'SN&CIA BLOG' },
  about: {
    label: 'ABOUT US',
    featured: {
      tag: 'ABOUT',
      title: <>A boutique <em>by choice</em>, not scale</>,
      meta: 'BRAZIL'
    },
    columns: [
      {
        title: 'ABOUT US',
        items: [
          { label: 'Founders', href: '#socios' },
          { label: 'Sectors', href: '#setores' }
        ]
      },
      {
        title: 'CAREER',
        items: [
          { label: 'Associate program', href: '#associates' }
        ]
      }
    ]
  }
};

const MegaPanel = ({ data, open }) => {
  if (!data) return null;
  return (
    <div className={`mega-panel ${open ? 'open' : ''}`}>
      {data.columns.map((col, i) => (
        <div key={i} className="mega-col">
          <h4>{col.title}</h4>
          <ul>
            {col.items.map((item, j) => (
              <li key={j}>
                <a href={item.href}>
                  <span>{item.label}</span>
                  <span className="arrow">→</span>
                </a>
              </li>
            ))}
          </ul>
        </div>
      ))}
      <div className="mega-featured">
        <span className="tag">{data.featured.tag}</span>
        <h5>{data.featured.title}</h5>
        <span className="meta">{data.featured.meta}</span>
      </div>
    </div>
  );
};

const Header = () => {
  const { lang, setLang, t } = useLang();
  const [scrolled, setScrolled] = useStateHd(false);
  const [openKey, setOpenKey] = useStateHd(null);
  const [overDark, setOverDark] = useStateHd(true);
  const [mobileOpen, setMobileOpen] = useStateHd(false);
  const closeTimer = useRefHd(null);
  const drawerRef = useRefHd(null);

  const MEGA = lang === 'en' ? MEGA_EN : MEGA_PT;

  useEffectHd(() => {
    const onScroll = () => {
      setScrolled(window.scrollY > 40);
      const hero = document.querySelector('.hero');
      if (hero) {
        const heroBottom = hero.getBoundingClientRect().bottom;
        setOverDark(heroBottom > 80);
      }
    };
    onScroll();
    window.addEventListener('scroll', onScroll);
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  // Lock body scroll when drawer is open + ESC closes it
  useEffectHd(() => {
    if (!mobileOpen) return;
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    const onKey = (e) => { if (e.key === 'Escape') setMobileOpen(false); };
    document.addEventListener('keydown', onKey);
    // Focus first link in drawer on open
    setTimeout(() => {
      drawerRef.current?.querySelector('a, button')?.focus();
    }, 50);
    return () => {
      document.body.style.overflow = prevOverflow;
      document.removeEventListener('keydown', onKey);
    };
  }, [mobileOpen]);

  const openMega = (key) => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    setOpenKey(key);
  };
  const closeMega = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => setOpenKey(null), 150);
  };

  // 'insights' (Blog) is a direct link (no mega-menu); it is rendered
  // separately in the nav below, between MÉTODO and SOBRE NÓS.
  const keysBeforeBlog = ['services', 'approach'];
  const keysAfterBlog = ['about'];
  const keys = [...keysBeforeBlog, ...keysAfterBlog];
  const closeDrawer = () => setMobileOpen(false);

  return (
    <>
      <header className={`site-header ${scrolled ? 'scrolled' : ''} ${openKey ? 'mega-open' : ''} ${overDark && !scrolled && !openKey ? 'over-dark' : ''}`}
        onMouseLeave={closeMega}>
        <a href="#top" className="brand" aria-label="Souza Nunes & Cia">
          <LogoMark size={40}/>
          <div className="brand-text">
            <span className="mark-big">Souza Nunes &amp; Cia</span>
            <span className="mark-small">Butique de estratégia</span>
          </div>
        </a>
        <nav className="nav" aria-label={lang === 'pt' ? 'Navegação principal' : 'Main navigation'}>
          {keysBeforeBlog.map(k => (
            <div key={k} className="nav-item" onMouseEnter={() => openMega(k)}>
              <a href={`#${k === 'services' ? 'solucoes' : k === 'approach' ? 'metodo' : k}`}>
                {MEGA[k].label}
              </a>
            </div>
          ))}
          <a href="#blog" onMouseEnter={closeMega} style={{color:'inherit'}}>{MEGA.insights.label}</a>
          {keysAfterBlog.map(k => (
            <div key={k} className="nav-item" onMouseEnter={() => openMega(k)}>
              <a href={`#${k === 'about' ? 'socios' : k}`}>
                {MEGA[k].label}
              </a>
            </div>
          ))}
          <a href="#contact" onMouseEnter={closeMega} style={{color:'inherit'}}>{t.nav.contact.toUpperCase()}</a>
        </nav>
        <div className="header-right">
          <div className="lang-toggle">
            <button className={lang==='pt'?'active':''} onClick={()=>setLang('pt')} aria-label="Português">PT</button>
            <button className={lang==='en'?'active':''} onClick={()=>setLang('en')} aria-label="English">EN</button>
          </div>
          {/* Hamburger - visible only on small screens */}
          <button
            className="nav-toggle"
            aria-label={lang === 'pt' ? 'Abrir menu' : 'Open menu'}
            aria-expanded={mobileOpen}
            aria-controls="mobile-drawer"
            onClick={() => setMobileOpen(true)}>
            <span/><span/><span/>
          </button>
        </div>
        {keys.map(k => (
          <MegaPanel key={k} data={MEGA[k]} open={openKey === k}/>
        ))}
      </header>

      {/* Mobile drawer + scrim */}
      <div
        className={`drawer-scrim ${mobileOpen ? 'open' : ''}`}
        onClick={closeDrawer}
        aria-hidden="true"/>
      <aside
        id="mobile-drawer"
        ref={drawerRef}
        className={`mobile-drawer ${mobileOpen ? 'open' : ''}`}
        role="dialog"
        aria-modal="true"
        aria-label={lang === 'pt' ? 'Menu de navegação' : 'Navigation menu'}>
        <div className="drawer-head">
          <span className="drawer-title">
            {lang === 'pt' ? 'Menu' : 'Menu'}
          </span>
          <button
            className="drawer-close"
            onClick={closeDrawer}
            aria-label={lang === 'pt' ? 'Fechar menu' : 'Close menu'}>
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" aria-hidden="true">
              <path d="M5 5 L15 15 M15 5 L5 15"/>
            </svg>
          </button>
        </div>
        <nav className="drawer-nav" aria-label={lang === 'pt' ? 'Navegação móvel' : 'Mobile navigation'}>
          {keysBeforeBlog.map((k, idx) => (
            <a key={k} href={`#${k === 'services' ? 'solucoes' : k === 'approach' ? 'metodo' : k}`} onClick={closeDrawer}>
              <span className="drawer-num">0{idx + 1}</span>
              <span className="drawer-label">{MEGA[k].label}</span>
            </a>
          ))}
          <a href="#blog" onClick={closeDrawer}>
            <span className="drawer-num">0{keysBeforeBlog.length + 1}</span>
            <span className="drawer-label">{MEGA.insights.label}</span>
          </a>
          {keysAfterBlog.map((k, idx) => (
            <a key={k} href={`#${k === 'about' ? 'socios' : k}`} onClick={closeDrawer}>
              <span className="drawer-num">0{keysBeforeBlog.length + 2 + idx}</span>
              <span className="drawer-label">{MEGA[k].label}</span>
            </a>
          ))}
          <a href="#contact" onClick={closeDrawer}>
            <span className="drawer-num">0{keys.length + 2}</span>
            <span className="drawer-label">{t.nav.contact.toUpperCase()}</span>
          </a>
        </nav>
        <div className="drawer-footer">
          <div className="lang-toggle">
            <button className={lang==='pt'?'active':''} onClick={()=>setLang('pt')}>PT</button>
            <button className={lang==='en'?'active':''} onClick={()=>setLang('en')}>EN</button>
          </div>
        </div>
      </aside>
    </>
  );
};

window.Header = Header;
