/* ============================================================
   CONTACT PAGE
   ============================================================ */

function ContactPage({ go, t }) {
  const [form, setForm] = React.useState({ name: "", email: "", subject: "", message: "" });
  const [status, setStatus] = React.useState("idle"); // idle | sending | sent | error
  const [touched, setTouched] = React.useState({});

  const set = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const touch = (k) => setTouched((t) => ({ ...t, [k]: true }));

  const errors = {
    name: !form.name.trim() ? "Name is required" : null,
    email: !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email) ? "Valid email required" : null,
    subject: !form.subject.trim() ? "Subject is required" : null,
    message: form.message.trim().length < 10 ? "Please write at least 10 characters" : null
  };
  const isValid = !Object.values(errors).some(Boolean);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setTouched({ name: true, email: true, subject: true, message: true });
    if (!isValid) return;
    setStatus("sending");
    try {
      const res = await fetch("https://formsubmit.co/ajax/teamgsracers.org@gmail.com", {
        method: "POST",
        headers: { "Content-Type": "application/json", "Accept": "application/json" },
        body: JSON.stringify({
          name: form.name,
          email: form.email,
          _subject: `[Website] ${form.subject}`,
          message: form.message,
          _template: "table",
          _replyto: form.email
        })
      });
      if (!res.ok) throw new Error("Request failed");
      setStatus("sent");
    } catch (err) {
      setStatus("error");
    }
  };

  const Field = ({ id, label, type = "text", multiline, placeholder }) => {
    const err = touched[id] && errors[id];
    const base = {
      width: "100%", padding: "14px 16px",
      background: "var(--surface-2)", border: `1px solid ${err ? "var(--orange)" : "var(--border)"}`,
      color: "var(--text)", fontFamily: "var(--f-body)", fontSize: 15, outline: "none",
      transition: "border-color .15s",
      borderRadius: t.cardShape === "rounded" ? 6 : 0,
      resize: multiline ? "vertical" : undefined
    };
    return (
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        <label className="label" style={{ fontSize: 12, color: "var(--muted)", letterSpacing: "0.1em" }}>{label}</label>
        {multiline ?
          <textarea value={form[id]} onChange={(e) => set(id, e.target.value)} onBlur={() => touch(id)}
            placeholder={placeholder} rows={5} style={base} /> :
          <input type={type} value={form[id]} onChange={(e) => set(id, e.target.value)} onBlur={() => touch(id)}
            placeholder={placeholder} style={base} />
        }
        {err && <span className="body" style={{ fontSize: 12, color: "var(--orange)" }}>{err}</span>}
      </div>
    );
  };

  return (
    <main>
      {/* ── Header ── */}
      <section style={{ borderBottom: "1px solid var(--border)", position: "relative", overflow: "hidden", minHeight: 200, paddingTop: 44, paddingBottom: 44, display: "flex", alignItems: "center" }}>
        <div aria-hidden style={{
          position: "absolute", right: -20, top: "50%", transform: "translateY(-50%)",
          fontFamily: "var(--f-head)", fontSize: "clamp(100px,18vw,280px)",
          color: "rgba(255,107,0,0.05)", lineHeight: 1, pointerEvents: "none", userSelect: "none"
        }}>TALK</div>
        <div className="wrap" style={{ paddingTop: 0, paddingBottom: 0, width: "100%" }}>
          <div style={{ position: "relative", zIndex: 2 }}>
            <div className="eyebrow" style={{ marginBottom: 10 }}>Get in Touch</div>
            <div className="sec-title" style={{ marginBottom: 12 }}>
              <span className="bar" />
              <h1 className="head" style={{ margin: 0, fontSize: "clamp(40px,6vw,80px)" }}>Contact Us</h1>
            </div>
            <p className="label" style={{ margin: "0 0 0 24px", fontSize: "clamp(13px,1.4vw,17px)", color: "var(--text)", maxWidth: 520 }}>
              Sponsors, press, recruits, or just a fan — <span style={{ color: "var(--orange)" }}>reach the team you need.</span>
            </p>
          </div>
        </div>
      </section>

      {/* ── Reach a Team — team captain per team ── */}
      <section style={{ borderBottom: "1px solid var(--border)", background: "var(--surface)" }}>
        <div className="wrap" style={{ paddingTop: 40, paddingBottom: 48 }}>
          <div className="label" style={{ fontSize: 13, color: "var(--muted)", letterSpacing: "0.12em", marginBottom: 28 }}>Reach a Team Captain</div>
          <div className="key-contacts-grid" style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 20 }}>
            {TEAM_ORDER.map((id) => {
              const tm = TEAMS[id];
              const c = tm.captain;
              return (
                <div key={id} className="card" style={{
                  padding: "24px 24px 22px", display: "flex", flexDirection: "column",
                  borderLeft: `4px solid ${tm.accent}`, position: "relative",
                }}>
                  <div className="head" style={{ fontSize: 18, lineHeight: 0.95, marginTop: 14, marginBottom: 14, color: "var(--muted)" }}>{tm.name}</div>
                  <div className="label" style={{ fontSize: 10, color: "var(--muted)", letterSpacing: "0.1em", marginBottom: 6 }}>{tm.captainTag || "TEAM CAPTAIN"}</div>
                  <p className="head" style={{ fontSize: 26, lineHeight: 1, margin: "0 0 14px" }}>{c.name}</p>
                  <div style={{ display: "flex", flexDirection: "column", gap: 5, marginTop: "auto" }}>
                    {c.email && <a href={`mailto:${c.email}`} className="body" style={{ fontSize: 14, color: tm.accent }}>{c.email}</a>}
                    <a href={`tel:${c.phone}`} className="body" style={{ fontSize: 14, color: "var(--text)" }}>{c.phone}</a>
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </section>

      {/* ── Main content: form + info ── */}
      <section className="wrap" style={{ paddingTop: 72, paddingBottom: 80 }}>
        <div className="contact-grid" style={{ display: "grid", gridTemplateColumns: "1.2fr 0.8fr", gap: 64, alignItems: "start" }}>

          {/* FORM */}
          <div>
            <div className="label" style={{ fontSize: 13, color: "var(--muted)", letterSpacing: "0.12em", marginBottom: 12 }}>Send a Message</div>
            <p className="body muted" style={{ fontSize: 13, margin: "0 0 20px", lineHeight: 1.6 }}>
              <span style={{ color: "var(--text)", fontWeight: 600 }}>This form sends your message straight to our official inbox,</span>{" "}
              <a href="mailto:teamgsracers.org@gmail.com" style={{ color: "var(--orange)", fontWeight: 600 }}>teamgsracers.org@gmail.com</a>.
            </p>

            {status === "sent" ?
              <div className="card" style={{ padding: "52px 40px", borderLeft: "6px solid var(--orange)", textAlign: "center" }}>
                <div className="head" style={{ fontSize: 52, marginBottom: 12, color: "var(--orange)" }}>SENT.</div>
                <p className="body muted" style={{ fontSize: 16, lineHeight: 1.7, margin: "0 0 28px" }}>
                  We got your message. A human will reply within 24–48 hours.
                </p>
                <button className="btn btn-ghost" onClick={() => { setStatus("idle"); setForm({ name: "", email: "", subject: "", message: "" }); setTouched({}); }}>
                  Send Another
                </button>
              </div> :

              <form onSubmit={handleSubmit} noValidate style={{ display: "flex", flexDirection: "column", gap: 22 }}>
                <div className="form-row-2" style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 18 }}>
                  {Field({ id: "name", label: "Full Name", placeholder: "Lorem Ipsum" })}
                  {Field({ id: "email", label: "Email Address", type: "email", placeholder: "lorem@example.com" })}
                </div>
                {Field({ id: "subject", label: "Subject", placeholder: "Sponsorship · Press · Joining the team" })}
                {Field({ id: "message", label: "Message", multiline: true, placeholder: "Tell us what's on your mind..." })}
                {status === "error" &&
                  <div className="body" style={{ fontSize: 13, color: "var(--orange)", borderLeft: "3px solid var(--orange)", paddingLeft: 12 }}>
                    Something went wrong sending your message. Please try again, or email us directly at{" "}
                    <a href="mailto:teamgsracers.org@gmail.com" style={{ color: "var(--orange)" }}>teamgsracers.org@gmail.com</a>.
                  </div>
                }
                <div style={{ display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
                  <button type="submit" className="btn btn-primary" disabled={status === "sending"}
                    style={{ opacity: status === "sending" ? 0.7 : 1 }}>
                    {status === "sending" ? "Sending…" : "Send Message"}
                    {status !== "sending" && <span className="arrow"><Icon name="arrow" size={16} color="#0A0A0A" /></span>}
                  </button>
                  <span className="body muted" style={{ fontSize: 13 }}>We reply within 48 hours</span>
                </div>
              </form>
            }
          </div>

          {/* INFO */}
          <div style={{ display: "flex", flexDirection: "column", gap: 36 }}>

            {/* Address */}
            <div>
              <div className="label" style={{ fontSize: 13, color: "var(--muted)", letterSpacing: "0.12em", marginBottom: 16 }}>Garage</div>
              <div className="card" style={{ padding: "26px 28px", borderLeft: "4px solid var(--orange)" }}>
                <div className="head" style={{ fontSize: 24, marginBottom: 8 }}>{ORG.locationName}</div>
                <p className="body muted" style={{ fontSize: 15, lineHeight: 1.7, margin: 0 }}>
                  {ORG.locationLines.map((ln, i) => <React.Fragment key={i}>{ln}<br /></React.Fragment>)}
                </p>
                <div style={{ marginTop: 16 }}>
                  <a href={`mailto:${ORG.email}`} className="label" style={{ fontSize: 14, color: "var(--orange)" }}>
                    {ORG.email}
                  </a>
                </div>
              </div>
            </div>

            {/* Map */}
            <div>
              <div className="label" style={{ fontSize: 13, color: "var(--muted)", letterSpacing: "0.12em", marginBottom: 16 }}>Find Us</div>
              <div className="card" style={{ padding: 0, overflow: "hidden", height: 240, border: "1px solid var(--border)" }}>
                <iframe
                  title="SGSITS Indore location"
                  src="https://www.google.com/maps?q=Shri+G.S.+Institute+of+Technology+%26+Science,+23,+Park+Rd,+Indore,+Madhya+Pradesh+452003&output=embed"
                  width="100%"
                  height="100%"
                  style={{ border: 0, display: "block" }}
                  loading="lazy"
                  referrerPolicy="no-referrer-when-downgrade"
                />
              </div>
              <a
                href="https://maps.app.goo.gl/T1bA248R15WJjmUaA"
                target="_blank"
                rel="noopener noreferrer"
                className="label"
                style={{ display: "inline-block", marginTop: 10, fontSize: 13, color: "var(--orange)" }}
              >
                Open in Google Maps →
              </a>
            </div>


          </div>
        </div>
      </section>
    </main>
  );

}

Object.assign(window, { ContactPage });