// screens/contact.jsx — Contact page with form, channels, hours

// Messages are emailed to the studio via Web3Forms (same backend-less service
// the cart uses). The key is tied to the inbox registered at web3forms.com.
const CONTACT_WEB3FORMS_KEY = "8ad75003-acbb-4b11-8424-6371efb47af6";

// Upload an optional attachment to a free, no-account file host and return a
// public link. Returns null if every host fails, so the message still sends.
async function uploadContactFile(file) {
  try {
    const fd = new FormData();
    fd.append("file", file);
    const r = await fetch("https://file.io/?expires=1w", { method: "POST", body: fd });
    const j = await r.json();
    if (j && j.success && j.link) return j.link;
  } catch (e) { /* try next */ }
  try {
    const fd2 = new FormData();
    fd2.append("file", file);
    const r2 = await fetch("https://tmpfiles.org/api/v1/upload", { method: "POST", body: fd2 });
    const j2 = await r2.json();
    if (j2 && j2.data && j2.data.url) return j2.data.url.replace("tmpfiles.org/", "tmpfiles.org/dl/");
  } catch (e) { /* give up */ }
  return null;
}

const SUBJECT_LABELS = { general: "General enquiry", quote: "Manual quote", cad: "CAD design", cfd: "CFD analysis" };

