const { Input, Textarea, Select, Button, Eyebrow } = window.NRTRDesignSystem_47db9c;

// Contact-form endpoint (Formspree — accepts a JSON POST).
const CONTACT_ENDPOINT = "https://formspree.io/f/xpqgoddq";

function InfoRow({ label, children }) {
  return (
    <div style={{ padding: "20px 0", borderBottom: "1px solid var(--line-soft)" }}>
      <div style={{ fontFamily: "var(--font-label)", fontSize: "11px", fontWeight: 500, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--text-brand)", marginBottom: "8px" }}>{label}</div>
      <div style={{ fontFamily: "var(--font-body)", fontSize: "17px", lineHeight: 1.55, color: "var(--text-body)" }}>{children}</div>
    </div>
  );
}

function ContactSections() {
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [name, setName] = React.useState("");
  const [email, setEmail] = React.useState("");
  const [topic, setTopic] = React.useState("Join the founding list");
  const [message, setMessage] = React.useState("");
  const [submitError, setSubmitError] = React.useState("");
  const [attempted, setAttempted] = React.useState(false);
  const emailOk = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim());
  const nameOk = name.trim().length > 1;
  const submit = async () => {
    setAttempted(true);
    if (!nameOk || !emailOk) return;
    setSubmitting(true);
    setSubmitError("");
    const payload = { name: name.trim(), email: email.trim(), topic, message: message.trim(), source: "contact" };
    try {
      const res = await fetch(CONTACT_ENDPOINT, {
        method: "POST",
        headers: { "Content-Type": "application/json", Accept: "application/json" },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error("Request failed");
      setSubmitting(false);
      setSent(true);
    } catch (err) {
      setSubmitting(false);
      setSubmitError("Something went wrong. Please try again, or email us at jacob@nrtr.life.");
    }
  };
  return (
    <>
      {/* Location + details */}
      <section id="location" style={{ background: "var(--surface-page)", scrollMarginTop: "var(--nav-h)" }}>
        <div data-reveal-group style={{ maxWidth: "var(--container)", margin: "0 auto", padding: "var(--section-pad) var(--space-6)", display: "grid", gridTemplateColumns: "1fr 1fr", gap: "clamp(32px, 6vw, 72px)", alignItems: "start" }} className="nrtr-two">
          <div>
            <Eyebrow>Visit</Eyebrow>
            <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 400, fontSize: "var(--fs-section)", lineHeight: 1.08, letterSpacing: "-0.01em", color: "var(--text-strong)", margin: "14px 0 8px", maxWidth: "16ch" }}>
              65 Church Street, Montclair.
            </h2>
            <div style={{ marginTop: "12px" }}>
              <InfoRow label="Address">65 Church Street<br />Montclair, New Jersey</InfoRow>
              <InfoRow label="Opening">Spring 2027 — founding-list members hear first.</InfoRow>
              <InfoRow label="Hours">Open six days a week · closed Sundays<br /><span style={{ color: "var(--text-muted)", fontSize: "15px" }}>Exact hours confirmed ahead of opening.</span></InfoRow>
              <InfoRow label="Getting there">In the heart of downtown Montclair, minutes from the Bay Street and Walnut Street stations.</InfoRow>
            </div>
          </div>
          {/* Live map — Google Maps embed (no API key needed) */}
          <div style={{ minHeight: 380, height: "100%", borderRadius: "var(--radius-xl)", overflow: "hidden", border: "1px solid var(--line-soft)", boxShadow: "var(--shadow-md)" }}>
            <iframe
              title="Map to NRTR — 65 Church Street, Montclair, NJ"
              src="https://www.google.com/maps?q=65%20Church%20Street%2C%20Montclair%2C%20NJ&output=embed"
              loading="lazy"
              referrerPolicy="no-referrer-when-downgrade"
              style={{ width: "100%", height: "100%", minHeight: 380, border: 0, display: "block" }}
            ></iframe>
          </div>
        </div>
      </section>

      {/* Contact form */}
      <section id="tour" style={{ background: "var(--espresso)", color: "var(--linen)", position: "relative", overflow: "hidden", scrollMarginTop: "var(--nav-h)" }}>
        <img src="assets/icons/mark-inverted-camel.svg" alt="" aria-hidden="true" style={{ position: "absolute", right: "-4%", top: "50%", transform: "translateY(-50%)", height: "150%", width: "auto", opacity: 0.1, pointerEvents: "none" }} />
        <div style={{ position: "relative", maxWidth: "760px", margin: "0 auto", padding: "var(--section-pad) var(--space-6)" }}>
          <Eyebrow tone="dark">Get in touch</Eyebrow>
          <h2 style={{ fontFamily: "var(--font-display)", fontWeight: 400, fontSize: "var(--fs-section-lg)", lineHeight: 1.08, letterSpacing: "-0.01em", color: "var(--linen)", margin: "14px 0 0", maxWidth: "18ch" }}>
            Questions, a tour, or your place in line.
          </h2>
          <p style={{ fontFamily: "var(--font-body)", fontSize: "18px", lineHeight: 1.6, color: "var(--text-on-dark-muted)", margin: "18px 0 0", maxWidth: "48ch" }}>
            Tell us what you're after and we'll get back to you within one business day.
          </p>

          <div style={{ marginTop: "36px", background: "var(--surface-raised)", borderRadius: "var(--radius-xl)", border: "1px solid var(--line-soft)", padding: "clamp(24px, 6vw, 48px)", boxShadow: "var(--shadow-lg)" }}>
            {sent ? (
              <div style={{ padding: "24px 0", textAlign: "center" }}>
                <img src="assets/icons/mark-primary-terracotta.svg" alt="" style={{ width: 60, height: 60, marginBottom: "16px" }} />
                <p style={{ fontFamily: "var(--font-body)", fontSize: "19px", color: "var(--text-strong)", margin: "0 0 6px" }}>Thanks — message received.</p>
                <p style={{ fontFamily: "var(--font-body)", fontSize: "16px", color: "var(--text-muted)", margin: "0 auto", maxWidth: "40ch", lineHeight: 1.55 }}>We'll reply to <strong style={{ color: "var(--text-strong)", fontWeight: 500 }}>{email || "your inbox"}</strong> within one business day. If it's about the founding list, you're already noted.</p>
              </div>
            ) : (
              <div style={{ display: "flex", flexDirection: "column", gap: "16px" }}>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: "16px" }} className="nrtr-two">
                  <Input label="Full Name" placeholder="Jordan Rivera" value={name} onChange={(e) => setName(e.target.value)} error={attempted && !nameOk ? "Please enter your name." : undefined} required autoComplete="name" />
                  <Input label="Email" type="email" placeholder="you@example.com" value={email} onChange={(e) => setEmail(e.target.value)} error={attempted && !emailOk ? "Enter a valid email address." : undefined} required autoComplete="email" />
                </div>
                <Select label="What can we help with?" options={["Join the founding list", "Tour the space", "Membership question", "General question"]} value={topic} onChange={(e) => setTopic(e.target.value)} />
                <Textarea label="Message" placeholder="A little about what you're looking for…" rows={4} value={message} onChange={(e) => setMessage(e.target.value)} />
                {submitError && (
                  <p role="alert" style={{ fontFamily: "var(--font-body)", fontSize: "14px", lineHeight: 1.5, color: "var(--terracotta)", margin: 0 }}>{submitError}</p>
                )}
                <Button variant="primary" size="lg" fullWidth disabled={submitting} onClick={submit} style={{ marginTop: "6px" }}>{submitting ? "Sending…" : "Send message"}</Button>
                <p style={{ fontFamily: "var(--font-body)", fontSize: "12.5px", lineHeight: 1.5, color: "var(--text-muted)", margin: "2px 0 0" }}>We'll get back to you within one business day.</p>
              </div>
            )}
          </div>
        </div>
      </section>
    </>
  );
}

window.ContactSections = ContactSections;
