/* Volunteer application — #volunteer-apply (shared desktop + mobile) */
async function submitVolunteerApplication(d) {
  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: `Volunteer application — ${d.name}`,
      from_name: "London LOGIC Basketball — Volunteer Application",
      replyto: d.email,
      "Name": d.name, "Age": d.age, "Email": d.email, "Phone": d.phone,
      "School / current role": d.school,
      "Interested in": d.roles.join(", "),
      "Availability": d.availability,
      "Why I want to volunteer with LOGIC": d.why,
    }),
  });
  const json = await res.json().catch(() => ({}));
  if (!res.ok || !json.success) throw new Error(json.message || `Submission failed (${res.status})`);
}

const VOL_ROLES = ["Camp media", "Assistant coaching", "Check-in & operations", "Showcase game day"];
const volFieldStyle = { padding: "12px 14px", borderRadius: 10, border: "1.5px solid var(--c-line)", background: "var(--c-bg)", color: "var(--c-ink)", fontFamily: "inherit", fontSize: 15, width: "100%", boxSizing: "border-box" };

function VolField({ label, hint, full, children, as }) {
  const Tag = as || "label";
  return (
    <Tag style={{ display: "flex", flexDirection: "column", gap: 6, gridColumn: full ? "1 / -1" : undefined, minWidth: 0 }}>
      <span className="mono" style={{ color: "var(--c-ink-soft)" }}>{label}</span>
      {hint && <span style={{ fontSize: 13, color: "var(--c-ink-soft)", lineHeight: 1.45 }}>{hint}</span>}
      {children}
    </Tag>);
}

function VolunteerApplyForm({ compact }) {
  const [d, setD] = React.useState({ name: "", age: "", email: "", phone: "", school: "", roles: [], availability: "", why: "" });
  const [sending, setSending] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const [err, setErr] = React.useState(null);
  const up = (k) => (e) => setD({ ...d, [k]: e.target.value });
  const toggle = (r) => setD({ ...d, roles: d.roles.includes(r) ? d.roles.filter((x) => x !== r) : [...d.roles, r] });
  const ready = d.name.trim() && d.age && d.email.includes("@") && d.roles.length && d.availability.trim() && d.why.trim();

  if (sent) return (
    <div style={{ background: "var(--c-paper)", border: "1px solid var(--c-line)", borderRadius: "var(--radius-card)", padding: compact ? 22 : "clamp(28px, 4vw, 48px)" }}>
      <span className="mono" style={{ color: "var(--c-red)" }}>Application received</span>
      <div className="display" style={{ marginTop: 10, fontSize: compact ? 30 : "clamp(32px, 4vw, 52px)", lineHeight: 1 }}>Thanks, {d.name.split(" ")[0]}.</div>
      <p style={{ margin: "14px 0 0", fontSize: 16, lineHeight: 1.6, color: "var(--c-ink-soft)", maxWidth: "52ch" }}>
        Your application has been sent to the LOGIC staff. Every application is reviewed, and we'll contact you at <strong style={{ color: "var(--c-ink)" }}>{d.email}</strong> with further details.
      </p>
    </div>);

  return (
    <form onSubmit={async (e) => {
      e.preventDefault(); if (!ready || sending) return;
      setSending(true); setErr(null);
      try { await submitVolunteerApplication(d); setSent(true); } 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="vol-apply-grid" style={{ display: "grid", gridTemplateColumns: compact ? "1fr" : "2fr 1fr", gap: 16 }}>
        <VolField label="Full name"><input required value={d.name} onChange={up("name")} autoComplete="name" style={volFieldStyle} /></VolField>
        <VolField label="Age"><input required type="number" min="12" max="99" inputMode="numeric" value={d.age} onChange={up("age")} style={volFieldStyle} /></VolField>
        <VolField label="Email"><input required type="email" value={d.email} onChange={up("email")} autoComplete="email" style={volFieldStyle} /></VolField>
        <VolField label="Phone (optional)"><input type="tel" value={d.phone} onChange={up("phone")} autoComplete="tel" style={volFieldStyle} /></VolField>
        <VolField label="School / current role (optional)" full><input value={d.school} onChange={up("school")} style={volFieldStyle} /></VolField>
        <VolField as="div" label="Where would you like to help?" hint="Pick any that apply." full>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {VOL_ROLES.map((r) => {
              const on = d.roles.includes(r);
              return <button type="button" key={r} onClick={() => toggle(r)} aria-pressed={on} className="tappable" style={{
                padding: "10px 14px", minHeight: 44, borderRadius: 999, cursor: "pointer", fontFamily: "inherit", fontSize: 14, fontWeight: 600,
                border: `1.5px solid ${on ? "var(--c-red)" : "var(--c-line)"}`, background: on ? "var(--c-red)" : "var(--c-bg)", color: on ? "#fff" : "var(--c-ink)",
              }}>{r}</button>;
            })}
          </div>
        </VolField>
        <VolField label="Availability" hint="Which weeks or days can you commit to?" full>
          <textarea required rows={3} value={d.availability} onChange={up("availability")} style={{ ...volFieldStyle, resize: "vertical", lineHeight: 1.5 }} />
        </VolField>
        <VolField label="Why LOGIC?" hint="In a few sentences — why do you want to volunteer with LOGIC?" full>
          <textarea required rows={5} value={d.why} onChange={up("why")} 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 application"}</button>
        <span style={{ fontSize: 13, color: "var(--c-ink-soft)" }}>Applications are reviewed by the LOGIC staff.</span>
      </div>
      {err && <p style={{ margin: "12px 0 0", color: "var(--c-red)", fontSize: 14 }}>Couldn't send: {err}</p>}
    </form>);
}

function VolunteerApplyPage() {
  return (
    <React.Fragment>
      {window.TeamCrumb && <window.TeamCrumb current="Volunteer Application" />}
      <section data-screen-label="Volunteer Application" style={{ padding: "32px 0 96px" }}>
        <div className="container">
          <SectionHead eyebrow="Join the crew"
            title={<span>Volunteer with <span style={{ color: "var(--c-red)" }}>LOGIC.</span></span>}
            kicker="Tell us who you are and where you'd like to help. All applications will be reviewed, and applicants will be contacted with further details." />
          <div className="vol-apply-wrap" style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.6fr) minmax(0, 1fr)", gap: "clamp(20px, 3vw, 40px)", alignItems: "start" }}>
            <VolunteerApplyForm />
            <aside style={{ borderTop: "2px solid var(--c-red)", paddingTop: 16 }}>
              <div><Eyebrow color="var(--c-red)">Next steps</Eyebrow></div>
              <ol style={{ margin: "16px 0 0", padding: 0, listStyle: "none", display: "flex", flexDirection: "column", gap: 16 }}>
                {[["01", "Submit", "Send your application through this form."], ["02", "Review", "The LOGIC staff reviews every application."], ["03", "Contact", "Applicants will be contacted with further details."]].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>
            </aside>
          </div>
        </div>
        <style>{`@media (max-width: 900px){.vol-apply-wrap{grid-template-columns:1fr !important}} @media (max-width: 600px){.vol-apply-grid{grid-template-columns:1fr !important}}`}</style>
      </section>
    </React.Fragment>);
}
Object.assign(window, { VolunteerApplyPage, VolunteerApplyForm });
