// Contact section — simple email-first form (replaces the old multi-step booking flow)

const { useState: useStateB } = React;

// ─────────────────────────────────────────────────────────────
// Contact delivery — submissions are emailed to Ina automatically.
//
// SETUP (one-time, ~3 min):
//   1. Go to https://formspree.io and create a free account.
//   2. Create a new form, set the recipient to ina@nordicsubstrate.com.
//   3. Copy the form's endpoint (looks like https://formspree.io/f/abcdwxyz).
//   4. Paste it below, replacing the placeholder.
// Until a real endpoint is set, the form falls back to opening the
// visitor's email client addressed to Ina.
// ─────────────────────────────────────────────────────────────
const FORMSPREE_ENDPOINT = "https://formspree.io/f/mqevaqjv";
const NOTIFY_EMAIL = "christian@nordicsubstrate.com,ina@nordicsubstrate.com";

// keep the exported name `Booking` so app.jsx wiring stays unchanged
function Booking() {
  const [data, setData] = useStateB({
    name: "",
    email: "",
    company: "",
    interest: "",
    message: "",
  });
  const [sending, setSending] = useStateB(false);
  const [submitted, setSubmitted] = useStateB(false);

  const update = (k, v) => setData((d) => ({ ...d, [k]: v }));

  const interests = [
    { id: "custom", label: "Custom production / trial" },
    { id: "bot", label: "Build–Operate–Transfer" },
    { id: "distribution", label: "Distribution / reselling" },
    { id: "other", label: "Something else" },
  ];

  const canSubmit = data.name && data.email && data.company;

  const submit = async (e) => {
    e.preventDefault();
    if (!canSubmit) return;

    const interestLabel = interests.find((i) => i.id === data.interest)?.label || "—";
    const payload = {
      _subject: `Website enquiry — ${data.company}`,
      Name: data.name,
      Email: data.email,
      Company: data.company,
      Interest: interestLabel,
      Message: data.message || "—",
    };

    const useFormspree = FORMSPREE_ENDPOINT && !FORMSPREE_ENDPOINT.includes("REPLACE_WITH_FORM_ID");

    if (useFormspree) {
      setSending(true);
      try {
        const res = await fetch(FORMSPREE_ENDPOINT, {
          method: "POST",
          headers: { "Content-Type": "application/json", Accept: "application/json" },
          body: JSON.stringify(payload),
        });
        setSending(false);
        if (res.ok) { setSubmitted(true); return; }
      } catch (err) {
        setSending(false);
      }
      // network/endpoint failure → fall through to mailto
    }

    // Fallback: open the visitor's email client, pre-filled and addressed to Ina.
    const body = Object.entries(payload)
      .filter(([k]) => k !== "_subject")
      .map(([k, v]) => `${k}: ${v}`)
      .join("\n");
    window.location.href =
      "mailto:" + NOTIFY_EMAIL +
      "?subject=" + encodeURIComponent(payload._subject) +
      "&body=" + encodeURIComponent("New enquiry from the NSS website:\n\n" + body);
    setSubmitted(true);
  };

  if (submitted) {
    return (
      <section id="book" style={{ background: "var(--bg-alt)" }}>
        <div className="wrap">
          <div style={{ maxWidth: 720, margin: "0 auto", textAlign: "center" }}>
            <div className="mono" style={{ fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--accent)" }}>
              ✓ Message sent
            </div>
            <h2 className="display" style={{ margin: "20px 0", fontSize: "clamp(36px, 5vw, 64px)" }}>
              Thanks, {data.name.split(" ")[0]}.
            </h2>
            <p style={{ margin: 0, color: "var(--ink-soft)", fontSize: 17, maxWidth: 520, marginInline: "auto" }}>
              We've received your message and will reply to <strong>{data.email}</strong> as soon as possible.
            </p>
            <p style={{ margin: "16px auto 0", color: "var(--muted)", fontSize: 13, maxWidth: 520 }}>
              Prefer email? Reach us any time at{" "}
              <a href="mailto:christian@nordicsubstrate.com,ina@nordicsubstrate.com" style={{ color: "var(--accent)", borderBottom: "1px solid var(--accent)" }}>christian@ or ina@nordicsubstrate.com</a>.
            </p>
            <button
              onClick={() => { setSubmitted(false); setData({ name: "", email: "", company: "", interest: "", message: "" }); }}
              className="btn btn--ghost"
              style={{ marginTop: 32 }}
            >
              Send another message <span className="arrow">→</span>
            </button>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section id="book" style={{ background: "var(--bg-alt)" }}>
      <div className="wrap">
        <div className="eyebrow">
          <span className="dot"></span>
          <span className="label">Get in touch · 08</span>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1.4fr", gap: 56, alignItems: "start" }} className="book-grid">
          <div>
            <h2 className="display" style={{ margin: 0, fontSize: "clamp(36px, 5vw, 64px)" }}>
              Let's grow <span style={{ color: "var(--accent)" }}>together.</span>
            </h2>
            <p style={{ marginTop: 20, color: "var(--ink-soft)", fontSize: 17, maxWidth: 480 }}>
              Tell us a little about your operation and what you're looking for. We'll reply
              with the right person, relevant technical materials, and next steps. No commitment.
            </p>

            <div style={{ marginTop: 40, paddingTop: 24, borderTop: "1px solid var(--rule)" }}>
              <div className="label">What happens next</div>
              <ul style={{ margin: "16px 0 0", padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 12 }}>
                {[
                  "A short reply from our team, usually within a day or two",
                  "Technical brief matched to your crop & site",
                  "Sample plugs available on request",
                  "A call only once it's useful, never as step one",
                ].map((t, i) => (
                  <li key={i} style={{ display: "grid", gridTemplateColumns: "20px 1fr", gap: 12, fontSize: 14, color: "var(--ink-soft)", paddingTop: 12, borderTop: i === 0 ? "0" : "1px dashed var(--rule-soft)" }}>
                    <span className="mono" style={{ fontSize: 11, color: "var(--accent)" }}>{String(i + 1).padStart(2, "0")}</span>
                    <span>{t}</span>
                  </li>
                ))}
              </ul>

              <div style={{ marginTop: 32, paddingTop: 20, borderTop: "1px solid var(--rule-soft)" }}>
                <div className="label">Or email us directly</div>
                <div style={{ display: "flex", flexDirection: "column", gap: 6, marginTop: 10 }}>
                  <a href="mailto:christian@nordicsubstrate.com" style={{ fontSize: 16, color: "var(--accent)", borderBottom: "1px solid var(--accent)", alignSelf: "flex-start" }}>christian@nordicsubstrate.com</a>
                  <a href="mailto:ina@nordicsubstrate.com" style={{ fontSize: 16, color: "var(--accent)", borderBottom: "1px solid var(--accent)", alignSelf: "flex-start" }}>ina@nordicsubstrate.com</a>
                </div>
              </div>
            </div>
          </div>

          <div style={{ background: "var(--bg)", border: "1px solid var(--rule)", padding: 28 }}>
            <form onSubmit={submit}>
              <div className="form-grid">
                <div className="field">
                  <label>Full name *</label>
                  <input required value={data.name} onChange={(e) => update("name", e.target.value)} placeholder="Anna Lindgren" />
                </div>
                <div className="field">
                  <label>Email *</label>
                  <input type="email" required value={data.email} onChange={(e) => update("email", e.target.value)} placeholder="anna@grower.com" />
                </div>
                <div className="field">
                  <label>Company *</label>
                  <input required value={data.company} onChange={(e) => update("company", e.target.value)} placeholder="Greenhouse Group AB" />
                </div>
                <div className="field">
                  <label>I'm interested in</label>
                  <select value={data.interest} onChange={(e) => update("interest", e.target.value)}>
                    <option value="">Select…</option>
                    {interests.map((i) => (
                      <option key={i.id} value={i.id}>{i.label}</option>
                    ))}
                  </select>
                </div>
                <div className="field" style={{ gridColumn: "1 / -1" }}>
                  <label>How can we help?</label>
                  <textarea value={data.message} onChange={(e) => update("message", e.target.value)} placeholder="Tell us briefly about your crop, volume, and what you'd like to explore." />
                </div>
              </div>

              <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 28, gap: 16, flexWrap: "wrap" }}>
                <span className="mono" style={{ fontSize: 11, letterSpacing: "0.06em", color: "var(--muted)", textTransform: "uppercase" }}>
                  We reply to every enquiry
                </span>
                <button type="submit" className="btn" disabled={!canSubmit || sending} style={{ opacity: canSubmit && !sending ? 1 : 0.4 }}>
                  {sending ? "Sending…" : "Send message"} <span className="arrow">→</span>
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
      <style>{`
        @media (max-width: 900px) {
          .book-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </section>
  );
}

window.Booking = Booking;
