/* Community Partner inquiry — #partner-inquiry?type=<key> */
const PARTNER_TYPES = [
  { key: "free-throw", name: "Free Throw", sub: "Local Supporter · $500", color: "#5b8a72" },
  { key: "three-point", name: "Three-Point", sub: "Supporting Partner · $1,000", color: "#3c6997" },
  { key: "half-court", name: "Half-Court", sub: "Premier Partner · $2,500", color: "#7a3b86" },
  { key: "court", name: "Court Sponsor", sub: "Exclusive Title Partner · $5,000", color: "var(--c-red)" },
  { key: "in-kind", name: "Product / In-Kind", sub: "Food, drinks, merch or branded items", color: "var(--c-ink)" },
  { key: "event", name: "Event Partner", sub: "Camp week, booth or showcase activation", color: "var(--c-ink)" },
  { key: "other", name: "Not sure yet", sub: "Help us find the right fit", color: "var(--c-ink-soft)" },
];

async function submitPartnerInquiry(d) {
  const type = PARTNER_TYPES.find((t) => t.key === d.type);
  const res = await fetch("https://api.web3forms.com/submit", {
    method: "POST",
    headers: { "Content-Type": "application/json", "Accept": "application/json" },
    body: JSON.stringify({
      access_key: "b8d90ff4-9ffd-422f-a59d-c0c2d5e120c6",
      subject: `[Partner Inquiry] ${d.business} — ${type ? type.name : "?"}`,
      from_name: "London LOGIC Basketball — Community Partner Inquiry",
      replyto: d.email,
      "Business name": d.business,
      "Contact name": d.name,
      "Email": d.email,
      "Phone": d.phone,
      "Website / social": d.website || "—",
      "Partnership type": type ? `${type.name} (${type.sub})` : "—",
      "Notes / other ways to partner": d.notes || "—",
    }),
  });
  const json = await res.json().catch(() => ({}));
  if (!res.ok || !json.success) throw new Error(json.message || `Submission failed (${res.status})`);
}

