/* Coaching staff application — #coach-apply */
async function submitCoachApplication(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: `Coaching staff application — ${d.name}`,
      from_name: "London LOGIC Basketball — Coaching Application",
      replyto: d.email,
      "Name": d.name, "Age": d.age, "Email": d.email, "Phone": d.phone,
      "Level of education": d.education,
      "Basketball / coaching experience": d.experience,
      "Why I'd be a valuable member of the LOGIC staff": d.why,
    }),
  });
  const json = await res.json().catch(() => ({}));
  if (!res.ok || !json.success) throw new Error(json.message || `Submission failed (${res.status})`);
}

const COACH_EDU = ["", "High school (in progress)", "High school diploma", "College (in progress)", "College diploma", "University (in progress)", "Bachelor's degree", "Graduate degree", "Other"];
const coachFieldStyle = { 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 CoachField({ label, hint, full, children }) {
  return (
    <label 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}
    </label>);
}

function CoachApplyForm({ compact }) {
  const [d, setD] = React.useState({ name: "", age: "", email: "", phone: "", education: "", experience: "", 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 ready = d.name.trim() && d.age && d.email.includes("@") && d.education && d.experience.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 submitCoachApplication(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="coach-apply-grid" style={{ display: "grid", gridTemplateColumns: compact ? "1fr" : "2fr 1fr", gap: 16 }}>
        <CoachField label="Full name"><input required value={d.name} onChange={up("name")} autoComplete="name" style={coachFieldStyle} /></CoachField>
        <CoachField label="Age"><input required type="number" min="13" max="99" inputMode="numeric" value={d.age} onChange={up("age")} style={coachFieldStyle} /></CoachField>
        <CoachField label="Email"><input required type="email" value={d.email} onChange={up("email")} autoComplete="email" style={coachFieldStyle} /></CoachField>
        <CoachField label="Phone (optional)"><input type="tel" value={d.phone} onChange={up("phone")} autoComplete="tel" style={coachFieldStyle} /></CoachField>
        <CoachField label="Level of education" full>
          <select required value={d.education} onChange={up("education")} style={coachFieldStyle}>
            {COACH_EDU.map((o) => <option key={o} value={o}>{o || "Select…"}</option>)}
          </select>
        </CoachField>
        <CoachField label="Basketball / coaching experience" hint="Teams played for, levels coached, camps, clinics, certifications." full>
          <textarea required rows={5} value={d.experience} onChange={up("experience")} style={{ ...coachFieldStyle, resize: "vertical", lineHeight: 1.5 }} />
        </CoachField>
        <CoachField label="Why LOGIC?" hint="In a few sentences — why would you be a valuable member of the LOGIC coaching staff?" full>
          <textarea required rows={5} value={d.why} onChange={up("why")} style={{ ...coachFieldStyle, resize: "vertical", lineHeight: 1.5 }} />
        </CoachField>
      </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 CoachApplyPage() {
  return (
    <section data-screen-label="Coach Application" style={{ padding: "60px 0 96px" }}>
      <div className="container">
        <SectionHead eyebrow="Join the staff"
          title={<span>Coach with <span style={{ color: "var(--c-red)" }}>LOGIC.</span></span>}
          kicker="Tell us who you are and how you've been around the game. All applications will be reviewed, and applicants will be contacted with further details." />
        <div className="coach-apply-wrap" style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.6fr) minmax(0, 1fr)", gap: "clamp(20px, 3vw, 40px)", alignItems: "start" }}>
          <CoachApplyForm />
          <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){.coach-apply-wrap{grid-template-columns:1fr !important}} @media (max-width: 600px){.coach-apply-grid{grid-template-columns:1fr !important}}`}</style>
    </section>);
}
Object.assign(window, { CoachApplyPage, CoachApplyForm });
