/* ============================================================
   OMNIO — Contact page · alt layout
   Inquiry type as left-rail navigation; contextual form on right
   ============================================================ */
const { useState: useStateC } = React;

// Google Apps Script Web App endpoint — appends each submission as a row to the linked Google Sheet.
const CONTACT_ENDPOINT = "https://script.google.com/macros/s/AKfycby7OcTYzgb_HJ0382uNrZqH7fGmvSl0lf4unTsXJK0jbC7zIbF9vFwwp8AwpFhGJMAh/exec";

const INQUIRIES = [
{
  key: "Partnerships",
  n: "01",
  blurb: "Clinical pilots, channel & distribution, OEM integration.",
  prompt: "Tell us about the partnership you'd like to explore."
},
{
  key: "Press",
  n: "02",
  blurb: "Editorial coverage, interviews, embargoed news.",
  prompt: "Outline your story — deadlines, format, audience."
},
{
  key: "Investors",
  n: "03",
  blurb: "Capital introductions, diligence, follow-on rounds.",
  prompt: "A few words on your firm and what you're exploring."
},
{
  key: "Careers",
  n: "04",
  blurb: "Open roles & speculative applications from operators in diagnostics.",
  prompt: "Tell us about your background and what you're looking for."
},
{
  key: "General",
  n: "05",
  blurb: "Anything else — feedback, questions, introductions.",
  prompt: "What's on your mind?"
}];


