---
import BaseLayout from "../layouts/BaseLayout.astro";
import SiteHeader from "../components/SiteHeader.astro";
import SiteFooter from "../components/SiteFooter.astro";
import { navigationItems } from "../lib/navigation";

const pageSeo = {
    title: "Participant Application",
    description:
        "Apply to join Highland Group RDA with our participant application form. Share your details, support needs, and emergency contact information online.",
    keywords:
        "Highland Group RDA participant application, RDA application form, riding for the disabled application, Highland RDA participant form",
    canonicalPath: "/participant-application",
};

const turnstileSiteKey = import.meta.env.PUBLIC_TURNSTILE_SITE_KEY ?? "";

const supportQuestions: [string, string][] = [
    ["allergies",            "Do you have any allergies we need to be aware of?"],
    ["triggers",             "Do you have any known triggers, physical, emotional or environmental?"],
    ["simple_instructions",  "Would it help if we used very simple instructions?"],
    ["learning_disability",  "Do you have a learning disability?"],
    ["neurodiverse",         "Are you neurodiverse?"],
    ["sensitive_to_crowds",  "Are you sensitive to strangers or crowds?"],
    ["sensory_sensitivities","Are you sensitive to light, temperature, noise, clothing or hats?"],
    ["anxiety_low_mood",     "Do you experience anxiety, depression or low mood?"],
    ["panic_attacks",        "Do you experience panic attacks?"],
    ["speech_difficulties",  "Do you have difficulty with speech or making yourself understood?"],
    ["communication_system", "Do you use a communication system such as Makaton, PECS or AAC?"],
    ["hearing_aid",          "Do you wear a hearing aid?"],
    ["cochlear_implant",     "Do you have a cochlear implant?"],
    ["bsl",                  "Do you use BSL to communicate?"],
    ["blind",                "Are you blind?"],
    ["partially_sighted",    "Are you partially sighted beyond what glasses or lenses correct?"],
    ["dexterity_difficulties","Do you have dexterity difficulties?"],
    ["balance_problems",     "Do you have problems with balance?"],
    ["weight_through_feet",  "Can you take weight through your feet, for example sit to stand?"],
    ["help_walking",         "Do you need any help with walking?"],
    ["steps_mounting_block", "Can you walk up a few steps, for example onto a mounting block?"],
    ["wheelchair_user",      "Are you a wheelchair user?"],
    ["walking_aids",         "Do you use any walking aids or supports?"],
    ["prosthetic_limb",      "Do you wear a prosthetic limb?"],
    ["long_term_pain",       "Do you experience long-term pain?"],
    ["breathing_stamina",    "Do you have difficulties with breathing or stamina?"],
    ["epilepsy",             "Do you have epilepsy, and is it controlled by medication?"],
];
---

