---
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 Reference Form",
    description:
        "Volunteer reference form for Highland Group RDA. Complete this form if you have been asked to provide a reference for a volunteer applicant.",
    keywords: "",
    canonicalPath: "/volunteer-reference",
};

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>
    )}
    <Fragment slot="head">
        <meta name="robots" content="noindex, nofollow" />
    </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: 110px; }

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

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

        @media (max-width: 767px) {
            .grid-2 { grid-template-columns: 1fr !important; }
            .grid-3 { grid-template-columns: 1fr !important; }
            .progress-wrap { gap: 4px !important; }
            .progress-pill { font-size: 0; padding: 8px 10px; }
            .progress-pill .pill-label { display: none; }
        }
    </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% 35%;"
                    src="/274864973_7295359163837841_5927911936073070889_n-1920w.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;">Volunteer reference</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(30px,4.5vw,50px);color:#F6F1E8;line-height:1.1;margin-bottom:16px;">Volunteer Reference Form</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;">You've been asked to provide a reference for someone applying to volunteer with us. All information is treated in the strictest confidence and used only for assessing the application.</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:820px;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 for your reference!</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:460px;margin:0 auto 32px;">
                                Your reference has been received by Highland Group RDA and will be treated in the strictest confidence. The applicant's coordinator will be in touch if further information is needed.
                            </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: THE APPLICANT ── -->
                        <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;">The applicant</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;">Please enter the name of the person you are providing a reference for. If you're unsure of the exact spelling, check with the person who sent you this link.</p>

                            <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                                <div>
                                    <label class="field-label" for="f-app-first">Applicant's first name(s) <span class="req">*</span></label>
                                    <input class="field-input" id="f-app-first" name="applicant_first_names" type="text" placeholder="Jane" autocomplete="off" />
                                    <p class="field-error" id="err-app-first">Please enter the applicant's first name.</p>
                                </div>
                                <div>
                                    <label class="field-label" for="f-app-last">Applicant's last name <span class="req">*</span></label>
                                    <input class="field-input" id="f-app-last" name="applicant_last_name" type="text" placeholder="Smith" autocomplete="off" />
                                    <p class="field-error" id="err-app-last">Please enter the applicant's last name.</p>
                                </div>
                            </div>
                        </div>

                        <!-- ── STEP 1: YOUR DETAILS ── -->
                        <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;">Your details</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;">Your contact details as the person providing this reference.</p>

                            <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                                <div>
                                    <label class="field-label" for="f-ref-name">Your full name <span class="req">*</span></label>
                                    <input class="field-input" id="f-ref-name" name="referee_name" type="text" placeholder="Alex Mackenzie" autocomplete="name" />
                                    <p class="field-error" id="err-ref-name">Please enter your full name.</p>
                                </div>
                                <div>
                                    <label class="field-label" for="f-ref-email">Your email address <span class="req">*</span></label>
                                    <input class="field-input" id="f-ref-email" name="referee_email" type="email" placeholder="alex@example.com" autocomplete="email" />
                                    <p class="field-error" id="err-ref-email">Please enter a valid email address.</p>
                                </div>
                                <div>
                                    <label class="field-label" for="f-ref-job">Job title or role</label>
                                    <input class="field-input" id="f-ref-job" name="referee_job_title" type="text" placeholder="e.g. Teacher" />
                                </div>
                                <div>
                                    <label class="field-label" for="f-ref-tel">Telephone</label>
                                    <input class="field-input" id="f-ref-tel" name="referee_telephone" type="tel" placeholder="07700 900000" autocomplete="tel" />
                                </div>
                                <div style="grid-column:1/-1;">
                                    <label class="field-label" for="f-ref-org">Organisation (if applicable)</label>
                                    <input class="field-input" id="f-ref-org" name="referee_organisation" type="text" placeholder="e.g. Inverness Academy" />
                                </div>
                                <div style="grid-column:1/-1;">
                                    <label class="field-label" for="f-ref-addr">Address</label>
                                    <textarea class="field-input" id="f-ref-addr" name="referee_address" placeholder="Street, Town, Postcode" style="min-height:80px;"></textarea>
                                </div>
                            </div>
                        </div>

                        <!-- ── STEP 2: YOUR RELATIONSHIP ── -->
                        <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;">Your relationship</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;">Please tell us how you know the applicant and for how long.</p>

                            <div style="display:flex;flex-direction:column;gap:28px;">

                                <div>
                                    <label class="field-label">In what capacity do you know the applicant? <span class="req">*</span></label>
                                    <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:4px;">
                                        {["Employer / line manager", "Colleague", "Teacher / tutor", "Community or faith leader", "Friend", "Other"].map((opt) => (
                                            <div class="choice" data-group="relationship_capacity" 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-capacity" />
                                    <p class="field-error" id="err-capacity">Please select your relationship to the applicant.</p>
                                </div>

                                <div>
                                    <label class="field-label" for="f-rel-other">If you selected "Other", please describe your relationship</label>
                                    <input class="field-input" id="f-rel-other" name="relationship_other" type="text" placeholder="e.g. Neighbour, club leader…" />
                                </div>

                                <div>
                                    <label class="field-label" for="f-known-duration">How long have you known the applicant? <span class="req">*</span></label>
                                    <input class="field-input" id="f-known-duration" name="known_duration" type="text" placeholder="e.g. 3 years" />
                                    <p class="field-error" id="err-known-duration">Please enter how long you have known the applicant.</p>
                                </div>

                                <div>
                                    <label class="field-label">Are you related to the applicant?</label>
                                    <p class="field-hint" style="margin-bottom:10px;">RDA requires references from people who are not related to the applicant.</p>
                                    <div style="display:flex;gap:10px;flex-wrap:wrap;">
                                        {["Yes", "No"].map((opt) => (
                                            <div class="choice" data-group="related_to_applicant" data-val={opt} style="flex:0 0 auto;min-width:100px;">
                                                <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-related" />
                                </div>

                            </div>
                        </div>

                        <!-- ── STEP 3: ASSESSMENT ── -->
                        <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;">Your assessment</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;">Please give your honest assessment. These questions help us ensure the safety and wellbeing of our participants, who include children and vulnerable adults.</p>

                            <div style="display:flex;flex-direction:column;gap:28px;">

                                <div>
                                    <label class="field-label" for="f-character">How would you describe the applicant's character and personal qualities? <span class="req">*</span></label>
                                    <textarea class="field-input" id="f-character" name="character_assessment" placeholder="Please share your honest impressions of their personality, values, and how they interact with others…"></textarea>
                                    <p class="field-error" id="err-character">Please provide a character assessment.</p>
                                </div>

                                <div>
                                    <label class="field-label">Do you consider them reliable and punctual?</label>
                                    <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:4px;">
                                        {["Yes", "No", "Not sure"].map((opt) => (
                                            <div class="choice" data-group="reliable_punctual" data-val={opt} style="flex:0 0 auto;min-width:100px;">
                                                <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-reliable" />
                                </div>

                                <div>
                                    <label class="field-label">Do you consider them suitable to work with people with disabilities, including children and vulnerable adults? <span class="req">*</span></label>
                                    <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:4px;">
                                        {["Yes", "No", "Not sure"].map((opt) => (
                                            <div class="choice" data-group="suitable_for_role" data-val={opt} style="flex:0 0 auto;min-width:100px;">
                                                <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-suitable" />
                                    <p class="field-error" id="err-suitable">Please indicate whether you consider the applicant suitable for this role.</p>
                                </div>

                                <div>
                                    <label class="field-label" for="f-concerns">Is there anything we should be aware of regarding the applicant's suitability to work with vulnerable people?</label>
                                    <textarea class="field-input" id="f-concerns" name="suitability_concerns" placeholder="If yes, please describe. If not, you can leave this blank."></textarea>
                                </div>

                                <div>
                                    <label class="field-label" for="f-additional">Any other comments you would like to add?</label>
                                    <textarea class="field-input" id="f-additional" name="additional_comments" placeholder="Optional — any further information that might be helpful."></textarea>
                                </div>

                            </div>
                        </div>

                        <!-- ── STEP 4: DECLARATION ── -->
                        <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;">Declaration</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;">Please confirm the following before submitting your reference.</p>

                            <div style="display:flex;flex-direction:column;gap:28px;">

                                <div>
                                    <label class="field-label">Please read and confirm <span class="req">*</span></label>
                                    <div style="display:flex;flex-direction:column;gap:10px;margin-top:4px;">
                                        <div class="choice" data-group="declaration_truth" data-val="Yes" data-multi="true">
                                            <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 the information provided in this reference is true and accurate to the best of my knowledge. <span style="color:#7DA371;">*</span></span>
                                        </div>
                                        <div class="choice" data-group="declaration_consent" data-val="Yes" data-multi="true">
                                            <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 this reference will be treated as confidential and used only to assess the above applicant's suitability to volunteer with Highland Group RDA, in line with the Data Protection Act 2018.</span>
                                        </div>
                                    </div>
                                    <p class="field-error" id="err-declaration">Please confirm the declaration of truth to submit.</p>
                                </div>

                                <div class="grid-2" style="display:grid;grid-template-columns:1fr 1fr;gap:16px;">
                                    <div>
                                        <label class="field-label" for="f-sig">Signature name</label>
                                        <input class="field-input" id="f-sig" name="declaration_signature" type="text" placeholder="Your full name" autocomplete="name" />
                                    </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>
                                        <div class="cf-turnstile" data-sitekey={turnstileSiteKey}></div>
                                    </div>
                                )}

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

                            </div>
                        </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 be happy to assist.
                    </p>
                </div>
            </section>

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

    <script>
    (() => {
        const STEPS = [
            { label: 'The applicant' },
            { label: 'Your details' },
            { label: 'Relationship' },
            { label: 'Assessment' },
            { label: 'Declaration' },
        ];

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

        const multiState = {
            declaration_truth: [],
            declaration_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));
                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');
                p.classList.remove('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 reference <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>`;
            }
            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 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 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 hiddenMap = {
                        relationship_capacity: 'hid-capacity',
                        related_to_applicant:  'hid-related',
                        reliable_punctual:     'hid-reliable',
                        suitable_for_role:     'hid-suitable',
                    };
                    const hidId = hiddenMap[group];
                    if (hidId) document.getElementById(hidId).value = cardVal;
                }

                // Clear relevant errors
                const errMap = {
                    relationship_capacity: 'err-capacity',
                    suitable_for_role: 'err-suitable',
                    declaration_truth: 'err-declaration',
                };
                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 fieldVal(id) {
            return (document.getElementById(id)?.value || '').trim();
        }

        function validateStep(s) {
            let ok = true;
            if (s === 0) {
                if (!fieldVal('f-app-first')) { showErr('err-app-first', true);  ok = false; } else showErr('err-app-first', false);
                if (!fieldVal('f-app-last'))  { showErr('err-app-last', true);   ok = false; } else showErr('err-app-last', false);
            }
            if (s === 1) {
                if (!fieldVal('f-ref-name'))  { showErr('err-ref-name', true);   ok = false; } else showErr('err-ref-name', false);
                const email = fieldVal('f-ref-email');
                if (!email || !/\S+@\S+\.\S+/.test(email)) { showErr('err-ref-email', true); ok = false; } else showErr('err-ref-email', false);
            }
            if (s === 2) {
                if (!fieldVal('hid-capacity'))     { showErr('err-capacity', true);      ok = false; } else showErr('err-capacity', false);
                if (!fieldVal('f-known-duration')) { showErr('err-known-duration', true); ok = false; } else showErr('err-known-duration', false);
            }
            if (s === 3) {
                if (!fieldVal('f-character')) { showErr('err-character', true); ok = false; } else showErr('err-character', false);
                if (!fieldVal('hid-suitable')) { showErr('err-suitable', true); ok = false; } else showErr('err-suitable', false);
            }
            if (s === 4) {
                if (!multiState.declaration_truth.includes('Yes')) { showErr('err-declaration', true); ok = false; } else showErr('err-declaration', false);
            }
            return ok;
        }

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

            const body = new URLSearchParams();

            // All named text fields
            const fields = [
                ['applicant_first_names', 'f-app-first'],
                ['applicant_last_name',   'f-app-last'],
                ['referee_name',          'f-ref-name'],
                ['referee_email',         'f-ref-email'],
                ['referee_job_title',     'f-ref-job'],
                ['referee_telephone',     'f-ref-tel'],
                ['referee_organisation',  'f-ref-org'],
                ['referee_address',       'f-ref-addr'],
                ['relationship_other',    'f-rel-other'],
                ['known_duration',        'f-known-duration'],
                ['character_assessment',  'f-character'],
                ['suitability_concerns',  'f-concerns'],
                ['additional_comments',   'f-additional'],
                ['declaration_signature', 'f-sig'],
                ['declaration_date',      'f-date'],
                // radio hidden inputs
                ['relationship_capacity', 'hid-capacity'],
                ['related_to_applicant',  'hid-related'],
                ['reliable_punctual',     'hid-reliable'],
                ['suitable_for_role',     'hid-suitable'],
            ];
            fields.forEach(([name, id]) => {
                const el = document.getElementById(id);
                if (el && el.value.trim()) body.append(name, el.value.trim());
            });

            // Checkbox declarations
            if (multiState.declaration_truth.includes('Yes'))   body.append('declaration_truth',   'Yes');
            if (multiState.declaration_consent.includes('Yes')) body.append('declaration_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-reference', {
                    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';
                window.scrollTo({ top: 0, behavior: 'smooth' });
            } catch (err) {
                errEl.textContent = err instanceof Error ? err.message : 'Sorry, something went wrong. Please try again.';
                errEl.classList.add('visible');
                btnNext.disabled = false;
                btnNext.innerHTML = `Submit reference <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) {
                if (!validateStep(currentStep)) return;
                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>