function ContactPage() {
  const [form, setForm] = useStateC({
    firstName: "",
    lastName: "",
    email: "",
    company: "",
    message: ""
  });
  const [inquiryIdx, setInquiryIdx] = useStateC(0);
  const [sent, setSent] = useStateC(false);
  const [sending, setSending] = useStateC(false);
  const [error, setError] = useStateC(false);

  const inquiry = INQUIRIES[inquiryIdx];

  const onSubmit = async (e) => {
    e.preventDefault();
    if (sending) return;
    setError(false);
    setSending(true);
    try {
      await fetch(CONTACT_ENDPOINT, {
        method: "POST",
        mode: "no-cors",
        // text/plain avoids a CORS preflight that Apps Script can't answer;
        // the script reads the raw body via e.postData.contents.
        headers: { "Content-Type": "text/plain;charset=utf-8" },
        body: JSON.stringify({
          inquiry: inquiry.key,
          firstName: form.firstName,
          lastName: form.lastName,
          email: form.email,
          company: form.company,
          message: form.message
        })
      });
      setSent(true);
    } catch (err) {
      // Network failure — keep the form data so the visitor can retry.
      setError(true);
    } finally {
      setSending(false);
    }
  };

  return (
    <>
      {/* HERO */}
      <section className="section dense" style={{ paddingTop: 80, paddingBottom: 56 }}>
        <div className="container">
          <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 36 }}>
            <span className="eyebrow">Contact</span>
          </div>
          <div style={{ display: "grid", gridTemplateColumns: "1.4fr auto", gap: 56, alignItems: "end" }} className="contact-hero">
            <h1 className="display-xl" style={{ maxWidth: "13ch", margin: 0 }}>
              Get in touch<span style={{ color: "var(--magenta)" }}>.</span>
            </h1>
            <div style={{ display: "flex", flexDirection: "column", gap: 8, fontFamily: "var(--mono)", fontWeight: 200, fontSize: 11, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--ink-mute)", alignItems: "flex-end", textAlign: "right" }}>
              <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                <span style={{ width: 6, height: 6, borderRadius: "50%", background: "var(--magenta)" }} />
                Carlsbad, California
              </div>
              <div>Pacific Time · UTC−8</div>
              <div></div>
            </div>
          </div>
          <style>{`@media (max-width: 760px) { .contact-hero { grid-template-columns: 1fr !important; gap: 24px !important; align-items: start !important; } .contact-hero > div:nth-child(2) { align-items: flex-start !important; text-align: left !important; } }`}</style>
        </div>
      </section>

      {/* FORM */}
      <section style={{ paddingTop: 0, paddingBottom: "clamp(80px, 9vw, 140px)" }}>
        <div className="container">
          <div style={{ border: "1px solid var(--line-strong)", background: "var(--cream)" }}>
            <div className="contact-form-pane" style={{ padding: "clamp(36px, 4vw, 64px)" }}>
              {sent ?
              <div style={{ paddingTop: 6, display: "flex", flexDirection: "column", gap: 18, alignItems: "flex-start", minHeight: 360 }}>
                  <div style={{ width: 10, height: 10, borderRadius: "50%", background: "var(--magenta)" }} />
                  <h3 className="display-md" style={{ maxWidth: "20ch", margin: 0 }}>Thank you — we'll be in touch.</h3>
                  <button className="btn ghost" onClick={() => {setSent(false);setError(false);setForm({ firstName: "", lastName: "", email: "", company: "", message: "" });}} style={{ marginTop: 12 }}>
                    Send another →
                  </button>
                </div> :

              <form onSubmit={onSubmit} style={{ display: "flex", flexDirection: "column", gap: 0 }}>
                  {/* Inquiry pills */}
                  <Field label="I'd like to discuss">
                    <div role="radiogroup" aria-label="Inquiry type" style={{ display: "flex", flexWrap: "wrap", gap: 8, marginTop: 14, marginBottom: 4 }}>
                      {INQUIRIES.map((inq, i) => {
                      const on = i === inquiryIdx;
                      return (
                        <button
                          type="button"
                          key={inq.key}
                          role="radio"
                          aria-checked={on}
                          onClick={() => setInquiryIdx(i)}
                          style={{
                            padding: "9px 18px",
                            borderRadius: 999,
                            fontFamily: "var(--mono)",
                            fontWeight: 200,
                            fontSize: 11.5,
                            letterSpacing: "0.16em",
                            textTransform: "uppercase",
                            border: `1px solid ${on ? "var(--ink)" : "var(--line-strong)"}`,
                            background: on ? "var(--ink)" : "transparent",
                            color: on ? "var(--cream)" : "var(--ink)",
                            cursor: "pointer",
                            transition: "all 0.2s"
                          }}>
                            {inq.key}
                          </button>);
                    })}
                    </div>
                  </Field>

                  <Row two>
                    <Field label="First name" required>
                      <input required placeholder="Marie"
                    value={form.firstName}
                    onChange={(e) => setForm({ ...form, firstName: e.target.value })} />
                    </Field>
                    <Field label="Last name" required>
                      <input required placeholder="Curie"
                    value={form.lastName}
                    onChange={(e) => setForm({ ...form, lastName: e.target.value })} />
                    </Field>
                  </Row>

                  <Row two>
                    <Field label="Email" required>
                      <input required type="email" placeholder="marie@institution.org"
                    value={form.email}
                    onChange={(e) => setForm({ ...form, email: e.target.value })} />
                    </Field>
                    <Field label="Company or institution">
                      <input placeholder="Optional"
                    value={form.company}
                    onChange={(e) => setForm({ ...form, company: e.target.value })} />
                    </Field>
                  </Row>

                  <Row>
                    <Field label="Message" required>
                      <textarea required rows={4} placeholder="A few sentences is plenty."
                    value={form.message}
                    onChange={(e) => setForm({ ...form, message: e.target.value })} />
                    </Field>
                  </Row>

                  <div style={{ display: "flex", justifyContent: "flex-end", alignItems: "center", paddingTop: 36, marginTop: 8, borderTop: "1px solid var(--line)", flexWrap: "wrap", gap: 16 }}>
                    {error &&
                    <span style={{ fontFamily: "var(--mono)", fontWeight: 200, fontSize: 11, letterSpacing: "0.14em", textTransform: "uppercase", color: "var(--magenta)", marginRight: "auto" }}>
                        Couldn't send — please try again.
                      </span>}
                    <button type="submit" className="contact-submit" disabled={sending} style={{ opacity: sending ? 0.5 : 1, cursor: sending ? "default" : "pointer" }}>
                      <span>{sending ? "Sending…" : "Submit"}</span>
                      {!sending && <span style={{ fontSize: 18, lineHeight: 1 }}>→</span>}
                    </button>
                  </div>
                </form>
              }
            </div>
          </div>

          <style>{`
            .contact-form-pane input,
            .contact-form-pane textarea {
              width: 100%;
              background: transparent;
              border: none;
              border-bottom: 1px solid var(--line-strong);
              padding: 12px 0 14px;
              font-family: var(--body);
              font-size: 17px;
              color: var(--ink);
              outline: none;
              transition: border-color 0.2s;
              resize: vertical;
            }
            .contact-form-pane input::placeholder,
            .contact-form-pane textarea::placeholder { color: var(--ink-mute); }
            .contact-form-pane input:focus,
            .contact-form-pane textarea:focus { border-bottom-color: var(--ink); }
            .contact-submit {
              display: inline-flex;
              align-items: center;
              gap: 12px;
              padding: 6px 0 8px;
              border: none;
              background: transparent;
              color: var(--ink);
              font-family: var(--body);
              font-weight: 500;
              font-size: 17px;
              cursor: pointer;
              border-bottom: 1px solid var(--ink);
              transition: color 0.2s, border-color 0.2s, gap 0.2s;
            }
            .contact-submit:hover { color: var(--magenta); border-bottom-color: var(--magenta); gap: 18px; }
          `}</style>
        </div>
      </section>
    </>);
}

/* ---------- helpers ---------- */
function Field({ label, required, children }) {
  return (
    <label style={{ display: "flex", flexDirection: "column", gap: 0, width: "100%" }}>
      <span style={{ fontFamily: "var(--mono)", fontWeight: 200, fontSize: 10.5, letterSpacing: "0.18em", textTransform: "uppercase", color: "var(--ink-mute)" }}>
        {label}{required && <span style={{ color: "var(--magenta)", marginLeft: 4 }}>*</span>}
      </span>
      {children}
    </label>);
}

function Row({ two, children }) {
  return (
    <div style={{
      display: "grid",
      gridTemplateColumns: two ? "1fr 1fr" : "1fr",
      gap: two ? 40 : 0,
      paddingTop: 32
    }} className={two ? "form-row" : ""}>
      {children}
      <style>{`@media (max-width: 640px) { .form-row { grid-template-columns: 1fr !important; gap: 32px !important; } }`}</style>
    </div>);
}

function ContactApp() {
  return (
    <>
      <window.Nav />
      <main>
        <ContactPage />
      </main>
      <window.Footer />
    </>);
}

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