function PartnerThanksModal({ name, onClose }) {
  React.useEffect(() => {
    const k = (e) => e.key === "Escape" && onClose();
    window.addEventListener("keydown", k);
    return () => window.removeEventListener("keydown", k);
  }, []);
  return (
    <div role="dialog" aria-modal="true" onClick={onClose} style={{ position: "fixed", inset: 0, zIndex: 200, background: "rgba(0,0,0,0.62)", display: "grid", placeItems: "center", padding: 20 }}>
      <div className="reveal" onClick={(e) => e.stopPropagation()} style={{ position: "relative", overflow: "hidden", maxWidth: 560, width: "100%", background: "#0a0a0a", color: "#fff", borderRadius: "var(--radius-card)", borderTop: "5px solid var(--c-red)", padding: "clamp(28px, 5vw, 48px)", textAlign: "center" }}>
        {window.HalfCourt && <div style={{ position: "absolute", bottom: -60, right: -60, opacity: 0.1, pointerEvents: "none" }}><window.HalfCourt width={320} color="#fff" opacity={1} /></div>}
        <div style={{ position: "relative" }}>
          <span className="mono" style={{ color: "var(--c-red)" }}>Inquiry received</span>
          <h2 className="display" style={{ margin: "14px 0 0", fontSize: "clamp(38px, 6vw, 60px)", lineHeight: 0.96, color: "#fff" }}>
            Thank you for investing in <span style={{ color: "var(--c-red)" }}>the future.</span>
          </h2>
          <p style={{ margin: "18px auto 0", maxWidth: "40ch", fontSize: 16, lineHeight: 1.6, color: "rgba(255,255,255,0.8)" }}>
            {name ? `Thanks, ${name.split(" ")[0]}. ` : ""}Coach AD will be in touch shortly to talk through your partnership with London LOGIC.
          </p>
          <div style={{ marginTop: 26, display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap" }}>
            <a href="#sponsors" onClick={onClose} style={{ display: "inline-flex", alignItems: "center", gap: 10, padding: "14px 22px", borderRadius: 999, background: "var(--c-red)", color: "#fff", fontFamily: "var(--font-display)", letterSpacing: "0.06em", textTransform: "uppercase", fontSize: 15 }}>Back to Community Partners {window.Arrow ? <window.Arrow size={13} /> : "→"}</a>
            <button type="button" onClick={onClose} style={{ padding: "14px 22px", borderRadius: 999, background: "transparent", border: "2px solid rgba(255,255,255,0.4)", color: "#fff", fontFamily: "var(--font-display)", letterSpacing: "0.06em", textTransform: "uppercase", fontSize: 15 }}>Close</button>
          </div>
        </div>
      </div>
    </div>);
}

function PartnerInquiryForm({ compact }) {
  const initialType = () => {
    const q = new URLSearchParams(window.location.hash.split("?")[1] || "");
    const t = q.get("type");
    return PARTNER_TYPES.some((x) => x.key === t) ? t : "";
  };
  const blank = () => ({ business: "", name: "", email: "", phone: "", website: "", type: initialType(), notes: "" });
  const [d, setD] = React.useState(blank);
  const [sending, setSending] = React.useState(false);
  const [sent, setSent] = React.useState(null);
  const [err, setErr] = React.useState(null);
  React.useEffect(() => {
    const h = () => { const t = initialType(); if (t) setD((p) => ({ ...p, type: t })); };
    window.addEventListener("hashchange", h);
    return () => window.removeEventListener("hashchange", h);
  }, []);
  const up = (k) => (e) => setD({ ...d, [k]: e.target.value });
  const ready = d.business.trim() && d.name.trim() && d.email.includes("@") && d.phone.trim().length >= 7 && d.type;

  return (
    <React.Fragment>
      <form onSubmit={async (e) => {
        e.preventDefault(); if (!ready || sending) return;
        setSending(true); setErr(null);
        try { await submitPartnerInquiry(d); setSent(d.name); setD(blank()); } catch (x) { setErr(x.message || "Network error."); } finally { setSending(false); }
      }} style={{ background: "var(--c-paper)", border: "1px solid var(--c-line)", borderRadius: "var(--radius-card)", padding: compact ? 20 : "clamp(24px, 3.4vw, 40px)" }}>
        <div className="pi-grid" style={{ display: "grid", gridTemplateColumns: compact ? "1fr" : "1fr 1fr", gap: 16 }}>
          <VolField label="Business name" full><input required value={d.business} onChange={up("business")} autoComplete="organization" style={volFieldStyle} /></VolField>
          <VolField label="Contact name"><input required value={d.name} onChange={up("name")} autoComplete="name" style={volFieldStyle} /></VolField>
          <VolField label="Phone number"><input required type="tel" value={d.phone} onChange={up("phone")} autoComplete="tel" style={volFieldStyle} /></VolField>
          <VolField label="Email"><input required type="email" value={d.email} onChange={up("email")} autoComplete="email" style={volFieldStyle} /></VolField>
          <VolField label="Website / social (optional)"><input value={d.website} onChange={up("website")} autoComplete="url" style={volFieldStyle} /></VolField>
          <VolField as="div" label="Partnership type" hint="Choose the partnership you're interested in." full>
            <div className="pi-types" style={{ display: "grid", gridTemplateColumns: compact ? "1fr" : "repeat(2, minmax(0, 1fr))", gap: 8 }}>
              {PARTNER_TYPES.map((t) => {
                const on = d.type === t.key;
                return <button type="button" key={t.key} onClick={() => setD({ ...d, type: t.key })} aria-pressed={on} className="tappable" style={{
                  display: "flex", alignItems: "center", gap: 12, textAlign: "left", padding: "12px 14px", minHeight: 56, borderRadius: 10, cursor: "pointer", fontFamily: "inherit",
                  border: `1.5px solid ${on ? "var(--c-red)" : "var(--c-line)"}`, background: on ? "color-mix(in oklab, var(--c-red) 10%, var(--c-bg))" : "var(--c-bg)", color: "var(--c-ink)",
                }}>
                  <span style={{ flex: "0 0 auto", width: 18, height: 18, borderRadius: 999, border: `2px solid ${on ? "var(--c-red)" : "var(--c-line)"}`, display: "grid", placeItems: "center" }}>
                    {on && <span style={{ width: 8, height: 8, borderRadius: 999, background: "var(--c-red)" }}></span>}
                  </span>
                  <span style={{ flex: "0 0 auto", width: 4, alignSelf: "stretch", borderRadius: 2, background: t.color }}></span>
                  <span style={{ display: "flex", flexDirection: "column", gap: 2, minWidth: 0 }}>
                    <span className="display" style={{ fontSize: 20, lineHeight: 1 }}>{t.name}</span>
                    <span style={{ fontSize: 13, color: "var(--c-ink-soft)", lineHeight: 1.35 }}>{t.sub}</span>
                  </span>
                </button>;
              })}
            </div>
          </VolField>
          <VolField label="Notes (optional)" hint="Looking to partner in other ways? Tell us what you have in mind — in-kind products, a specific camp week, an event booth, or anything else." full>
            <textarea rows={5} value={d.notes} onChange={up("notes")} style={{ ...volFieldStyle, resize: "vertical", lineHeight: 1.5 }} />
          </VolField>
        </div>
        <div style={{ marginTop: 22, display: "flex", alignItems: "center", gap: 16, flexWrap: "wrap" }}>
          <button type="submit" disabled={!ready || sending} className="btn tappable" style={{
            padding: "14px 22px", borderRadius: 999, border: 0, background: "var(--c-red)", color: "#fff",
            fontFamily: "var(--font-mono)", fontSize: 12, letterSpacing: "0.12em", textTransform: "uppercase", fontWeight: 700,
            cursor: ready && !sending ? "pointer" : "not-allowed", opacity: ready && !sending ? 1 : 0.45, width: compact ? "100%" : "auto",
          }}>{sending ? "Sending…" : "Submit partner inquiry"}</button>
          <span style={{ fontSize: 13, color: "var(--c-ink-soft)" }}>No commitment — Coach AD will follow up personally.</span>
        </div>
        {err && <p style={{ margin: "12px 0 0", color: "var(--c-red)", fontSize: 14 }}>Couldn't send: {err}</p>}
      </form>
      {sent !== null && <PartnerThanksModal name={sent} onClose={() => setSent(null)} />}
    </React.Fragment>);
}

function PartnerInquiryPage() {
  return (
    <section data-screen-label="Partner Inquiry" style={{ padding: "48px 0 96px" }}>
      <div className="container">
        <a href="#sponsors" className="mono" style={{ display: "inline-flex", gap: 8, color: "var(--c-ink-soft)", marginBottom: 20 }}>← Community Partners</a>
        <SectionHead eyebrow="Community Partner inquiry"
          title={<span>Become a LOGIC <span style={{ color: "var(--c-red)" }}>Community Partner.</span></span>}
          kicker="Tell us about your business and the partnership you're interested in. We'll reach out to confirm details and match you to the partnership that fits." />
        <div className="pi-wrap" style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.6fr) minmax(0, 1fr)", gap: "clamp(20px, 3vw, 40px)", alignItems: "start" }}>
          <PartnerInquiryForm />
          <aside style={{ borderTop: "2px solid var(--c-red)", paddingTop: 16 }}>
            <Eyebrow color="var(--c-red)">What happens next</Eyebrow>
            <ol style={{ margin: "16px 0 0", padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 16 }}>
              {[["01", "Inquire", "Send your details and preferred partnership."], ["02", "Connect", "Coach AD reaches out to talk through the fit."], ["03", "Confirm", "We finalize benefits, logo assets and timing."]].map(([n, t, b]) =>
              <li key={n} style={{ display: "grid", gridTemplateColumns: "34px 1fr", gap: 10 }}>
                <span className="mono" style={{ color: "var(--c-red)" }}>{n}</span>
                <div><div className="display" style={{ fontSize: 22, lineHeight: 1 }}>{t}</div><p style={{ margin: "6px 0 0", fontSize: 14.5, lineHeight: 1.5, color: "var(--c-ink-soft)" }}>{b}</p></div>
              </li>)}
            </ol>
            <p style={{ margin: "22px 0 0", fontSize: 14, lineHeight: 1.55, color: "var(--c-ink-soft)" }}>
              Prefer email? <a href={`mailto:${PARTNER_EMAIL}`} style={{ color: "var(--c-red)", fontWeight: 700 }}>{PARTNER_EMAIL}</a>
            </p>
          </aside>
        </div>
      </div>
      <style>{`@media (max-width: 900px){.pi-wrap{grid-template-columns:1fr !important}} @media (max-width: 600px){.pi-grid,.pi-types{grid-template-columns:1fr !important}}`}</style>
    </section>);
}
Object.assign(window, { PartnerInquiryPage, PartnerInquiryForm });
