/* Nav.jsx — sticky glass top nav with services popover and mobile drawer */
const Nav = ({ active, onNav }) => {
  const [scrolled, setScrolled] = React.useState(false);
  const [menu, setMenu] = React.useState(false);
  const [servicesOpen, setServicesOpen] = React.useState(false);
  const servicesRef = React.useRef(null);

  const serviceLinks = [
    { icon: 'bot', label: 'Agentes de IA', description: 'Atendimento e vendas 24/7', href: '/servicos/agentes-de-ia/' },
    { icon: 'workflow', label: 'Automações de processos', description: 'Fluxos e tarefas automatizados', href: '/servicos/automacoes/' },
    { icon: 'share-2', label: 'Integrações de canais', description: 'Canais e sistemas conectados', href: '/servicos/integracoes/' },
    { icon: 'globe', label: 'Criação de sites com IA', description: 'Sites modernos e otimizados', href: '/servicos/sites-e-sistemas/' },
    { icon: 'layout-dashboard', label: 'Aplicativos web e mobile', description: 'Apps e painéis sob medida', href: '/servicos/sites-e-sistemas/' },
    { icon: 'server', label: 'Sistemas internos', description: 'Dados, processos e equipes', href: '/servicos/sites-e-sistemas/' },
  ];

  const items = [
    { id: 'como', label: 'Como funciona' },
    { id: 'beneficios', label: 'Benefícios' },
    { id: 'solucoes', label: 'Soluções' },
    { id: 'sobre', label: 'Sobre' },
    { id: 'contato', label: 'Contato' },
  ];

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

  React.useEffect(() => {
    const onPointerDown = (event) => {
      if (servicesRef.current && !servicesRef.current.contains(event.target)) setServicesOpen(false);
    };
    const onKeyDown = (event) => {
      if (event.key === 'Escape') setServicesOpen(false);
    };
    document.addEventListener('pointerdown', onPointerDown);
    document.addEventListener('keydown', onKeyDown);
    return () => {
      document.removeEventListener('pointerdown', onPointerDown);
      document.removeEventListener('keydown', onKeyDown);
    };
  }, []);

  React.useEffect(() => {
    if (window.lucide) window.lucide.createIcons();
  }, [menu, servicesOpen]);

  const go = (id) => {
    setMenu(false);
    setServicesOpen(false);
    onNav(id);
  };

  return (
    <nav style={{
      position: 'sticky', top: 0, zIndex: 60,
      background: scrolled ? 'rgba(5,7,13,0.82)' : 'transparent',
      backdropFilter: scrolled ? 'blur(18px) saturate(140%)' : 'none',
      WebkitBackdropFilter: scrolled ? 'blur(18px) saturate(140%)' : 'none',
      borderBottom: `1px solid ${scrolled ? 'var(--ar-border)' : 'transparent'}`,
      transition: 'all 220ms var(--ar-ease)',
    }}>
      <Container style={{ display: 'flex', alignItems: 'center', gap: 28, padding: scrolled ? '12px 80px' : '18px 80px', transition: 'padding 220ms' }}>
        <a href="/" onClick={(event) => { event.preventDefault(); go('top'); }} style={{ display: 'flex', alignItems: 'center', gap: 12, cursor: 'pointer' }}>
          <img src="/assets/logo-white.png" alt="AR · Agência de IA & Automações" style={{ width: 38, height: 38, filter: 'drop-shadow(0 0 14px rgba(0,212,255,0.35))' }} />
          <span style={{ fontFamily: 'var(--ar-font-body)', fontSize: 11, fontWeight: 600, letterSpacing: '0.16em', color: 'var(--ar-text-muted)', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>Agência de IA &amp; Automações</span>
        </a>

        <div className="nav-links" style={{ display: 'flex', gap: 26, marginLeft: 8, alignItems: 'center' }}>
          <div ref={servicesRef} className="nav-services-wrap" style={{ position: 'relative' }}>
            <button
              type="button"
              aria-expanded={servicesOpen}
              aria-haspopup="true"
              onClick={() => setServicesOpen(open => !open)}
              style={{
                display: 'inline-flex', alignItems: 'center', gap: 6,
                fontFamily: 'var(--ar-font-body)', fontSize: 14, fontWeight: 500,
                color: active === 'servicos' || servicesOpen ? 'var(--ar-text-main)' : 'var(--ar-text-muted)',
                cursor: 'pointer', padding: '6px 0', background: 'transparent', border: 0,
                borderBottom: active === 'servicos' ? '2px solid var(--ar-cyan)' : '2px solid transparent',
                transition: 'color 140ms, border-color 140ms',
              }}
            >
              Serviços
              <i data-lucide="chevron-down" className={servicesOpen ? 'nav-services-chevron open' : 'nav-services-chevron'}></i>
            </button>

            <div className={servicesOpen ? 'nav-services-popover open' : 'nav-services-popover'} aria-hidden={!servicesOpen}>
              <div className="nav-services-head">
                <div>
                  <span>Serviços AR</span>
                  <strong>IA aplicada à sua operação</strong>
                </div>
                <a href="/#servicos" onClick={(e) => { e.preventDefault(); go('servicos'); }}>Ver todos <i data-lucide="arrow-right"></i></a>
              </div>
              <div className="nav-services-grid">
                {serviceLinks.map(service => (
                  <a key={service.href} href={service.href} className="nav-service-link">
                    <span className="nav-service-icon"><i data-lucide={service.icon}></i></span>
                    <span>
                      <strong>{service.label}</strong>
                      <small>{service.description}</small>
                    </span>
                    <i data-lucide="arrow-up-right" className="nav-service-arrow"></i>
                  </a>
                ))}
              </div>
            </div>
          </div>

          {items.map(it => (
            <a key={it.id} href={'/#' + it.id} onClick={(event) => { event.preventDefault(); go(it.id); }} style={{
              fontFamily: 'var(--ar-font-body)', fontSize: 14, fontWeight: 500,
              color: active === it.id ? 'var(--ar-text-main)' : 'var(--ar-text-muted)',
              cursor: 'pointer', padding: '6px 0',
              borderBottom: active === it.id ? '2px solid var(--ar-cyan)' : '2px solid transparent',
              transition: 'color 140ms, border-color 140ms',
            }}>{it.label}</a>
          ))}
        </div>

        <div className="nav-cta" style={{ marginLeft: 'auto', display: 'flex', gap: 12, alignItems: 'center' }}>
          <Button size="sm" onClick={() => go('contato')}>Solicitar demonstração</Button>
        </div>

        <button className="nav-burger" onClick={() => setMenu(open => !open)} aria-label="Menu" aria-expanded={menu} style={{
          display: 'none', marginLeft: 'auto', width: 42, height: 42, borderRadius: 12,
          background: 'rgba(255,255,255,0.04)', border: '1px solid var(--ar-border)',
          color: 'var(--ar-text-main)', cursor: 'pointer', alignItems: 'center', justifyContent: 'center',
        }}>
          <i data-lucide={menu ? 'x' : 'menu'} style={{ width: 20, height: 20 }}></i>
        </button>
      </Container>

      <div className="nav-mobile-drawer" style={{
        display: menu ? 'block' : 'none',
        background: 'rgba(5,7,13,0.98)', backdropFilter: 'blur(18px)',
        borderBottom: '1px solid var(--ar-border)',
        padding: '8px 22px 20px',
      }}>
        <button type="button" className="nav-mobile-service-toggle" aria-expanded={servicesOpen} onClick={() => setServicesOpen(open => !open)}>
          <span>Serviços</span>
          <i data-lucide="chevron-down" className={servicesOpen ? 'nav-services-chevron open' : 'nav-services-chevron'}></i>
        </button>
        {servicesOpen && (
          <div className="nav-mobile-services">
            {serviceLinks.map(service => (
              <a key={service.href} href={service.href}>
                <i data-lucide={service.icon}></i>
                <span>{service.label}</span>
                <i data-lucide="arrow-right"></i>
              </a>
            ))}
            <a href="/#servicos" onClick={(e) => { e.preventDefault(); go('servicos'); }}>
              <i data-lucide="layout-grid"></i>
              <span>Ver todos os serviços</span>
              <i data-lucide="arrow-right"></i>
            </a>
          </div>
        )}
        {items.map(it => (
          <a key={it.id} href={'/#' + it.id} onClick={(event) => { event.preventDefault(); go(it.id); }} style={{
            display: 'block', padding: '13px 4px', fontFamily: 'var(--ar-font-body)', fontSize: 16,
            color: active === it.id ? 'var(--ar-cyan)' : 'var(--ar-text-main)',
            borderBottom: '1px solid rgba(255,255,255,0.06)', cursor: 'pointer',
          }}>{it.label}</a>
        ))}
        <div style={{ marginTop: 16 }}>
          <Button size="md" style={{ width: '100%' }} onClick={() => go('contato')}>Solicitar demonstração</Button>
        </div>
      </div>

      <style>{`
        .nav-services-chevron { width: 15px; height: 15px; transition: transform 180ms var(--ar-ease); }
        .nav-services-chevron.open { transform: rotate(180deg); }
        .nav-services-popover {
          position: absolute; top: calc(100% + 16px); left: -22px; width: 650px;
          padding: 14px; border: 1px solid var(--ar-border-strong); border-radius: var(--ar-radius-xl);
          background: rgba(11,16,32,0.98); box-shadow: var(--ar-shadow-modal);
          opacity: 0; visibility: hidden; pointer-events: none;
          transform: translateY(-8px) scale(0.985); transform-origin: top left;
          transition: opacity 180ms, transform 220ms var(--ar-ease), visibility 180ms;
        }
        .nav-services-popover::before {
          content: ''; position: absolute; top: -6px; left: 52px; width: 11px; height: 11px;
          background: var(--ar-bg-section); border-left: 1px solid var(--ar-border-strong);
          border-top: 1px solid var(--ar-border-strong); transform: rotate(45deg);
        }
        .nav-services-popover.open { opacity: 1; visibility: visible; pointer-events: auto; transform: none; }
        .nav-services-head {
          display: flex; justify-content: space-between; align-items: center; gap: 20px;
          padding: 8px 10px 14px; border-bottom: 1px solid var(--ar-border);
        }
        .nav-services-head span {
          display: block; color: var(--ar-cyan); font: 600 10px/1 var(--ar-font-body);
          letter-spacing: 0.16em; text-transform: uppercase; margin-bottom: 6px;
        }
        .nav-services-head strong { color: var(--ar-text-main); font: 600 16px/1.2 var(--ar-font-title); }
        .nav-services-head a {
          display: inline-flex; align-items: center; gap: 7px; color: var(--ar-cyan);
          font: 600 12px/1 var(--ar-font-body); white-space: nowrap;
        }
        .nav-services-head a svg { width: 14px; height: 14px; }
        .nav-services-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 5px; padding-top: 10px; }
        .nav-service-link {
          position: relative; display: grid; grid-template-columns: 38px 1fr 16px; align-items: center; gap: 11px;
          padding: 11px; border-radius: var(--ar-radius-md); border: 1px solid transparent;
          transition: background 160ms, border-color 160ms, transform 180ms var(--ar-ease);
        }
        .nav-service-link:hover, .nav-service-link:focus-visible {
          background: rgba(0,94,255,0.10); border-color: var(--ar-border-blue); transform: translateY(-1px); outline: none;
        }
        .nav-service-icon {
          width: 38px; height: 38px; border-radius: var(--ar-radius-sm); display: flex; align-items: center; justify-content: center;
          color: var(--ar-cyan); background: rgba(0,212,255,0.08); border: 1px solid rgba(0,212,255,0.22);
        }
        .nav-service-icon svg { width: 18px; height: 18px; }
        .nav-service-link strong { display: block; color: var(--ar-text-main); font: 600 13px/1.25 var(--ar-font-body); }
        .nav-service-link small { display: block; color: var(--ar-text-muted); font: 400 11px/1.35 var(--ar-font-body); margin-top: 3px; }
        .nav-service-arrow { width: 14px; height: 14px; color: var(--ar-text-dim); transition: color 160ms, transform 160ms; }
        .nav-service-link:hover .nav-service-arrow { color: var(--ar-cyan); transform: translate(1px,-1px); }
        .nav-mobile-service-toggle {
          width: 100%; display: flex; align-items: center; justify-content: space-between; padding: 13px 4px;
          color: var(--ar-text-main); background: transparent; border: 0; border-bottom: 1px solid rgba(255,255,255,0.06);
          font: 500 16px/1.2 var(--ar-font-body); cursor: pointer;
        }
        .nav-mobile-services {
          display: grid; grid-template-columns: 1fr 1fr; gap: 7px; padding: 10px 0 12px;
          border-bottom: 1px solid rgba(255,255,255,0.06);
        }
        .nav-mobile-services a {
          display: grid; grid-template-columns: 18px 1fr 14px; align-items: center; gap: 8px;
          min-height: 46px; padding: 9px 10px; border-radius: var(--ar-radius-sm);
          background: rgba(255,255,255,0.03); border: 1px solid var(--ar-border);
          color: var(--ar-text-main); font: 500 12px/1.25 var(--ar-font-body);
        }
        .nav-mobile-services a svg { width: 15px; height: 15px; color: var(--ar-cyan); }
        @media (max-width: 1120px) {
          .nav-links, .nav-cta { display: none !important; }
          .nav-burger { display: flex !important; }
        }
        @media (max-width: 520px) {
          .nav-mobile-services { grid-template-columns: 1fr; }
        }
        @media (prefers-reduced-motion: reduce) {
          .nav-services-popover, .nav-services-chevron, .nav-service-link, .nav-service-arrow { transition: none !important; }
        }
      `}</style>
    </nav>
  );
};

window.Nav = Nav;
