/* =============================================================
   KICK IT KIDS SOCCER — REGISTRATION FORM
   Supports: School Program | Private Group (child waiver) | Soccer Party (host waiver)
   ============================================================= */
const { useState } = React;
const D = window.KICKIT;
const BIZ = D.business.name;

/* ---- Helpers ---- */
function isValidPhone(v) {
  return /^[+]?[(]?[0-9]{3}[)]?[-\s.]?[0-9]{3}[-\s.]?[0-9]{4}$/.test(
    String(v || '').trim()
  );
}
function isValidEmail(v) {
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(v || '').trim());
}
function todayISO() {
  const d = new Date();
  return `${d.getFullYear()}-${String(d.getMonth()+1).padStart(2,'0')}-${String(d.getDate()).padStart(2,'0')}`;
}
function todayDisplay() {
  return new Date().toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
}
function prefilledSchool() {
  try {
    const name = decodeURIComponent(new URLSearchParams(window.location.search).get('school') || '');
    if (!name) return '';
    const match = D.schools.find(s => s.name.toLowerCase() === name.toLowerCase() && s.status !== 'Closed');
    return match ? match.name : '';
  } catch { return ''; }
}
function detectContext() {
  try {
    const hash = window.location.hash.replace(/^#/, '');
    if (hash === 'privateGroup') return { type: 'privateGroup', locked: true };
    if (hash === 'party')        return { type: 'party',        locked: true };
    const params = new URLSearchParams(window.location.search);
    const t = params.get('type');
    if (t === 'privateGroup') return { type: 'privateGroup', locked: true };
    if (t === 'party')        return { type: 'party',        locked: true };
    // ?school= means they came from a school card — lock to school form
    if (params.get('school'))  return { type: 'school', locked: true };
    return { type: 'school', locked: false };
  } catch { return { type: 'school', locked: false }; }
}

/* ---- Blank form state per type ---- */
function blankForType(type) {
  if (type === 'party') return {
    programType: 'party',
    partyName: '', hostName: '', hostEmail: '', hostPhone: '',
    eventDate: '', eventTime: '', eventLocation: '',
    numberOfKids: '', ageRange: '', notes: '',
    liabilityWaiver: false, firstAidConsent: false, photoConsent: '',
    depositAcknowledgement: false, hostSignature: '',
  };
  if (type === 'privateGroup') return {
    programType: 'privateGroup',
    privateGroupName: '', privateGroupLocation: '',
    preferredDate: '', preferredTime: '', alternateDatetime: '',
    studentName: '', studentDOB: '',
    parentName: '', parentPhone: '', parentEmail: '',
    emergencyName: '', emergencyPhone: '',
    allergies: '', medicalConditions: '', medications: '',
    physicalLimitations: '', specialRequests: '',
    liabilityWaiver: false, firstAidConsent: false, photoConsent: '', signature: '',
  };
  return {
    programType: 'school',
    studentName: '', studentDOB: '', program: prefilledSchool(),
    parentName: '', parentPhone: '', parentEmail: '',
    emergencyName: '', emergencyPhone: '',
    allergies: '', medicalConditions: '', medications: '',
    physicalLimitations: '', specialRequests: '',
    liabilityWaiver: false, firstAidConsent: false, photoConsent: '', signature: '',
  };
}

/* ---- Validation ---- */
function validateSchool(f) {
  const e = {};
  if (!f.studentName.trim()) e.studentName = 'Student name is required.';
  if (!f.studentDOB) {
    e.studentDOB = 'Date of birth is required.';
  } else {
    const [y, m, d] = f.studentDOB.split('-').map(Number);
    const dob = new Date(y, m - 1, d);
    const today = new Date(); today.setHours(0, 0, 0, 0);
    if (isNaN(dob.getTime())) e.studentDOB = 'Enter a valid date.';
    else if (dob >= today) e.studentDOB = 'Date of birth cannot be today or in the future.';
  }
  if (!f.program) e.program = 'Please select a school.';
  if (!f.parentName.trim()) e.parentName = 'Parent/guardian name is required.';
  if (!f.parentPhone.trim()) e.parentPhone = 'Phone number is required.';
  else if (!isValidPhone(f.parentPhone)) e.parentPhone = 'Enter a valid phone number (e.g. 555-123-4567 or (555) 123-4567).';
  if (!f.parentEmail.trim()) e.parentEmail = 'Email address is required.';
  else if (!isValidEmail(f.parentEmail)) e.parentEmail = 'Enter a valid email address.';
  if (!f.emergencyName.trim()) e.emergencyName = 'Emergency contact name is required.';
  if (!f.emergencyPhone.trim()) e.emergencyPhone = 'Emergency contact phone is required.';
  else if (!isValidPhone(f.emergencyPhone)) e.emergencyPhone = 'Enter a valid phone number.';
  if (!f.liabilityWaiver) e.liabilityWaiver = 'You must accept the liability waiver to continue.';
  if (!f.firstAidConsent) e.firstAidConsent = 'You must authorize first aid consent to continue.';
  if (!['yes','no'].includes(f.photoConsent)) e.photoConsent = 'Please choose Yes or No for photo/video consent.';
  if (!f.signature.trim()) e.signature = 'Your typed signature is required.';
  return e;
}

function validatePrivateGroup(f) {
  const e = {};
  if (!f.privateGroupName.trim()) e.privateGroupName = 'Group name is required.';
  if (!f.studentName.trim()) e.studentName = 'Student name is required.';
  if (!f.studentDOB) {
    e.studentDOB = 'Date of birth is required.';
  } else {
    const [y, m, d] = f.studentDOB.split('-').map(Number);
    const dob = new Date(y, m - 1, d);
    const today = new Date(); today.setHours(0, 0, 0, 0);
    if (isNaN(dob.getTime())) e.studentDOB = 'Enter a valid date.';
    else if (dob >= today) e.studentDOB = 'Date of birth cannot be today or in the future.';
  }
  if (!f.parentName.trim()) e.parentName = 'Parent/guardian name is required.';
  if (!f.parentPhone.trim()) e.parentPhone = 'Phone number is required.';
  else if (!isValidPhone(f.parentPhone)) e.parentPhone = 'Enter a valid phone number.';
  if (!f.parentEmail.trim()) e.parentEmail = 'Email address is required.';
  else if (!isValidEmail(f.parentEmail)) e.parentEmail = 'Enter a valid email address.';
  if (!f.emergencyName.trim()) e.emergencyName = 'Emergency contact name is required.';
  if (!f.emergencyPhone.trim()) e.emergencyPhone = 'Emergency contact phone is required.';
  else if (!isValidPhone(f.emergencyPhone)) e.emergencyPhone = 'Enter a valid phone number.';
  if (!f.liabilityWaiver) e.liabilityWaiver = 'You must accept the liability waiver to continue.';
  if (!f.firstAidConsent) e.firstAidConsent = 'You must authorize first aid consent to continue.';
  if (!['yes','no'].includes(f.photoConsent)) e.photoConsent = 'Please choose Yes or No for photo/video consent.';
  if (!f.signature.trim()) e.signature = 'Your typed signature is required.';
  return e;
}

function validateParty(f) {
  const e = {};
  if (!f.partyName.trim()) e.partyName = 'Party or event name is required.';
  if (!f.hostName.trim()) e.hostName = 'Host name is required.';
  if (!f.hostEmail.trim()) e.hostEmail = 'Email address is required.';
  else if (!isValidEmail(f.hostEmail)) e.hostEmail = 'Enter a valid email address.';
  if (!f.hostPhone.trim()) e.hostPhone = 'Phone number is required.';
  else if (!isValidPhone(f.hostPhone)) e.hostPhone = 'Enter a valid phone number.';
  if (!f.eventDate) e.eventDate = 'Event date is required.';
  if (!f.eventLocation.trim()) e.eventLocation = 'Event location is required.';
  const n = Number(f.numberOfKids);
  if (!f.numberOfKids || isNaN(n) || n < 1) e.numberOfKids = 'Please enter the expected number of kids.';
  if (!f.liabilityWaiver) e.liabilityWaiver = 'You must accept the liability waiver to continue.';
  if (!f.firstAidConsent) e.firstAidConsent = 'You must authorize first aid consent to continue.';
  if (!['yes','no'].includes(f.photoConsent)) e.photoConsent = 'Please choose Yes or No for photo/video consent.';
  if (!f.depositAcknowledgement) e.depositAcknowledgement = 'You must acknowledge the $50 deposit policy to continue.';
  if (!f.hostSignature.trim()) e.hostSignature = 'Your typed signature is required.';
  return e;
}

function validate(f) {
  if (f.programType === 'party') return validateParty(f);
  if (f.programType === 'privateGroup') return validatePrivateGroup(f);
  return validateSchool(f);
}

/* ---- Shared sub-components ---- */
function RegSection({ num, title, description, children }) {
  return (
    <div className="reg-section">
      <div className="reg-section-head">
        <div className="reg-section-num">{num}</div>
        <div>
          <h2 className="reg-section-title">{title}</h2>
          {description && <p className="reg-section-desc">{description}</p>}
        </div>
      </div>
      <div className="reg-fields">{children}</div>
    </div>
  );
}

function Field({ label, required, hint, error, children }) {
  return (
    <div className={"reg-field" + (error ? " has-error" : "")}>
      {label && (
        <label className="reg-label">
          {label}
          {required && <span className="reg-req" aria-hidden="true"> *</span>}
        </label>
      )}
      {hint && <p className="reg-hint">{hint}</p>}
      {children}
      {error && <span className="reg-error-msg" role="alert">{error}</span>}
    </div>
  );
}

function ParentSection({ num, form, setField, errors }) {
  return (
    <RegSection num={num} title="Parent / Guardian Information">
      <Field label="Parent/Guardian Full Name" required error={errors.parentName}>
        <input className="reg-input" type="text" value={form.parentName} onChange={setField('parentName')}
          placeholder="First and last name" autoComplete="name" />
      </Field>
      <Field label="Phone Number" required error={errors.parentPhone}>
        <input className="reg-input" type="tel" value={form.parentPhone} onChange={setField('parentPhone')}
          placeholder="(555) 123-4567" autoComplete="tel" />
      </Field>
      <Field label="Email Address" required error={errors.parentEmail}>
        <input className="reg-input" type="email" value={form.parentEmail} onChange={setField('parentEmail')}
          placeholder="you@example.com" autoComplete="email" />
      </Field>
    </RegSection>
  );
}

function EmergencySection({ num, form, setField, errors }) {
  return (
    <RegSection num={num} title="Emergency Contact"
      description="Provide a contact we can reach in an emergency — someone other than yourself if possible.">
      <Field label="Emergency Contact Name" required error={errors.emergencyName}>
        <input className="reg-input" type="text" value={form.emergencyName} onChange={setField('emergencyName')}
          placeholder="Full name" />
      </Field>
      <Field label="Emergency Contact Phone" required error={errors.emergencyPhone}>
        <input className="reg-input" type="tel" value={form.emergencyPhone} onChange={setField('emergencyPhone')}
          placeholder="(555) 123-4567" />
      </Field>
    </RegSection>
  );
}

function MedicalSection({ num, form, setField, errors }) {
  return (
    <RegSection num={num} title="Medical & Allergy Information"
      description="All fields in this section are optional. Please share anything that would help us support your child safely during class.">
      <p className="reg-privacy-note">
        Please only include information needed to help us support the student safely during class.
      </p>
      <Field label="Allergies" error={errors.allergies}>
        <textarea className="reg-input reg-textarea" value={form.allergies} onChange={setField('allergies')}
          placeholder="Food, insect, medication, or environmental allergies — include severity and whether an EpiPen is needed…" rows={3} />
      </Field>
      <Field label="Medical Conditions" error={errors.medicalConditions}>
        <textarea className="reg-input reg-textarea" value={form.medicalConditions} onChange={setField('medicalConditions')}
          placeholder="Any diagnosed conditions the coach should be aware of (e.g. asthma, diabetes, epilepsy)…" rows={3} />
      </Field>
      <Field label="Medications" error={errors.medications}>
        <textarea className="reg-input reg-textarea" value={form.medications} onChange={setField('medications')}
          placeholder="Any medications your child takes, including as-needed (e.g. inhaler, EpiPen)…" rows={2} />
      </Field>
      <Field label="Physical Limitations" error={errors.physicalLimitations}>
        <textarea className="reg-input reg-textarea" value={form.physicalLimitations} onChange={setField('physicalLimitations')}
          placeholder="Any physical restrictions that should limit activity or require modifications…" rows={2} />
      </Field>
      <Field label="Special Requests / Notes" error={errors.specialRequests}>
        <textarea className="reg-input reg-textarea" value={form.specialRequests} onChange={setField('specialRequests')}
          placeholder="Anything else that would help us support your child during class…" rows={3} />
      </Field>
    </RegSection>
  );
}

function LiabilitySection({ num, form, setField, errors, isParty }) {
  return (
    <RegSection num={num} title="Liability Waiver / Assumption of Risk">
      <div className="reg-consent-box">
        <p>
          I understand that participation in classes, activities, instruction, movement,
          games, exercises, events, or related programming may involve certain risks,
          including but not limited to slips, falls, physical contact, minor injuries,
          or other unexpected incidents.
        </p>
        {isParty ? (
          <p>I confirm that all participating children are physically able to participate in soccer activities at this event.</p>
        ) : (
          <p>I confirm that my child is physically able to participate in the selected class or program, unless I have noted limitations or special needs above.</p>
        )}
        <p>
          {isParty ? 'On behalf of myself and all event participants, I' : 'On behalf of myself and my child, I'} acknowledge and accept the ordinary risks associated with participation. I agree to release and hold harmless{' '}
          <strong>{BIZ}</strong>, its owners, instructors, staff, volunteers, representatives, and facility partners from claims arising out of ordinary participation in the program, except where prohibited by law.
        </p>
        <p className="reg-legal-note">
          Note: The above waiver language is a starting point and should be reviewed by an attorney before use.
        </p>
      </div>
      <Field error={errors.liabilityWaiver}>
        <label className={"reg-check" + (form.liabilityWaiver ? " is-checked" : "")}>
          <input type="checkbox" checked={form.liabilityWaiver} onChange={setField('liabilityWaiver')} />
          <span>I have read and agree to the Liability Waiver / Assumption of Risk.{' '}
            <span className="reg-req" aria-hidden="true">*</span>
          </span>
        </label>
      </Field>
    </RegSection>
  );
}

function FirstAidSection({ num, form, setField, errors, isParty }) {
  return (
    <RegSection num={num} title="First Aid / Emergency Medical Treatment Consent">
      <div className="reg-consent-box">
        <p>
          In the event of illness, injury, accident, or emergency{isParty ? ' involving any participant at the event' : ' involving my child'}, I authorize{' '}
          <strong>{BIZ}</strong> staff or instructors to provide basic first aid and/or seek emergency medical assistance if they believe it is reasonably necessary.
        </p>
        <p>
          {isParty
            ? "I understand that every effort will be made to contact the event host or a parent/guardian as soon as possible. Each parent/guardian is responsible for their child's medical costs arising from care provided by emergency responders or medical providers."
            : "I understand that every effort will be made to contact the parent/guardian or emergency contact as soon as possible. I also understand that I am responsible for any medical costs or expenses related to care provided by emergency responders, medical providers, or treatment facilities."
          }
        </p>
        <p className="reg-legal-note">
          Note: The above consent language is a starting point and should be reviewed by an attorney before use.
        </p>
      </div>
      <Field error={errors.firstAidConsent}>
        <label className={"reg-check" + (form.firstAidConsent ? " is-checked" : "")}>
          <input type="checkbox" checked={form.firstAidConsent} onChange={setField('firstAidConsent')} />
          <span>I authorize first aid and emergency medical assistance if reasonably necessary.{' '}
            <span className="reg-req" aria-hidden="true">*</span>
          </span>
        </label>
      </Field>
    </RegSection>
  );
}

function PhotoConsentSection({ num, form, setField, errors, isParty }) {
  return (
    <RegSection num={num} title="Photo / Video Consent">
      <p className="reg-photo-note">
        <strong>{BIZ}</strong> will make reasonable efforts to honor your selection.
      </p>
      <Field error={errors.photoConsent}>
        <div className="reg-radio-group" role="radiogroup" aria-label="Photo and video consent">
          <label className={"reg-radio-label" + (form.photoConsent === 'yes' ? ' is-selected' : '')}>
            <input type="radio" name="photoConsent" value="yes"
              checked={form.photoConsent === 'yes'} onChange={setField('photoConsent')} />
            <span>
              <strong>Yes</strong> — I give permission for <strong>{BIZ}</strong> to
              photograph or record {isParty ? 'children at the event' : 'my child'} during classes, events, or activities.
              I understand these photos/videos may be used for business purposes such as
              website content, social media, flyers, promotional materials, or class documentation.
            </span>
          </label>
          <label className={"reg-radio-label" + (form.photoConsent === 'no' ? ' is-selected' : '')}>
            <input type="radio" name="photoConsent" value="no"
              checked={form.photoConsent === 'no'} onChange={setField('photoConsent')} />
            <span>
              <strong>No</strong> — I do not give permission for{' '}
              {isParty ? 'children at this event' : 'my child'} to be photographed or recorded for promotional use.
            </span>
          </label>
        </div>
      </Field>
    </RegSection>
  );
}

/* ---- Header ---- */
function RegHeader() {
  return (
    <header className="header">
      <div className="wrap header-inner">
        <a className="logo" href="index.html" aria-label="Kick It Kids Soccer — back to home">
          <img className="logo-img" src={D.business.logo} alt="Kick It Kids Soccer" />
        </a>
        <img className="mobile-wordmark" src="assets/kickit-kids-soccer-logo.png" alt="Kick It Kids Soccer" />
        <nav className="nav">
          <a href="index.html">← Back to Home</a>
          <a href="index.html#schools">Find a School</a>
        </nav>
        <div className="header-cta">
          <a className="header-phone" href={"tel:" + D.business.phone.replace(/[^0-9+]/g, "")}>
            {D.business.phone}
          </a>
        </div>
      </div>
    </header>
  );
}

/* ---- Success screen ---- */
function SuccessScreen({ programType }) {
  const msgs = {
    school:       { title: 'Registration Submitted', body: "We'll review the information and contact you if anything else is needed. You should receive a confirmation email shortly." },
    privateGroup: { title: 'Waiver Submitted',        body: "Your child's waiver for the private group has been submitted. Coach Evan will be in touch." },
    party:        { title: 'Party Request Submitted', body: "Coach Evan will follow up to confirm availability, location, final pricing, and next steps." },
  };
  const { title, body } = msgs[programType] || msgs.school;
  return (
    <div className="reg-success">
      <div className="reg-success-icon" aria-hidden="true">✓</div>
      <h2>{title}</h2>
      <p>{body}</p>
      <a href="index.html" className="btn btn-primary btn-lg">Back to Home</a>
    </div>
  );
}

/* ---- Disclaimer box ---- */
function Disclaimer({ children }) {
  return <div className="reg-disclaimer">{children}</div>;
}

/* ---- Main form ---- */
function RegistrationForm() {
  const { type: defaultType, locked } = detectContext();
  const [programType, setProgramType] = useState(defaultType);
  const [form, setForm] = useState(blankForType(defaultType));
  const [errors, setErrors] = useState({});
  const [status, setStatus] = useState('idle');
  const [submitError, setSubmitError] = useState('');

  function switchType(t) {
    setProgramType(t);
    setForm(blankForType(t));
    setErrors({});
    setStatus('idle');
  }

  function setField(field) {
    return (e) => {
      const val = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
      setForm(f => ({ ...f, [field]: val }));
      if (errors[field]) setErrors(er => { const n = { ...er }; delete n[field]; return n; });
    };
  }

  async function handleSubmit(e) {
    e.preventDefault();
    const errs = validate(form);
    if (Object.keys(errs).length > 0) {
      setErrors(errs);
      setTimeout(() => {
        const el = document.querySelector('.has-error');
        if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
      }, 40);
      return;
    }
    setStatus('submitting');
    setSubmitError('');
    try {
      const res = await fetch('/api/student-registration', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, submittedAt: new Date().toISOString() }),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok) {
        throw new Error(json.error || 'Submission failed');
      }
      setStatus('success');
      window.scrollTo({ top: 0, behavior: 'smooth' });
    } catch (err) {
      console.error('Submission error:', err.message);
      setSubmitError(err.message);
      setStatus('error');
    }
  }

  if (status === 'success') return <SuccessScreen programType={programType} />;

  const schoolOptions = D.schools
    .filter(s => s.status !== 'Closed')
    .map(s => ({ value: s.name, label: `${s.name}${s.status === 'Waitlist' ? ' (Waitlist)' : ''}` }));

  const submitLabels = {
    school: 'Submit Registration',
    privateGroup: 'Submit Waiver',
    party: 'Request a Party',
  };

  return (
    <form className="reg-form" onSubmit={handleSubmit} noValidate aria-label="Registration form">

      {/* Program type tabs — only shown when user arrived without a specific context */}
      {!locked && (
        <div className="reg-type-tabs" role="group" aria-label="Program type">
          {[
            { value: 'school',       label: 'School Program' },
            { value: 'privateGroup', label: 'Private Group' },
            { value: 'party',        label: 'Soccer Party' },
          ].map(({ value, label }) => (
            <button key={value} type="button"
              className={"reg-type-tab" + (programType === value ? ' active' : '')}
              onClick={() => switchType(value)}>
              {label}
            </button>
          ))}
        </div>
      )}

      {/* ===== SCHOOL PROGRAM ===== */}
      {programType === 'school' && (
        <>
          <RegSection num={1} title="Student Information">
            <Field label="Student Full Name" required error={errors.studentName}>
              <input className="reg-input" type="text" value={form.studentName}
                onChange={setField('studentName')} placeholder="First and last name" autoComplete="off" />
            </Field>
            <Field label="Date of Birth" required error={errors.studentDOB}>
              <input className="reg-input" type="date" value={form.studentDOB}
                onChange={setField('studentDOB')} max={todayISO()} />
            </Field>
            <Field label="School / Program" required error={errors.program}>
              <select className="reg-input reg-select" value={form.program} onChange={setField('program')}>
                <option value="">Select a school…</option>
                {schoolOptions.map(o => <option key={o.value} value={o.value}>{o.label}</option>)}
              </select>
            </Field>
          </RegSection>

          <ParentSection num={2} form={form} setField={setField} errors={errors} />
          <EmergencySection num={3} form={form} setField={setField} errors={errors} />
          <MedicalSection num={4} form={form} setField={setField} errors={errors} />
          <LiabilitySection num={5} form={form} setField={setField} errors={errors} isParty={false} />
          <FirstAidSection num={6} form={form} setField={setField} errors={errors} isParty={false} />
          <PhotoConsentSection num={7} form={form} setField={setField} errors={errors} isParty={false} />

          <RegSection num={8} title="Parent / Guardian Agreement">
            <p className="reg-agreement-text">
              By signing below, I confirm that I am the parent or legal guardian of the student
              listed above. I confirm that the information I provided is accurate, and I agree
              to the selected consents and acknowledgments above. I also agree to the{' '}
              <a href="terms.html" target="_blank" rel="noopener noreferrer">Terms &amp; Conditions</a>{' '}
              and acknowledge the{' '}
              <a href="privacy-policy.html" target="_blank" rel="noopener noreferrer">Privacy Policy</a>.
            </p>
            <Field label="Parent/Guardian Typed Signature" required
              hint="Type your full legal name as your electronic signature." error={errors.signature}>
              <input className="reg-input reg-signature-input" type="text" value={form.signature}
                onChange={setField('signature')} placeholder="Type your full name"
                autoComplete="off" spellCheck="false" />
            </Field>
            <div className="reg-datestamp">Submission date: <strong>{todayDisplay()}</strong></div>
          </RegSection>
        </>
      )}

      {/* ===== PRIVATE GROUP — child waiver ===== */}
      {programType === 'privateGroup' && (
        <>
          <RegSection num={1} title="Group Information">
            <Field label="Group Name" required error={errors.privateGroupName}
              hint="Give your group a name (e.g. family name, neighborhood, or school name).">
              <input className="reg-input" type="text" value={form.privateGroupName}
                onChange={setField('privateGroupName')} placeholder="e.g. Smith Family Group" />
            </Field>
            <Field label="Preferred Location" error={errors.privateGroupLocation}
              hint="Where would you like sessions held? (e.g. Playa del Rey beach, Lincoln Park, home backyard)">
              <input className="reg-input" type="text" value={form.privateGroupLocation}
                onChange={setField('privateGroupLocation')} placeholder="e.g. Playa del Rey beach" />
            </Field>
            <Field label="Preferred Date" error={errors.preferredDate}>
              <input className="reg-input" type="date" value={form.preferredDate}
                onChange={setField('preferredDate')} />
            </Field>
            <Field label="Preferred Time" error={errors.preferredTime}>
              <input className="reg-input" type="time" value={form.preferredTime}
                onChange={setField('preferredTime')} />
            </Field>
            <Field label="Alternate Date / Time" error={errors.alternateDatetime}
              hint="Optional — provide a backup if your preferred time is unavailable.">
              <input className="reg-input" type="text" value={form.alternateDatetime}
                onChange={setField('alternateDatetime')} placeholder="e.g. Saturdays after 10am" />
            </Field>
          </RegSection>

          <RegSection num={2} title="Student Information">
            <Field label="Student Full Name" required error={errors.studentName}>
              <input className="reg-input" type="text" value={form.studentName}
                onChange={setField('studentName')} placeholder="First and last name" autoComplete="off" />
            </Field>
            <Field label="Date of Birth" required error={errors.studentDOB}>
              <input className="reg-input" type="date" value={form.studentDOB}
                onChange={setField('studentDOB')} max={todayISO()} />
            </Field>
          </RegSection>

          <ParentSection num={3} form={form} setField={setField} errors={errors} />
          <EmergencySection num={4} form={form} setField={setField} errors={errors} />
          <MedicalSection num={5} form={form} setField={setField} errors={errors} />
          <LiabilitySection num={6} form={form} setField={setField} errors={errors} isParty={false} />
          <FirstAidSection num={7} form={form} setField={setField} errors={errors} isParty={false} />
          <PhotoConsentSection num={8} form={form} setField={setField} errors={errors} isParty={false} />

          <RegSection num={9} title="Parent / Guardian Agreement">
            <p className="reg-agreement-text">
              By signing below, I confirm that I am the parent or legal guardian of the student
              listed above. I confirm that the information I provided is accurate, and I agree
              to the selected consents and acknowledgments above. I also agree to the{' '}
              <a href="terms.html" target="_blank" rel="noopener noreferrer">Terms &amp; Conditions</a>{' '}
              and acknowledge the{' '}
              <a href="privacy-policy.html" target="_blank" rel="noopener noreferrer">Privacy Policy</a>.
            </p>
            <Field label="Parent/Guardian Typed Signature" required
              hint="Type your full legal name as your electronic signature." error={errors.signature}>
              <input className="reg-input reg-signature-input" type="text" value={form.signature}
                onChange={setField('signature')} placeholder="Type your full name"
                autoComplete="off" spellCheck="false" />
            </Field>
            <div className="reg-datestamp">Submission date: <strong>{todayDisplay()}</strong></div>
          </RegSection>

          <Disclaimer>
            <strong>Please note:</strong> Submitting this form does not confirm your booking.
            Coach Evan will follow up to confirm availability, location, schedule, final pricing,
            and next steps.
          </Disclaimer>
        </>
      )}

      {/* ===== SOCCER PARTY — host waiver ===== */}
      {programType === 'party' && (
        <>
          <RegSection num={1} title="Party Details">
            <Field label="Party / Event Name" required error={errors.partyName}
              hint={`Give your event a name (e.g. "Emma's 7th Birthday Party").`}>
              <input className="reg-input" type="text" value={form.partyName}
                onChange={setField('partyName')} placeholder="e.g. Emma's 7th Birthday Party" />
            </Field>
            <Field label="Event Date" required error={errors.eventDate}>
              <input className="reg-input" type="date" value={form.eventDate}
                onChange={setField('eventDate')} />
            </Field>
            <Field label="Event Time" error={errors.eventTime}>
              <input className="reg-input" type="time" value={form.eventTime}
                onChange={setField('eventTime')} />
            </Field>
            <Field label="Event Location" required error={errors.eventLocation}>
              <input className="reg-input" type="text" value={form.eventLocation}
                onChange={setField('eventLocation')} placeholder="Park name, address, or venue" />
            </Field>
            <Field label="Number of Kids" required error={errors.numberOfKids}>
              <input className="reg-input" type="number" min="1" value={form.numberOfKids}
                onChange={setField('numberOfKids')} placeholder="e.g. 12" />
            </Field>
            <Field label="Age Range" error={errors.ageRange}
              hint="Optional — approximate ages of the kids attending.">
              <input className="reg-input" type="text" value={form.ageRange}
                onChange={setField('ageRange')} placeholder="e.g. 5–9 years old" />
            </Field>
            <div className="reg-price-table">
              <p><strong>Party Pricing</strong></p>
              <ul>
                <li>Under 10 kids — <strong>$250</strong></li>
                <li>10–20 kids — <strong>$300</strong></li>
                <li>Over 20 kids — <strong>$350</strong></li>
              </ul>
              <p className="reg-hint">Includes a 60-minute session with games, scrimmaging, and soccer goodie bags for all kids.</p>
            </div>
          </RegSection>

          <RegSection num={2} title="Host Information">
            <Field label="Host Full Name" required error={errors.hostName}>
              <input className="reg-input" type="text" value={form.hostName}
                onChange={setField('hostName')} placeholder="First and last name" autoComplete="name" />
            </Field>
            <Field label="Email Address" required error={errors.hostEmail}>
              <input className="reg-input" type="email" value={form.hostEmail}
                onChange={setField('hostEmail')} placeholder="you@example.com" autoComplete="email" />
            </Field>
            <Field label="Phone Number" required error={errors.hostPhone}>
              <input className="reg-input" type="tel" value={form.hostPhone}
                onChange={setField('hostPhone')} placeholder="(555) 123-4567" autoComplete="tel" />
            </Field>
          </RegSection>

          <RegSection num={3} title="Notes / Special Requests">
            <Field label="Notes" error={errors.notes}
              hint="Optional — anything else Coach Evan should know about the event.">
              <textarea className="reg-input reg-textarea" value={form.notes} onChange={setField('notes')}
                placeholder="Theme, special accommodations, questions for Coach Evan…" rows={4} />
            </Field>
          </RegSection>

          <LiabilitySection num={4} form={form} setField={setField} errors={errors} isParty={true} />
          <FirstAidSection num={5} form={form} setField={setField} errors={errors} isParty={true} />
          <PhotoConsentSection num={6} form={form} setField={setField} errors={errors} isParty={true} />

          <RegSection num={7} title="Party Deposit Acknowledgement">
            <div className="reg-deposit-notice">
              <p>
                I understand that a <strong>$50 nonrefundable deposit</strong> is required after
                Coach Evan confirms the party date, location, availability, and final price.
                I understand that the party is not officially booked until the deposit is paid.
              </p>
            </div>
            <Field error={errors.depositAcknowledgement}>
              <label className={"reg-check" + (form.depositAcknowledgement ? " is-checked" : "")}>
                <input type="checkbox" checked={form.depositAcknowledgement}
                  onChange={setField('depositAcknowledgement')} />
                <span>
                  I agree to the $50 nonrefundable deposit policy.{' '}
                  <span className="reg-req" aria-hidden="true">*</span>
                </span>
              </label>
            </Field>
          </RegSection>

          <RegSection num={8} title="Host Agreement & Signature">
            <p className="reg-agreement-text">
              I confirm that I am the adult host for this event and that I am responsible
              for communicating activity details to participating families. I understand that
              children should participate with parent/guardian knowledge and permission.
            </p>
            <p className="reg-agreement-text">
              By signing below, I confirm that the information I provided is accurate and
              I agree to the waivers, consents, and acknowledgments above. I also agree to the{' '}
              <a href="terms.html" target="_blank" rel="noopener noreferrer">Terms &amp; Conditions</a>{' '}
              and acknowledge the{' '}
              <a href="privacy-policy.html" target="_blank" rel="noopener noreferrer">Privacy Policy</a>.
            </p>
            <Field label="Host Typed Signature" required
              hint="Type your full legal name as your electronic signature." error={errors.hostSignature}>
              <input className="reg-input reg-signature-input" type="text" value={form.hostSignature}
                onChange={setField('hostSignature')} placeholder="Type your full name"
                autoComplete="off" spellCheck="false" />
            </Field>
            <div className="reg-datestamp">Submission date: <strong>{todayDisplay()}</strong></div>
          </RegSection>

          <Disclaimer>
            <strong>Please note:</strong> Submitting this form does not confirm your booking.
            Coach Evan will follow up to confirm availability, location, final pricing, and next steps.
          </Disclaimer>
        </>
      )}

      {/* Error banner */}
      {status === 'error' && (
        <div className="reg-error-banner" role="alert">
          {submitError || 'Something went wrong while submitting.'}{' '}
          Please try again or{' '}
          <a href={"mailto:" + D.business.email}>contact us directly</a>.
        </div>
      )}

      {/* Submit */}
      <div className="reg-submit-area">
        {programType !== 'party' && (
          <p className="reg-submit-note">
            By submitting this form, you confirm that you are the parent or legal guardian
            of the student listed above.
          </p>
        )}
        <button type="submit" className="btn btn-primary btn-lg reg-submit-btn"
          disabled={status === 'submitting'}>
          {status === 'submitting' ? 'Submitting…' : (submitLabels[programType] || 'Submit')}
        </button>
        {Object.keys(errors).length > 0 && (
          <p className="reg-has-errors" role="alert">
            Please fix the highlighted fields above before submitting.
          </p>
        )}
        <p className="reg-charity-note">
          💚 Making a difference together — a percentage of every enrollment will be donated to soccer-based charities across the globe.
        </p>
      </div>
    </form>
  );
}

