// ───────────────────────────────────────────────────────────
// Autenticación (Firebase) + mensajes
//   • Métodos: Google · Email/contraseña · Anónimo (sin registro)
//   • Base unificada: Firebase Auth (usuarios) + Firestore (mensajes)
//   • Copia: cada mensaje también se envía a la planilla (Apps Script)
//
// Scope: los <script type="text/babel"> comparten alcance global,
// por eso usamos React.useState (no redeclaramos hooks).
// ───────────────────────────────────────────────────────────

const CFG = window.MINNESOTA_CONFIG || {};

// ── Inicialización de Firebase (una sola vez) ────────────────
let _auth = null, _db = null, _fbReady = false;
function initFirebase() {
  if (_fbReady) return true;
  if (!(CFG.isFirebaseReady && CFG.isFirebaseReady())) return false;
  if (!(window.firebase && firebase.initializeApp)) return false;
  if (!firebase.apps || !firebase.apps.length) firebase.initializeApp(CFG.firebase);
  _auth = firebase.auth();
  try { _db = firebase.firestore(); } catch (e) { _db = null; }
  _fbReady = true;
  return true;
}

// ── Store de sesión (lo alimenta onAuthStateChanged) ─────────
const AuthStore = (() => {
  let user = null;
  const subs = new Set();
  const emit = () => subs.forEach((fn) => fn(user));
  return {
    get: () => user,
    set: (u) => { user = u; emit(); },
    subscribe: (fn) => { subs.add(fn); return () => subs.delete(fn); },
  };
})();

function mapUser(u) {
  if (!u) return null;
  const pid = u.isAnonymous
    ? "anonymous"
    : ((u.providerData && u.providerData[0] && u.providerData[0].providerId) || "desconocido");
  return {
    uid: u.uid,
    email: u.email || "",
    name: u.displayName || "",
    picture: u.photoURL || "",
    anon: !!u.isAnonymous,
    provider: pid,
  };
}

// Arrancar el observador de sesión apenas carga el archivo.
(function bootAuth() {
  if (!initFirebase()) return;
  _auth.onAuthStateChanged((u) => AuthStore.set(mapUser(u)));
  // Volvemos de un signInWithRedirect (Google): registramos al usuario.
  // El popup falla en navegadores con COOP/bloqueadores y en móviles, por eso
  // usamos redirect como respaldo (ver GoogleButton).
  _auth.getRedirectResult().then((res) => {
    if (res && res.user) registerUser(mapUser(res.user));
    try { sessionStorage.removeItem("minnesota_pending_google"); } catch (e) {}
  }).catch(() => {
    try { sessionStorage.removeItem("minnesota_pending_google"); } catch (e) {}
  });
})();

function useAuth() {
  const [user, setUser] = React.useState(AuthStore.get());
  React.useEffect(() => AuthStore.subscribe(setUser), []);
  const signOut = React.useCallback(() => { if (_auth) _auth.signOut(); }, []);
  return { user, signOut };
}

// ── Etiqueta legible del proveedor ───────────────────────────
function providerLabel(p) {
  return p === "google.com" ? "Google" : p === "password" ? "Email" : p === "anonymous" ? "Anónimo" : (p || "—");
}

// ── Copia del mensaje a la planilla (Apps Script) ────────────
async function postToSheets(payload) {
  if (!(CFG.isSheetsReady && CFG.isSheetsReady())) return { ok: false, reason: "not-configured" };
  try {
    const res = await fetch(CFG.SHEETS_WEBAPP_URL, {
      method: "POST",
      headers: { "Content-Type": "text/plain;charset=utf-8" },
      body: JSON.stringify(payload),
      redirect: "follow",
    });
    let data = null;
    try { data = await res.json(); } catch (e) {}
    return { ok: data ? data.ok !== false : true, data };
  } catch (e) {
    return { ok: false, reason: "network", error: String(e) };
  }
}

