// Shared header — sticky nav with mega-dropdown for Productos
function Header({ active }) {
  const [scrolled, setScrolled] = useState(false);
  const [open, setOpen] = useState(null); // 'productos' | 'sectores' | null
  const [mobile, setMobile] = useState(false);

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

  const link = (label, href, key) => (
    <a href={href} style={{
      color: active === key ? 'var(--brand-primary)' : 'var(--fg-strong)',
      fontWeight: active === key ? 600 : 500,
      fontSize: 14, textDecoration: 'none', padding: '8px 12px', borderRadius: 8,
      transition: 'color 120ms, background 120ms',
    }} onMouseEnter={e => e.currentTarget.style.background = 'var(--surface-subtle)'}
       onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
      {label}
    </a>
  );

  const dropTrigger = (label, key, allHref) => (
    <div style={{ position: 'relative', paddingBottom: 12, marginBottom: -12 }} onMouseEnter={() => setOpen(key)} onMouseLeave={() => setOpen(null)}>
      <a href={allHref || '#'} onClick={e => { if (!allHref) e.preventDefault(); }} style={{
        display: 'flex', alignItems: 'center', gap: 4, background: 'transparent', border: 0,
        color: 'var(--fg-strong)', fontWeight: 500, fontSize: 14, padding: '8px 12px',
        borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit', textDecoration: 'none',
      }}>
        {label} <Icon name="chevronDown" size={14}/>
      </a>
      {open === key && key === 'productos' && <ProductosMenu/>}
      {open === key && key === 'sectores' && <SectoresMenu/>}
    </div>
  );

  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 100,
      background: scrolled ? 'rgba(255,255,255,0.85)' : 'rgba(255,255,255,0.7)',
      backdropFilter: 'blur(12px)', WebkitBackdropFilter: 'blur(12px)',
      borderBottom: scrolled ? '1px solid var(--border-default)' : '1px solid transparent',
      transition: 'background 200ms, border-color 200ms',
    }}>
      <div style={{ maxWidth: 1280, margin: '0 auto', padding: '0 24px', height: 68, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <a href="/" style={{ display: 'flex', alignItems: 'center' }}>
          <Logo/>
        </a>
        <nav className="afer-desktop-nav" style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          {dropTrigger('Productos', 'productos')}
          {dropTrigger('Sectores', 'sectores', '/sectores/')}
          {link('Precios', '/precios/', 'pricing')}
          {link('FAQs', '/faqs/', 'faqs')}
          <a href="/asesorias/" style={{ color: 'var(--fg-strong)', fontWeight: 500, fontSize: 14, padding: '8px 12px', textDecoration: 'none' }}>Asesorías</a>
        </nav>
        <div className="afer-desktop-nav" style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <a href="https://prosuite.aferapp.com" style={{ color: 'var(--fg-strong)', fontWeight: 500, fontSize: 14, padding: '8px 12px', textDecoration: 'none' }}>Iniciar sesión</a>
          <a href="/sobre-nosotros/" style={{ color: 'var(--fg-strong)', fontWeight: 500, fontSize: 14, padding: '8px 12px', textDecoration: 'none' }}>Sobre nosotros</a>
          <Button variant="primary" onClick={openCalendly}>Solicita una demo</Button>
        </div>
        <button className="afer-mobile-toggle" onClick={() => setMobile(!mobile)} style={{
          display: 'none', background: 'transparent', border: 0, cursor: 'pointer', padding: 8,
        }}>
          <Icon name={mobile ? 'x' : 'menu'} size={24}/>
        </button>
      </div>
      {mobile && <MobileMenu close={() => setMobile(false)}/>}
      <style>{`
        @media (max-width: 920px) {
          .afer-desktop-nav { display: none !important; }
          .afer-mobile-toggle { display: block !important; }
        }
      `}</style>
    </header>
  );
}