<BaseLayout {...pageSeo}>
    {turnstileSiteKey && (
        <Fragment slot="head">
            <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
        </Fragment>
    )}

    <style>
        /* ── Nav ── */
        #site-nav { transition: background 0.4s ease, backdrop-filter 0.4s ease; }
        #site-nav.scrolled { background: rgba(0,0,0,0.82); backdrop-filter: blur(8px); }

        /* ── Animations ── */
        @keyframes fadeUp  { from { opacity:0; transform:translateY(14px); } to { opacity:1; transform:translateY(0); } }
        @keyframes slideIn { from { opacity:0; transform:translateX(18px); } to { opacity:1; transform:translateX(0); } }
        .anim-fade-up { animation: fadeUp 0.9s ease both; }
        .step-anim    { animation: slideIn 0.35s ease both; }

        /* ── Fields ── */
        .field-input {
            width: 100%;
            border: 1.5px solid rgba(0,0,0,0.18);
            border-radius: 6px;
            padding: 11px 14px;
            font-family: 'Public Sans', sans-serif;
            font-size: 15px; font-weight: 600;
            color: #000; background: #fff;
            outline: none;
            transition: border-color 0.2s ease, box-shadow 0.2s ease;
            appearance: none;
            box-sizing: border-box;
        }
        .field-input:focus { border-color: #7DA371; box-shadow: 0 0 0 3px rgba(125,163,113,0.18); }
        .field-input::placeholder { color: rgba(0,0,0,0.35); font-weight: 500; }
        textarea.field-input { resize: vertical; line-height: 1.6; min-height: 96px; }
        select.field-input {
            cursor: pointer;
            background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%23555' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E");
            background-repeat: no-repeat;
            background-position: right 14px center;
            padding-right: 40px;
        }

        /* ── Choice cards ── */
        .choice {
            display: flex; align-items: flex-start; gap: 12px;
            cursor: pointer; padding: 13px 15px; border-radius: 6px;
            border: 1.5px solid rgba(0,0,0,0.15); background: #fff;
            transition: border-color 0.2s ease, background 0.2s ease;
            user-select: none;
        }
        .choice:hover { border-color: #7DA371; }
        .choice.selected { border-color: #7DA371; background: rgba(125,163,113,0.07); }
        .choice-mark {
            width: 18px; height: 18px; flex-shrink: 0; margin-top: 2px;
            border: 2px solid rgba(0,0,0,0.25);
            display: flex; align-items: center; justify-content: center;
            transition: all 0.2s;
        }
        .choice-mark.radio { border-radius: 9999px; }
        .choice-mark.check { border-radius: 4px; }
        .choice.selected .choice-mark { border-color: #7DA371; background: #7DA371; }

        /* ── Buttons ── */
        .btn-primary {
            display: inline-flex; align-items: center; gap: 10px;
            background: #7DA371; color: #fff; border: none; border-radius: 9999px;
            padding: 13px 28px;
            font-family: 'Public Sans', sans-serif; font-weight: 800; font-size: 13px;
            letter-spacing: 0.06em; text-transform: uppercase;
            cursor: pointer; transition: opacity 0.2s ease;
        }
        .btn-primary:hover:not(:disabled) { opacity: 0.88; }
        .btn-primary:disabled { opacity: 0.4; cursor: not-allowed; }
        .btn-secondary {
            display: inline-flex; align-items: center; gap: 10px;
            background: transparent; color: #000;
            border: 2px solid rgba(0,0,0,0.2); border-radius: 9999px;
            padding: 11px 24px;
            font-family: 'Public Sans', sans-serif; font-weight: 800; font-size: 13px;
            letter-spacing: 0.06em; text-transform: uppercase;
            cursor: pointer; transition: border-color 0.2s ease;
        }
        .btn-secondary:hover:not(:disabled) { border-color: #7DA371; }
        .btn-secondary:disabled { opacity: 0.35; cursor: not-allowed; }

        /* ── Progress ── */
        .progress-pill {
            display: inline-flex; align-items: center; gap: 9px;
            border-radius: 9999px; padding: 8px 15px;
            font-family: 'Public Sans', sans-serif; font-weight: 700; font-size: 12px;
            letter-spacing: 0.04em; white-space: nowrap;
            cursor: default; border: 1.5px solid transparent;
            transition: all 0.25s ease;
        }
        .progress-pill.active   { background: #7DA371; color: #fff; border-color: #7DA371; }
        .progress-pill.done     { background: rgba(125,163,113,0.12); color: #7DA371; border-color: rgba(125,163,113,0.35); cursor: pointer; }
        .progress-pill.upcoming { background: transparent; color: rgba(0,0,0,0.4); border-color: rgba(0,0,0,0.12); }
        .pill-num {
            width: 20px; height: 20px; border-radius: 9999px;
            display: inline-flex; align-items: center; justify-content: center;
            font-size: 11px; font-weight: 800;
        }
        .progress-pill.active   .pill-num { background: rgba(255,255,255,0.25); color: #fff; }
        .progress-pill.done     .pill-num { background: #7DA371; color: #fff; }
        .progress-pill.upcoming .pill-num { background: rgba(0,0,0,0.08); color: rgba(0,0,0,0.4); }

        /* ── Field label ── */
        .field-label {
            font-family: 'Public Sans', sans-serif;
            font-weight: 700; font-size: 13px;
            color: rgba(0,0,0,0.7); letter-spacing: 0.04em;
            text-transform: uppercase; margin-bottom: 8px; display: block;
        }
        .field-label .req { color: #7DA371; margin-left: 3px; }
        .field-hint { margin-top: 4px; font-family: 'Public Sans', sans-serif; font-weight: 500; font-size: 13px; color: rgba(0,0,0,0.5); line-height: 1.55; }
        .field-error { font-family: 'Public Sans', sans-serif; font-weight: 600; font-size: 13px; color: #c0392b; margin-top: 6px; display: none; }
        .field-error.visible { display: block; }

        /* ── Callout ── */
        .callout {
            background: rgba(125,163,113,0.08);
            border: 1.5px solid rgba(125,163,113,0.25);
            border-radius: 7px;
            padding: 16px 20px;
            display: flex; gap: 14px; align-items: flex-start;
            margin-bottom: 28px;
        }
        .callout p {
            font-family: 'Public Sans', sans-serif; font-weight: 600;
            font-size: 14px; color: rgba(0,0,0,0.7); line-height: 1.6; margin: 0;
        }

        /* ── Section subheading ── */
        .section-sub {
            font-family: 'Merriweather', serif;
            font-weight: 700; font-size: 18px; color: #000;
            margin: 28px 0 14px;
        }

        /* ── Steps ── */
        .step-panel { display: none; }
        .step-panel.active { display: block; }

        /* ── Review ── */
        .review-row {
            border-top: 1px solid rgba(0,0,0,0.1);
            padding: 18px 0;
            display: grid;
            grid-template-columns: 160px 1fr auto;
            gap: 20px;
            align-items: flex-start;
        }
        .review-label { font-family: 'Public Sans', sans-serif; font-weight: 800; font-size: 12px; color: rgba(0,0,0,0.45); letter-spacing: 0.08em; text-transform: uppercase; padding-top: 2px; }
        .review-value { font-family: 'Public Sans', sans-serif; font-weight: 600; font-size: 14px; color: #000; line-height: 1.7; }
        .review-edit  { font-family: 'Public Sans', sans-serif; font-weight: 800; font-size: 12px; color: #7DA371; letter-spacing: 0.06em; text-transform: uppercase; text-decoration: underline; background: none; border: none; cursor: pointer; white-space: nowrap; padding-top: 2px; }

        /* ── Visually hidden (for checkbox accessibility) ── */
        .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); border: 0; }

        /* ── Success ── */
        #success-panel { display: none; }

        @media (max-width: 767px) {
            .grid-2 { grid-template-columns: 1fr !important; }
            .grid-3 { grid-template-columns: 1fr !important; }
            .grid-4 { grid-template-columns: 1fr 1fr !important; }
            .grid-height-weight { grid-template-columns: 1fr 100px !important; }
            .progress-wrap { gap: 4px !important; }
            .progress-pill { font-size: 0; padding: 8px 10px; }
            .progress-pill .pill-label { display: none; }
            .review-row { grid-template-columns: 1fr; gap: 6px; }
            .review-edit { justify-self: start; }
        }
    </style>

    <!-- Fixed nav -->
    <div id="site-nav" class="fixed top-0 left-0 right-0 z-50 px-4 sm:px-10">
        <SiteHeader navigationItems={navigationItems} theme="dark" />
    </div>

    <div class="flex flex-col min-h-screen bg-[#e2e2e2]">
        <main class="w-full">

            <!-- ── HERO ── -->
            <section class="relative w-full overflow-hidden" style="min-height: 46vh;">
                <img
                    class="absolute inset-0 w-full h-full object-cover"
                    style="object-position: 50% 38%;"
                    src="/Samantha-and-Connolly-1920.webp"
                    alt=""
                    loading="eager" fetchpriority="high" decoding="async"
                />
                <div class="absolute inset-0" style="background: linear-gradient(160deg,rgba(0,0,0,0.78) 0%,rgba(0,0,0,0.42) 60%,rgba(0,0,0,0.55) 100%);" />
                <div class="relative flex flex-col justify-end" style="min-height: 46vh; padding: 100px clamp(24px,5vw,72px) 60px;">
                    <div class="anim-fade-up" style="max-width: 680px;">
                        <p style="font-family:'Public Sans',sans-serif;font-weight:700;font-size:12px;letter-spacing:0.25em;text-transform:uppercase;color:rgba(255,255,255,0.7);margin-bottom:14px;">Take part</p>
                        <div style="width:48px;height:2px;background:#7DA371;margin-bottom:20px;"></div>
                        <h1 style="font-family:'Merriweather',serif;font-weight:900;font-size:clamp(32px,4.5vw,52px);color:#F6F1E8;line-height:1.1;margin-bottom:16px;">Apply to ride with us.</h1>
                        <p style="font-family:'Public Sans',sans-serif;font-weight:600;font-size:clamp(15px,1.5vw,18px);color:rgba(246,241,232,0.82);line-height:1.65;">Tell us a bit about yourself or your young person — we'll be in touch to chat through what's best. The form takes around ten minutes.</p>
                    </div>
                </div>
            </section>

            <!-- ── FORM SECTION ── -->
            <section style="background:#d6d6d6;padding:clamp(48px,8vw,72px) clamp(24px,5vw,72px) clamp(64px,10vw,96px);">
                <div style="max-width:960px;margin:0 auto;" id="form-root">

                    <!-- ── PROGRESS ── -->
                    <div id="progress-wrapper" style="margin-bottom:36px;">
                        <div class="progress-wrap" style="display:flex;align-items:center;gap:6px;flex-wrap:wrap;" id="progress-pills"></div>
                        <div style="height:4px;background:rgba(0,0,0,0.1);border-radius:9999px;overflow:hidden;margin-top:20px;">
                            <div id="progress-bar" style="height:100%;background:#7DA371;border-radius:9999px;transition:width 0.4s ease;width:20%;"></div>
                        </div>
                    </div>

                    <!-- ── FORM CARD ── -->
                    <div style="background:#e2e2e2;border-radius:8px;padding:clamp(28px,5vw,48px) clamp(24px,5vw,52px);">

                        <!-- SUCCESS -->
                        <div id="success-panel" style="text-align:center;padding:48px 0;">
                            <div style="width:72px;height:72px;border-radius:9999px;background:#7DA371;display:flex;align-items:center;justify-content:center;margin:0 auto 24px;">
                                <svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>
                            </div>
                            <h2 style="font-family:'Merriweather',serif;font-weight:700;font-size:clamp(22px,2.5vw,30px);color:#000;margin-bottom:14px;">Thank you, <span id="success-name">there</span>!</h2>
                            <p style="font-family:'Public Sans',sans-serif;font-weight:600;font-size:16px;color:rgba(0,0,0,0.65);line-height:1.7;max-width:480px;margin:0 auto 8px;">
                                We've received your application. One of our coaches will be in touch within a few working days to arrange a visit and talk through next steps.
                            </p>
                            <p style="font-family:'Public Sans',sans-serif;font-weight:600;font-size:15px;color:rgba(0,0,0,0.5);line-height:1.7;max-width:440px;margin:0 auto 32px;">
                                A confirmation has been sent to <strong style="color:#000;" id="success-email"></strong>.
                            </p>
                            <a href="/" style="display:inline-flex;align-items:center;gap:10px;background:#7DA371;color:#fff;border-radius:9999px;padding:13px 28px;font-family:'Public Sans',sans-serif;font-weight:800;font-size:13px;letter-spacing:0.06em;text-transform:uppercase;text-decoration:none;">Back to homepage</a>
                        </div>

                        <!-- ── STEP 0: ABOUT THE PARTICIPANT ── -->
                        <div class="step-panel active step-anim" data-step="0">
                            <h2 style="font-family:'Merriweather',serif;font-weight:700;font-size:clamp(22px,2.2vw,28px);color:#000;margin-bottom:8px;">About the participant</h2>
                            <p style="font-family:'Public Sans',sans-serif;font-weight:600;font-size:15px;color:rgba(0,0,0,0.6);line-height:1.6;margin-bottom:32px;">Tell us about the person who would like to take part — that might be you, or a child or family member you're applying for.</p>

                            <!-- Who is filling this in -->
                            <div style="margin-bottom:24px;">
                                <label class="field-label">Who is filling in this form? <span class="req">*</span></label>
                                <div class="grid-3" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:10px;margin-top:4px;">
                                    {["Participant", "Parent", "Guardian / Carer"].map((opt) => (
                                        <div class="choice" data-group="filled_by" data-val={opt}>
                                            <div class="choice-mark radio">
                                                <div class="choice-dot" style="display:none;width:7px;height:7px;border-radius:9999px;background:#fff;"></div>
                                            </div>
                                            <span style="font-family:'Public Sans',sans-serif;font-size:14px;font-weight:600;color:#000;">{opt}</span>
                                        </div>
                                    ))}
                                </div>
                                <input type="hidden" id="hid-filled-by" />
                                <p class="field-error" id="err-filled-by">Please tell us who is completing this form.</p>
                            </div>

                            <!-- Participant details -->
                            <h3 class="section-sub">Participant details</h3>
                            <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                                <div>
                                    <label class="field-label" for="f-first">First name(s) <span class="req">*</span></label>
                                    <input class="field-input" id="f-first" name="participant_first_names" type="text" placeholder="Sam" autocomplete="given-name" />
                                    <p class="field-error" id="err-first">Please enter the participant's first name.</p>
                                </div>
                                <div>
                                    <label class="field-label" for="f-last">Last name <span class="req">*</span></label>
                                    <input class="field-input" id="f-last" name="participant_last_name" type="text" placeholder="Smith" autocomplete="family-name" />
                                    <p class="field-error" id="err-last">Please enter the participant's last name.</p>
                                </div>
                                <div>
                                    <label class="field-label" for="f-prefname">Preferred name or nickname</label>
                                    <input class="field-input" id="f-prefname" name="preferred_name" type="text" placeholder="e.g. Sam" />
                                </div>
                                <div>
                                    <label class="field-label" for="f-pronouns">Preferred pronouns</label>
                                    <input class="field-input" id="f-pronouns" name="preferred_pronouns" type="text" placeholder="e.g. she/her, they/them" />
                                </div>
                                <div>
                                    <label class="field-label" for="f-dob">Date of birth <span class="req">*</span></label>
                                    <input class="field-input" id="f-dob" name="date_of_birth" type="date" />
                                    <p class="field-error" id="err-dob">Please enter a date of birth.</p>
                                </div>
                                <div>
                                    <label class="field-label" for="f-sex">Sex</label>
                                    <select class="field-input" id="f-sex" name="sex">
                                        <option value="">Select…</option>
                                        <option>Female</option>
                                        <option>Male</option>
                                        <option>I identify in another way</option>
                                        <option>Prefer not to say</option>
                                    </select>
                                </div>
                                <div style="grid-column:1/-1;">
                                    <label class="field-label" for="f-langs">If the participant is not fluent in English, which language(s) do they use every day?</label>
                                    <input class="field-input" id="f-langs" name="languages_spoken" type="text" placeholder="Optional" />
                                </div>
                                <div style="grid-column:1/-1;">
                                    <label class="field-label" for="f-addr1">Address line 1 <span class="req">*</span></label>
                                    <input class="field-input" id="f-addr1" name="address_line_1" type="text" placeholder="Street address" autocomplete="address-line1" />
                                    <p class="field-error" id="err-addr1">Please enter an address.</p>
                                </div>
                                <div style="grid-column:1/-1;">
                                    <label class="field-label" for="f-addr2">Address line 2</label>
                                    <input class="field-input" id="f-addr2" name="address_line_2" type="text" autocomplete="address-line2" />
                                </div>
                                <div>
                                    <label class="field-label" for="f-post">Postcode <span class="req">*</span></label>
                                    <input class="field-input" id="f-post" name="postcode" type="text" placeholder="IV5 7PP" autocomplete="postal-code" />
                                    <p class="field-error" id="err-post">Please enter a postcode.</p>
                                </div>
                                <div></div>
                                <div>
                                    <label class="field-label" for="f-tel">Telephone</label>
                                    <input class="field-input" id="f-tel" name="telephone" type="tel" placeholder="01234 567890" autocomplete="tel" />
                                </div>
                                <div>
                                    <label class="field-label" for="f-mobile">Mobile</label>
                                    <input class="field-input" id="f-mobile" name="mobile" type="tel" placeholder="07700 900000" autocomplete="tel-national" />
                                </div>
                                <div style="grid-column:1/-1;">
                                    <label class="field-label" for="f-email">Email address <span class="req">*</span></label>
                                    <input class="field-input" id="f-email" name="email" type="email" placeholder="you@example.com" autocomplete="email" />
                                    <p class="field-error" id="err-email">Please enter a valid email address.</p>
                                </div>
                            </div>

                            <!-- Parent / guardian section -->
                            <h3 class="section-sub" style="margin-top:36px;">Parent or legal guardian</h3>
                            <p class="field-hint" style="margin-bottom:18px;">Complete this section if you are filling in the form on behalf of the participant, or if the participant is under 18.</p>
                            <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                                <div>
                                    <label class="field-label" for="f-guardian-name">Name</label>
                                    <input class="field-input" id="f-guardian-name" name="guardian_name" type="text" autocomplete="name" />
                                </div>
                                <div>
                                    <label class="field-label" for="f-guardian-rel">Relationship to participant</label>
                                    <input class="field-input" id="f-guardian-rel" name="guardian_relationship" type="text" placeholder="e.g. Parent, carer, foster parent" />
                                </div>
                                <div style="grid-column:1/-1;">
                                    <label class="field-label" for="f-guardian-addr1">Address line 1</label>
                                    <input class="field-input" id="f-guardian-addr1" name="guardian_address_line_1" type="text" />
                                </div>
                                <div style="grid-column:1/-1;">
                                    <label class="field-label" for="f-guardian-addr2">Address line 2</label>
                                    <input class="field-input" id="f-guardian-addr2" name="guardian_address_line_2" type="text" />
                                </div>
                                <div>
                                    <label class="field-label" for="f-guardian-post">Postcode</label>
                                    <input class="field-input" id="f-guardian-post" name="guardian_postcode" type="text" />
                                </div>
                                <div></div>
                                <div>
                                    <label class="field-label" for="f-guardian-tel">Telephone</label>
                                    <input class="field-input" id="f-guardian-tel" name="guardian_telephone" type="tel" />
                                </div>
                                <div>
                                    <label class="field-label" for="f-guardian-mob">Mobile</label>
                                    <input class="field-input" id="f-guardian-mob" name="guardian_mobile" type="tel" />
                                </div>
                            </div>
                        </div>

                        <!-- ── STEP 1: HEALTH & SUPPORT ── -->
                        <div class="step-panel step-anim" data-step="1">
                            <h2 style="font-family:'Merriweather',serif;font-weight:700;font-size:clamp(22px,2.2vw,28px);color:#000;margin-bottom:8px;">Health &amp; support</h2>
                            <p style="font-family:'Public Sans',sans-serif;font-weight:600;font-size:15px;color:rgba(0,0,0,0.6);line-height:1.6;margin-bottom:24px;">These details help us plan a safe and rewarding session. There are no wrong answers — we work with a wide range of needs and abilities.</p>

                            <div class="callout">
                                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#7DA371" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="flex-shrink:0;margin-top:2px;">
                                    <rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                                </svg>
                                <p>Your information is shared only with the coaches and trustees who need it, kept securely, and never used for any other purpose. In line with the Data Protection Act 2018.</p>
                            </div>

                            <div style="margin-bottom:24px;">
                                <label class="field-label" for="f-condition">Tell us about the disability or medical condition and how it affects the participant <span class="req">*</span></label>
                                <p class="field-hint" style="margin-bottom:10px;">Include any medication or support we should know about. A short summary in your own words is fine — we don't need formal diagnoses.</p>
                                <textarea class="field-input" id="f-condition" name="condition_details" placeholder="e.g. Down's syndrome, autism, cerebral palsy — and how it affects daily life…" style="min-height:120px;"></textarea>
                                <p class="field-error" id="err-condition">Please give us a brief description of the participant's condition or support needs.</p>
                            </div>

                            <div style="margin-bottom:28px;">
                                <label class="field-label">Please tick all that apply</label>
                                <p class="field-hint" style="margin-bottom:12px;">We may contact you for more detail where needed.</p>
                                <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:8px;">
                                    {supportQuestions.map(([name, question]) => (
                                        <div class="choice checkbox-card" data-cb-name={name}>
                                            <div class="choice-mark check">
                                                <svg class="choice-tick" width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="display:none;"><path d="M10 3L4.5 8.5 2 6"/></svg>
                                            </div>
                                            <span style="font-family:'Public Sans',sans-serif;font-size:13px;font-weight:600;color:#000;line-height:1.45;">{question}</span>
                                            <input type="checkbox" class="support-cb sr-only" name={name} value="Yes" tabindex="-1" aria-hidden="true" />
                                        </div>
                                    ))}
                                </div>
                            </div>

                            <!-- Height & Weight -->
                            <div class="grid-height-weight" style="display:grid;grid-template-columns:1fr 120px 1fr 120px;gap:14px;align-items:end;">
                                <div>
                                    <label class="field-label" for="f-height">Height</label>
                                    <input class="field-input" id="f-height" name="participant_height" type="text" placeholder="e.g. 145" />
                                </div>
                                <div>
                                    <label class="field-label" for="f-height-unit">Unit</label>
                                    <select class="field-input" id="f-height-unit" name="height_unit">
                                        <option value="">—</option>
                                        <option>cm</option>
                                        <option>ft &amp; in</option>
                                    </select>
                                </div>
                                <div>
                                    <label class="field-label" for="f-weight">Weight</label>
                                    <input class="field-input" id="f-weight" name="participant_weight" type="text" placeholder="e.g. 45" />
                                </div>
                                <div>
                                    <label class="field-label" for="f-weight-unit">Unit</label>
                                    <select class="field-input" id="f-weight-unit" name="weight_unit">
                                        <option value="">—</option>
                                        <option>kg</option>
                                        <option>st &amp; lb</option>
                                    </select>
                                </div>
                            </div>
                            <p class="field-hint" style="margin-top:8px;">Height and weight are used to match the participant with a suitable pony in line with welfare guidelines.</p>
                        </div>

                        <!-- ── STEP 2: ACTIVITIES ── -->
                        <div class="step-panel step-anim" data-step="2">
                            <h2 style="font-family:'Merriweather',serif;font-weight:700;font-size:clamp(22px,2.2vw,28px);color:#000;margin-bottom:8px;">Activities</h2>
                            <p style="font-family:'Public Sans',sans-serif;font-weight:600;font-size:15px;color:rgba(0,0,0,0.6);line-height:1.6;margin-bottom:32px;">Tell us about any previous experience and your interest in competing. We'll talk through what's best for the participant when we meet.</p>

                            <div style="margin-bottom:28px;">
                                <label class="field-label">Previous experience with these activities</label>
                                <p class="field-hint" style="margin-bottom:10px;">Select all that apply.</p>
                                <div style="display:flex;gap:10px;flex-wrap:wrap;">
                                    {["Riding", "Vaulting"].map((opt) => (
                                        <div class="choice" data-group="activity_experience" data-val={opt} data-multi="true" style="flex:0 0 auto;">
                                            <div class="choice-mark check">
                                                <svg class="choice-tick" width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="display:none;"><path d="M10 3L4.5 8.5 2 6"/></svg>
                                            </div>
                                            <span style="font-family:'Public Sans',sans-serif;font-size:14px;font-weight:600;color:#000;">{opt}</span>
                                        </div>
                                    ))}
                                </div>
                            </div>

                            <div style="margin-bottom:28px;">
                                <label class="field-label">Interested in competing?</label>
                                <p class="field-hint" style="margin-bottom:10px;">Classification may not be relevant for non-ridden activity.</p>
                                <div style="display:flex;gap:10px;flex-wrap:wrap;">
                                    {["Yes", "No"].map((opt) => (
                                        <div class="choice" data-group="interested_in_competing" data-val={opt} style="flex:0 0 auto;min-width:80px;">
                                            <div class="choice-mark radio">
                                                <div class="choice-dot" style="display:none;width:7px;height:7px;border-radius:9999px;background:#fff;"></div>
                                            </div>
                                            <span style="font-family:'Public Sans',sans-serif;font-size:14px;font-weight:600;color:#000;">{opt}</span>
                                        </div>
                                    ))}
                                </div>
                                <input type="hidden" id="hid-competing" />
                            </div>

                            <div style="margin-bottom:28px;">
                                <label class="field-label">Have you been classified?</label>
                                <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:4px;">
                                    {["Yes", "No"].map((opt) => (
                                        <div class="choice" data-group="been_classified" data-val={opt} style="flex:0 0 auto;min-width:80px;">
                                            <div class="choice-mark radio">
                                                <div class="choice-dot" style="display:none;width:7px;height:7px;border-radius:9999px;background:#fff;"></div>
                                            </div>
                                            <span style="font-family:'Public Sans',sans-serif;font-size:14px;font-weight:600;color:#000;">{opt}</span>
                                        </div>
                                    ))}
                                </div>
                                <input type="hidden" id="hid-classified" />
                            </div>

                            <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                                <div>
                                    <label class="field-label" for="f-class-detail">Classification (if classified)</label>
                                    <input class="field-input" id="f-class-detail" name="classification_details" type="text" placeholder="e.g. Grade Ia" />
                                </div>
                                <div>
                                    <label class="field-label" for="f-class-date">Date classification given</label>
                                    <input class="field-input" id="f-class-date" name="classification_date" type="date" />
                                </div>
                            </div>
                        </div>

                        <!-- ── STEP 3: EMERGENCY CONTACT & CONSENT ── -->
                        <div class="step-panel step-anim" data-step="3">
                            <h2 style="font-family:'Merriweather',serif;font-weight:700;font-size:clamp(22px,2.2vw,28px);color:#000;margin-bottom:8px;">Emergency contact &amp; consent</h2>
                            <p style="font-family:'Public Sans',sans-serif;font-weight:600;font-size:15px;color:rgba(0,0,0,0.6);line-height:1.6;margin-bottom:32px;">Almost there — just an emergency contact and a few important consents.</p>

                            <h3 class="section-sub" style="margin-top:0;">Emergency contact</h3>
                            <p class="field-hint" style="margin-bottom:16px;">Someone we can reach during a session if needed. Different from the participant or guardian where possible.</p>
                            <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px;">
                                <div>
                                    <label class="field-label" for="f-emerg-name">Name and relationship <span class="req">*</span></label>
                                    <input class="field-input" id="f-emerg-name" name="emergency_contact_name" type="text" placeholder="e.g. Jane Smith (Partner)" />
                                    <p class="field-error" id="err-emerg-name">Please provide an emergency contact name and relationship.</p>
                                </div>
                                <div>
                                    <label class="field-label" for="f-emerg-phone">Phone number <span class="req">*</span></label>
                                    <input class="field-input" id="f-emerg-phone" name="emergency_contact_phone" type="tel" placeholder="07700 900000" />
                                    <p class="field-error" id="err-emerg-phone">Please provide an emergency contact phone number.</p>
                                </div>
                            </div>
                            <div class="choice checkbox-card" data-cb-name="emergency_contact_consent" style="margin-bottom:28px;">
                                <div class="choice-mark check">
                                    <svg class="choice-tick" width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="display:none;"><path d="M10 3L4.5 8.5 2 6"/></svg>
                                </div>
                                <span style="font-family:'Public Sans',sans-serif;font-size:14px;font-weight:600;color:#000;line-height:1.55;">I confirm that I have the consent of the person named above to be contacted in an emergency during RDA activities.</span>
                                <input type="checkbox" class="decl-cb sr-only" name="emergency_contact_consent" value="Yes" tabindex="-1" aria-hidden="true" />
                            </div>

                            <h3 class="section-sub">Declaration</h3>
                            <p class="field-hint" style="margin-bottom:16px;">Please read and tick all that apply. Fields marked <span style="color:#7DA371;">*</span> are required to submit.</p>
                            <div style="display:flex;flex-direction:column;gap:10px;margin-bottom:24px;">
                                <div class="choice checkbox-card" data-cb-name="declaration_confirm">
                                    <div class="choice-mark check">
                                        <svg class="choice-tick" width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="display:none;"><path d="M10 3L4.5 8.5 2 6"/></svg>
                                    </div>
                                    <span style="font-family:'Public Sans',sans-serif;font-size:14px;font-weight:600;color:#000;line-height:1.55;">I wish to join an RDA group as a participant and confirm that the information provided on this form is true and accurate to the best of my knowledge. <span style="color:#7DA371;">*</span></span>
                                    <input type="checkbox" class="decl-cb sr-only" name="declaration_confirm" value="Yes" tabindex="-1" aria-hidden="true" />
                                </div>
                                <div class="choice checkbox-card" data-cb-name="provide_medical_details">
                                    <div class="choice-mark check">
                                        <svg class="choice-tick" width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="display:none;"><path d="M10 3L4.5 8.5 2 6"/></svg>
                                    </div>
                                    <span style="font-family:'Public Sans',sans-serif;font-size:14px;font-weight:600;color:#000;line-height:1.55;">I agree to provide additional details about medical conditions if requested, and to obtain a medical report where needed.</span>
                                    <input type="checkbox" class="decl-cb sr-only" name="provide_medical_details" value="Yes" tabindex="-1" aria-hidden="true" />
                                </div>
                                <div class="choice checkbox-card" data-cb-name="notify_changes">
                                    <div class="choice-mark check">
                                        <svg class="choice-tick" width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="display:none;"><path d="M10 3L4.5 8.5 2 6"/></svg>
                                    </div>
                                    <span style="font-family:'Public Sans',sans-serif;font-size:14px;font-weight:600;color:#000;line-height:1.55;">I will notify RDA immediately of any changes to the details or information given on this form.</span>
                                    <input type="checkbox" class="decl-cb sr-only" name="notify_changes" value="Yes" tabindex="-1" aria-hidden="true" />
                                </div>
                                <div class="choice checkbox-card" data-cb-name="risk_acknowledgement">
                                    <div class="choice-mark check">
                                        <svg class="choice-tick" width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="display:none;"><path d="M10 3L4.5 8.5 2 6"/></svg>
                                    </div>
                                    <span style="font-family:'Public Sans',sans-serif;font-size:14px;font-weight:600;color:#000;line-height:1.55;">I understand that horse-related activities carry inherent risks and agree to take reasonable precautions and follow advice and instructions.</span>
                                    <input type="checkbox" class="decl-cb sr-only" name="risk_acknowledgement" value="Yes" tabindex="-1" aria-hidden="true" />
                                </div>
                                <div class="choice checkbox-card" data-cb-name="vaulting_acknowledgement">
                                    <div class="choice-mark check">
                                        <svg class="choice-tick" width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="display:none;"><path d="M10 3L4.5 8.5 2 6"/></svg>
                                    </div>
                                    <span style="font-family:'Public Sans',sans-serif;font-size:14px;font-weight:600;color:#000;line-height:1.55;">For vaulting only — I understand the specific risks involved in participating on the barrel or horse without a hat.</span>
                                    <input type="checkbox" class="decl-cb sr-only" name="vaulting_acknowledgement" value="Yes" tabindex="-1" aria-hidden="true" />
                                </div>
                            </div>
                            <p class="field-error" id="err-declaration">Please confirm the declaration above to submit your application.</p>

                            <!-- Photos consent -->
                            <div style="margin-bottom:24px;margin-top:24px;">
                                <label class="field-label">Photographs and videos consent <span class="req">*</span></label>
                                <p class="field-hint" style="margin-bottom:10px;">This covers images used for training, publicity, website, social media, newsletters, and marketing materials.</p>
                                <div style="display:flex;gap:10px;flex-wrap:wrap;">
                                    {["Yes", "No"].map((opt) => (
                                        <div class="choice" data-group="photos_consent" data-val={opt} style="flex:0 0 auto;min-width:80px;">
                                            <div class="choice-mark radio">
                                                <div class="choice-dot" style="display:none;width:7px;height:7px;border-radius:9999px;background:#fff;"></div>
                                            </div>
                                            <span style="font-family:'Public Sans',sans-serif;font-size:14px;font-weight:600;color:#000;">{opt}</span>
                                        </div>
                                    ))}
                                </div>
                                <input type="hidden" id="hid-photos" />
                                <p class="field-error" id="err-photos">Please indicate your photos and videos consent.</p>
                            </div>

                            <!-- Newsletter consent -->
                            <div class="choice checkbox-card" data-cb-name="newsletter_consent" style="margin-bottom:28px;">
                                <div class="choice-mark check">
                                    <svg class="choice-tick" width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="display:none;"><path d="M10 3L4.5 8.5 2 6"/></svg>
                                </div>
                                <span style="font-family:'Public Sans',sans-serif;font-size:14px;font-weight:600;color:#000;line-height:1.55;">I also consent to be sent RDA newsletters and updates from the group.</span>
                                <input type="checkbox" class="decl-cb sr-only" name="newsletter_consent" value="Yes" tabindex="-1" aria-hidden="true" />
                            </div>

                            <!-- Signature & date -->
                            <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:24px;">
                                <div>
                                    <label class="field-label" for="f-sig">Signature name</label>
                                    <input class="field-input" id="f-sig" name="declaration_signature" type="text" placeholder="Participant / Parent / Guardian / Carer" />
                                </div>
                                <div>
                                    <label class="field-label" for="f-date">Date</label>
                                    <input class="field-input" id="f-date" name="declaration_date" type="date" />
                                </div>
                            </div>

                            {turnstileSiteKey && (
                                <div style="margin-top:4px;">
                                    <div class="cf-turnstile" data-sitekey={turnstileSiteKey}></div>
                                </div>
                            )}

                            <p class="field-error" id="err-submit" style="margin-top:12px;"></p>
                        </div>

                        <!-- ── STEP 4: REVIEW ── -->
                        <div class="step-panel step-anim" data-step="4">
                            <h2 style="font-family:'Merriweather',serif;font-weight:700;font-size:clamp(22px,2.2vw,28px);color:#000;margin-bottom:8px;">Review your application</h2>
                            <p style="font-family:'Public Sans',sans-serif;font-weight:600;font-size:15px;color:rgba(0,0,0,0.6);line-height:1.6;margin-bottom:24px;">Take a quick look before you send — you can edit any section.</p>
                            <div id="review-content"></div>
                            <p class="field-error" id="err-submit-review" style="margin-top:12px;"></p>
                        </div>

                        <!-- ── NAV BUTTONS ── -->
                        <div id="form-nav" style="margin-top:36px;padding-top:28px;border-top:1px solid rgba(0,0,0,0.12);display:flex;justify-content:space-between;align-items:center;gap:14px;flex-wrap:wrap;">
                            <button class="btn-secondary" id="btn-back" disabled>
                                <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M13 8H3M7 4L3 8l4 4"/></svg>
                                Back
                            </button>
                            <p id="step-counter" style="font-family:'Public Sans',sans-serif;font-weight:600;font-size:13px;color:rgba(0,0,0,0.5);">Step 1 of 5</p>
                            <button class="btn-primary" id="btn-next">
                                Continue
                                <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M3 8h10M9 4l4 4-4 4"/></svg>
                            </button>
                        </div>
                    </div>

                    <p style="margin-top:20px;font-family:'Public Sans',sans-serif;font-weight:600;font-size:13px;color:rgba(0,0,0,0.5);text-align:center;line-height:1.6;" id="help-text">
                        Need help? <a href="/contact" style="text-decoration:underline;color:#7DA371;">Contact us</a> and we'll happily talk you through it.
                    </p>
                </div>
            </section>

        </main>
        <SiteFooter fullBleedOnMobile />
    </div>

    <script>
    (() => {
        const STEPS = [
            { label: 'Participant' },
            { label: 'Health & support' },
            { label: 'Activities' },
            { label: 'Consent' },
            { label: 'Review' },
        ];

        const SUPPORT_LABELS = {
            allergies:             'Allergies',
            triggers:              'Known triggers',
            simple_instructions:   'Prefers simple instructions',
            learning_disability:   'Learning disability',
            neurodiverse:          'Neurodiverse',
            sensitive_to_crowds:   'Sensitive to crowds',
            sensory_sensitivities: 'Sensory sensitivities',
            anxiety_low_mood:      'Anxiety / low mood',
            panic_attacks:         'Panic attacks',
            speech_difficulties:   'Speech difficulties',
            communication_system:  'Uses communication system',
            hearing_aid:           'Hearing aid',
            cochlear_implant:      'Cochlear implant',
            bsl:                   'Uses BSL',
            blind:                 'Blind',
            partially_sighted:     'Partially sighted',
            dexterity_difficulties:'Dexterity difficulties',
            balance_problems:      'Balance problems',
            weight_through_feet:   'Can take weight through feet',
            help_walking:          'Needs help walking',
            steps_mounting_block:  'Can use mounting block steps',
            wheelchair_user:       'Wheelchair user',
            walking_aids:          'Uses walking aids',
            prosthetic_limb:       'Prosthetic limb',
            long_term_pain:        'Long-term pain',
            breathing_stamina:     'Breathing / stamina difficulties',
            epilepsy:              'Epilepsy',
        };

        let currentStep = 0;
        const completed = new Set();

        const multiState = {
            activity_experience: [],
        };

        // ── Pill rendering ──
        function renderPills() {
            const wrap = document.getElementById('progress-pills');
            wrap.innerHTML = '';
            STEPS.forEach((s, i) => {
                const isDone   = completed.has(i);
                const isActive = i === currentStep;
                const pill = document.createElement('button');
                pill.type = 'button';
                pill.className = 'progress-pill ' + (isActive ? 'active' : isDone ? 'done' : 'upcoming');
                pill.disabled = !(isDone || isActive);
                pill.innerHTML = `
                    <span class="pill-num">${isDone
                        ? '<svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3L4.5 8.5 2 6"/></svg>'
                        : (i + 1)
                    }</span>
                    <span class="pill-label">${s.label}</span>`;
                if (isDone) pill.addEventListener('click', () => goTo(i));
                if (i < STEPS.length - 1) {
                    wrap.appendChild(pill);
                    const sep = document.createElement('div');
                    sep.style.cssText = 'width:14px;height:1.5px;background:rgba(0,0,0,0.15);flex-shrink:0;';
                    wrap.appendChild(sep);
                } else {
                    wrap.appendChild(pill);
                }
            });
            const bar = document.getElementById('progress-bar');
            bar.style.width = `${((currentStep + 1) / STEPS.length) * 100}%`;
            document.getElementById('step-counter').textContent = `Step ${currentStep + 1} of ${STEPS.length}`;
        }

        // ── Step visibility ──
        function showStep(n) {
            document.querySelectorAll('.step-panel').forEach(p => {
                p.classList.remove('active', 'step-anim');
            });
            const panel = document.querySelector(`.step-panel[data-step="${n}"]`);
            if (panel) {
                panel.classList.add('active');
                void panel.offsetWidth;
                panel.classList.add('step-anim');
            }
            document.getElementById('btn-back').disabled = n === 0;
            const btnNext = document.getElementById('btn-next');
            if (n === STEPS.length - 1) {
                btnNext.innerHTML = `Submit application <svg width="14" height="14" viewBox="0 0 12 12" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3L4.5 8.5 2 6"/></svg>`;
            } else {
                btnNext.innerHTML = `Continue <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 8h10M9 4l4 4-4 4"/></svg>`;
            }
            if (n === STEPS.length - 1) renderReview();
            document.getElementById('form-root').scrollIntoView({ behavior: 'smooth', block: 'start' });
        }

        function goTo(n) {
            currentStep = n;
            renderPills();
            showStep(n);
        }

        // ── Choice card clicks ──
        document.querySelectorAll('.choice:not(.checkbox-card)').forEach(card => {
            card.addEventListener('click', () => {
                const group = card.dataset.group;
                const cardVal = card.dataset.val;
                const multi   = card.dataset.multi === 'true';

                if (multi) {
                    const arr = multiState[group] || [];
                    const idx = arr.indexOf(cardVal);
                    if (idx === -1) arr.push(cardVal); else arr.splice(idx, 1);
                    multiState[group] = arr;
                    document.querySelectorAll(`.choice[data-group="${group}"]`).forEach(c => {
                        const sel = arr.includes(c.dataset.val);
                        c.classList.toggle('selected', sel);
                        const tick = c.querySelector('.choice-tick');
                        if (tick) tick.style.display = sel ? 'block' : 'none';
                    });
                } else {
                    document.querySelectorAll(`.choice[data-group="${group}"]`).forEach(c => {
                        c.classList.remove('selected');
                        const dot = c.querySelector('.choice-dot');
                        if (dot) dot.style.display = 'none';
                    });
                    card.classList.add('selected');
                    const dot = card.querySelector('.choice-dot');
                    if (dot) dot.style.display = 'block';

                    const hidMap = {
                        filled_by:              'hid-filled-by',
                        interested_in_competing:'hid-competing',
                        been_classified:        'hid-classified',
                        photos_consent:         'hid-photos',
                    };
                    const hid = hidMap[group];
                    if (hid) document.getElementById(hid).value = cardVal;
                }

                // Clear errors
                const errMap = {
                    filled_by:    'err-filled-by',
                    photos_consent:'err-photos',
                };
                const errId = errMap[group];
                if (errId) document.getElementById(errId)?.classList.remove('visible');
            });
        });

        // ── Checkbox card clicks (support questions + declarations) ──
        document.querySelectorAll('.checkbox-card').forEach(card => {
            card.addEventListener('click', () => {
                const cb   = card.querySelector('input[type="checkbox"]');
                if (!cb) return;
                cb.checked = !cb.checked;
                card.classList.toggle('selected', cb.checked);
                const tick = card.querySelector('.choice-tick');
                if (tick) tick.style.display = cb.checked ? 'block' : 'none';
                // Clear declaration error when any declaration ticked
                if (cb.name === 'declaration_confirm') {
                    document.getElementById('err-declaration')?.classList.remove('visible');
                }
            });
        });

        // ── Validation ──
        function showErr(id, show) {
            const el = document.getElementById(id);
            if (el) el.classList.toggle('visible', show);
            return show;
        }
        function fv(id) {
            return (document.getElementById(id)?.value || '').trim();
        }

        function validateStep(s) {
            let ok = true;
            if (s === 0) {
                if (!fv('hid-filled-by'))  { showErr('err-filled-by', true); ok = false; } else showErr('err-filled-by', false);
                if (!fv('f-first'))        { showErr('err-first', true);     ok = false; } else showErr('err-first', false);
                if (!fv('f-last'))         { showErr('err-last', true);      ok = false; } else showErr('err-last', false);
                if (!fv('f-dob'))          { showErr('err-dob', true);       ok = false; } else showErr('err-dob', false);
                if (!fv('f-addr1'))        { showErr('err-addr1', true);     ok = false; } else showErr('err-addr1', false);
                if (!fv('f-post'))         { showErr('err-post', true);      ok = false; } else showErr('err-post', false);
                const em = fv('f-email');
                if (!em || !/\S+@\S+\.\S+/.test(em)) { showErr('err-email', true); ok = false; } else showErr('err-email', false);
            }
            if (s === 1) {
                if (!fv('f-condition'))    { showErr('err-condition', true); ok = false; } else showErr('err-condition', false);
            }
            // Step 2 has no required fields
            if (s === 3) {
                if (!fv('f-emerg-name'))   { showErr('err-emerg-name', true);  ok = false; } else showErr('err-emerg-name', false);
                if (!fv('f-emerg-phone'))  { showErr('err-emerg-phone', true); ok = false; } else showErr('err-emerg-phone', false);
                const declOk = document.querySelector('input[name="declaration_confirm"]')?.checked;
                if (!declOk)               { showErr('err-declaration', true); ok = false; } else showErr('err-declaration', false);
                if (!fv('hid-photos'))     { showErr('err-photos', true);      ok = false; } else showErr('err-photos', false);
            }
            return ok;
        }

        // ── Support questions helper ──
        function getCheckedSupport() {
            const ticked = [];
            document.querySelectorAll('.support-cb:checked').forEach(cb => {
                ticked.push(SUPPORT_LABELS[cb.name] || cb.name);
            });
            return ticked.join(', ');
        }

        // ── Review rendering ──
        function reviewRow(label, value, stepIdx) {
            if (!value) return '';
            return `<div class="review-row">
                <div class="review-label">${label}</div>
                <div class="review-value">${value}</div>
                <button class="review-edit" data-goto="${stepIdx}" type="button">Edit</button>
            </div>`;
        }

        function renderReview() {
            const filledBy  = fv('hid-filled-by');
            const firstName = fv('f-first');
            const lastName  = fv('f-last');
            const prefName  = fv('f-prefname');
            const pronouns  = fv('f-pronouns');
            const dob       = fv('f-dob');
            const sex       = document.getElementById('f-sex')?.value || '';
            const addr1     = fv('f-addr1');
            const addr2     = fv('f-addr2');
            const post      = fv('f-post');
            const email     = fv('f-email');
            const tel       = fv('f-tel');
            const mobile    = fv('f-mobile');
            const condition = fv('f-condition');
            const support   = getCheckedSupport();
            const height    = fv('f-height');
            const heightUnit= document.getElementById('f-height-unit')?.value || '';
            const weight    = fv('f-weight');
            const weightUnit= document.getElementById('f-weight-unit')?.value || '';
            const activity  = (multiState.activity_experience || []).join(', ');
            const competing = fv('hid-competing');
            const classified= fv('hid-classified');
            const classDet  = fv('f-class-detail');
            const emergName = fv('f-emerg-name');
            const emergPhone= fv('f-emerg-phone');
            const photos    = fv('hid-photos');
            const guardName = fv('f-guardian-name');
            const guardRel  = fv('f-guardian-rel');

            const declTicked = [];
            document.querySelectorAll('.decl-cb:checked').forEach(cb => {
                const labels = {
                    declaration_confirm:      'Declaration of truth',
                    provide_medical_details:  'Agrees to provide medical details if needed',
                    notify_changes:           'Will notify RDA of changes',
                    risk_acknowledgement:     'Risk acknowledgement',
                    vaulting_acknowledgement: 'Vaulting risk acknowledgement',
                    emergency_contact_consent:'Emergency contact consent',
                    newsletter_consent:       'Newsletter consent',
                };
                declTicked.push('✓ ' + (labels[cb.name] || cb.name));
            });

            let participantLine = `${firstName} ${lastName}`;
            if (prefName)  participantLine += ` (${prefName})`;
            if (pronouns)  participantLine += ` · ${pronouns}`;
            if (dob)       participantLine += `<br>DOB: ${dob}`;
            if (sex)       participantLine += ` · ${sex}`;
            participantLine += `<br>${addr1}${addr2 ? ', '+addr2 : ''}, ${post}`;
            participantLine += `<br>${email}`;
            if (tel || mobile) participantLine += ` · ${tel || mobile}`;
            if (filledBy)  participantLine += `<br>Completed by: ${filledBy}`;

            let guardianLine = '';
            if (guardName) guardianLine = `${guardName}${guardRel ? ' ('+guardRel+')' : ''}`;

            let healthLine = (condition.length > 180 ? condition.slice(0, 180) + '…' : condition);
            if (support)   healthLine += `<br><em style="color:rgba(0,0,0,0.55);font-style:normal;">${support}</em>`;
            if (height)    healthLine += `<br>Height: ${height}${heightUnit ? ' '+heightUnit : ''}`;
            if (weight)    healthLine += `<br>Weight: ${weight}${weightUnit ? ' '+weightUnit : ''}`;

            let activitiesLine = '';
            if (activity)   activitiesLine += `Previous experience: ${activity}`;
            if (competing)  activitiesLine += (activitiesLine ? '<br>' : '') + `Competing: ${competing}`;
            if (classified) activitiesLine += (activitiesLine ? '<br>' : '') + `Classified: ${classified}`;
            if (classDet)   activitiesLine += (activitiesLine ? '<br>' : '') + `Classification: ${classDet}`;

            let consentLine = `${emergName} · ${emergPhone}<br>Photos consent: ${photos || '—'}`;
            if (declTicked.length) consentLine += '<br>' + declTicked.join('<br>');

            document.getElementById('review-content').innerHTML = `
                ${reviewRow('Participant', participantLine, 0)}
                ${guardianLine ? reviewRow('Guardian', guardianLine, 0) : ''}
                ${reviewRow('Health &amp; support', healthLine, 1)}
                ${activitiesLine ? reviewRow('Activities', activitiesLine, 2) : ''}
                ${reviewRow('Emergency &amp; consent', consentLine, 3)}
            `;

            document.querySelectorAll('.review-edit').forEach(btn => {
                btn.addEventListener('click', () => goTo(parseInt(btn.dataset.goto)));
            });
        }

        // ── Submit ──
        async function submitForm() {
            const btnNext = document.getElementById('btn-next');
            const errEl   = document.getElementById('err-submit-review') || document.getElementById('err-submit');
            btnNext.disabled = true;
            btnNext.textContent = 'Submitting…';
            if (errEl) errEl.classList.remove('visible');

            const body = new URLSearchParams();

            // Text / select fields
            const fieldMap = [
                ['filled_by',               'hid-filled-by'],
                ['participant_first_names',  'f-first'],
                ['participant_last_name',    'f-last'],
                ['preferred_name',           'f-prefname'],
                ['preferred_pronouns',       'f-pronouns'],
                ['date_of_birth',            'f-dob'],
                ['sex',                      'f-sex'],
                ['languages_spoken',         'f-langs'],
                ['address_line_1',           'f-addr1'],
                ['address_line_2',           'f-addr2'],
                ['postcode',                 'f-post'],
                ['telephone',                'f-tel'],
                ['mobile',                   'f-mobile'],
                ['email',                    'f-email'],
                ['guardian_name',            'f-guardian-name'],
                ['guardian_relationship',    'f-guardian-rel'],
                ['guardian_address_line_1',  'f-guardian-addr1'],
                ['guardian_address_line_2',  'f-guardian-addr2'],
                ['guardian_postcode',        'f-guardian-post'],
                ['guardian_telephone',       'f-guardian-tel'],
                ['guardian_mobile',          'f-guardian-mob'],
                ['condition_details',        'f-condition'],
                ['participant_height',       'f-height'],
                ['height_unit',              'f-height-unit'],
                ['participant_weight',       'f-weight'],
                ['weight_unit',              'f-weight-unit'],
                ['interested_in_competing',  'hid-competing'],
                ['been_classified',          'hid-classified'],
                ['classification_details',   'f-class-detail'],
                ['classification_date',      'f-class-date'],
                ['emergency_contact_name',   'f-emerg-name'],
                ['emergency_contact_phone',  'f-emerg-phone'],
                ['photos_consent',           'hid-photos'],
                ['declaration_signature',    'f-sig'],
                ['declaration_date',         'f-date'],
            ];
            fieldMap.forEach(([name, id]) => {
                const el = document.getElementById(id);
                if (el && el.value.trim()) body.append(name, el.value.trim());
            });

            // Activity experience (multi-value)
            (multiState.activity_experience || []).forEach(v => body.append('activity_experience', v));

            // Support question checkboxes
            document.querySelectorAll('.support-cb:checked').forEach(cb => {
                body.append(cb.name, 'Yes');
            });

            // Declaration + other checkboxes
            document.querySelectorAll('.decl-cb:checked').forEach(cb => {
                body.append(cb.name, 'Yes');
            });

            // Turnstile
            const tsInput = document.querySelector('[name="cf-turnstile-response"]');
            if (tsInput) body.append('cf-turnstile-response', tsInput.value);

            try {
                const res = await fetch('/api/participant-application', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                    body,
                });
                const json = await res.json().catch(() => ({}));
                if (!res.ok) {
                    throw new Error(json.details ? `${json.error} (${json.details})` : (json.error || `Error ${res.status}`));
                }
                // Success
                document.getElementById('progress-wrapper').style.display = 'none';
                document.getElementById('form-nav').style.display = 'none';
                document.getElementById('help-text').style.display = 'none';
                document.querySelectorAll('.step-panel').forEach(p => p.classList.remove('active'));
                document.getElementById('success-panel').style.display = 'block';
                document.getElementById('success-name').textContent = fv('f-first') || 'there';
                document.getElementById('success-email').textContent = fv('f-email');
                window.scrollTo({ top: 0, behavior: 'smooth' });
            } catch (err) {
                if (errEl) {
                    errEl.textContent = err instanceof Error ? err.message : 'Sorry, something went wrong. Please try again.';
                    errEl.classList.add('visible');
                }
                btnNext.disabled = false;
                btnNext.innerHTML = `Submit application <svg width="14" height="14" viewBox="0 0 12 12" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3L4.5 8.5 2 6"/></svg>`;
            }
        }

        // ── Navigation ──
        document.getElementById('btn-next').addEventListener('click', () => {
            if (currentStep === STEPS.length - 1) {
                submitForm();
                return;
            }
            if (!validateStep(currentStep)) return;
            completed.add(currentStep);
            goTo(currentStep + 1);
        });

        document.getElementById('btn-back').addEventListener('click', () => {
            if (currentStep > 0) goTo(currentStep - 1);
        });

        // ── Scroll-aware nav ──
        const nav = document.getElementById('site-nav');
        if (nav) {
            window.addEventListener('scroll', () => {
                nav.classList.toggle('scrolled', window.scrollY > 40);
            }, { passive: true });
        }

        // ── Init ──
        renderPills();
        showStep(0);
    })();
    </script>
</BaseLayout>