function ContactScreen({ brand, onUpload, onHome, onNav, initialSubject }) {
  const [form, setForm] = React.useState({ name: "", email: "", subject: initialSubject || "general", message: "", file: null });
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState("");

  function update(k, v) { setForm(f => ({ ...f, [k]: v })); }
  async function submit(e) {
    e.preventDefault();
    if (!form.email || !form.message) return;
    setError(""); setSubmitting(true);
    try {
      const topic = SUBJECT_LABELS[form.subject] || form.subject;
      const fd = new FormData();
      fd.append("access_key", CONTACT_WEB3FORMS_KEY);
      fd.append("subject", `New enquiry (${topic}) — ${form.name || form.email}`);
      fd.append("from_name", form.name || "Sync enquiry");
      fd.append("email", form.email);
      fd.append("Name", form.name || "—");
      fd.append("Topic", topic);
      fd.append("Message", form.message);
      if (form.file) {
        const link = await uploadContactFile(form.file);
        fd.append("Attachment", link
          ? `${form.file.name}: ${link}`
          : `${form.file.name}: (upload failed — customer should reply with the file)`);
      }
      const res = await fetch("https://api.web3forms.com/submit", { method: "POST", body: fd });
      const j = await res.json().catch(() => ({}));
      if (res.ok && j.success) setSent(true);
      else setError((j && j.message) || "Couldn't send your message. Please email formasync3d@gmail.com directly.");
    } catch (err) {
      setError("Network error — please try again, or email formasync3d@gmail.com.");
    } finally {
      setSubmitting(false);
    }
  }

  if (sent) {
    return (
      <main>
        <section style={{ padding: "calc(var(--pad-y) * 1.4) var(--pad-x)" }}>
          <div className="mono upper" style={{ color: "var(--muted)", marginBottom: 22 }}>
            Message received
          </div>
          <h1 className="serif" style={{
            fontSize: "clamp(56px, 8.2vw, 132px)", lineHeight: 0.92, margin: 0,
            letterSpacing: "-0.035em", textWrap: "balance", maxWidth: 1100,
          }}>
            Thank you. We'll be in touch.
          </h1>
          <p style={{ maxWidth: 560, fontSize: 17, color: "var(--ink-soft)", marginTop: 28, lineHeight: 1.5 }}>
            We read every email by hand. Expect a reply from
            <span className="mono" style={{ background: "color-mix(in srgb, var(--ink) 8%, transparent)", padding: "1px 6px", borderRadius: 4, margin: "0 4px" }}>formasync3d@gmail.com</span>
            within one working day, Monday to Friday.
          </p>
          <div style={{ display: "flex", gap: 12, marginTop: 36, flexWrap: "wrap" }}>
            <button onClick={onHome} className="mono" style={{
              border: "none", appearance: "none", font: "inherit", cursor: "pointer",
              padding: "14px 22px", borderRadius: 999, background: "var(--ink)", color: "var(--bg)", fontSize: 13,
            }}>← Back to homepage</button>
            <button onClick={() => onUpload()} className="mono" style={{
              border: "1px solid var(--ink)", appearance: "none", font: "inherit", cursor: "pointer",
              padding: "14px 22px", borderRadius: 999, background: "transparent", color: "var(--ink)", fontSize: 13,
            }}>Quote another part →</button>
          </div>
        </section>
        <Footer brand={brand} onNav={onNav} />
      </main>
    );
  }

  return (
    <main>
      <section style={{ padding: "clamp(48px, 6vw, 96px) var(--pad-x) clamp(40px, 5vw, 64px)" }}>
        <div className="mono upper" style={{ color: "var(--muted)", marginBottom: 22 }}>Contact</div>
        <h1 className="serif" style={{
          fontSize: "clamp(56px, 8.4vw, 144px)", lineHeight: 0.92, margin: 0,
          letterSpacing: "-0.035em", textWrap: "balance", maxWidth: 1300,
        }}>
          Get in <span style={{ fontStyle: "italic" }}>touch</span>.
        </h1>
        <p style={{ maxWidth: 640, marginTop: 28, fontSize: 18, lineHeight: 1.5, color: "var(--ink-soft)" }}>
          For instant quotes, drop your STL on the homepage. For everything
          else — manual quotes, CAD design, CFD analysis, partnerships, support —
          message us below or use any of the channels listed.
        </p>
      </section>

      <section style={{
        padding: "var(--pad-y) var(--pad-x)",
        borderTop: "1px solid var(--line)",
        display: "grid", gridTemplateColumns: "1.3fr 1fr",
        gap: "clamp(28px, 4vw, 64px)", alignItems: "start",
      }}>
        {/* Form */}
        <form onSubmit={submit} style={{ display: "flex", flexDirection: "column", gap: 22 }}>
          <SectionHeader index="01 — Message" lead={<>Tell us about your <span style={{ fontStyle: "italic" }}>project</span>.</>} />

          <FieldGroup>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14 }}>
              <Field label="Your name">
                <input value={form.name} onChange={(e) => update("name", e.target.value)} className="contact-input"
                  style={contactInputStyle} placeholder="Alex Maker" />
              </Field>
              <Field label="Email · required">
                <input type="email" required value={form.email} onChange={(e) => update("email", e.target.value)}
                  style={contactInputStyle} placeholder="you@example.com" />
              </Field>
            </div>
          </FieldGroup>

          <FieldGroup>
            <Field label="What's it about?">
              <div className="r-2" style={{
                display: "grid", gridTemplateColumns: "repeat(4, 1fr)",
                border: "1px solid var(--line)", borderRadius: 8, overflow: "hidden",
              }}>
                {[
                  { v: "general",  l: "General" },
                  { v: "quote",    l: "Manual quote" },
                  { v: "cad",      l: "CAD design" },
                  { v: "cfd",      l: "CFD analysis" },
                ].map((o, i) => {
                  const active = form.subject === o.v;
                  return (
                    <button key={o.v} type="button" onClick={() => update("subject", o.v)} style={{
                      border: "none", appearance: "none", font: "inherit", cursor: "pointer",
                      padding: "12px 8px", textAlign: "center",
                      background: active ? "var(--ink)" : "transparent",
                      color: active ? "var(--bg)" : "var(--ink)",
                      borderLeft: i > 0 ? "1px solid var(--line)" : "none",
                      fontSize: 12, fontFamily: "var(--mono)",
                    }}>{o.l}</button>
                  );
                })}
              </div>
            </Field>
          </FieldGroup>

          <FieldGroup>
            <Field label="Message · required">
              <textarea required value={form.message} onChange={(e) => update("message", e.target.value)}
                rows={7}
                style={{ ...contactInputStyle, padding: 14, fontFamily: "var(--sans)", fontSize: 15, resize: "vertical", lineHeight: 1.5 }}
                placeholder="Describe your part, your timeline, the material you'd like…" />
            </Field>
          </FieldGroup>

          <FieldGroup>
            <Field label="Attach a file (optional)">
              <label style={{
                display: "flex", justifyContent: "space-between", alignItems: "center", gap: 12,
                padding: "12px 14px", borderRadius: 8,
                border: "1px dashed color-mix(in srgb, var(--ink) 30%, transparent)",
                cursor: "pointer", background: "color-mix(in srgb, var(--ink) 3%, transparent)",
              }}>
                <span className="mono" style={{ fontSize: 12, color: "var(--ink-soft)" }}>
                  {form.file ? form.file.name : "STL · STEP · PDF · image · ≤ 25MB"}
                </span>
                <span className="mono upper" style={{ color: "var(--muted)" }}>Browse</span>
                <input type="file" style={{ display: "none" }}
                  onChange={(e) => update("file", e.target.files?.[0] || null)} />
              </label>
            </Field>
          </FieldGroup>

          <div style={{ display: "flex", gap: 12, alignItems: "center", marginTop: 8 }}>
            <button type="submit" className="btn-primary" data-track="contact_submit" disabled={submitting} style={{
              padding: "15px 26px", fontSize: 15,
            }}>
              <span>{submitting ? "Sending…" : "Send message"}</span><span>→</span>
            </button>
            <span className="mono" style={{ color: "var(--muted)", fontSize: 11 }}>
              We reply within one working day.
            </span>
          </div>
          {error && (
            <div className="mono" style={{
              fontSize: 12, color: "#b42318", lineHeight: 1.5,
              background: "color-mix(in srgb, #b42318 8%, transparent)",
              border: "1px solid color-mix(in srgb, #b42318 24%, transparent)",
              padding: "10px 12px", borderRadius: 8,
            }}>
              {error}
            </div>
          )}
        </form>

        {/* Channels */}
        <aside style={{ display: "flex", flexDirection: "column", gap: 28 }}>
          <SectionHeader index="02 — Or reach out directly" lead={<><span style={{ fontStyle: "italic" }}>Channels</span>.</>} />

          <ContactRow label="Email">
            <a href="mailto:formasync3d@gmail.com" style={{ color: "var(--ink)", fontSize: 18, letterSpacing: "-0.005em" }}>
              formasync3d@gmail.com
            </a>
            <div className="mono" style={{ color: "var(--muted)", fontSize: 11, marginTop: 4 }}>
              Mon–Fri · 09:00 – 18:00 GMT
            </div>
          </ContactRow>
        </aside>
      </section>

      <Footer brand={brand} onNav={onNav} />
      <FloatingCTA onUpload={() => onNav && onNav("upload")} />
    </main>
  );
}

const contactInputStyle = {
  border: "1px solid var(--line)",
  appearance: "none",
  font: "inherit",
  width: "100%",
  boxSizing: "border-box",
  padding: "12px 14px",
  borderRadius: 8,
  background: "color-mix(in srgb, var(--ink) 3%, transparent)",
  color: "var(--ink)",
  fontSize: 14,
  outline: "none",
};

const Field = ({ label, children }) => (
  <div style={{ display: "flex", flexDirection: "column", gap: 7 }}>
    <div className="mono upper" style={{ color: "var(--ink)" }}>{label}</div>
    {children}
  </div>
);
const FieldGroup = ({ children }) => <div>{children}</div>;

const ContactRow = ({ label, children }) => (
  <div style={{ paddingBottom: 22, borderBottom: "1px solid var(--line)" }}>
    <div className="mono upper" style={{ color: "var(--muted)", marginBottom: 10 }}>{label}</div>
    {children}
  </div>
);

window.ContactScreen = ContactScreen;
