// LeadForm — used in hero + final CTA. Validation, mask, tracking, submit.
const { useState: lfUseState, useRef: lfUseRef, useEffect: lfUseEffect } = React;

// Brazilian phone mask helper
const maskBR = (raw) => {
  const d = String(raw || "").replace(/\D/g, "").slice(0, 11);
  if (d.length <= 2) return d.length ? `(${d}` : "";
  if (d.length <= 7) return `(${d.slice(0, 2)}) ${d.slice(2)}`;
  if (d.length <= 10) return `(${d.slice(0, 2)}) ${d.slice(2, 6)}-${d.slice(6)}`;
  return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`;
};

const isValidEmail = (s) => /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(s || "").trim());
const isValidPhone = (s) => {
  const d = String(s || "").replace(/\D/g, "");
  return d.length === 10 || d.length === 11;
};

// Capture UTM + gclid once per session
const readUTMs = () => {
  if (typeof window === "undefined") return {};
  try {
    const stored = sessionStorage.getItem("__cl_attrib");
    if (stored) return JSON.parse(stored);
  } catch {}
  const sp = new URLSearchParams(window.location.search);
  const keep = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "gclid", "fbclid", "intent"];
  const out = {};
  keep.forEach(k => { if (sp.get(k)) out[k] = sp.get(k); });
  try { sessionStorage.setItem("__cl_attrib", JSON.stringify(out)); } catch {}
  return out;
};

const LeadForm = ({ location = "hero", defaultIntent = "" }) => {
  const [values, setValues] = lfUseState({
    nome: "",
    whatsapp: "",
    email: "",
    intent: defaultIntent || "",
    faixa: "",
    hp: "", // honeypot
  });
  const [touched, setTouched] = lfUseState({});
  const [errors, setErrors] = lfUseState({});
  const [submitting, setSubmitting] = lfUseState(false);
  const startedRef = lfUseRef(false);
  const submittedRef = lfUseRef(false);

  // Abandon detection
  lfUseEffect(() => {
    const onLeave = () => {
      if (startedRef.current && !submittedRef.current) {
        const completed = Object.keys(values).filter(k => k !== "hp" && values[k]).length;
        track("form_abandon", {
          form_location: location,
          last_field: Object.keys(touched).pop() || "unknown",
          fields_completed_count: completed,
        });
      }
    };
    window.addEventListener("pagehide", onLeave);
    return () => window.removeEventListener("pagehide", onLeave);
  }, [values, touched, location]);

  const validateField = (name, val) => {
    switch (name) {
      case "nome":
        if (!val.trim()) return "Informe seu nome completo.";
        if (val.trim().split(" ").length < 2) return "Nome completo, por favor.";
        return "";
      case "whatsapp":
        if (!val) return "Informe seu WhatsApp.";
        if (!isValidPhone(val)) return "WhatsApp com DDD (11 dígitos).";
        return "";
      case "email":
        if (!val) return "Informe seu email.";
        if (!isValidEmail(val)) return "Email inválido.";
        return "";
      case "intent":
        if (!val) return "Selecione sua intenção.";
        return "";
      case "faixa":
        if (!val) return "Selecione a faixa.";
        return "";
      default: return "";
    }
  };

  const handleChange = (name) => (e) => {
    let v = e.target.value;
    if (name === "whatsapp") v = maskBR(v);
    setValues(prev => ({ ...prev, [name]: v }));
    if (!startedRef.current) {
      startedRef.current = true;
      track("form_start", { form_location: location });
    }
    if (errors[name]) {
      const err = validateField(name, v);
      setErrors(prev => ({ ...prev, [name]: err }));
    }
  };

  const handleFocus = (name) => () => {
    track("form_field_focus", { form_location: location, field_name: name });
  };

  const handleBlur = (name) => () => {
    setTouched(prev => ({ ...prev, [name]: true }));
    const err = validateField(name, values[name]);
    setErrors(prev => ({ ...prev, [name]: err }));
    if (!err && values[name]) {
      track("form_field_complete", { form_location: location, field_name: name });
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    // Validate all
    const newErrors = {};
    ["nome", "whatsapp", "email", "intent", "faixa"].forEach(k => {
      const err = validateField(k, values[k]);
      if (err) newErrors[k] = err;
    });
    setTouched({ nome: true, whatsapp: true, email: true, intent: true, faixa: true });
    setErrors(newErrors);
    if (Object.keys(newErrors).length) {
      // Focus first invalid
      const first = Object.keys(newErrors)[0];
      const el = document.querySelector(`[name="${first}"][data-form="${location}"]`);
      if (el) el.focus();
      return;
    }
    // Honeypot check
    if (values.hp) return;

    setSubmitting(true);
    const attrib = readUTMs();
    const payload = {
      ...values,
      hp: undefined,
      form_location: location,
      attribution: attrib,
      page: typeof window !== "undefined" ? window.location.href : "",
      ts: new Date().toISOString(),
    };

    // Mock server action — production swaps to POST /api/lead
    track("generate_lead", {
      form_location: location,
      intent: values.intent,
      faixa: values.faixa,
      value: { ate500: 250000, "500-800": 650000, "800-1.2": 1000000, "1.2+": 1500000 }[values.faixa] || 0,
    });

    // Persist for thank-you page reconvert
    try {
      sessionStorage.setItem("__cl_lead", JSON.stringify({
        nome: values.nome.split(" ")[0],
        whatsapp: values.whatsapp,
        intent: values.intent,
      }));
    } catch {}

    submittedRef.current = true;
    await new Promise(r => setTimeout(r, 500)); // simulated network
    window.location.href = "obrigado.html";
  };

  const CTA_LABEL = location === "hero" ? "Receber tabela completa" : "Reservar minha unidade";

  return (
    <form className="lead-form" onSubmit={handleSubmit} noValidate aria-label="Formulário de contato">
      <div className="field">
        <label className="field-label" htmlFor={`${location}-nome`}>
          Nome completo <span className="req">*</span>
        </label>
        <input
          id={`${location}-nome`}
          name="nome"
          data-form={location}
          type="text"
          autoComplete="name"
          className={`input ${touched.nome && errors.nome ? "has-error" : ""}`}
          value={values.nome}
          onChange={handleChange("nome")}
          onFocus={handleFocus("nome")}
          onBlur={handleBlur("nome")}
          placeholder="Como devo te chamar?"
          aria-invalid={!!(touched.nome && errors.nome)}
          aria-describedby={touched.nome && errors.nome ? `${location}-nome-err` : undefined}
        />
        {touched.nome && errors.nome && (
          <span className="field-error" id={`${location}-nome-err`} role="alert">
            <Icon name="alert" size={12} /> {errors.nome}
          </span>
        )}
      </div>

      <div className="field">
        <label className="field-label" htmlFor={`${location}-whatsapp`}>
          WhatsApp <span className="req">*</span>
        </label>
        <input
          id={`${location}-whatsapp`}
          name="whatsapp"
          data-form={location}
          type="tel"
          inputMode="tel"
          autoComplete="tel-national"
          className={`input ${touched.whatsapp && errors.whatsapp ? "has-error" : ""}`}
          value={values.whatsapp}
          onChange={handleChange("whatsapp")}
          onFocus={handleFocus("whatsapp")}
          onBlur={handleBlur("whatsapp")}
          placeholder="(48) 9XXXX-XXXX"
          maxLength="16"
          aria-invalid={!!(touched.whatsapp && errors.whatsapp)}
          aria-describedby={touched.whatsapp && errors.whatsapp ? `${location}-wpp-err` : undefined}
        />
        {touched.whatsapp && errors.whatsapp && (
          <span className="field-error" id={`${location}-wpp-err`} role="alert">
            <Icon name="alert" size={12} /> {errors.whatsapp}
          </span>
        )}
      </div>

      <div className="field">
        <label className="field-label" htmlFor={`${location}-email`}>
          Email <span className="req">*</span>
        </label>
        <input
          id={`${location}-email`}
          name="email"
          data-form={location}
          type="email"
          autoComplete="email"
          className={`input ${touched.email && errors.email ? "has-error" : ""}`}
          value={values.email}
          onChange={handleChange("email")}
          onFocus={handleFocus("email")}
          onBlur={handleBlur("email")}
          placeholder="seu@email.com"
          aria-invalid={!!(touched.email && errors.email)}
          aria-describedby={touched.email && errors.email ? `${location}-email-err` : undefined}
        />
        {touched.email && errors.email && (
          <span className="field-error" id={`${location}-email-err`} role="alert">
            <Icon name="alert" size={12} /> {errors.email}
          </span>
        )}
      </div>

      <div className="field">
        <span className="field-label" id={`${location}-intent-label`}>
          Minha intenção é <span className="req">*</span>
        </span>
        <div className="radio-row" role="radiogroup" aria-labelledby={`${location}-intent-label`}>
          {[
            { v: "invest", label: "Investir" },
            { v: "live",   label: "Morar" },
            { v: "both",   label: "Ambos" },
          ].map(opt => (
            <label key={opt.v} className={values.intent === opt.v ? "is-checked" : ""}>
              <input
                type="radio"
                name="intent"
                data-form={location}
                value={opt.v}
                checked={values.intent === opt.v}
                onChange={handleChange("intent")}
                onFocus={handleFocus("intent")}
                onBlur={handleBlur("intent")}
              />
              {opt.label}
            </label>
          ))}
        </div>
        {touched.intent && errors.intent && (
          <span className="field-error" role="alert">
            <Icon name="alert" size={12} /> {errors.intent}
          </span>
        )}
      </div>

      <div className="field">
        <label className="field-label" htmlFor={`${location}-faixa`}>
          Faixa de investimento <span className="req">*</span>
        </label>
        <div className="select-wrap">
          <select
            id={`${location}-faixa`}
            name="faixa"
            data-form={location}
            className={`select ${touched.faixa && errors.faixa ? "has-error" : ""}`}
            value={values.faixa}
            onChange={handleChange("faixa")}
            onFocus={handleFocus("faixa")}
            onBlur={handleBlur("faixa")}
            aria-invalid={!!(touched.faixa && errors.faixa)}
          >
            {CONTENT.faixas.map(f => (
              <option key={f.value} value={f.value} disabled={f.value === ""}>
                {f.label}
              </option>
            ))}
          </select>
        </div>
        {touched.faixa && errors.faixa && (
          <span className="field-error" role="alert">
            <Icon name="alert" size={12} /> {errors.faixa}
          </span>
        )}
      </div>

      {/* Honeypot */}
      <div style={{ position: "absolute", left: "-9999px" }} aria-hidden="true">
        <label>Não preencher
          <input
            tabIndex="-1"
            autoComplete="off"
            type="text"
            name="hp"
            value={values.hp}
            onChange={handleChange("hp")}
          />
        </label>
      </div>

      <button type="submit" className="btn btn-primary btn-block btn-lg" disabled={submitting}>
        {submitting ? (
          <>
            <span className="lf-spinner" aria-hidden="true"></span>
            Enviando…
          </>
        ) : (
          <>
            {CTA_LABEL}
            <Icon name="arrowR" size={16} />
          </>
        )}
      </button>

      <p className="lf-footnote">
        <Icon name="shield" size={13} /> LGPD · resposta em até 24h úteis por email
      </p>
    </form>
  );
};

Object.assign(window, { LeadForm });
