// ───────────────────────────────────────────────────────────
// Lead form destination config — edit here if URLs change.
// ───────────────────────────────────────────────────────────
const FORMSPREE_ENDPOINT = "https://formspree.io/f/xqewgnad";
const CALENDLY_URL = "https://calendly.com/augusto-difiorecreative/30min";

const LeadForm = ({ variant = "light", compact = false, onSubmit }) => {
  const [state, setState] = React.useState({ name: "", email: "", company: "", website: "" });
  const [phase, setPhase] = React.useState("idle"); // idle | sending | success | error
  const [errorMsg, setErrorMsg] = React.useState("");
  const dark = variant === "dark";
  const APPLE_SANS = "-apple-system, BlinkMacSystemFont, 'SF Pro Display', 'Inter', sans-serif";
  const APPLE_TEXT = "-apple-system, BlinkMacSystemFont, 'SF Pro Text', 'Inter', sans-serif";

  const set = (k) => (e) => setState((s) => ({ ...s, [k]: e.target.value }));

  const submit = async (e) => {
    e.preventDefault();
    if (phase === "sending") return;
    setPhase("sending");
    setErrorMsg("");
    try {
      const response = await fetch(FORMSPREE_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify({
          ...state,
          _subject: `🔥 Nuovo lead Mese Gratuito — ${state.name || "sconosciuto"} (${state.company || ""})`,
        }),
      });
      if (!response.ok) throw new Error("bad response");
      onSubmit?.(state);
      setPhase("success");
      // Brief pause so user sees "Prenoto la tua call…" then redirect to Calendly
      setTimeout(() => { window.location.href = CALENDLY_URL; }, 900);
    } catch (err) {
      setPhase("error");
      setErrorMsg("Qualcosa è andato storto. Riprova oppure scrivici a info@difiorecreative.com.");
    }
  };

  const inputStyle = {
    width: "100%",
    padding: "15px 16px",
    fontFamily: APPLE_TEXT,
    fontSize: 16, letterSpacing: "-0.01em",
    color: dark ? "#fff" : "#051B42",
    background: dark ? "rgba(255,255,255,0.06)" : "#fff",
    border: `1px solid ${dark ? "rgba(255,255,255,0.14)" : "rgba(5,27,66,0.18)"}`,
    borderRadius: 12,
    outline: "none",
    boxSizing: "border-box",
    transition: "all 140ms ease",
  };
  const labelStyle = {
    fontFamily: APPLE_TEXT, fontSize: 12, fontWeight: 500,
    letterSpacing: "-0.005em",
    color: dark ? "rgba(255,255,255,0.65)" : "rgba(5,27,66,0.55)",
    marginBottom: 6, display: "block",
  };

  const sending = phase === "sending";
  const successfulSend = phase === "success";
  const buttonLabel = successfulSend
    ? "Prenoto la tua call…"
    : sending
      ? "Invio in corso…"
      : "Prenota il mio mese gratuito";

  return (
    <form onSubmit={submit} style={{ display: "grid", gap: 14 }}>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <div>
          <label style={labelStyle}>Nome</label>
          <input required style={inputStyle} placeholder="Marco Rossi" value={state.name} onChange={set("name")} disabled={sending || successfulSend}/>
        </div>
        <div>
          <label style={labelStyle}>Email</label>
          <input required type="email" style={inputStyle} placeholder="tu@brand.com" value={state.email} onChange={set("email")} disabled={sending || successfulSend}/>
        </div>
      </div>
      <div>
        <label style={labelStyle}>Azienda</label>
        <input required style={inputStyle} placeholder="Il tuo brand" value={state.company} onChange={set("company")} disabled={sending || successfulSend}/>
      </div>
      <div>
        <label style={labelStyle}>Sito web</label>
        <input required style={inputStyle} placeholder="https://iltuobrand.com" value={state.website} onChange={set("website")} disabled={sending || successfulSend}/>
      </div>
      <button type="submit" disabled={sending || successfulSend} style={{
        marginTop: 6,
        background: "#051B42", color: "#fff", border: 0,
        padding: "16px 24px", borderRadius: 999,
        fontFamily: APPLE_TEXT, fontWeight: 500, fontSize: 17, letterSpacing: "-0.01em",
        cursor: (sending || successfulSend) ? "default" : "pointer",
        opacity: (sending || successfulSend) ? 0.9 : 1,
        display: "inline-flex", alignItems: "center",
        justifyContent: "center", gap: 8,
        transition: "all 160ms ease",
      }}
      onMouseEnter={(e)=>{ if (!sending && !successfulSend) e.currentTarget.style.background="#0A2A5C"; }}
      onMouseLeave={(e)=>{ if (!sending && !successfulSend) e.currentTarget.style.background="#051B42"; }}
      >
        {(sending || successfulSend) && (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" style={{ animation: "df-spin 0.8s linear infinite" }}>
            <circle cx="12" cy="12" r="10" stroke="rgba(255,255,255,0.25)" strokeWidth="2.5"/>
            <path d="M12 2 a10 10 0 0 1 10 10" stroke="#fff" strokeWidth="2.5" strokeLinecap="round"/>
          </svg>
        )}
        {buttonLabel}
        {!sending && !successfulSend && (
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round" strokeLinejoin="round">
            <path d="m9 6 6 6-6 6"/>
          </svg>
        )}
      </button>
      <style>{`@keyframes df-spin { to { transform: rotate(360deg); } }`}</style>
      {phase === "error" && (
        <div style={{
          fontFamily: APPLE_TEXT, fontSize: 13,
          color: dark ? "#ffb4b4" : "#b3261e",
          background: dark ? "rgba(255,180,180,0.08)" : "rgba(179,38,30,0.06)",
          border: `1px solid ${dark ? "rgba(255,180,180,0.25)" : "rgba(179,38,30,0.25)"}`,
          borderRadius: 10, padding: "10px 14px", marginTop: 2,
        }}>
          {errorMsg}
        </div>
      )}
      <div style={{
        display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap",
        fontFamily: APPLE_TEXT, fontSize: 12,
        color: dark ? "rgba(255,255,255,0.55)" : "rgba(5,27,66,0.55)",
        marginTop: 2,
      }}>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#051B42" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
          Senza carta di credito
        </span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#051B42" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
          Senza contratto
        </span>
        <span style={{ display: "inline-flex", alignItems: "center", gap: 5 }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="#051B42" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
          Consegna in 72 ore
        </span>
      </div>
    </form>
  );
};

window.LeadForm = LeadForm;