/* global React */

// ─── Configuração dos botões de CTA ───────────────────────────────
// Por enquanto, todos os CTAs abrem o WhatsApp diretamente.
// Para REABILITAR o modal de cadastro (e tirar o WhatsApp do ar),
// basta trocar USE_WHATSAPP_CTA para false. É só isso.
const USE_WHATSAPP_CTA = true;
const WHATSAPP_NUMBER = "551153043190";
const WHATSAPP_MESSAGE = "Oi, Vaguinho!";

const SCRIPT_URL =
  "https://script.google.com/macros/s/AKfycbz3wpaXl03vquaT1Ppo4gSj8tLLvY0SxAFvD1YtOi1fisjLbMOwXPDj3IeagS-X9QvHQQ/exec";

const GEO_FALLBACK = { cidade: "Não detectado", pais: "Não detectado" };

async function fetchGeo() {
  try {
    const r = await fetch("https://ipapi.co/json/");
    const d = await r.json();
    if (d.city && d.country_name) {
      return { cidade: d.city, pais: d.country_name };
    }
    throw new Error("sem dados");
  } catch (err1) {
    try {
      const r = await fetch("https://ipwho.is/");
      const d = await r.json();
      if (d.city && d.country) {
        return { cidade: d.city, pais: d.country };
      }
      return GEO_FALLBACK;
    } catch (err2) {
      return GEO_FALLBACK;
    }
  }
}

// Inicia busca de geo imediatamente ao carregar o script,
// com timeout de 4s para nunca bloquear o submit.
const geoPromise = Promise.race([
  fetchGeo(),
  new Promise(function(resolve) {
    setTimeout(function() { resolve(GEO_FALLBACK); }, 4000);
  }),
]);

