// ── SHARED NAVBAR ──────────────────────────────────────────────────────────
(function () {
  const { useState, useEffect } = React;

  // ── Inyecta favicon ────────────────────────────────────────────────────
  (function injectFavicon() {
    if (!document.querySelector('link[rel="icon"]')) {
      const link = document.createElement('link');
      link.rel = 'icon'; link.type = 'image/png'; link.href = '/img/ui/favicon.png';
      document.head.appendChild(link);
    }
  })();

  // ── Inyecta estilos del menú ───────────────────────────────────────────
  (function injectStyles() {
    if (document.getElementById('navbar-styles')) return;
    const s = document.createElement('style');
    s.id = 'navbar-styles';
    s.textContent = `
      .nav-overlay {
        position: fixed; inset: 0; z-index: 99;
        display: flex; flex-direction: column;
        opacity: 0; pointer-events: none;
        transition: opacity .35s ease;
      }
      .nav-overlay.open {
        opacity: 1; pointer-events: all;
      }
      .nav-overlay-bg {
        position: absolute; inset: 0;
        background: linear-gradient(160deg, #0a1f44 0%, #1A4FAB 55%, #2b8ed4 100%);
      }
      .nav-overlay-inner {
        position: relative; z-index: 1;
        display: flex; flex-direction: column;
        align-items: center; justify-content: center;
        height: 100%; gap: 8px;
        padding: 80px 32px 48px;
      }
      .nav-overlay-link {
        color: rgba(255,255,255,0.75);
        text-decoration: none;
        font-size: 2rem;
        font-weight: 800;
        letter-spacing: -0.5px;
        padding: 10px 0;
        border-bottom: 2px solid transparent;
        transition: color .2s, border-color .2s;
        width: 100%; text-align: center;
      }
      .nav-overlay-link:hover,
      .nav-overlay-link.active {
        color: white;
        border-bottom-color: rgba(255,255,255,0.4);
      }
      .nav-overlay-link.active {
        color: white;
        border-bottom-color: white;
      }
      .nav-overlay-divider {
        width: 40px; height: 1px;
        background: rgba(255,255,255,0.15);
        margin: 8px 0;
      }
      .nav-overlay-cta {
        margin-top: 24px;
        background: white;
        border: none; border-radius: 12px;
        padding: 16px 40px;
        font-weight: 800; font-size: 1rem;
        cursor: pointer;
        transition: transform .2s, opacity .2s;
        font-family: inherit;
        width: 100%;
      }
      .nav-overlay-cta:hover { opacity: .88; transform: translateY(-2px); }
      .hamburger-btn {
        background: none; border: none; cursor: pointer;
        padding: 6px; display: flex; flex-direction: column;
        gap: 5px; z-index: 101; position: relative;
      }
      .hamburger-btn span {
        display: block; width: 24px; height: 2px;
        background: white; border-radius: 2px;
        transition: transform .3s ease, opacity .3s ease, width .3s ease;
        transform-origin: center;
      }
      .hamburger-btn.open span:nth-child(1) { transform: translateY(7px) rotate(45deg); }
      .hamburger-btn.open span:nth-child(2) { opacity: 0; width: 0; }
      .hamburger-btn.open span:nth-child(3) { transform: translateY(-7px) rotate(-45deg); }
    `;
    document.head.appendChild(s);
  })();

  function useMobileNav(bp = 768) {
    const [mobile, setMobile] = useState(window.innerWidth < bp);
    useEffect(() => {
      const h = () => setMobile(window.innerWidth < bp);
      window.addEventListener('resize', h);
      return () => window.removeEventListener('resize', h);
    }, [bp]);
    return mobile;
  }

  const currentPath = window.location.pathname.replace(/\/$/, '') || '/';

  const NAV_LINKS = [
    { href: '/servicios',     label: 'Servicios' },
    { href: '/instalaciones', label: 'Instalaciones' },
    { href: '/contacto',      label: 'Contacto' },
    { href: '/blog',          label: 'Blog' },
  ];

  function SharedNavbar({ accentColor = '#1A4FAB', scrollToForm }) {
    const mobile = useMobileNav();
    const [menuOpen, setMenuOpen] = useState(false);

    // Bloquea scroll del body cuando el menú está abierto
    useEffect(() => {
      document.body.style.overflow = menuOpen ? 'hidden' : '';
      return () => { document.body.style.overflow = ''; };
    }, [menuOpen]);

    // Cierra el menú si cambia a desktop
    useEffect(() => { if (!mobile) setMenuOpen(false); }, [mobile]);

    const handleCTA = () => {
      setMenuOpen(false);
      setTimeout(() => scrollToForm && scrollToForm(), 350);
    };

    return (
      <>
        <nav style={{
          position: 'fixed', top: 0, left: 0, right: 0, zIndex: 100,
          background: `linear-gradient(135deg, #0a1f44 0%, ${accentColor} 60%, #2b8ed4 100%)`,
          padding: `0 ${mobile ? 16 : 24}px`,
          boxShadow: '0 2px 16px rgba(0,0,0,0.18)',
        }}>
          <div style={{
            maxWidth: 1100, margin: '0 auto',
            height: mobile ? 60 : 80,
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          }}>
            {/* Logo */}
            <a href="https://aireacondicionadomollet.es/" style={{ display: 'flex', alignItems: 'center', flexShrink: 0, zIndex: 101 }}>
              <img src="/img/ui/logo.png" alt="Clima Comfort" style={{ height: mobile ? 34 : 48, objectFit: 'contain' }} />
            </a>

            {/* Desktop nav */}
            {!mobile && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 20 }}>
                {NAV_LINKS.map(({ href, label }) => {
                  const isActive = href === '/' ? currentPath === '/' : currentPath === href || currentPath.startsWith(href + '/');
                  return (
                    <a key={href} href={href} style={{
                      color: isActive ? 'white' : 'rgba(255,255,255,0.72)',
                      textDecoration: 'none', fontWeight: isActive ? 700 : 600, fontSize: 14,
                      borderBottom: isActive ? '2px solid white' : '2px solid transparent',
                      paddingBottom: 2, transition: 'color .2s, border-color .2s',
                    }}
                    onMouseEnter={e => { e.currentTarget.style.color = 'white'; e.currentTarget.style.borderBottomColor = 'rgba(255,255,255,0.5)'; }}
                    onMouseLeave={e => {
                      e.currentTarget.style.color = isActive ? 'white' : 'rgba(255,255,255,0.72)';
                      e.currentTarget.style.borderBottomColor = isActive ? 'white' : 'transparent';
                    }}>
                      {label}
                    </a>
                  );
                })}
                <a href="/contacto" style={{
                  background: 'white', color: accentColor, border: 'none', borderRadius: 8,
                  padding: '10px 20px', fontWeight: 700, fontSize: 14, cursor: 'pointer',
                  transition: 'opacity .2s', whiteSpace: 'nowrap', fontFamily: 'inherit',
                  textDecoration: 'none', display: 'inline-block',
                }}
                onMouseEnter={e => e.currentTarget.style.opacity = '.85'}
                onMouseLeave={e => e.currentTarget.style.opacity = '1'}>
                  Pedir presupuesto
                </a>
              </div>
            )}

            {/* Mobile: CTA + hamburger */}
            {mobile && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, zIndex: 101 }}>
                <a href="/contacto" style={{
                  background: 'white', color: accentColor, border: 'none', borderRadius: 8,
                  padding: '8px 14px', fontWeight: 700, fontSize: 13, cursor: 'pointer',
                  transition: 'opacity .2s', whiteSpace: 'nowrap', fontFamily: 'inherit',
                  textDecoration: 'none', display: 'inline-block',
                }}
                onMouseEnter={e => e.currentTarget.style.opacity = '.85'}
                onMouseLeave={e => e.currentTarget.style.opacity = '1'}>
                  Pedir presupuesto
                </a>
                <button
                  className={`hamburger-btn${menuOpen ? ' open' : ''}`}
                  onClick={() => setMenuOpen(o => !o)}
                  aria-label={menuOpen ? 'Cerrar menú' : 'Abrir menú'}
                >
                  <span/><span/><span/>
                </button>
              </div>
            )}
          </div>
        </nav>

        {/* Full-screen overlay menu */}
        <div className={`nav-overlay${menuOpen ? ' open' : ''}`}>
          <div className="nav-overlay-bg"/>
          <div className="nav-overlay-inner">
            {NAV_LINKS.map(({ href, label }, i) => {
              const isActive = href === '/' ? currentPath === '/' : currentPath === href || currentPath.startsWith(href + '/');
              return (
                <React.Fragment key={href}>
                  <a
                    href={href}
                    className={`nav-overlay-link${isActive ? ' active' : ''}`}
                    onClick={() => setMenuOpen(false)}
                  >
                    {label}
                  </a>
                  {i < NAV_LINKS.length - 1 && <div className="nav-overlay-divider"/>}
                </React.Fragment>
              );
            })}

          </div>
        </div>
      </>
    );
  }

  window.SharedNavbar = SharedNavbar;
})();
