// ===== Elejemais — Formulário público de cadastro de apoiador =====

const { useState: useState_pf, useEffect: useEffect_pf } = React;

const COLOR_MAP_PF = {
  verde: "oklch(0.44 0.11 155)",
  azul:  "oklch(0.46 0.13 250)",
  ocre:  "oklch(0.55 0.13 75)",
  vinho: "oklch(0.42 0.14 20)",
};

function PublicForm({ token }) {
  const [campaign,     setCampaign]     = useState_pf(null);
  const [municipios,   setMunicipios]   = useState_pf([]);
  const [loadErr,      setLoadErr]      = useState_pf(null);
  const [nome,         setNome]         = useState_pf("");
  const [telefone,     setTelefone]     = useState_pf("");
  const [municipio,    setMunicipio]    = useState_pf("");
  const [honeypot,     setHoneypot]     = useState_pf("");
  const [submitting,   setSubmitting]   = useState_pf(false);
  const [done,         setDone]         = useState_pf(false);
  const [erro,         setErro]         = useState_pf("");
  const [startTime]                     = useState_pf(Date.now());

  useEffect_pf(() => {
    if (!token) { setLoadErr("Link inválido."); return; }
    window.sb.rpc("get_campaign_public", { p_token: token })
      .then(({ data, error }) => {
        if (error || !data || data.length === 0) {
          setLoadErr("Este link não é válido ou a campanha foi encerrada.");
          return;
        }
        const c = data[0];
        setCampaign({ ...c, leaderNome: c.leader_nome || null });
        // Load municipalities for this state
        return window.sb
          .from("municipalities")
          .select("name")
          .eq("state", c.uf)
          .order("name");
      })
      .then(res => {
        if (res && res.data) setMunicipios(res.data.map(m => m.name));
      })
      .catch(() => setLoadErr("Erro ao carregar formulário."));
  }, [token]);

  async function handleSubmit(e) {
    e.preventDefault();
    setErro("");

    // Timing guard: reject if form was submitted in under 2 seconds (bot behaviour)
    if (Date.now() - startTime < 2000) return;

    // Client-side validation
    const nomeTrimmed = nome.trim();
    if (nomeTrimmed.length < 2)   { setErro("Por favor, informe seu nome completo."); return; }
    if (nomeTrimmed.length > 120) { setErro("Nome muito longo (máx. 120 caracteres)."); return; }

    setSubmitting(true);
    try {
      const { error } = await window.sb.rpc("register_public", {
        p_token:    token,
        p_nome:     nomeTrimmed,
        p_telefone: telefone.trim() || null,
        p_municipio: municipio || null,
        p_honeypot: honeypot || null,
      });
      if (error) {
        const msg = error.message || "";
        if      (msg.includes("limite_excedido"))  setErro("Muitos cadastros em pouco tempo. Tente novamente em 1 hora.");
        else if (msg.includes("link_invalido"))     setErro("Link inválido ou expirado.");
        else if (msg.includes("nome_obrigatorio"))  setErro("Por favor, informe seu nome.");
        else if (msg.includes("nome_muito_longo"))  setErro("Nome muito longo.");
        else                                        setErro("Erro ao enviar. Tente novamente.");
      } else {
        setDone(true);
      }
    } catch {
      setErro("Erro de conexão. Verifique sua internet.");
    } finally {
      setSubmitting(false);
    }
  }

  // ── Loading / error ──────────────────────────────────────────────────────
  if (loadErr) {
    return (
      <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "#f5f4f0", padding: 24 }}>
        <div style={{ textAlign: "center", maxWidth: 340 }}>
          <div style={{ fontSize: 40, marginBottom: 16 }}>🔗</div>
          <h2 style={{ fontFamily: "Georgia, serif", fontSize: 22, margin: "0 0 10px" }}>Link inválido</h2>
          <p style={{ color: "#666", fontSize: 14, lineHeight: 1.6 }}>{loadErr}</p>
        </div>
      </div>
    );
  }

  if (!campaign) {
    return (
      <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", background: "#f5f4f0" }}>
        <p style={{ color: "#888", fontSize: 14 }}>Carregando…</p>
      </div>
    );
  }

  const accent = COLOR_MAP_PF[campaign.cor] || COLOR_MAP_PF.verde;

  // ── Success ──────────────────────────────────────────────────────────────
  if (done) {
    return (
      <div style={{ minHeight: "100vh", background: "#f5f4f0", display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: 24 }}>
        <div style={{ background: "#fff", borderRadius: 20, padding: "40px 32px", maxWidth: 420, width: "100%", textAlign: "center", boxShadow: "0 4px 32px rgba(0,0,0,0.07)" }}>
          <div style={{ width: 64, height: 64, borderRadius: "50%", background: accent, display: "flex", alignItems: "center", justifyContent: "center", margin: "0 auto 20px", fontSize: 28 }}>✓</div>
          <h2 style={{ fontFamily: "Georgia, serif", fontSize: 26, margin: "0 0 10px", color: "#1a1a14" }}>Cadastro realizado!</h2>
          <p style={{ color: "#666", fontSize: 14, lineHeight: 1.7, margin: 0 }}>
            Obrigado por apoiar <strong style={{ color: "#1a1a14" }}>{campaign.candidato}</strong>!
            Seu cadastro foi registrado com sucesso.
          </p>
        </div>
      </div>
    );
  }

  // ── Form ─────────────────────────────────────────────────────────────────
  const tipoLabel = { "vereador": "Vereador(a)", "prefeito": "Prefeito(a)", "deputado_estadual": "Dep. Estadual", "deputado_federal": "Dep. Federal", "senador": "Senador(a)", "governador": "Governador(a)" };

  return (
    <div style={{ minHeight: "100vh", background: "#f5f4f0", fontFamily: "Inter, system-ui, sans-serif" }}>
      {/* Hero banner */}
      <div style={{
        height: 160,
        background: campaign.banner_url
          ? `url(${campaign.banner_url}) center/cover no-repeat`
          : `linear-gradient(135deg, ${accent} 0%, ${accent}cc 100%)`,
        position: "relative",
      }}>
        <div style={{ position: "absolute", inset: 0, background: "rgba(0,0,0,0.25)" }} />
        <div style={{ position: "absolute", bottom: 20, left: 24, color: "#fff" }}>
          <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: "0.1em", textTransform: "uppercase", opacity: 0.85 }}>
            {tipoLabel[campaign.tipo] || campaign.tipo} · {campaign.cidade || campaign.uf}
          </div>
          <div style={{ fontFamily: "Georgia, serif", fontSize: 22, fontWeight: 700, marginTop: 4 }}>
            {campaign.candidato}
          </div>
        </div>
      </div>

      {/* Card */}
      <div style={{ maxWidth: 480, margin: "0 auto", padding: "0 16px 60px" }}>
        <div style={{ background: "#fff", borderRadius: 20, padding: "28px 24px", marginTop: -24, position: "relative", boxShadow: "0 4px 32px rgba(0,0,0,0.07)" }}>
          <h2 style={{ fontFamily: "Georgia, serif", fontSize: 22, margin: "0 0 6px", color: "#1a1a14" }}>
            Quero apoiar!
          </h2>
          <p style={{ color: "#777", fontSize: 13, margin: "0 0 24px", lineHeight: 1.6 }}>
            {campaign.leaderNome
              ? <>Você foi convidado(a) por <strong style={{ color: "#333" }}>{campaign.leaderNome}</strong> para apoiar a candidatura de <strong style={{ color: "#333" }}>{campaign.candidato}</strong>.</>
              : <>Preencha seus dados para registrar seu apoio à candidatura de <strong style={{ color: "#333" }}>{campaign.candidato}</strong>.</>
            }
          </p>

          <form onSubmit={handleSubmit} noValidate>
            {/* Honeypot — invisible to humans, filled by bots */}
            <div style={{ position: "absolute", left: "-9999px", top: 0, opacity: 0, height: 0, overflow: "hidden" }} aria-hidden="true">
              <label>Deixe este campo em branco
                <input
                  type="text"
                  name="website"
                  value={honeypot}
                  onChange={e => setHoneypot(e.target.value)}
                  tabIndex={-1}
                  autoComplete="off"
                />
              </label>
            </div>

            <div style={{ marginBottom: 16 }}>
              <label style={{ display: "block", fontSize: 12, fontWeight: 600, color: "#555", marginBottom: 6, letterSpacing: "0.03em" }}>
                NOME COMPLETO *
              </label>
              <input
                type="text"
                value={nome}
                onChange={e => setNome(e.target.value.slice(0, 120))}
                placeholder="Seu nome"
                maxLength={120}
                autoComplete="name"
                required
                style={{ width: "100%", padding: "11px 14px", border: "1.5px solid #e0dfd8", borderRadius: 10, fontSize: 15, fontFamily: "inherit", outline: "none", boxSizing: "border-box", transition: "border-color 140ms" }}
                onFocus={e => e.target.style.borderColor = accent}
                onBlur={e => e.target.style.borderColor = "#e0dfd8"}
              />
            </div>

            <div style={{ marginBottom: 16 }}>
              <label style={{ display: "block", fontSize: 12, fontWeight: 600, color: "#555", marginBottom: 6, letterSpacing: "0.03em" }}>
                WHATSAPP / TELEFONE
              </label>
              <input
                type="tel"
                value={telefone}
                onChange={e => setTelefone(e.target.value.slice(0, 20))}
                placeholder="(79) 9 0000-0000"
                maxLength={20}
                autoComplete="tel"
                style={{ width: "100%", padding: "11px 14px", border: "1.5px solid #e0dfd8", borderRadius: 10, fontSize: 15, fontFamily: "inherit", outline: "none", boxSizing: "border-box", transition: "border-color 140ms" }}
                onFocus={e => e.target.style.borderColor = accent}
                onBlur={e => e.target.style.borderColor = "#e0dfd8"}
              />
            </div>

            {municipios.length > 0 && (
              <div style={{ marginBottom: 24 }}>
                <label style={{ display: "block", fontSize: 12, fontWeight: 600, color: "#555", marginBottom: 6, letterSpacing: "0.03em" }}>
                  SEU MUNICÍPIO
                </label>
                <select
                  value={municipio}
                  onChange={e => setMunicipio(e.target.value)}
                  style={{ width: "100%", padding: "11px 14px", border: "1.5px solid #e0dfd8", borderRadius: 10, fontSize: 15, fontFamily: "inherit", outline: "none", appearance: "none", background: "#fff", boxSizing: "border-box" }}
                  onFocus={e => e.target.style.borderColor = accent}
                  onBlur={e => e.target.style.borderColor = "#e0dfd8"}
                >
                  <option value="">Selecionar município…</option>
                  {municipios.map(m => (
                    <option key={m} value={m}>{m}</option>
                  ))}
                </select>
              </div>
            )}

            {erro && (
              <div style={{ background: "#fff0f0", border: "1px solid #fecaca", borderRadius: 8, padding: "10px 14px", fontSize: 13, color: "#b91c1c", marginBottom: 16 }}>
                {erro}
              </div>
            )}

            <button
              type="submit"
              disabled={submitting}
              style={{
                width: "100%", padding: "14px", borderRadius: 10, border: 0,
                background: accent, color: "#fff",
                fontSize: 15, fontWeight: 600, fontFamily: "inherit",
                cursor: submitting ? "not-allowed" : "pointer",
                opacity: submitting ? 0.7 : 1,
                transition: "opacity 150ms",
              }}
            >
              {submitting ? "Enviando…" : "Confirmar apoio"}
            </button>
          </form>

          <p style={{ textAlign: "center", fontSize: 11, color: "#aaa", marginTop: 20, marginBottom: 0, lineHeight: 1.5 }}>
            Seus dados são usados exclusivamente pela equipe de campanha e nunca serão vendidos.
          </p>
        </div>
      </div>
    </div>
  );
}

window.PublicForm = PublicForm;
