// Auditbnb logo — usable as inline SVG component
const LogoMark = ({ size = 28, color = 'currentColor' }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
    {/* roof/house silhouette + checkmark */}
    <path d="M4 15.5L16 5l12 10.5V27a2 2 0 01-2 2H6a2 2 0 01-2-2V15.5z" fill={color} opacity="0.12"/>
    <path d="M4 15.5L16 5l12 10.5" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
    <path d="M11 18.5l3.2 3.2L21 15" stroke={color} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round"/>
    <path d="M6 15.5V27a2 2 0 002 2h16a2 2 0 002-2V15.5" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" opacity="0.35"/>
  </svg>
);

const Logo = ({ size = 24 }) => (
  <a href="/" className="logo">
    <LogoMark size={size} />
    <span>Auditbnb</span>
  </a>
);

// La cookie ab_session es HttpOnly (no accesible desde JS por seguridad).
// Para saber si el usuario está autenticado, preguntamos al servidor via /api/v2/me.
// Esto se llama on-mount y actualiza el UI cuando la respuesta llega.

const Nav = ({ active }) => {
  const [session, setSession] = React.useState(null);
  const [sessionLoaded, setSessionLoaded] = React.useState(false);

  React.useEffect(() => {
    let cancelled = false;
    fetch('/api/v2/me', { credentials: 'include' })
      .then((r) => r.json())
      .then((data) => {
        if (cancelled) return;
        if (data && data.authenticated) {
          setSession({ email: data.email, user_id: data.user_id });
        }
        setSessionLoaded(true);
      })
      .catch(() => { if (!cancelled) setSessionLoaded(true); });
    return () => { cancelled = true; };
  }, []);

  const email = session && (session.email || session.user_id || '');
  const [menuOpen, setMenuOpen] = React.useState(false);
  const toggle = () => setMenuOpen((o) => !o);
  const close = () => setMenuOpen(false);

  return (
    <nav className="nav">
      <div className="wrap nav-inner">
        <Logo />
        <div className={`nav-links${menuOpen ? ' is-open' : ''}`}>
          <a href="/ejemplo" className={active === "ejemplo" ? "active" : ""} onClick={close}>Ejemplo premium</a>
          <a href="/premium" className={active === "premium" ? "active" : ""} onClick={close}>Precios</a>
          {session && (
            <a href="/dashboard" className={active === "dashboard" ? "active" : ""} onClick={close}>Dashboard</a>
          )}
          {!session && (
            <a href="/login" onClick={close}>Iniciar sesión</a>
          )}
        </div>
        <div className="nav-right">
          {session ? (
            <>
              <a href="/dashboard" className={`btn btn-ghost ${active === "dashboard" ? "active" : ""}`}>Dashboard</a>
              {email && (
                <span className="muted" style={{ fontSize: 13, maxWidth: 180, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }} title={email}>
                  {email}
                </span>
              )}
              <a href="/#audit" className="btn btn-primary">Audita tu Airbnb</a>
            </>
          ) : (
            <>
              <a href="/login" className="btn btn-ghost">Iniciar sesión</a>
              <a href="/#audit" className="btn btn-primary">Audita tu Airbnb</a>
            </>
          )}
          <button
            type="button"
            className="nav-hamburger"
            aria-label={menuOpen ? 'Cerrar menú' : 'Abrir menú'}
            aria-expanded={menuOpen}
            onClick={toggle}
          >
            {menuOpen ? (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6L6 18M6 6l12 12"/></svg>
            ) : (
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M4 7h16M4 12h16M4 17h16"/></svg>
            )}
          </button>
        </div>
      </div>
    </nav>
  );
};

const Footer = () => (
  <footer className="footer">
    <div className="wrap">
      <div className="footer-grid">
        <div>
          <div style={{display:'flex', alignItems:'center', gap: 10, marginBottom: 12}}>
            <LogoMark size={24} />
            <span className="serif" style={{fontSize: 20}}>Auditbnb</span>
          </div>
          <p style={{maxWidth: 340, margin: 0, lineHeight: 1.5}}>
            Auditorías de Airbnb con IA. Un score, 9 categorías evaluadas
            y un plan de acción claro para aumentar reservas y revenue.
          </p>
        </div>
        <div>
          <h5>Producto</h5>
          <ul>
            <li><a href="/">Inicio</a></li>
            <li><a href="/#como-funciona">Cómo funciona</a></li>
            <li><a href="/premium">Precios</a></li>
            <li><a href="/premium#faq">FAQ</a></li>
          </ul>
        </div>
        <div>
          <h5>Recursos</h5>
          <ul>
            <li><a href="/guias/">Guías para hosts</a></li>
            <li><a href="/zonas/">Zonas por ciudad</a></li>
            <li><a href="/guias/superhost-90-dias.html">Superhost en 90 días</a></li>
            <li><a href="mailto:hola@auditbnb.com">Contacto</a></li>
          </ul>
        </div>
        <div>
          <h5>Compañía</h5>
          <ul>
            <li><a href="/login">Iniciar sesión</a></li>
            <li><a href="mailto:hola@auditbnb.com?subject=Privacidad">Privacidad</a></li>
            <li><a href="mailto:hola@auditbnb.com?subject=Términos">Términos</a></li>
          </ul>
        </div>
      </div>
      <div style={{marginTop: 48, paddingTop: 24, borderTop: '1px solid var(--line)', display:'flex', justifyContent:'space-between', fontSize: 12}}>
        <span>© 2026 Auditbnb · Hecho para anfitriones que quieren mejorar.</span>
        <span className="mono muted">v1.4.0</span>
      </div>
    </div>
  </footer>
);

Object.assign(window, { Nav, Footer, Logo, LogoMark });