function ProductosMenu() {
  const items = [
    { icon: 'file', title: 'Facturación', desc: 'Verifactu, cobros, bancos, proyectos y CRM', href: '/software-facturacion-cloud/', color: 'var(--brand-primary)' },
    { icon: 'clock', title: 'Control horario', desc: 'Fichajes, vacaciones, contratos', href: '/software-control-horario/', color: '#16A34A' },
    { icon: 'whatsapp', title: 'Fichaje por WhatsApp', desc: 'Tu equipo ficha respondiendo a un mensaje', href: '/fichaje-por-whatsapp/', color: '#25D366' },
    { icon: 'sparkle', title: 'Inteligencia artificial', desc: 'OCR, conciliación, asistente', href: '/erp-con-ia/', color: '#7C3AED' },
    { icon: 'message', title: 'Agentes IA por WhatsApp', desc: 'Citas, gastos, atención 24/7', href: '/agentes-whatsapp-para-pymes/', color: '#25D366' },
  ];
  return (
    <div style={{
      position: 'absolute', top: '100%', left: -200, width: 640,
      background: '#fff', border: '1px solid var(--border-default)', borderRadius: 16,
      boxShadow: '0 24px 60px rgba(15,23,42,0.14)', padding: 16,
      display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 4,
    }}>
      {items.map(it => (
        <a key={it.title} href={it.href} style={{
          display: 'flex', alignItems: 'flex-start', gap: 14, padding: 14, borderRadius: 10,
          textDecoration: 'none', color: 'inherit', transition: 'background 120ms',
        }}
        onMouseEnter={e => e.currentTarget.style.background = 'var(--surface-subtle)'}
        onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
          <div style={{ width: 38, height: 38, flexShrink: 0, borderRadius: 10, background: 'var(--brand-primary-soft)', color: it.color, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <Icon name={it.icon} size={20} color={it.color}/>
          </div>
          <div>
            <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg-strong)', marginBottom: 2 }}>{it.title}</div>
            <div style={{ fontSize: 12, color: 'var(--fg-muted)', lineHeight: 1.4 }}>{it.desc}</div>
          </div>
        </a>
      ))}
    </div>
  );
}

function SectoresMenu() {
  const sectors = [
    ['Construcción', '/software-gestion-empresas-construccion/'],
    ['Jardinería', '/software-gestion-empresas-jardineria-mantenimiento/'],
    ['Industria & oficios', '/software-gestion-industriales-carpinteria-fontaneria-electricidad-herreria/'],
    ['Servicios profesionales', '/software-gestion-servicios-profesionales-abogados-consultores-asesorias/'],
    ['Retail', '/software-gestion-tiendas-retail/'],
    ['Marketing & diseño', '/software-gestion-agencias-marketing-diseno/'],
    ['Marina', '/software-gestion-empresas-nautica/'],
    ['Asesorías', '/asesorias/'],
  ];
  return (
    <div style={{
      position: 'absolute', top: '100%', left: -100, width: 480,
      background: '#fff', border: '1px solid var(--border-default)', borderRadius: 16,
      boxShadow: '0 24px 60px rgba(15,23,42,0.14)', padding: 20,
    }}>
      <div style={{ fontSize: 12, fontWeight: 600, color: 'var(--brand-accent)', marginBottom: 12 }}>SECTORES</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 4 }}>
        {sectors.map(([label, href]) => (
          <a key={label} href={href} style={{
            padding: '10px 12px', borderRadius: 8, fontSize: 14, color: 'var(--fg-strong)',
            textDecoration: 'none', transition: 'background 120ms',
          }}
          onMouseEnter={e => e.currentTarget.style.background = 'var(--surface-subtle)'}
          onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
            {label}
          </a>
        ))}
      </div>
      <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid var(--border-default)' }}>
        <a href="/sectores/" style={{ fontSize: 13, fontWeight: 600, color: 'var(--brand-accent)', display: 'inline-flex', alignItems: 'center', gap: 4 }}>
          Ver todos los sectores <Icon name="arrow" size={14}/>
        </a>
      </div>
    </div>
  );
}

function MobileMenu({ close }) {
  return (
    <div style={{ borderTop: '1px solid var(--border-default)', background: '#fff', padding: 16 }}>
      {[
        ['Facturación', '/software-facturacion-cloud/'],
        ['Control horario', '/software-control-horario/'],
        ['IA', '/erp-con-ia/'],
        ['Sectores', '/sectores/'],
        ['Precios', '/precios/'],
      ].map(([label, href]) => (
        <a key={label} href={href} onClick={close} style={{
          display: 'block', padding: '12px 0', fontSize: 16, fontWeight: 500,
          color: 'var(--fg-strong)', textDecoration: 'none', borderBottom: '1px solid var(--border-default)',
        }}>{label}</a>
      ))}
      <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
        <Button variant="secondary" style={{ flex: 1 }} href="https://prosuite.aferapp.com">Iniciar sesión</Button>
        <Button variant="primary" style={{ flex: 1 }} onClick={openCalendly}>Demo</Button>
      </div>
      <a href="/sobre-nosotros/" onClick={close} style={{ display: 'block', textAlign: 'center', fontSize: 13, color: 'var(--fg-muted)', marginTop: 12, textDecoration: 'none' }}>Sobre nosotros</a>
    </div>
  );
}

window.Header = Header;