// ── Escrituras en Firestore (base unificada) ─────────────────
function tsNow() {
  return (window.firebase && firebase.firestore && firebase.firestore.FieldValue)
    ? firebase.firestore.FieldValue.serverTimestamp() : new Date();
}
async function fsUpsertUser(u) {
  if (!_db || !u || u.anon) return;
  try {
    await _db.collection("usuarios").doc(u.uid).set({
      email: u.email, nombre: u.name, telefono: u.telefono || "",
      proveedor: u.provider, ultimoIngreso: tsNow(),
      primerIngreso: tsNow(), // merge no pisa si ya existe vía transform? -> usamos merge abajo
    }, { merge: true });
  } catch (e) { /* las reglas o la red pueden fallar; no bloquea */ }
}
async function fsAddMessage(m) {
  if (!_db) return false;
  try {
    await _db.collection("mensajes").add({
      nombre: m.name || "", email: m.email || "", telefono: m.telefono || "",
      motivo: m.motivo || "", mensaje: m.mensaje || "", proveedor: m.provider || "",
      uid: m.uid || "", fecha: tsNow(), origen: m.page || "",
    });
    return true;
  } catch (e) { return false; }
}

// ── Acciones de alto nivel ───────────────────────────────────
function registerUser(u) {           // al ingresar (no anónimo)
  if (!u || u.anon) return;
  fsUpsertUser(u);
  postToSheets({
    action: "register", uid: u.uid, sub: u.uid, email: u.email,
    name: u.name, telefono: u.telefono || "", provider: u.provider, page: location.href,
  });
}
async function sendMessage(m) {       // mensaje (cualquier método)
  const a = fsAddMessage(m);
  const b = postToSheets({
    action: "message", uid: m.uid, sub: m.uid, email: m.email, name: m.name,
    telefono: m.telefono || "", motivo: m.motivo || "", mensaje: m.mensaje || "",
    provider: m.provider || "", page: location.href,
  });
  const [okA, rB] = await Promise.all([a, b]);
  // Éxito si al menos una base recibió el dato (o si Sheets no está configurado, no frustramos).
  return okA || rB.ok || rB.reason === "not-configured";
}

// ── Mapeo de errores de Firebase a español ───────────────────
function authError(code) {
  const m = {
    "auth/invalid-email": "El correo no es válido.",
    "auth/missing-password": "Ingresá una contraseña.",
    "auth/weak-password": "La contraseña debe tener al menos 6 caracteres.",
    "auth/email-already-in-use": "Ese correo ya tiene una cuenta. Probá ingresar.",
    "auth/wrong-password": "Contraseña incorrecta.",
    "auth/user-not-found": "No encontramos una cuenta con ese correo. Creá una.",
    "auth/invalid-credential": "Correo o contraseña incorrectos.",
    "auth/popup-closed-by-user": "Cerraste la ventana de Google antes de terminar.",
    "auth/popup-blocked": "El navegador bloqueó la ventana. Permití las ventanas emergentes.",
    "auth/too-many-requests": "Demasiados intentos. Probá de nuevo en un rato.",
    "auth/network-request-failed": "Problema de conexión. Revisá tu internet.",
    "auth/unauthorized-domain": "Este sitio no está habilitado para el ingreso. Avisanos por WhatsApp.",
    "auth/operation-not-allowed": "El ingreso con Google no está disponible en este momento.",
  };
  return m[code] || "No pudimos completar el ingreso. Probá de nuevo.";
}

