// Contact / schedule page. Single form that posts to /api/contact and
// emails the team via the Vercel serverless function. The exact recipient
// address is configured server-side (see app/api/contact/route.ts) so we
// don't expose it as plain text on the page (spam-harvesting risk).
const { useState: useStateContact } = React;

function ContactPage() {
  const lang = (window.detectInitialLang ? window.detectInitialLang() : "es");
  const L = lang === "en";

  const params = new URLSearchParams(window.location.search || "");
  const initialSubject = params.get("subject") === "demo" ? "demo" : "general";

  const [subject, setSubject] = useStateContact(initialSubject);
  const [name, setName] = useStateContact("");
  const [email, setEmail] = useStateContact("");
  const [company, setCompany] = useStateContact("");
  const [phone, setPhone] = useStateContact("");
  const [message, setMessage] = useStateContact("");
  const [status, setStatus] = useStateContact("idle"); // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = useStateContact("");

  const handleSubmit = async (e) => {
    e.preventDefault();
    if (status === "sending") return;
    setStatus("sending");
    setErrorMsg("");
    // Forward utm_* params from the current URL so we can attribute leads.
    const utm = {};
    for (const [k, v] of params) {
      if (k.toLowerCase().startsWith("utm_")) utm[k] = v;
    }
    try {
      const res = await fetch("/api/contact", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          subject,
          name,
          email,
          company,
          phone,
          message,
          locale: lang,
          page: window.location.pathname,
          utm,
        }),
      });
      if (!res.ok) {
        const body = await res.json().catch(() => ({}));
        throw new Error(body.error || ("HTTP " + res.status));
      }
      setStatus("sent");
    } catch (err) {
      setStatus("error");
      setErrorMsg(err && err.message ? err.message : "Error");
    }
  };

  const isDemo = subject === "demo";
  const heroTitle = L
    ? (isDemo ? <>Schedule a <em>meeting</em> with us.</> : <>Talk to <em>us</em>.</>)
    : (isDemo ? <>Agenda una <em>reunión</em> con nosotros.</> : <>Habla con <em>nosotros</em>.</>);
  const heroLede = L
    ? (isDemo
        ? "Tell us a bit about your business and we'll book a 30-minute meeting to walk you through NextScenario with your real numbers."
        : "Drop us a message — we read every email and reply within 24 hours.")
    : (isDemo
        ? "Cuéntanos un poco sobre tu negocio y agendamos una reunión de 30 min para enseñarte NextScenario con tus números reales."
        : "Escríbenos — leemos cada email y respondemos en menos de 24 horas.");

  return (
    <>
      <SubNav current={L ? "contact" : "contacto"} />
      <section className="sub-hero" style={{ borderTop: "none", paddingBottom: 32 }}>
        <div className="container">
          <div className="sub-kicker">{L ? (isDemo ? "Schedule a meeting" : "Contact") : (isDemo ? "Agendar una reunión" : "Contacto")}</div>
          <h1 className="sub-h1">{heroTitle}</h1>
          <p className="sub-lede">{heroLede}</p>
        </div>
      </section>

      <section style={{ borderTop: "1px solid var(--line)", paddingTop: 48, paddingBottom: 80 }}>
        <div className="container" style={{ maxWidth: 720 }}>
          {status === "sent" ? (
            <div style={{ padding: 32, border: "1px solid var(--line-strong)", borderRadius: 18, background: "var(--paper-2)" }}>
              <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--pos)", marginBottom: 8 }}>
                {L ? "Message sent" : "Mensaje enviado"}
              </div>
              <h2 style={{ fontFamily: "var(--font-sans)", fontWeight: 500, fontSize: 32, letterSpacing: "-0.025em", margin: "0 0 12px" }}>
                {L ? "Thanks — we'll be in touch shortly." : "Gracias — te respondemos en breve."}
              </h2>
              <p style={{ color: "var(--mute)", fontSize: 16, lineHeight: 1.5, margin: 0 }}>
                {L
                  ? "We typically reply within 24 hours."
                  : "Solemos contestar en menos de 24 horas."}
              </p>
              <div style={{ marginTop: 24 }}>
                <a className="btn btn-ghost" href="index.html">{L ? "← Back to home" : "← Volver al inicio"}</a>
              </div>
            </div>
          ) : (
            <form onSubmit={handleSubmit} style={{ display: "flex", flexDirection: "column", gap: 20 }}>
              {/* Subject toggle */}
              <div style={{ display: "flex", gap: 8 }}>
                <button type="button" onClick={() => setSubject("demo")} className={"btn " + (subject === "demo" ? "btn-primary" : "btn-ghost")} style={{ fontSize: 13 }}>
                  {L ? "Schedule a meeting" : "Agendar una reunión"}
                </button>
                <button type="button" onClick={() => setSubject("general")} className={"btn " + (subject === "general" ? "btn-primary" : "btn-ghost")} style={{ fontSize: 13 }}>
                  {L ? "General question" : "Pregunta general"}
                </button>
              </div>

              <Field label={L ? "Name" : "Nombre"} value={name} onChange={setName} required />
              <Field label={L ? "Email" : "Email"} type="email" value={email} onChange={setEmail} required />
              <Field label={L ? "Company" : "Empresa"} value={company} onChange={setCompany} required={isDemo} />
              <Field label={L ? "Phone (optional)" : "Teléfono (opcional)"} type="tel" value={phone} onChange={setPhone} />

              <label style={{ display: "flex", flexDirection: "column", gap: 8 }}>
                <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--mute)" }}>
                  {L
                    ? (isDemo ? "What would you like to see in the meeting?" : "Your message")
                    : (isDemo ? "¿Qué te gustaría ver en la reunión?" : "Tu mensaje")}
                </span>
                <textarea
                  value={message}
                  onChange={(e) => setMessage(e.target.value)}
                  required={!isDemo}
                  rows={5}
                  style={{ border: "1px solid var(--line-strong)", borderRadius: 12, padding: "12px 14px", fontFamily: "var(--font-sans)", fontSize: 15, background: "white", color: "var(--ink)", resize: "vertical" }}
                />
              </label>

              {status === "error" && (
                <div style={{ padding: "12px 16px", border: "1px solid #E24A4A", borderRadius: 10, background: "rgba(226,74,74,0.06)", color: "#9b1f1f", fontSize: 14 }}>
                  {L ? "Something went wrong: " : "Algo ha fallado: "}{errorMsg || (L ? "please try again." : "vuelve a intentarlo.")}
                </div>
              )}

              <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 8 }}>
                <button type="submit" disabled={status === "sending"} className="btn btn-primary" style={{ minWidth: 200, justifyContent: "center" }}>
                  {status === "sending"
                    ? (L ? "Sending…" : "Enviando…")
                    : (isDemo
                        ? (L ? "Schedule meeting" : "Agendar reunión")
                        : (L ? "Send message" : "Enviar mensaje"))}
                </button>
                <span style={{ fontSize: 13, color: "var(--mute)", alignSelf: "center" }}>
                  {L ? "We read every message — typical reply within 24 h." : "Leemos todos los mensajes — respondemos en menos de 24 h."}
                </span>
              </div>
            </form>
          )}
        </div>
      </section>

      <SubFooter />
    </>
  );
}

function Field({ label, type = "text", value, onChange, required }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 8 }}>
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, letterSpacing: "0.12em", textTransform: "uppercase", color: "var(--mute)" }}>
        {label}{required ? " *" : ""}
      </span>
      <input
        type={type}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        required={required}
        style={{ border: "1px solid var(--line-strong)", borderRadius: 12, padding: "12px 14px", fontFamily: "var(--font-sans)", fontSize: 15, background: "white", color: "var(--ink)" }}
      />
    </label>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<ContactPage />);
