/* global React, Logo, Btn, Icon */
const { useState, useEffect, useRef } = React;

// Resolve URL prefix: pages in /servicios/* need '../' to reach root.
// Centralised so every link in the Nav is consistent across depths.
const ROOT = (typeof window !== 'undefined' && (window.location.pathname.includes('/servicios/') || window.location.pathname.includes('/blog/'))) ? '../' : '';

const SERVICES = [
  { label: 'Ethical Hacking', href: ROOT + 'servicios/ethical-hacking.html', desc: 'Pentesting & Red Team' },
  { label: 'Offensive Security', href: ROOT + 'servicios/offensive-security.html', desc: 'Adversary simulation' },
  { label: 'Defensive Team', href: ROOT + 'servicios/defensive-team.html', desc: 'Blue Team & SOC' },
  { label: 'DevSecOps', href: ROOT + 'servicios/devsecops.html', desc: 'Pipelines seguros' },
  { label: 'GRC', href: ROOT + 'servicios/grc.html', desc: 'Gobierno, Riesgo y Cumplimiento' },
  { label: 'Prevención de Riesgos', href: ROOT + 'servicios/prevencion-de-riesgos.html', desc: 'Análisis & continuidad' },
  { label: 'Cyber Threat Intelligence', href: ROOT + 'servicios/cyber-threat-intelligence.html', desc: 'Dark Web & marca digital' },
];