function LeadModal() {
  const [open, setOpen] = React.useState(false);
  const [campaign, setCampaign] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [emailFocused, setEmailFocused] = React.useState(false);
  const [status, setStatus] = React.useState("idle"); // idle | loading | success | error
  React.useEffect(() => {
    const openHandler = (e) => {
      setCampaign(e.detail.campaign || "");
      setEmail("");
      setStatus("idle");
      setOpen(true);
    };
    window.addEventListener("vaguinho:open-modal", openHandler);
    return () => window.removeEventListener("vaguinho:open-modal", openHandler);
  }, []);

  React.useEffect(() => {
    if (!open) return;
    const escHandler = (e) => {
      if (e.key === "Escape") setOpen(false);
    };
    window.addEventListener("keydown", escHandler);
    return () => window.removeEventListener("keydown", escHandler);
  }, [open]);

  const close = () => {
    if (status !== "loading") setOpen(false);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (!email || status === "loading") return;
    setStatus("loading");

    const params = new URLSearchParams(window.location.search);
    const origem = window.location.pathname.includes("empresas")
      ? "empresa"
      : "candidato";

    try {
      const geo = await geoPromise;
      await fetch(SCRIPT_URL, {
        method: "POST",
        mode: "no-cors",
        headers: { "Content-Type": "text/plain" },
        body: JSON.stringify({
          email,
          origem,
          utm_source: params.get("utm_source") || "direct",
          utm_campaign: campaign,
          cidade: geo.cidade,
          pais: geo.pais,
        }),
      });
      setStatus("success");
    } catch (err) {
      setStatus("error");
    }
  };

  if (!open) return null;

  const overlay = {
    position: "fixed",
    inset: 0,
    zIndex: 9999,
    background: "rgba(0,0,0,0.72)",
    backdropFilter: "blur(8px)",
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    padding: "20px",
    animation: "fadeIn 0.18s ease-out",
  };

  const card = {
    background: "#123328",
    border: "1px solid rgba(244,251,233,0.1)",
    borderRadius: 24,
    padding: "36px 32px",
    maxWidth: 440,
    width: "100%",
    position: "relative",
    boxShadow: "0 24px 60px rgba(0,0,0,0.6)",
    animation: "slideUp 0.22s cubic-bezier(0.22,1,0.36,1)",
  };

  return (
    <div style={overlay} onClick={close}>
      <style>{`
        @keyframes fadeIn { from { opacity: 0 } to { opacity: 1 } }
        @keyframes slideUp { from { opacity: 0; transform: translateY(20px) } to { opacity: 1; transform: translateY(0) } }
      `}</style>
      <div style={card} onClick={(e) => e.stopPropagation()}>
        {/* Botão fechar */}
        <button
          onClick={close}
          aria-label="Fechar"
          style={{
            position: "absolute",
            top: 14,
            right: 14,
            background: "rgba(244,251,233,0.06)",
            border: "1px solid rgba(244,251,233,0.1)",
            borderRadius: 999,
            width: 32,
            height: 32,
            color: "#8FA597",
            cursor: "pointer",
            display: "flex",
            alignItems: "center",
            justifyContent: "center",
            fontSize: 20,
            lineHeight: 1,
            padding: 0,
          }}
        >
          ×
        </button>

        {status === "success" ? (
          /* ── Estado de sucesso ── */
          <div style={{ textAlign: "center", padding: "8px 0 4px" }}>
            <div
              style={{
                width: 80,
                height: 80,
                borderRadius: 999,
                overflow: "hidden",
                border: "3px solid rgba(199,255,110,0.35)",
                margin: "0 auto 20px",
                background: "#1A4534",
              }}
            >
              <img
                src="assets/vaguinho-face.png"
                alt="Vaguinho"
                style={{
                  width: "100%",
                  height: "100%",
                  objectFit: "cover",
                  objectPosition: "50% 20%",
                }}
              />
            </div>
            <h3
              style={{
                fontFamily: "Bricolage Grotesque",
                fontSize: 28,
                fontWeight: 800,
                color: "#F4FBE9",
                margin: "0 0 12px",
                letterSpacing: "-0.03em",
              }}
            >
              Anotado! 🎉
            </h3>
            <p
              style={{
                color: "#C9D6C0",
                fontSize: 16,
                lineHeight: 1.6,
                margin: "0 0 28px",
              }}
            >
              Vamos te avisar assim que tudo estiver 100% pronto.
              <br />
              Fique de olho no e-mail!
            </p>
            <button
              onClick={close}
              style={{
                background: "#C7FF6E",
                color: "#0B201A",
                border: "none",
                borderRadius: 999,
                padding: "13px 32px",
                fontWeight: 700,
                fontSize: 15,
                cursor: "pointer",
                fontFamily: "Plus Jakarta Sans",
                boxShadow: "0 0 0 4px rgba(199,255,110,0.16)",
              }}
            >
              Fechar
            </button>
          </div>
        ) : (
          /* ── Estado do formulário ── */
          <>
            <div
              style={{
                display: "inline-flex",
                alignItems: "center",
                gap: 8,
                background: "rgba(199,255,110,0.1)",
                border: "1px solid rgba(199,255,110,0.25)",
                borderRadius: 999,
                padding: "5px 12px",
                color: "#C7FF6E",
                fontSize: 12,
                fontWeight: 600,
                marginBottom: 16,
              }}
            >
              <span
                style={{
                  width: 6,
                  height: 6,
                  borderRadius: 999,
                  background: "#C7FF6E",
                  flexShrink: 0,
                }}
              ></span>
              Cadastro
            </div>

            <h2
              style={{
                fontFamily: "Bricolage Grotesque",
                fontSize: 26,
                fontWeight: 800,
                color: "#F4FBE9",
                margin: "0 0 10px",
                letterSpacing: "-0.035em",
                lineHeight: 1.1,
              }}
            >
              Estamos chegando!
            </h2>

            <p
              style={{
                color: "#C9D6C0",
                fontSize: 15,
                lineHeight: 1.6,
                margin: "0 0 24px",
              }}
            >
              Ainda não estamos em sua região. Deixe seu e-mail para ser avisado
              quando lançarmos por aí!
            </p>

            <form onSubmit={handleSubmit}>
              <label
                style={{
                  display: "block",
                  color: "#8FA597",
                  fontSize: 11,
                  fontWeight: 600,
                  marginBottom: 6,
                  textTransform: "uppercase",
                  letterSpacing: "0.1em",
                }}
              >
                Seu e-mail
              </label>
              <input
                type="email"
                required
                placeholder="voce@exemplo.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                onFocus={() => setEmailFocused(true)}
                onBlur={() => setEmailFocused(false)}
                style={{
                  display: "block",
                  width: "100%",
                  background: "rgba(244,251,233,0.05)",
                  border: emailFocused
                    ? "1.5px solid #C7FF6E"
                    : "1px solid rgba(244,251,233,0.14)",
                  borderRadius: 12,
                  padding: "14px 16px",
                  color: "#F4FBE9",
                  fontSize: 16,
                  outline: "none",
                  marginBottom: 14,
                  fontFamily: "Plus Jakarta Sans",
                  transition: "border-color 0.15s",
                  boxSizing: "border-box",
                }}
              />

              {status === "error" && (
                <p
                  style={{
                    color: "#FF6B6B",
                    fontSize: 13,
                    margin: "-6px 0 12px",
                  }}
                >
                  Ops, algo deu errado. Tenta de novo?
                </p>
              )}

              <button
                type="submit"
                disabled={status === "loading"}
                style={{
                  width: "100%",
                  background: status === "loading" ? "#5C7268" : "#C7FF6E",
                  color: status === "loading" ? "#C9D6C0" : "#0B201A",
                  border: "none",
                  borderRadius: 999,
                  padding: "16px",
                  fontWeight: 700,
                  fontSize: 16,
                  cursor: status === "loading" ? "not-allowed" : "pointer",
                  boxShadow:
                    status === "loading"
                      ? "none"
                      : "0 0 0 4px rgba(199,255,110,0.16)",
                  fontFamily: "Plus Jakarta Sans",
                  transition: "background 0.2s, color 0.2s",
                }}
              >
                {status === "loading"
                  ? "Enviando..."
                  : "Me avisa quando lançar →"}
              </button>
            </form>
          </>
        )}
      </div>
    </div>
  );
}

/* Função global para abrir o modal de qualquer componente */
window.openLeadModal = function (campaign) {
  window.dispatchEvent(
    new CustomEvent("vaguinho:open-modal", { detail: { campaign } }),
  );
};

/* Ponto único de entrada dos botões de CTA.
   Decide entre abrir o WhatsApp ou o modal conforme USE_WHATSAPP_CTA. */
window.openCTA = function (campaign) {
  if (USE_WHATSAPP_CTA) {
    const url =
      "https://wa.me/" +
      WHATSAPP_NUMBER +
      "?text=" +
      encodeURIComponent(WHATSAPP_MESSAGE);
    window.open(url, "_blank", "noopener,noreferrer");
  } else {
    window.openLeadModal(campaign);
  }
};

window.LeadModal = LeadModal;
