function Contact({ onInquire }) {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [firm, setFirm] = useState("");
  const [role, setRole] = useState("");
  const [sector, setSector] = useState("");
  const [interest, setInterest] = useState("");
  const [message, setMessage] = useState("");
  const [touched, setTouched] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [done, setDone] = useState(false);

  const SECTORS = [
    "Hardware / Semiconductors",
    "Electronics Manufacturing",
    "Contract Manufacturing",
    "PE / VC / Investment",
    "Corporate Strategy",
    "Industrial Real Estate",
    "Customs / Trade Compliance",
    "Other",
  ];
  const INTERESTS = [
    "R003 Pulse",
    "R003 Bundle",
    "R003 Extended",
    "Custom intelligence",
    "Methodology questions",
    "Just exploring",
  ];

  const filledRequired =
    name.trim() && email.trim() && firm.trim() && role.trim() && sector && interest;

  async function submit(ev) {
    ev.preventDefault();
    setTouched(true);
    setError(null);

    if (!isValidEmail(email)) {
      setError("Please enter a valid email address.");
      return;
    }
    if (!isWorkEmail(email)) {
      setError("Please use your work email. Free email providers (gmail, yahoo, etc.) are not accepted.");
      return;
    }
    if (!filledRequired) {
      setError("Please complete all required fields.");
      return;
    }

    setLoading(true);
    try {
      const response = await fetch(
        "https://leads.vstrade.co/subscribe",
        {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            email: email.toLowerCase().trim(),
            source: "homepage_inquiry",
            name: name.trim(),
            firm: firm.trim(),
            role: role.trim(),
            sector,
            interest,
            message: message.trim() || undefined,
            utm_payload: serializeUtmPayload() || undefined,
          }),
        }
      );
      let data = {};
      try { data = await response.json(); } catch (_) { /* non-JSON */ }

      if (response.status === 201 || response.status === 200) {
        // GTM dataLayer push — only on confirmed worker success.
        try {
          const utm = readUtmObject();
          window.dataLayer = window.dataLayer || [];
          window.dataLayer.push({
            event: "contact_inquiry",
            source: "contact_form",
            product: null,
            utm_source: utm.utm_source,
            utm_medium: utm.utm_medium,
            utm_campaign: utm.utm_campaign,
            utm_content: utm.utm_content,
            utm_term: utm.utm_term,
            gclid: utm.gclid,
            lang: "en",
          });
        } catch (_) { /* GTM optional; never block UX */ }
        setDone(true);
      } else if (response.status === 400) {
        setError(data.error || "Some fields look invalid. Please re-check.");
      } else if (response.status === 429) {
        setError("Too many requests. Please try again in a minute.");
      } else {
        setError("Something went wrong. Please email hello@vstrade.co instead.");
      }
    } catch (err) {
      setError("Network error. Please check your connection and try again.");
    } finally {
      setLoading(false);
    }
  }

  const labelStyle = {
    fontFamily: "Inter, sans-serif", fontSize: 12, fontWeight: 600,
    color: PALETTE.navy, letterSpacing: ".02em",
    display: "block", marginBottom: 6,
  };
  const inputStyle = {
    width: "100%", padding: "10px 12px",
    fontFamily: "Inter, sans-serif", fontSize: 14, color: PALETTE.navy,
    background: PALETTE.white, border: `1px solid ${PALETTE.rule}`,
    borderRadius: 4, outline: "none",
    transition: "border-color 120ms",
    boxSizing: "border-box",
  };
  const requiredMark = (
    <span style={{ color: PALETTE.amber, marginLeft: 2 }} aria-hidden="true">*</span>
  );

  return (
    <section id="contact" style={{ background: PALETTE.paper2, borderBottom: `1px solid ${PALETTE.rule}` }}>
      <div style={{ maxWidth: 1000, margin: "0 auto", padding: "96px 32px" }} className="vst-section">
        <div style={{ maxWidth: 720, marginBottom: 40 }}>
          <Eyebrow style={{ marginBottom: 14 }}>Contact · Industry inquiry</Eyebrow>
          <h2 className="vst-h2" style={{
            fontFamily: "'Source Serif 4', serif", fontSize: 40, fontWeight: 600,
            lineHeight: 1.14, letterSpacing: "-.018em", color: PALETTE.navy, margin: 0,
          }}>
            Tell us what you're trying to figure out.
          </h2>
          <p style={{
            fontFamily: "Inter, sans-serif", fontSize: 16, lineHeight: 1.55,
            color: PALETTE.mute1, marginTop: 14, marginBottom: 0, maxWidth: 620,
          }}>
            Founder reply within one business day. We won't enrol you in a sales sequence —
            replies are specific to your scope and SLA. Prefer email? Write to{" "}
            <a href="mailto:hello@vstrade.co" style={{ color: PALETTE.blue, textDecoration: "none" }}>hello@vstrade.co</a>.
          </p>
        </div>

        {done ? (
          <div style={{
            background: PALETTE.white, border: `1px solid ${PALETTE.rule}`,
            borderLeft: `3px solid ${PALETTE.green}`,
            padding: "24px 28px", maxWidth: 720,
          }}>
            <div style={{
              fontFamily: "Inter, sans-serif", fontSize: 15, lineHeight: 1.6, color: PALETTE.navy,
            }}>
              <strong>Thanks{name ? `, ${name.split(/\s+/)[0]}` : ""}.</strong> Your inquiry landed.
              You'll hear back at <span style={{ fontFamily: "JetBrains Mono, monospace", color: PALETTE.navy }}>{email}</span> within one business day —
              the reply comes from Sebastián, the founder, and addresses scope, pricing, and delivery
              timeline for {interest || "your request"}.
            </div>
          </div>
        ) : (
          <form onSubmit={submit} noValidate style={{
            background: PALETTE.white, border: `1px solid ${PALETTE.rule}`,
            padding: 32, maxWidth: 720,
          }}>
            <div className="vst-grid-2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, marginBottom: 18 }}>
              <div>
                <label style={labelStyle} htmlFor="c-name">Name{requiredMark}</label>
                <input id="c-name" type="text" required value={name} onChange={e => setName(e.target.value)} style={inputStyle} autoComplete="name"/>
              </div>
              <div>
                <label style={labelStyle} htmlFor="c-email">Work email{requiredMark}</label>
                <input id="c-email" type="email" required value={email} onChange={e => setEmail(e.target.value)} style={inputStyle} autoComplete="email" inputMode="email"/>
              </div>
            </div>

            <div className="vst-grid-2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, marginBottom: 18 }}>
              <div>
                <label style={labelStyle} htmlFor="c-firm">Firm{requiredMark}</label>
                <input id="c-firm" type="text" required value={firm} onChange={e => setFirm(e.target.value)} style={inputStyle} autoComplete="organization"/>
              </div>
              <div>
                <label style={labelStyle} htmlFor="c-role">Role{requiredMark}</label>
                <input id="c-role" type="text" required value={role} onChange={e => setRole(e.target.value)} style={inputStyle} placeholder="e.g. Director of Strategy" autoComplete="organization-title"/>
              </div>
            </div>

            <div className="vst-grid-2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18, marginBottom: 18 }}>
              <div>
                <label style={labelStyle} htmlFor="c-sector">Sector{requiredMark}</label>
                <select id="c-sector" required value={sector} onChange={e => setSector(e.target.value)} style={inputStyle}>
                  <option value="" disabled>Select sector…</option>
                  {SECTORS.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
              </div>
              <div>
                <label style={labelStyle} htmlFor="c-interest">Interested in{requiredMark}</label>
                <select id="c-interest" required value={interest} onChange={e => setInterest(e.target.value)} style={inputStyle}>
                  <option value="" disabled>Select interest…</option>
                  {INTERESTS.map(s => <option key={s} value={s}>{s}</option>)}
                </select>
              </div>
            </div>

            <div style={{ marginBottom: 22 }}>
              <label style={labelStyle} htmlFor="c-message">Message <span style={{ color: PALETTE.mute2, fontWeight: 400 }}>(optional)</span></label>
              <textarea
                id="c-message" rows={4}
                value={message} onChange={e => setMessage(e.target.value)}
                style={{ ...inputStyle, resize: "vertical", minHeight: 96, fontFamily: "Inter, sans-serif" }}
                placeholder="What are you trying to figure out? Specific firms, timeframes, comparison sets — anything that helps us scope."
              />
            </div>

            {error && (
              <div style={{
                marginBottom: 16, padding: "10px 14px",
                background: "#FEF2F2", border: "1px solid #FCA5A5", borderRadius: 4,
                fontFamily: "Inter, sans-serif", fontSize: 13, color: "#991B1B",
              }}>{error}</div>
            )}

            <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 20, flexWrap: "wrap" }}>
              <p style={{
                fontFamily: "Inter, sans-serif", fontSize: 12, lineHeight: 1.5,
                color: PALETTE.mute1, margin: 0, maxWidth: 380,
              }}>
                We use your email for the requested follow-up only. No list-sharing.{" "}
                <a href="/privacy" target="_blank" rel="noopener" style={{ color: PALETTE.blue }}>Privacy →</a>
              </p>
              <button
                type="submit"
                disabled={loading}
                style={{
                  background: PALETTE.amber, color: PALETTE.paper, border: 0, borderRadius: 4,
                  padding: "12px 24px", fontFamily: "Inter, sans-serif", fontSize: 14, fontWeight: 600,
                  cursor: loading ? "wait" : "pointer", opacity: loading ? 0.7 : 1,
                }}
                className="vst-btn-primary"
              >{loading ? "Sending…" : "Send inquiry"}</button>
            </div>
          </form>
        )}
      </div>
    </section>
  );
}

window.Contact = Contact;