/* ---- Page shell ---- */
const PAGE_META = {
  school:       { title: 'Student Registration',         sub: <>Complete this form to register your child for a <strong>{BIZ}</strong> program.</> },
  privateGroup: { title: 'Private Group — Child Waiver', sub: <>Complete this form to submit your child's waiver for a private group session with <strong>{BIZ}</strong>.</> },
  party:        { title: 'Soccer Party Request',         sub: <>Complete this form to request a <strong>{BIZ}</strong> soccer party.</> },
};

function App() {
  const { type } = detectContext();
  const meta = PAGE_META[type] || PAGE_META.school;
  return (
    <React.Fragment>
      <RegHeader />
      <main className="reg-main">
        <div className="wrap">
          <div className="reg-page-head">
            <h1>{meta.title}</h1>
            <p>
              {meta.sub} Required fields are marked with{' '}
              <span className="reg-req" aria-label="asterisk, required">*</span>.
            </p>
          </div>
          <RegistrationForm />
        </div>
      </main>
      <footer className="footer">
        <div className="wrap">
          <p className="footer-note" style={{ marginTop: 0 }}>
            Registration information is kept private and used only for program scheduling,
            attendance, and parent communication.
          </p>
          <div className="footer-bottom">
            <span>© {new Date().getFullYear()} Kick It Kids Soccer LLC. All rights reserved.</span>
            <span className="footer-legal">
              <a href="privacy-policy.html">Privacy Policy</a>
              <a href="terms.html">Terms &amp; Conditions</a>
            </span>
          </div>
        </div>
      </footer>
    </React.Fragment>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