const Nav = () => {
  const [scrolled, setScrolled] = useState(false);
  const [openServices, setOpenServices] = useState(false);
  const closeT = useRef(null);

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

  // Top-level pages — all real files, all clean relative paths from any depth.
  // "Inicio" is rendered separately BEFORE the Servicios dropdown.
  // The rest follow after it.
  // On the home page, anchor links should be pure hashes so they scroll smoothly
  // instead of forcing a full page reload to a same-document URL.
  const onHome = typeof window !== 'undefined' && !window.location.pathname.includes('/servicios/');
  const homeHref = onHome ? '#top' : ROOT + 'index.html';
  const arianaHref = onHome ? '#ariana' : ROOT + 'index.html#ariana';
  const casosHref = onHome ? '#casos' : ROOT + 'index.html#casos';

  const homeLink = { label: 'Inicio', href: homeHref };
  const links = [
    { label: 'Ariana',   href: arianaHref },
    { label: 'Casos de uso', href: casosHref },
    { label: 'Blog',     href: ROOT + 'Blog.html' },
    { label: 'Contacto', href: ROOT + 'contacto.html' },
  ];

  const openMenu = () => { clearTimeout(closeT.current); setOpenServices(true); };
  const closeMenu = () => { closeT.current = setTimeout(() => setOpenServices(false), 120); };

  return (
    <nav aria-label="Principal" style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
      padding: '18px 5vw',
      background: scrolled ? 'rgba(23,23,23,.78)' : 'transparent',
      backdropFilter: scrolled ? 'blur(16px)' : 'none',
      borderBottom: scrolled ? '1px solid rgba(255,255,255,.08)' : '1px solid transparent',
      transition: 'all .24s cubic-bezier(.16,1,.3,1)',
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
    }}>
      <div style={{display:'flex', alignItems:'center', gap: 56}}>
        <a href={ROOT + 'index.html'} aria-label="Brotek — Inicio" style={{display:'block'}}>
          <Logo height={26}/>
        </a>
        <div style={{display:'flex', gap: 28, alignItems:'center'}}>
          {/* Inicio — sits before the Servicios dropdown */}
          <a href={homeLink.href}
            style={{
              fontFamily:'var(--font-body)', fontWeight: 500, fontSize: 14,
              color:'var(--fg)', textDecoration:'none', opacity: .85,
              transition: 'opacity .15s',
            }}
            onMouseEnter={e => e.currentTarget.style.opacity = '1'}
            onMouseLeave={e => e.currentTarget.style.opacity = '.85'}>{homeLink.label}</a>

          {/* Servicios — top-level link to servicios.html, with hover dropdown for shortcuts */}
          <div style={{position:'relative'}}
            onMouseEnter={openMenu} onMouseLeave={closeMenu}>
            <a href={ROOT + 'index.html#solucion'}
              aria-haspopup="true" aria-expanded={openServices}
              style={{
                fontFamily:'var(--font-body)', fontWeight: 500, fontSize: 14,
                color:'var(--fg)', textDecoration:'none', opacity: .85,
                display:'inline-flex', alignItems:'center', gap: 6,
                transition: 'opacity .15s',
              }}>
              Servicios
              <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"
                style={{ transform: openServices ? 'rotate(180deg)' : 'rotate(0)', transition:'transform .2s' }}>
                <polyline points="6 9 12 15 18 9"/>
              </svg>
            </a>
            {openServices && (
              <div role="menu" style={{
                position:'absolute', top: 'calc(100% + 14px)', left: -16,
                background: 'rgba(31,31,31,.96)', backdropFilter:'blur(24px)',
                border: '1px solid rgba(255,255,255,.10)', borderRadius: 16,
                padding: 10, minWidth: 320, boxShadow:'0 24px 60px rgba(0,0,0,.5)',
                animation:'fadeUp .18s ease-out',
              }}>
                <a href={ROOT + 'index.html#solucion'} role="menuitem" style={{
                  display:'flex', alignItems:'center', justifyContent:'space-between',
                  padding: '10px 14px', borderRadius: 10, textDecoration:'none',
                  color:'var(--fg)', borderBottom:'1px solid rgba(255,255,255,.06)', marginBottom: 4,
                  transition:'background .15s',
                }}
                onMouseEnter={e => e.currentTarget.style.background='rgba(255,255,255,.06)'}
                onMouseLeave={e => e.currentTarget.style.background='transparent'}>
                  <span style={{fontFamily:'var(--font-display)', fontWeight:500, fontSize:14}}>Ver todos los servicios</span>
                  <span style={{color:'var(--brotek-magenta)', fontSize: 16}}>→</span>
                </a>
                {SERVICES.map(s => (
                  <a key={s.href} href={s.href} role="menuitem" style={{
                    display:'flex', flexDirection:'column', gap: 2,
                    padding: '10px 14px', borderRadius: 10, textDecoration:'none',
                    color:'var(--fg)', transition:'background .15s',
                  }}
                  onMouseEnter={e => e.currentTarget.style.background='rgba(255,255,255,.06)'}
                  onMouseLeave={e => e.currentTarget.style.background='transparent'}>
                    <span style={{fontFamily:'var(--font-display)', fontWeight:500, fontSize:14}}>{s.label}</span>
                    <span style={{fontFamily:'var(--font-mono)', fontSize:11, color:'var(--fg-subtle)', letterSpacing:'.04em'}}>{s.desc}</span>
                  </a>
                ))}
              </div>
            )}
          </div>

          {links.map(l => {
            const isHash = l.href.startsWith('#');
            return (
              <a key={l.label} href={l.href}
                onClick={isHash ? (e) => {
                  e.preventDefault();
                  const id = l.href.slice(1);
                  const target = id === 'top' ? document.body : document.getElementById(id);
                  if (target) {
                    const top = id === 'top' ? 0 : target.getBoundingClientRect().top + window.scrollY - 80;
                    window.scrollTo({ top, behavior: 'smooth' });
                  }
                } : undefined}
                style={{
                  fontFamily:'var(--font-body)', fontWeight: 500, fontSize: 14,
                  color:'var(--fg)', textDecoration:'none', opacity: .85,
                  transition: 'opacity .15s', cursor:'pointer',
                }}
                onMouseEnter={e => e.currentTarget.style.opacity = '1'}
                onMouseLeave={e => e.currentTarget.style.opacity = '.85'}>{l.label}</a>
            );
          })}
        </div>
      </div>
      <div style={{display:'flex', alignItems:'center', gap: 14}}>
        <Btn variant="ghost" href={ROOT + 'contacto.html'}>Contáctanos</Btn>
        <Btn variant="primary" icon="arrow-up-right" href="https://calendar.google.com/calendar/u/0/appointments/schedules/AcZssZ03LzoOyBnS6ZQylmBi2miXKi2eqVs6DxXcx48byUlVPWTC4Cw9BxRHRHjYOO5s2vPvppukA3C-" target="_blank">Agendar diagnóstico</Btn>
      </div>
    </nav>
  );
};

window.Nav = Nav;
