---
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: "Volunteer Application",
    description:
        "Apply to volunteer with Highland Group RDA. Complete the volunteer application form with your details, experience, references, and declarations.",
    keywords:
        "Highland Group RDA volunteer application, RDA volunteer form, volunteer with horses Highlands, disabled riding charity volunteer",
    canonicalPath: "/volunteer-application",
};

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

<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; }

        /* ── 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; cursor: default; }
        .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); cursor: default; }
        .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); }
        .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; }

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

        /* ── Review table ── */
        .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; }

        /* ── 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; }
            .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% 28%;"
                    src="/Vols5-2880w-1024x768.avif"
                    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: 660px;">
                        <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;">Get involved</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;">Volunteer 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;">No horse experience needed — just kindness, reliability, and a willingness to muck in. The form takes about five 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:900px;margin:0 auto;" id="form-root">

                    <!-- Hidden group details (required by API) -->
                    <input type="hidden" id="hid-group-name"    value="Highland Group RDA" />
                    <input type="hidden" id="hid-charity-num"   value="SC007357" />
                    <input type="hidden" id="hid-contact-name"  value="Steve Byford" />
                    <input type="hidden" id="hid-contact-addr"  value="Sandycroft, Reelig, Kirkhill, IV5 7PP" />
                    <input type="hidden" id="hid-contact-email" value="info@highlandgrouprda.org.uk" />

                    <!-- ── 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:440px;margin:0 auto 8px;">
                                We've received your volunteer application. One of our coordinators will be in touch within a few working days.
                            </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 YOU ── -->
                        <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 you</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;">We just need a few basics so we can get in touch.</p>

                            <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                                <div>
                                    <label class="field-label" for="f-first">First name <span class="req">*</span></label>
                                    <input class="field-input" id="f-first" name="volunteer_first_names" type="text" placeholder="Jane" autocomplete="given-name" />
                                    <p class="field-error" id="err-first">Please enter your 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="volunteer_last_name" type="text" placeholder="Smith" autocomplete="family-name" />
                                    <p class="field-error" id="err-last">Please enter your last name.</p>
                                </div>
                                <div>
                                    <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="jane@example.com" autocomplete="email" />
                                    <p class="field-error" id="err-email">Please enter a valid email address.</p>
                                </div>
                                <div>
                                    <label class="field-label" for="f-mobile">Mobile <span class="req">*</span></label>
                                    <input class="field-input" id="f-mobile" name="mobile" type="tel" placeholder="07123 456789" autocomplete="tel" />
                                    <p class="field-error" id="err-mobile">Please enter a phone number.</p>
                                </div>
                            </div>

                            <div style="margin-top:4px;">
                                <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 and number" autocomplete="address-line1" />
                                <p class="field-error" id="err-addr1">Please enter your address.</p>
                            </div>
                            <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:16px;">
                                <div>
                                    <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 your postcode.</p>
                                </div>
                            </div>

                            <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:16px;">
                                <div>
                                    <label class="field-label" for="f-dob">Date of birth</label>
                                    <input class="field-input" id="f-dob" name="date_of_birth" type="date" />
                                </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>

                            <div style="margin-top:20px;">
                                <label class="field-label">Age range <span class="req">*</span></label>
                                <p class="field-hint" style="margin-bottom:10px;">Volunteers must be 14 or over. Under-18s need a parent or guardian to consent.</p>
                                <div class="grid-4" style="display:grid;grid-template-columns:repeat(4,1fr);gap:10px;">
                                    {["Under 18", "18–25", "26–50", "51+"].map(opt => (
                                        <div class="choice" data-group="age_range" 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>
                                            <p style="font-family:'Public Sans',sans-serif;font-weight:700;font-size:14px;color:#000;">{opt}</p>
                                        </div>
                                    ))}
                                </div>
                                <input type="hidden" id="hid-age" name="age_range" />
                                <p class="field-error" id="err-age">Please select an age range.</p>
                            </div>

                            <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-top:20px;">
                                <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" />
                                </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>
                        </div>

                        <!-- ── STEP 1: AVAILABILITY ── -->
                        <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;">When can you help?</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;">Our sessions run Tuesday to Friday mornings. Regular help is wonderful, but flexible is fine too.</p>

                            <div style="margin-bottom:24px;">
                                <label class="field-label">Which mornings could you help? <span class="req">*</span></label>
                                <p class="field-hint" style="margin-bottom:10px;">Tick all that could potentially work for you.</p>
                                <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                                    {["Tuesday", "Wednesday", "Thursday", "Friday"].map(day => (
                                        <div class="choice" data-group="days" data-val={day} data-multi="true">
                                            <div class="choice-mark check">
                                                <svg class="choice-tick" style="display:none;" width="11" height="11" 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>
                                            </div>
                                            <p style="font-family:'Public Sans',sans-serif;font-weight:700;font-size:14px;color:#000;">{day} morning</p>
                                        </div>
                                    ))}
                                </div>
                                <p class="field-error" id="err-days">Please pick at least one morning.</p>
                            </div>

                            <div style="margin-bottom:24px;">
                                <label class="field-label">How often could you help? <span class="req">*</span></label>
                                <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                                    {[
                                        {id:"weekly",     label:"Weekly — same morning each week"},
                                        {id:"fortnight",  label:"Fortnightly"},
                                        {id:"monthly",    label:"Monthly"},
                                        {id:"flexible",   label:"Flexible — when I can"},
                                        {id:"school-hol", label:"School holidays only"},
                                    ].map(c => (
                                        <div class="choice" data-group="volunteer_commitment" data-val={c.id}>
                                            <div class="choice-mark radio"><div class="choice-dot" style="display:none;width:7px;height:7px;border-radius:9999px;background:#fff;"></div></div>
                                            <p style="font-family:'Public Sans',sans-serif;font-weight:700;font-size:14px;color:#000;">{c.label}</p>
                                        </div>
                                    ))}
                                </div>
                                <input type="hidden" id="hid-commitment" name="volunteer_commitment" />
                                <p class="field-error" id="err-commitment">Please choose how often you can help.</p>
                            </div>

                            <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                                <div>
                                    <label class="field-label" for="f-start">Earliest start date</label>
                                    <input class="field-input" id="f-start" name="volunteer_start_date" type="date" />
                                </div>
                                <div>
                                    <label class="field-label">Do you have your own transport?</label>
                                    <div style="display:flex;gap:10px;margin-top:2px;">
                                        {["Yes","No","Sometimes"].map(t => (
                                            <div class="choice" data-group="volunteer_transport" data-val={t} style="flex:1;">
                                                <div class="choice-mark radio"><div class="choice-dot" style="display:none;width:7px;height:7px;border-radius:9999px;background:#fff;"></div></div>
                                                <p style="font-family:'Public Sans',sans-serif;font-weight:700;font-size:14px;color:#000;">{t}</p>
                                            </div>
                                        ))}
                                    </div>
                                    <input type="hidden" name="volunteer_transport" id="hid-transport" />
                                </div>
                            </div>
                        </div>

                        <!-- ── STEP 2: ROLES & EXPERIENCE ── -->
                        <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;">What would you like to do?</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 where you'd like to help — we match everyone to roles where they'll thrive. Full training is provided for every role.</p>

                            <div style="margin-bottom:24px;">
                                <label class="field-label">Volunteer roles <span class="req">*</span></label>
                                <p class="field-hint" style="margin-bottom:10px;">Pick all that interest you.</p>
                                <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                                    {[
                                        {id:"sidewalker",  label:"Side walker",      desc:"Walk alongside the rider to provide support during sessions."},
                                        {id:"leader",      label:"Horse leader",     desc:"Lead the pony safely around the arena."},
                                        {id:"groomer",     label:"Groomer",          desc:"Help prepare ponies before and after sessions."},
                                        {id:"fundraiser",  label:"Fundraiser",       desc:"Help organise events and fundraising campaigns."},
                                        {id:"maintenance", label:"Maintenance",      desc:"General upkeep, fencing, painting, odd jobs."},
                                        {id:"admin",       label:"Admin / comms",    desc:"Communications, social media, admin tasks."},
                                        {id:"undecided",   label:"Not sure yet",     desc:"Happy to be matched to where help is most needed."},
                                    ].map(r => (
                                        <div class="choice" data-group="volunteer_roles" data-val={r.id} data-multi="true">
                                            <div class="choice-mark check">
                                                <svg class="choice-tick" style="display:none;" width="11" height="11" 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>
                                            </div>
                                            <div>
                                                <p style="font-family:'Public Sans',sans-serif;font-weight:700;font-size:14px;color:#000;line-height:1.3;">{r.label}</p>
                                                <p style="margin-top:3px;font-family:'Public Sans',sans-serif;font-weight:500;font-size:13px;color:rgba(0,0,0,0.55);line-height:1.5;">{r.desc}</p>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                                <p class="field-error" id="err-roles">Please pick at least one role (or "Not sure yet").</p>
                            </div>

                            <div style="margin-bottom:24px;">
                                <label class="field-label">Experience with horses <span class="req">*</span></label>
                                <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:10px;">
                                    {[
                                        {id:"none",         label:"No experience",   desc:"I have never worked with or around horses."},
                                        {id:"little",       label:"A little",        desc:"Some riding lessons or stable visits."},
                                        {id:"experienced",  label:"Experienced",     desc:"Comfortable around horses, regular riding or stable work."},
                                        {id:"professional", label:"Professional",    desc:"Equestrian background, coaching, or competing."},
                                    ].map(e => (
                                        <div class="choice" data-group="equine_experience" data-val={e.id}>
                                            <div class="choice-mark radio"><div class="choice-dot" style="display:none;width:7px;height:7px;border-radius:9999px;background:#fff;"></div></div>
                                            <div>
                                                <p style="font-family:'Public Sans',sans-serif;font-weight:700;font-size:14px;color:#000;line-height:1.3;">{e.label}</p>
                                                <p style="margin-top:3px;font-family:'Public Sans',sans-serif;font-weight:500;font-size:13px;color:rgba(0,0,0,0.55);line-height:1.5;">{e.desc}</p>
                                            </div>
                                        </div>
                                    ))}
                                </div>
                                <input type="hidden" id="hid-horseexp" name="equine_experience" />
                                <p class="field-error" id="err-horseexp">Please tell us your horse experience.</p>
                            </div>

                            <div style="margin-bottom:20px;">
                                <label class="field-label" for="f-disability-exp">Experience working with people with disabilities</label>
                                <textarea class="field-input" id="f-disability-exp" name="disability_experience" placeholder="Optional — share any relevant experience."></textarea>
                            </div>
                            <div style="margin-bottom:20px;">
                                <label class="field-label" for="f-skills">Skills or qualifications that may help</label>
                                <textarea class="field-input" id="f-skills" name="skills_qualifications" placeholder="Optional — first aid, coaching, administration, etc."></textarea>
                            </div>
                            <div style="margin-bottom:20px;">
                                <label class="field-label" for="f-motivation">Why would you like to volunteer with us?</label>
                                <textarea class="field-input" id="f-motivation" name="volunteer_motivation" placeholder="Optional — tell us a bit about what drew you to RDA."></textarea>
                            </div>
                            <div>
                                <label class="field-label" for="f-considerations">Any considerations we should know about?</label>
                                <p class="field-hint" style="margin-bottom:8px;">Disabilities, health conditions, language preferences — anything that helps us support you well.</p>
                                <textarea class="field-input" id="f-considerations" name="placement_considerations" placeholder="Optional — share whatever you're comfortable with."></textarea>
                            </div>
                        </div>

                        <!-- ── STEP 3: SAFEGUARDING ── -->
                        <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;">Safeguarding</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;">Because we work with vulnerable people, we ask all volunteers for emergency contact details and two references. We also ask you to join the PVG scheme — we help you with the paperwork.</p>

                            <div style="background:rgba(125,163,113,0.08);border:1.5px solid rgba(125,163,113,0.25);border-radius:7px;padding:18px 22px;margin-bottom:32px;display:flex;gap:14px;align-items:flex-start;">
                                <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;" aria-hidden="true">
                                    <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/>
                                </svg>
                                <p style="font-family:'Public Sans',sans-serif;font-weight:600;font-size:14px;color:rgba(0,0,0,0.7);line-height:1.6;">We'll guide you through the PVG application as part of your induction. There is no cost to you — RDA covers the fee.</p>
                            </div>

                            <h3 style="font-family:'Merriweather',serif;font-weight:700;font-size:18px;color:#000;margin-bottom:16px;">Emergency contact</h3>
                            <div class="grid-3" style="display:grid;grid-template-columns:1fr 1fr 1fr;gap:16px;margin-bottom:32px;">
                                <div>
                                    <label class="field-label" for="f-emerg-name">Name <span class="req">*</span></label>
                                    <input class="field-input" id="f-emerg-name" name="emergency_contact_name" type="text" />
                                    <p class="field-error" id="err-emerg-name">Required.</p>
                                </div>
                                <div>
                                    <label class="field-label" for="f-emerg-rel">Relationship <span class="req">*</span></label>
                                    <input class="field-input" id="f-emerg-rel" name="emergency_contact_relationship" type="text" placeholder="Partner, parent…" />
                                    <p class="field-error" id="err-emerg-rel">Required.</p>
                                </div>
                                <div>
                                    <label class="field-label" for="f-emerg-phone">Phone <span class="req">*</span></label>
                                    <input class="field-input" id="f-emerg-phone" name="emergency_contact_phone" type="tel" />
                                    <p class="field-error" id="err-emerg-phone">Required.</p>
                                </div>
                            </div>

                            <h3 style="font-family:'Merriweather',serif;font-weight:700;font-size:18px;color:#000;margin-bottom:6px;">References</h3>
                            <p style="font-family:'Public Sans',sans-serif;font-weight:500;font-size:14px;color:rgba(0,0,0,0.55);margin-bottom:18px;line-height:1.6;">Two people who have known you for at least two years and are not family. Employers, teachers, or neighbours are all fine.</p>

                            {[1,2].map(n => (
                                <div style="background:rgba(0,0,0,0.05);border-radius:7px;padding:18px 22px 8px;margin-bottom:14px;">
                                    <p style="font-family:'Public Sans',sans-serif;font-weight:800;font-size:12px;color:rgba(0,0,0,0.5);letter-spacing:0.08em;text-transform:uppercase;margin-bottom:14px;">Reference {n}</p>
                                    <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                                        <div>
                                            <label class="field-label" for={`f-ref${n}-name`}>Name <span class="req">*</span></label>
                                            <input class="field-input" id={`f-ref${n}-name`} name={`reference_${n}_name`} type="text" />
                                            <p class="field-error" id={`err-ref${n}-name`}>Required.</p>
                                        </div>
                                        <div>
                                            <label class="field-label" for={`f-ref${n}-rel`}>How they know you <span class="req">*</span></label>
                                            <input class="field-input" id={`f-ref${n}-rel`} name={`reference_${n}_address`} type="text" placeholder="Employer, teacher, neighbour…" />
                                            <p class="field-error" id={`err-ref${n}-rel`}>Required.</p>
                                        </div>
                                        <div>
                                            <label class="field-label" for={`f-ref${n}-email`}>Email <span class="req">*</span></label>
                                            <input class="field-input" id={`f-ref${n}-email`} name={`reference_${n}_email`} type="email" />
                                            <p class="field-error" id={`err-ref${n}-email`}>Valid email required.</p>
                                        </div>
                                        <div>
                                            <label class="field-label" for={`f-ref${n}-phone`}>Phone (optional)</label>
                                            <input class="field-input" id={`f-ref${n}-phone`} name={`reference_${n}_phone`} type="tel" />
                                        </div>
                                    </div>
                                </div>
                            ))}

                            <div style="margin-top:24px;display:flex;flex-direction:column;gap:12px;">
                                <div class="choice" data-group="declaration_truth" data-val="Yes" data-multi="true" id="chk-declaration">
                                    <div class="choice-mark check"><svg class="choice-tick" style="display:none;" width="11" height="11" 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></div>
                                    <div><p style="font-family:'Public Sans',sans-serif;font-weight:700;font-size:14px;color:#000;line-height:1.4;">I wish to apply to join an RDA Group as a volunteer, and confirm that all details given are true and accurate to the best of my knowledge. <span style="color:#7DA371;">*</span></p></div>
                                </div>
                                <div class="choice" data-group="disclosure_consent" data-val="Yes" data-multi="true">
                                    <div class="choice-mark check"><svg class="choice-tick" style="display:none;" width="11" height="11" 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></div>
                                    <p style="font-family:'Public Sans',sans-serif;font-weight:700;font-size:14px;color:#000;line-height:1.4;">I consent to an enhanced disclosure / PVG check being made and will abide by the group's safeguarding policies.</p>
                                </div>
                                <div class="choice" data-group="declaration_risk" data-val="Yes" data-multi="true">
                                    <div class="choice-mark check"><svg class="choice-tick" style="display:none;" width="11" height="11" 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></div>
                                    <p style="font-family:'Public Sans',sans-serif;font-weight:700;font-size:14px;color:#000;line-height:1.4;">I recognise this activity involves risk and will take all reasonable precautions and follow advice given at all times.</p>
                                </div>
                                <div class="choice" data-group="data_consent" data-val="Yes" data-multi="true">
                                    <div class="choice-mark check"><svg class="choice-tick" style="display:none;" width="11" height="11" 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></div>
                                    <p style="font-family:'Public Sans',sans-serif;font-weight:700;font-size:14px;color:#000;line-height:1.4;">I consent to Highland Group RDA storing my details for the purposes of this application. <span style="color:#7DA371;">*</span></p>
                                </div>
                                <p class="field-error" id="err-consents">Please tick the required declarations above.</p>
                            </div>

                            <div style="margin-top:24px;">
                                <label class="field-label">Photos and videos consent <span class="req">*</span></label>
                                <div style="display:flex;gap:10px;margin-top:2px;">
                                    {["Yes","No"].map(opt => (
                                        <div class="choice" data-group="photos_consent" data-val={opt} style="flex:1;">
                                            <div class="choice-mark radio"><div class="choice-dot" style="display:none;width:7px;height:7px;border-radius:9999px;background:#fff;"></div></div>
                                            <p style="font-family:'Public Sans',sans-serif;font-weight:700;font-size:14px;color:#000;">{opt}</p>
                                        </div>
                                    ))}
                                </div>
                                <input type="hidden" id="hid-photos" name="photos_consent" />
                                <p class="field-error" id="err-photos">Please indicate your photos and videos consent.</p>
                            </div>

                            {turnstileSiteKey && (
                                <div style="margin-top:24px;">
                                    <div class="cf-turnstile" data-sitekey={turnstileSiteKey}></div>
                                </div>
                            )}
                        </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;">A quick check before you send — you can edit any section.</p>
                            <div id="review-content"></div>
                            <p class="field-error" id="err-submit" 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: 'About you' },
            { label: 'Availability' },
            { label: 'Roles & experience' },
            { label: 'Safeguarding' },
            { label: 'Review' },
        ];

        const ROLE_LABELS = {
            sidewalker: 'Side walker', leader: 'Horse leader', groomer: 'Groomer',
            fundraiser: 'Fundraiser', maintenance: 'Maintenance', admin: 'Admin / comms', undecided: 'Not sure yet',
        };
        const COMMITMENT_LABELS = {
            weekly: 'Weekly', fortnight: 'Fortnightly', monthly: 'Monthly',
            flexible: 'Flexible — when I can', 'school-hol': 'School holidays only',
        };
        const HORSE_EXP_LABELS = {
            none: 'No experience', little: 'A little', experienced: 'Experienced', professional: 'Professional',
        };

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

        // Multi-value state (for checkboxes)
        const multiState = {
            days: [],
            volunteer_roles: [],
            declaration_truth: [],
            disclosure_consent: [],
            declaration_risk: [],
            data_consent: [],
        };

        // ── 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));
                // Add separator
                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);
                }
            });
            // Progress bar
            const bar = document.getElementById('progress-bar');
            bar.style.width = `${((currentStep + 1) / STEPS.length) * 100}%`;
            // Step counter
            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');
                p.classList.remove('step-anim');
            });
            const panel = document.querySelector(`.step-panel[data-step="${n}"]`);
            if (panel) {
                panel.classList.add('active');
                void panel.offsetWidth; // reflow to trigger animation
                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 cards ──
        document.querySelectorAll('.choice').forEach(card => {
            card.addEventListener('click', () => {
                const group = card.dataset.group;
                const val   = card.dataset.val;
                const multi = card.dataset.multi === 'true';

                if (multi) {
                    // Toggle in multiState array
                    const arr = multiState[group] || [];
                    const idx = arr.indexOf(val);
                    if (idx === -1) arr.push(val); else arr.splice(idx, 1);
                    multiState[group] = arr;
                    // Update UI for all cards in group
                    document.querySelectorAll(`.choice[data-group="${group}"]`).forEach(c => {
                        const isSelected = arr.includes(c.dataset.val);
                        c.classList.toggle('selected', isSelected);
                        const tick = c.querySelector('.choice-tick');
                        if (tick) tick.style.display = isSelected ? 'block' : 'none';
                    });
                } else {
                    // Radio: deselect all in group
                    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';
                    // Update hidden input
                    const hidden = document.getElementById('hid-' + {
                        age_range: 'age',
                        volunteer_commitment: 'commitment',
                        equine_experience: 'horseexp',
                        volunteer_transport: 'transport',
                        photos_consent: 'photos',
                    }[group]);
                    if (hidden) hidden.value = val;
                    // Also handle transport (two hidden inputs with same name)
                    if (group === 'volunteer_transport') {
                        document.getElementById('hid-transport').value = val;
                    }
                }
                // Clear error
                const errMap = {
                    age_range: 'err-age', days: 'err-days',
                    volunteer_commitment: 'err-commitment', volunteer_roles: 'err-roles',
                    equine_experience: 'err-horseexp', photos_consent: 'err-photos',
                    declaration_truth: 'err-consents', data_consent: 'err-consents',
                };
                const errId = errMap[group];
                if (errId) document.getElementById(errId)?.classList.remove('visible');
            });
        });

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

        function val(id) {
            return (document.getElementById(id)?.value || '').trim();
        }

        function validateStep(s) {
            let ok = true;
            if (s === 0) {
                if (!val('f-first'))  { showErr('err-first', true);  ok = false; } else showErr('err-first', false);
                if (!val('f-last'))   { showErr('err-last', true);   ok = false; } else showErr('err-last', false);
                const email = val('f-email');
                if (!email || !/\S+@\S+\.\S+/.test(email)) { showErr('err-email', true); ok = false; } else showErr('err-email', false);
                if (!val('f-mobile')) { showErr('err-mobile', true); ok = false; } else showErr('err-mobile', false);
                if (!val('f-addr1'))  { showErr('err-addr1', true);  ok = false; } else showErr('err-addr1', false);
                if (!val('f-post'))   { showErr('err-post', true);   ok = false; } else showErr('err-post', false);
                if (!document.getElementById('hid-age').value) { showErr('err-age', true); ok = false; } else showErr('err-age', false);
            }
            if (s === 1) {
                if (!multiState.days.length)      { showErr('err-days', true);       ok = false; } else showErr('err-days', false);
                if (!val('hid-commitment'))        { showErr('err-commitment', true); ok = false; } else showErr('err-commitment', false);
            }
            if (s === 2) {
                if (!multiState.volunteer_roles.length) { showErr('err-roles', true);    ok = false; } else showErr('err-roles', false);
                if (!val('hid-horseexp'))               { showErr('err-horseexp', true); ok = false; } else showErr('err-horseexp', false);
            }
            if (s === 3) {
                if (!val('f-emerg-name'))  { showErr('err-emerg-name', true);  ok = false; } else showErr('err-emerg-name', false);
                if (!val('f-emerg-rel'))   { showErr('err-emerg-rel', true);   ok = false; } else showErr('err-emerg-rel', false);
                if (!val('f-emerg-phone')) { showErr('err-emerg-phone', true); ok = false; } else showErr('err-emerg-phone', false);
                [1,2].forEach(n => {
                    if (!val(`f-ref${n}-name`))  { showErr(`err-ref${n}-name`, true);  ok = false; } else showErr(`err-ref${n}-name`, false);
                    if (!val(`f-ref${n}-rel`))   { showErr(`err-ref${n}-rel`, true);   ok = false; } else showErr(`err-ref${n}-rel`, false);
                    const re = (document.getElementById(`f-ref${n}-email`)?.value || '').trim();
                    if (!re || !/\S+@\S+\.\S+/.test(re)) { showErr(`err-ref${n}-email`, true); ok = false; } else showErr(`err-ref${n}-email`, false);
                });
                const consentsOk = multiState.declaration_truth.includes('Yes') && multiState.data_consent.includes('Yes');
                if (!consentsOk) { showErr('err-consents', true); ok = false; } else showErr('err-consents', false);
                if (!val('hid-photos')) { showErr('err-photos', true); ok = false; } else showErr('err-photos', false);
            }
            return ok;
        }

        // ── Review rendering ──
        function reviewRow(label, value, stepIndex) {
            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="${stepIndex}" type="button">Edit</button>
            </div>`;
        }

        function renderReview() {
            const roleLabels = (multiState.volunteer_roles || []).map(r => ROLE_LABELS[r] || r).join(', ');
            const daysList   = (multiState.days || []).join(', ');
            const declaredItems = [
                multiState.declaration_truth.includes('Yes') ? '✓ Declaration of truth' : '',
                multiState.disclosure_consent.includes('Yes') ? '✓ PVG / disclosure consent' : '',
                multiState.declaration_risk.includes('Yes') ? '✓ Risk acknowledgement' : '',
                multiState.data_consent.includes('Yes') ? '✓ Data storage consent' : '',
            ].filter(Boolean).join('<br>');

            document.getElementById('review-content').innerHTML = `
                ${reviewRow('About you', `${val('f-first')} ${val('f-last')}${val('f-prefname') ? ' (' + val('f-prefname') + ')' : ''}<br>${val('f-email')}<br>${val('f-mobile')}<br>${val('f-addr1')}${val('f-addr2') ? ', '+val('f-addr2') : ''}, ${val('f-post')}<br>Age: ${document.getElementById('hid-age').value}`, 0)}
                ${reviewRow('Availability', `Days: ${daysList || '—'}<br>Frequency: ${COMMITMENT_LABELS[val('hid-commitment')] || '—'}${val('f-start') ? '<br>Earliest start: '+val('f-start') : ''}${val('hid-transport') ? '<br>Transport: '+val('hid-transport') : ''}`, 1)}
                ${reviewRow('Roles & experience', `Roles: ${roleLabels || '—'}<br>Horse experience: ${HORSE_EXP_LABELS[val('hid-horseexp')] || '—'}${val('f-motivation') ? '<br>Motivation: '+val('f-motivation') : ''}`, 2)}
                ${reviewRow('Emergency contact', `${val('f-emerg-name')} (${val('f-emerg-rel')}) · ${val('f-emerg-phone')}`, 3)}
                ${reviewRow('Reference 1', `${val('f-ref1-name')} — ${val('f-ref1-rel')} · ${val('f-ref1-email')}`, 3)}
                ${reviewRow('Reference 2', `${val('f-ref2-name')} — ${val('f-ref2-rel')} · ${val('f-ref2-email')}`, 3)}
                ${reviewRow('Declarations', declaredItems, 3)}
                ${reviewRow('Photos consent', val('hid-photos'), 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 errSubmit = document.getElementById('err-submit');
            btnNext.disabled = true;
            btnNext.textContent = 'Submitting…';
            errSubmit.classList.remove('visible');

            const body = new URLSearchParams();

            // Group details
            body.append('group_name',          'Highland Group RDA');
            body.append('charity_number',       'SC007357');
            body.append('group_contact_name',   'Steve Byford');
            body.append('group_contact_address','Sandycroft, Reelig, Kirkhill, IV5 7PP');
            body.append('group_contact_email',  'info@highlandgrouprda.org.uk');

            // All named inputs
            const fieldIds = [
                ['volunteer_first_names', 'f-first'],
                ['volunteer_last_name',   'f-last'],
                ['preferred_name',        'f-prefname'],
                ['preferred_pronouns',    'f-pronouns'],
                ['date_of_birth',         'f-dob'],
                ['sex',                   'f-sex'],
                ['address_line_1',        'f-addr1'],
                ['address_line_2',        'f-addr2'],
                ['postcode',              'f-post'],
                ['mobile',                'f-mobile'],
                ['email',                 'f-email'],
                ['age_range',             'hid-age'],
                ['volunteer_commitment',  'hid-commitment'],
                ['volunteer_start_date',  'f-start'],
                ['volunteer_transport',   'hid-transport'],
                ['equine_experience',     'hid-horseexp'],
                ['disability_experience', 'f-disability-exp'],
                ['skills_qualifications', 'f-skills'],
                ['volunteer_motivation',  'f-motivation'],
                ['placement_considerations','f-considerations'],
                ['emergency_contact_name',        'f-emerg-name'],
                ['emergency_contact_relationship','f-emerg-rel'],
                ['emergency_contact_phone',       'f-emerg-phone'],
                ['reference_1_name',  'f-ref1-name'],
                ['reference_1_address','f-ref1-rel'],
                ['reference_1_email', 'f-ref1-email'],
                ['reference_1_phone', 'f-ref1-phone'],
                ['reference_2_name',  'f-ref2-name'],
                ['reference_2_address','f-ref2-rel'],
                ['reference_2_email', 'f-ref2-email'],
                ['reference_2_phone', 'f-ref2-phone'],
                ['photos_consent',    'hid-photos'],
            ];

            fieldIds.forEach(([name, id]) => {
                const el = document.getElementById(id);
                if (el && el.value.trim()) body.append(name, el.value.trim());
            });

            // Multi-value fields
            (multiState.days || []).forEach(d => body.append('volunteer_days', d));
            (multiState.volunteer_roles || []).forEach(r => body.append('volunteer_roles', ROLE_LABELS[r] || r));
            if (multiState.declaration_truth.includes('Yes'))   body.append('declaration_truth', 'Yes');
            if (multiState.disclosure_consent.includes('Yes'))  body.append('disclosure_consent', 'Yes');
            if (multiState.declaration_risk.includes('Yes'))    body.append('declaration_risk', 'Yes');
            if (multiState.data_consent.includes('Yes'))        body.append('data_consent', '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/volunteer-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}`));
                }
                // Show 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 = val('f-first') || 'there';
                document.getElementById('success-email').textContent = val('f-email');
                window.scrollTo({ top: 0, behavior: 'smooth' });
            } catch (err) {
                errSubmit.textContent = err instanceof Error ? err.message : 'Sorry, something went wrong. Please try again.';
                errSubmit.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 buttons ──
        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 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>