// ── Botón de Google (estilo de marca) ────────────────────────
function GoogleButton({ onError, onDone }) {
  const [busy, setBusy] = React.useState(false);
  const go = async () => {
    setBusy(true);
    const provider = new firebase.auth.GoogleAuthProvider();
    try {
      const cred = await _auth.signInWithPopup(provider);
      registerUser(mapUser(cred.user));
      onDone && onDone();
    } catch (e) {
      // El popup falla en navegadores con COOP, móviles y bloqueadores de
      // ventanas. En esos casos caemos a redirect (el flujo más confiable):
      // recarga la página y getRedirectResult() completa el registro.
      const REDIRECT_FALLBACK = new Set([
        "auth/popup-blocked", "auth/popup-closed-by-user",
        "auth/cancelled-popup-request", "auth/internal-error",
        "auth/web-storage-unsupported",
        "auth/operation-not-supported-in-this-environment",
      ]);
      if (!e.code || REDIRECT_FALLBACK.has(e.code)) {
        try {
          try { sessionStorage.setItem("minnesota_pending_google", "1"); } catch (_) {}
          await _auth.signInWithRedirect(provider);
          return; // navega fuera del sitio; no reseteamos "busy"
        } catch (e2) { onError && onError(authError(e2.code)); }
      } else {
        onError && onError(authError(e.code));
      }
    } finally { setBusy(false); }
  };
  return (
    <button type="button" onClick={go} disabled={busy}
      className="w-full inline-flex items-center justify-center gap-3 rounded-full font-cta transition-all disabled:opacity-60"
      style={{ padding: "0.85rem 1.4rem", background: "#fff", color: "var(--tinta)", border: "1px solid var(--gris-suave)", boxShadow: "0 8px 24px -16px rgba(28,28,28,0.5)" }}>
      <svg width="20" height="20" viewBox="0 0 48 48" aria-hidden="true" style={{ flexShrink: 0 }}>
        <path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9 3.6l6.7-6.7C35.6 2.5 30.2 0 24 0 14.6 0 6.4 5.4 2.5 13.3l7.9 6.1C12.2 13.3 17.6 9.5 24 9.5z" />
        <path fill="#4285F4" d="M46.1 24.5c0-1.6-.1-3.1-.4-4.5H24v9h12.4c-.5 2.9-2.1 5.3-4.6 7l7.1 5.5c4.2-3.9 6.6-9.6 6.6-16z" />
        <path fill="#FBBC05" d="M10.4 28.6c-.5-1.5-.8-3-.8-4.6s.3-3.1.8-4.6l-7.9-6.1C.9 16.5 0 20.1 0 24s.9 7.5 2.5 10.7l7.9-6.1z" />
        <path fill="#34A853" d="M24 48c6.2 0 11.4-2 15.2-5.5l-7.1-5.5c-2 1.3-4.6 2.1-8.1 2.1-6.4 0-11.8-3.8-13.6-9.4l-7.9 6.1C6.4 42.6 14.6 48 24 48z" />
      </svg>
      <span>{busy ? "Abriendo…" : "Continuar con Google"}</span>
    </button>
  );
}

// ── Form de email/contraseña ─────────────────────────────────
function EmailForm({ onBack, onDone }) {
  const [mode, setMode] = React.useState("signin"); // signin | signup
  const [nombre, setNombre] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [pass, setPass] = React.useState("");
  const [err, setErr] = React.useState("");
  const [busy, setBusy] = React.useState(false);
  const field = "w-full rounded-2xl px-4 py-3 text-[var(--tinta)] bg-[var(--papel)] border transition-colors outline-none focus:border-[var(--verde)] focus:ring-2 focus:ring-[rgba(93,174,158,0.25)]";

  const submit = async (ev) => {
    ev.preventDefault();
    setErr(""); setBusy(true);
    try {
      if (mode === "signup") {
        const cred = await _auth.createUserWithEmailAndPassword(email.trim(), pass);
        if (nombre.trim()) { try { await cred.user.updateProfile({ displayName: nombre.trim() }); } catch (e) {} }
        const mu = mapUser(_auth.currentUser); if (mu && nombre.trim()) mu.name = nombre.trim();
        registerUser(mu);
      } else {
        const cred = await _auth.signInWithEmailAndPassword(email.trim(), pass);
        registerUser(mapUser(cred.user));
      }
      onDone && onDone();
    } catch (e) { setErr(authError(e.code)); }
    finally { setBusy(false); }
  };

  return (
    <form onSubmit={submit} className="flex flex-col gap-3.5 w-full">
      {mode === "signup" && (
        <div>
          <label className="form-label" htmlFor="e-nombre">Nombre</label>
          <input id="e-nombre" className={field} style={{ borderColor: "var(--gris-suave)" }} value={nombre} onChange={(e) => setNombre(e.target.value)} placeholder="Tu nombre" />
        </div>
      )}
      <div>
        <label className="form-label" htmlFor="e-email">Correo electrónico</label>
        <input id="e-email" type="email" className={field} style={{ borderColor: "var(--gris-suave)" }} value={email} onChange={(e) => setEmail(e.target.value)} placeholder="tucorreo@ejemplo.com" />
      </div>
      <div>
        <label className="form-label" htmlFor="e-pass">Contraseña</label>
        <input id="e-pass" type="password" className={field} style={{ borderColor: "var(--gris-suave)" }} value={pass} onChange={(e) => setPass(e.target.value)} placeholder="Al menos 6 caracteres" />
      </div>
      {err && <p className="form-err">{err}</p>}
      <button type="submit" disabled={busy} className="cta inline-flex items-center justify-center gap-2 rounded-full font-cta bg-[var(--verde)] text-white hover:brightness-[1.05] transition-all disabled:opacity-60" style={{ padding: "0.9rem 1.4rem" }}>
        {busy ? "Procesando…" : (mode === "signup" ? "Crear cuenta" : "Ingresar")}
      </button>
      <div className="flex items-center justify-between text-[0.85rem]">
        <button type="button" onClick={() => { setErr(""); setMode(mode === "signup" ? "signin" : "signup"); }} className="text-[var(--pinar)] font-cta" style={{ fontWeight: 700 }}>
          {mode === "signup" ? "Ya tengo cuenta" : "Crear cuenta nueva"}
        </button>
        <button type="button" onClick={onBack} className="text-[var(--gris-medio)]" style={{ fontWeight: 600 }}>← Otras opciones</button>
      </div>
    </form>
  );
}

// ── Chip del usuario ─────────────────────────────────────────
function UserChip({ user, onSignOut }) {
  const initial = (user.name || user.email || "?").trim().charAt(0).toUpperCase() || "A";
  const display = user.name || (user.anon ? "Invitado/a" : user.email) || "Invitado/a";
  return (
    <div className="flex items-center gap-3 rounded-full pl-2 pr-4 py-2" style={{ background: "var(--crema)", border: "1px solid rgba(47,111,98,0.12)" }}>
      {user.picture
        ? <img src={user.picture} alt="" referrerPolicy="no-referrer" style={{ width: 36, height: 36, borderRadius: "50%", objectFit: "cover", flexShrink: 0 }} />
        : <span style={{ width: 36, height: 36, borderRadius: "50%", background: user.anon ? "var(--durazno)" : "var(--verde)", color: user.anon ? "var(--tinta)" : "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 800, flexShrink: 0 }}>{user.anon ? "?" : initial}</span>}
      <span className="leading-tight" style={{ minWidth: 0 }}>
        <span className="block font-title text-[var(--tinta)] truncate" style={{ fontWeight: 700, fontSize: "0.95rem", maxWidth: 180 }}>{display}</span>
        <button type="button" onClick={onSignOut} className="text-[var(--gris-medio)] hover:text-[var(--pinar)] transition-colors" style={{ fontSize: "0.78rem", fontWeight: 600 }}>{user.anon ? "Salir del modo invitado" : "Cerrar sesión"}</button>
      </span>
    </div>
  );
}

// ── Panel de ingreso (elige método) ──────────────────────────
function LoginPanel() {
  const [view, setView] = React.useState("choose"); // choose | email
  const [err, setErr] = React.useState("");
  const [busyAnon, setBusyAnon] = React.useState(false);

  const goAnon = async () => {
    setErr(""); setBusyAnon(true);
    try { await _auth.signInAnonymously(); }
    catch (e) { setErr(authError(e.code)); }
    finally { setBusyAnon(false); }
  };

  return (
    <div className="rounded-[28px] p-7 sm:p-9 bg-[var(--papel)] border border-[rgba(47,111,98,0.12)] flex flex-col items-start gap-5" style={{ boxShadow: "0 24px 50px -38px rgba(28,28,28,0.4)" }}>
      <div className="flex items-center gap-3">
        <Wing color="var(--durazno)" style={{ width: 30, height: 30 }} />
        <h3 className="font-title text-[var(--pinar)]" style={{ fontWeight: 800, fontSize: "1.35rem" }}>Ingresá para escribirnos</h3>
      </div>
      <p className="text-[var(--grafito)]" style={{ fontSize: "1rem", lineHeight: 1.55 }}>
        Elegí cómo querés ingresar. Es para poder responderte y acompañar tu consulta con cuidado. Tus datos quedan resguardados — ver <a href="privacidad.html" target="_blank" rel="noopener noreferrer" style={{ color: "var(--pinar)", fontWeight: 700 }}>Política de privacidad</a>.
      </p>

      {err && <p className="form-err w-full">{err}</p>}

      {view === "choose" ? (
        <div className="w-full flex flex-col gap-3">
          <GoogleButton onError={setErr} />
          <button type="button" onClick={() => { setErr(""); setView("email"); }}
            className="w-full inline-flex items-center justify-center gap-3 rounded-full font-cta transition-all"
            style={{ padding: "0.85rem 1.4rem", background: "var(--crema)", color: "var(--pinar)", border: "1px solid rgba(47,111,98,0.18)" }}>
            <Icon name="consejeria" size={20} /> Continuar con correo electrónico
          </button>
          <button type="button" onClick={goAnon} disabled={busyAnon}
            className="w-full text-center text-[var(--gris-medio)] hover:text-[var(--pinar)] transition-colors disabled:opacity-60"
            style={{ fontSize: "0.92rem", fontWeight: 600, paddingTop: 2 }}>
            {busyAnon ? "Entrando…" : "Prefiero escribir sin registrarme →"}
          </button>
        </div>
      ) : (
        <EmailForm onBack={() => setView("choose")} />
      )}

      <div className="w-full h-px" style={{ background: "rgba(47,111,98,0.1)" }} />
      <div className="flex items-center gap-3 flex-wrap">
        <span className="text-[var(--gris-medio)]" style={{ fontSize: "0.9rem" }}>¿Preferís WhatsApp?</span>
        <CTA href={DATA.wa} external variant="primary" icon="wa" className="!py-2.5 !px-5 text-[15px]">Hablá con nosotros</CTA>
      </div>
    </div>
  );
}

// ── Panel principal: orquesta no-config / login / formulario ─
function MessagePanel() {
  const { user, signOut } = useAuth();
  const ready = !!(CFG.isFirebaseReady && CFG.isFirebaseReady()) && _fbReady;

  const [nombre, setNombre] = React.useState("");
  const [telefono, setTelefono] = React.useState("");
  const [emailResp, setEmailResp] = React.useState("");
  const [motivo, setMotivo] = React.useState("");
  const [mensaje, setMensaje] = React.useState("");
  const [consent, setConsent] = React.useState(false);
  const [errors, setErrors] = React.useState({});
  const [status, setStatus] = React.useState("idle"); // idle | sending | sent | error

  const motivos = ["Para mí", "Para un familiar", "Consulta general", "Prevención · charlas", "Otro"];
  const field = "w-full rounded-2xl px-4 py-3.5 text-[var(--tinta)] bg-[var(--papel)] border transition-colors outline-none focus:border-[var(--verde)] focus:ring-2 focus:ring-[rgba(93,174,158,0.25)]";

  const onSubmit = async (ev) => {
    ev.preventDefault();
    const e = {};
    if (!mensaje.trim()) e.mensaje = "Escribinos unas líneas.";
    if (user && user.anon && !telefono.trim() && !emailResp.trim()) e.contacto = "Dejanos al menos un teléfono o correo para poder responderte.";
    if (!consent) e.consent = "Necesitamos tu consentimiento.";
    setErrors(e);
    if (Object.keys(e).length) return;

    setStatus("sending");
    const ok = await sendMessage({
      uid: user.uid,
      name: user.name || nombre.trim(),
      email: user.email || emailResp.trim(),
      telefono: telefono.trim(),
      provider: user.provider,
      motivo, mensaje,
    });
    setStatus(ok ? "sent" : "error");
  };

  const waLink = () => {
    const t = `Hola, soy ${(user && user.name) || nombre || ""}. ${motivo ? "Motivo: " + motivo + ". " : ""}${mensaje || "Quiero hacer una consulta."}`;
    return "https://wa.me/543875181401?text=" + encodeURIComponent(t);
  };

  // ── Firebase aún sin configurar ──
  if (!ready) {
    return (
      <div className="rounded-[28px] p-7 sm:p-9 bg-[var(--papel)] border border-[rgba(47,111,98,0.12)] flex flex-col items-start gap-5" style={{ boxShadow: "0 24px 50px -38px rgba(28,28,28,0.4)" }}>
        <div className="flex items-center gap-3">
          <Wing color="var(--durazno)" style={{ width: 30, height: 30 }} />
          <h3 className="font-title text-[var(--pinar)]" style={{ fontWeight: 800, fontSize: "1.35rem" }}>Ingresá para escribirnos</h3>
        </div>
        <div className="rounded-2xl px-5 py-4 w-full" style={{ background: "rgba(244,166,120,0.12)", border: "1px solid rgba(244,166,120,0.4)" }}>
          <p className="font-cta" style={{ color: "var(--pinar)", fontWeight: 700, fontSize: "0.95rem" }}>Ingreso — pendiente de configurar</p>
          <p className="mt-1 text-[var(--grafito)]" style={{ fontSize: "0.85rem", lineHeight: 1.45 }}>
            Cargá los datos de Firebase en <span className="font-mono">js/config.js</span> (ver <span className="font-mono">CONFIGURACION-FIREBASE.md</span>). Mientras tanto, escribinos por WhatsApp.
          </p>
        </div>
        <CTA href={DATA.wa} external variant="primary" icon="wa">Hablá con nosotros</CTA>
      </div>
    );
  }

  // ── No logueado ──
  if (!user) return <LoginPanel />;

  // ── Enviado ──
  if (status === "sent") {
    return (
      <div className="rounded-[28px] p-9 bg-[var(--papel)] border border-[rgba(47,111,98,0.12)] text-center flex flex-col items-center" style={{ boxShadow: "0 24px 50px -36px rgba(28,28,28,0.4)" }}>
        <span className="inline-flex items-center justify-center w-16 h-16 rounded-full text-white" style={{ background: "var(--verde)" }}><Icon name="check" size={32} stroke={2} /></span>
        <h3 className="mt-5 font-title text-[var(--pinar)]" style={{ fontWeight: 800, fontSize: "1.6rem" }}>Recibimos tu mensaje.</h3>
        <p className="mt-3 text-[var(--grafito)]" style={{ lineHeight: 1.55, maxWidth: 420 }}>
          Gracias por escribirnos{(user.name || nombre) ? ", " + ((user.name || nombre).split(" ")[0]) : ""}. Te vamos a responder a la brevedad. Si querés, seguimos ahora por WhatsApp.
        </p>
        <div className="mt-7 flex flex-col sm:flex-row gap-3">
          <CTA href={waLink()} external variant="primary" icon="wa">Continuar por WhatsApp</CTA>
          <button type="button" onClick={() => { setMensaje(""); setMotivo(""); setConsent(false); setStatus("idle"); }} className="cta inline-flex items-center justify-center gap-2 rounded-full font-cta text-[var(--pinar)] border-2 border-[var(--verde)] hover:bg-[rgba(93,174,158,0.1)] transition-all" style={{ padding: "0.85rem 1.4rem" }}>
            Escribir otro mensaje
          </button>
        </div>
      </div>
    );
  }

  // ── Logueado: formulario de mensaje ──
  const needNombre = !user.name;       // anónimo o cuenta sin nombre
  const needEmail = !user.email;       // anónimo o sin email
  return (
    <form onSubmit={onSubmit} noValidate className="rounded-[28px] p-7 sm:p-9 bg-[var(--papel)] border border-[rgba(47,111,98,0.12)]" style={{ boxShadow: "0 24px 50px -38px rgba(28,28,28,0.4)" }}>
      <div className="flex items-center justify-between gap-3 flex-wrap mb-6">
        <span className="text-[var(--gris-medio)]" style={{ fontSize: "0.85rem", fontWeight: 600 }}>{user.anon ? "Estás como invitado/a" : "Ingresaste como"}</span>
        <UserChip user={user} onSignOut={signOut} />
      </div>
      <div className="flex flex-col gap-5">
        {needNombre && (
          <div>
            <label className="form-label" htmlFor="m-nombre">Nombre {user.anon && <span style={{ color: "var(--gris-medio)", fontWeight: 400 }}>(opcional)</span>}</label>
            <input id="m-nombre" className={field} style={{ borderColor: "var(--gris-suave)" }} value={nombre} onChange={(e) => setNombre(e.target.value)} placeholder="¿Cómo te llamás?" />
          </div>
        )}
        {needEmail && (
          <div>
            <label className="form-label" htmlFor="m-emailresp">Correo para responderte {user.anon && <span style={{ color: "var(--gris-medio)", fontWeight: 400 }}>(opcional)</span>}</label>
            <input id="m-emailresp" type="email" className={field} style={{ borderColor: errors.contacto ? "#d8775a" : "var(--gris-suave)" }} value={emailResp} onChange={(e) => setEmailResp(e.target.value)} placeholder="tucorreo@ejemplo.com" />
          </div>
        )}
        <div>
          <label className="form-label" htmlFor="m-tel">Teléfono <span style={{ color: "var(--gris-medio)", fontWeight: 400 }}>(opcional)</span></label>
          <input id="m-tel" type="tel" className={field} style={{ borderColor: errors.contacto ? "#d8775a" : "var(--gris-suave)" }} value={telefono} onChange={(e) => setTelefono(e.target.value)} placeholder="Ej: 387 5 18 1401" />
        </div>
        <div>
          <label className="form-label" htmlFor="m-motivo">Motivo de consulta</label>
          <select id="m-motivo" className={field} style={{ borderColor: "var(--gris-suave)" }} value={motivo} onChange={(e) => setMotivo(e.target.value)}>
            <option value="">Elegí una opción</option>
            {motivos.map((m) => <option key={m} value={m}>{m}</option>)}
          </select>
        </div>
        <div>
          <label className="form-label" htmlFor="m-mensaje">Mensaje</label>
          <textarea id="m-mensaje" rows={4} className={field} style={{ borderColor: errors.mensaje ? "#d8775a" : "var(--gris-suave)", resize: "vertical" }} value={mensaje} onChange={(e) => setMensaje(e.target.value)} placeholder="Contanos en qué podemos ayudarte" />
          {errors.mensaje && <p className="form-err">{errors.mensaje}</p>}
        </div>
        {errors.contacto && <p className="form-err -mt-2">{errors.contacto}</p>}
        <label className="flex items-start gap-3 cursor-pointer select-none">
          <input type="checkbox" className="mt-1 w-5 h-5 accent-[var(--verde)] shrink-0" checked={consent} onChange={(e) => setConsent(e.target.checked)} />
          <span className="text-[var(--grafito)]" style={{ fontSize: "0.92rem", lineHeight: 1.45 }}>
            Doy mi consentimiento para que Fundación Minnesota use estos datos únicamente para responder mi consulta. Ver <a href="privacidad.html" target="_blank" rel="noopener noreferrer" style={{ color: "var(--pinar)", fontWeight: 700 }}>Política de privacidad</a>.
          </span>
        </label>
        {errors.consent && <p className="form-err -mt-2">{errors.consent}</p>}
        {status === "error" && <p className="form-err">No pudimos enviar el mensaje. Probá de nuevo o escribinos por WhatsApp.</p>}
        <button type="submit" disabled={status === "sending"} className="cta inline-flex items-center justify-center gap-2.5 rounded-full font-cta bg-[var(--verde)] text-white hover:brightness-[1.05] transition-all duration-300 disabled:opacity-60" style={{ padding: "1rem 1.6rem", boxShadow: "0 12px 30px -14px rgba(93,174,158,0.9)" }}>
          {status === "sending" ? "Enviando…" : "Enviar mensaje"} <Icon name="arrow" size={18} />
        </button>
      </div>
    </form>
  );
}

Object.assign(window, { useAuth, MessagePanel, LoginPanel, AuthStore, sendMessage, postToSheets });
