// Event detail + signup form

const { useState: useStateS } = React;

const SOURCE_OPTIONS = ['Instagram', 'School / Coach referral', 'Recruiter', 'Friend / Word of mouth', 'Other'];
// Career fields per implementation brief Section 5.2
const CAREER_OPTIONS = ['PJ', 'CCT', 'SR', 'TACP', 'EOD', 'SERE', 'Unsure'];

function EventDetail({ event, t, onBack, onSubmit, user, onOpenAuth, onViewConfirmation }) {
  const existingReg = React.useMemo(() => {
    if (!user?.email) return null;
    const regs = window.Auth.getRegistrationsForUser(user.email);
    return regs.find(r => r.eventId === event.id && r.status === 'confirmed') || null;
  }, [user, event.id]);

  // Split existing single-name user profile into first/last for the form
  const splitName = (full) => {
    if (!full) return { first: '', last: '' };
    const parts = full.trim().split(/\s+/);
    return { first: parts[0] || '', last: parts.slice(1).join(' ') || '' };
  };
  const initialName = splitName(user?.name);
  const [form, setForm] = useStateS({
    firstName: user?.firstName || initialName.first,
    lastName: user?.lastName || initialName.last,
    email: user?.email || '',
    phone: user?.phone || '',
    age: user?.age || '',
    source: user?.source || '', recruiter: user?.recruiter || '',
    careers: user?.careers || [],
    medical: '', notes: '', waiver: false,
    saveProfile: !user,
  });
  const [errors, setErrors] = useStateS({});
  const [touched, setTouched] = useStateS({});

  const dateObj = new Date(event.date + 'T00:00:00');
  const dateStr = dateObj.toLocaleDateString('en-US', {
    weekday: 'long', month: 'long', day: 'numeric', year: 'numeric'
  }).toUpperCase();

  // Affirmative error copy per brief 5.2 ("Please enter a valid email", not "Invalid")
  const validate = (f) => {
    const e = {};
    if (!f.firstName.trim()) e.firstName = 'Please enter your first name.';
    if (!f.lastName.trim()) e.lastName = 'Please enter your last name.';
    if (!f.email.trim()) e.email = 'Please enter your email address.';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f.email)) e.email = 'Please enter a valid email address.';
    // Phone optional per brief: validate only if provided
    if (f.phone.trim() && f.phone.replace(/\D/g, '').length < 7) e.phone = 'Please enter a valid phone number.';
    const ageNum = parseInt(f.age, 10);
    if (!f.age) e.age = 'Please enter your age.';
    else if (isNaN(ageNum) || ageNum < 16 || ageNum > 39) e.age = 'Age must be between 16 and 39.';
    if (!f.waiver) e.waiver = 'Please acknowledge the waiver to continue.';
    return e;
  };
  // A field is "valid" (green check) once touched with a non-empty value and no error
  const isValid = (k) => {
    if (!touched[k]) return false;
    const errs = validate(form);
    if (errs[k]) return false;
    if (k === 'phone') return form.phone.trim().length > 0; // optional; only green if filled
    if (k === 'firstName') return form.firstName.trim().length > 0;
    if (k === 'lastName') return form.lastName.trim().length > 0;
    if (k === 'email') return form.email.trim().length > 0;
    if (k === 'age') return String(form.age).trim().length > 0;
    return false;
  };

  const handleChange = (k, v) => {
    const next = { ...form, [k]: v };
    setForm(next);
    if (touched[k]) setErrors(validate(next));
  };
  const handleBlur = (k) => {
    setTouched({ ...touched, [k]: true });
    setErrors(validate(form));
  };
  const toggleCareer = (c) => {
    const next = form.careers.includes(c)
      ? form.careers.filter(x => x !== c)
      : [...form.careers, c];
    setForm({ ...form, careers: next });
  };
  const [submitting, setSubmitting] = React.useState(false);
  const handleSubmit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    const errs = validate(form);
    setErrors(errs);
    setTouched({ firstName: true, lastName: true, email: true, phone: true, age: true, waiver: true });
    if (Object.keys(errs).length !== 0) {
      if (window.dataLayer) window.dataLayer.push({ event: 'form_submit_error', event_id: event.id });
      return;
    }
    if (window.dataLayer) window.dataLayer.push({ event: 'form_submit_success', event_id: event.id });
    setSubmitting(true);
    try {
      await onSubmit({ event, form: { ...form, name: `${form.firstName} ${form.lastName}`.trim() } });
    } finally {
      setSubmitting(false);
    }
  };

  const spotsLeft = event.capacity > 0 ? event.capacity - event.signed : Infinity;
  const isFull = event.capacity > 0 && spotsLeft <= 0;

  // Sticky mobile CTA — appears when form scrolls off screen
  const formRef = React.useRef(null);
  const [stickyVisible, setStickyVisible] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => {
      if (!formRef.current) return;
      const rect = formRef.current.getBoundingClientRect();
      // Show sticky CTA when form is off-screen (below viewport or above it)
      const viewport = window.innerHeight;
      setStickyVisible(rect.top > viewport - 80 || rect.bottom < 120);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, [existingReg]);
  const scrollToForm = () => {
    if (formRef.current) {
      const y = formRef.current.getBoundingClientRect().top + window.pageYOffset - 80;
      window.scrollTo({ top: y, behavior: 'smooth' });
    }
    if (window.dataLayer) window.dataLayer.push({ event: 'cta_click', event_id: event.id, cta: 'sticky' });
  };

  return (
    <div style={{ background: t.bg, color: t.fg, minHeight: '100vh' }}>
      <div style={{ padding: '24px 48px', borderBottom: `1px solid ${t.line}` }}>
        <button onClick={onBack} style={{
          background: 'transparent', border: 'none', color: t.dim,
          fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 11,
          letterSpacing: '0.2em', cursor: 'pointer', padding: 0,
        }}>◀ BACK TO CALENDAR</button>
      </div>

      <div style={{ padding: '48px 48px 56px', borderBottom: `1px solid ${t.line}` }}>
        <div style={{ maxWidth: 1200, margin: '0 auto' }}>
          <div style={{
            fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 11,
            letterSpacing: '0.3em', color: t.brass, marginBottom: 14,
          }}>FILE NO. {event.id.toUpperCase()} · {event.tag} · {event.type.toUpperCase()}</div>
          <h1 style={{
            fontFamily: 'Oswald, sans-serif', fontWeight: 700,
            fontSize: 'clamp(48px, 7vw, 96px)',
            color: t.fg, margin: 0, letterSpacing: '0.01em', lineHeight: 0.95,
          }}>{event.title}</h1>
        </div>
      </div>

      <div style={{ maxWidth: 1200, margin: '0 auto', padding: '48px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 420px', gap: 48 }}>
          <div>
            <div style={{
              height: 420, marginBottom: 32, position: 'relative',
              background: event.image ? t.cellBg : `repeating-linear-gradient(135deg, ${t.stripeA} 0 12px, ${t.stripeB} 12px 24px)`,
              border: `1px solid ${t.line}`, overflow: 'hidden',
            }}>
              {event.image ? (
                <img src={event.image} alt={event.title} style={{
                  width: '100%', height: '100%', objectFit: 'contain',
                  objectPosition: 'center', display: 'block',
                }} />
              ) : (
                <div style={{
                  position: 'absolute', inset: 0, display: 'flex',
                  alignItems: 'center', justifyContent: 'center',
                }}>
                  <span style={{
                    fontFamily: 'ui-monospace, monospace', fontSize: 12,
                    color: t.dim, letterSpacing: '0.2em',
                  }}>[ HERO IMAGE / {event.type.toUpperCase()} ]</span>
                </div>
              )}
              <div style={{
                position: 'absolute', top: 16, left: 16,
                fontFamily: 'Barlow, sans-serif', fontWeight: 600, fontSize: 10,
                letterSpacing: '0.3em', color: '#0F1114',
                background: t.brass, padding: '4px 10px',
              }}>{event.tag}</div>
            </div>

            <div style={{
              display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 0, marginBottom: 40,
              border: `1px solid ${t.line}`,
            }}>
              <SpecCell label="DATE" value={dateStr} t={t} />
              <SpecCell label="TIME" value={`${event.time} – ${event.endTime}`} t={t} />
              <SpecCell label="LOCATION" value={event.location} t={t} />
              <SpecCell label="HOST" value={event.host} t={t} />
            </div>

            <div style={{ marginBottom: 40 }}>
              <SectionLabel t={t}>BRIEF</SectionLabel>
              <p style={{
                fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 18,
                color: t.fg, margin: '0 0 16px', lineHeight: 1.5,
              }}>{event.brief}</p>
              <p style={{
                fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 15,
                color: t.fg, opacity: 0.8, margin: 0, lineHeight: 1.65,
              }}>{event.details}</p>
            </div>

          </div>

          <div>
            <div ref={formRef} style={{
              position: 'sticky', top: 24, background: t.cellBg,
              border: `1px solid ${t.line}`, padding: 28,
            }}>
              <div style={{ marginBottom: 24 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 8 }}>
                  <span style={{
                    fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
                    letterSpacing: '0.25em', color: t.dim,
                  }}>CAPACITY</span>
                  <span style={{
                    fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 14,
                    color: isFull ? '#d06a4a' : t.brass, letterSpacing: '0.05em',
                  }}>{event.capacity > 0 ? `${event.signed} / ${event.capacity}` : `${event.signed} SIGNED`}</span>
                </div>
                {event.capacity > 0 && (
                  <div style={{
                    height: 4, background: t.accentBg,
                    position: 'relative', overflow: 'hidden',
                  }}>
                    <div style={{
                      height: '100%', background: t.brass,
                      width: `${Math.min(100, (event.signed / event.capacity) * 100)}%`,
                    }} />
                  </div>
                )}
                <div style={{
                  fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
                  letterSpacing: '0.2em', color: t.dim, marginTop: 6,
                }}>{isFull ? 'WAITLIST ONLY' : 'OPEN TO SIGN UP'}</div>
              </div>

              {existingReg ? (
                <div>
                  <div style={{
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '14px 16px', marginBottom: 18,
                    background: t.accentBg, border: `1px solid ${t.brass}`,
                  }}>
                    <span style={{
                      fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 11,
                      letterSpacing: '0.2em', color: t.brass,
                    }}>✓ LOCKED IN</span>
                    <span style={{
                      fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 11,
                      color: t.fg, opacity: 0.8,
                    }}>· You're confirmed for this event.</span>
                  </div>
                  <div style={{
                    fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 22,
                    color: t.fg, marginBottom: 6, letterSpacing: '0.03em',
                  }}>YOUR SPOT</div>
                  <div style={{
                    fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 12,
                    color: t.dim, marginBottom: 22, lineHeight: 1.5,
                  }}>Registered {new Date(existingReg.ts).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }).toUpperCase()}. Need the details? Pull up your confirmation.</div>
                  <button onClick={() => onViewConfirmation(existingReg)} style={{
                    width: '100%', padding: '18px',
                    background: t.brass, color: '#0F1114', border: 'none',
                    fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 14,
                    letterSpacing: '0.3em', cursor: 'pointer', transition: 'opacity 0.15s',
                  }}
                  onMouseEnter={e => e.target.style.opacity = '0.85'}
                  onMouseLeave={e => e.target.style.opacity = '1'}
                  >VIEW CONFIRMATION →</button>
                  <div style={{
                    fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 11,
                    color: t.dim, marginTop: 14, textAlign: 'center', letterSpacing: '0.1em',
                  }}>
                    Can't make it?{' '}
                    <span onClick={() => {
                      if (window.confirm('Cancel this registration?')) {
                        window.Auth.cancelRegistration(existingReg.id);
                        window.location.reload();
                      }
                    }} style={{
                      color: '#d06a4a', cursor: 'pointer', textDecoration: 'underline',
                    }}>CANCEL</span>
                  </div>
                </div>
              ) : (<>

              <div style={{
                fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 22,
                color: t.fg, marginBottom: 6, letterSpacing: '0.03em',
              }}>RESERVE MY SPOT</div>
              <div style={{
                fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 12,
                color: t.dim, marginBottom: 10, lineHeight: 1.5,
              }}>No hype. No fluff. Fill this out only if you plan to show up.</div>
              <div style={{
                fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
                color: t.dim, marginBottom: 18, letterSpacing: '0.15em',
              }}><span style={{ color: t.brass }}>*</span> REQUIRED FIELD</div>

              <form onSubmit={handleSubmit}
                onFocus={() => { if (!window.__afsw_form_started) { window.__afsw_form_started = true; if (window.dataLayer) window.dataLayer.push({ event: 'form_start', event_id: event.id }); } }}
              >
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                  <Field label="FIRST NAME" required value={form.firstName}
                    onChange={(v) => handleChange('firstName', v)}
                    onBlur={() => handleBlur('firstName')}
                    error={touched.firstName && errors.firstName}
                    valid={isValid('firstName')}
                    t={t} placeholder="First" autoComplete="given-name" />
                  <Field label="LAST NAME" required value={form.lastName}
                    onChange={(v) => handleChange('lastName', v)}
                    onBlur={() => handleBlur('lastName')}
                    error={touched.lastName && errors.lastName}
                    valid={isValid('lastName')}
                    t={t} placeholder="Last" autoComplete="family-name" />
                </div>
                <Field label="EMAIL" required value={form.email}
                  onChange={(v) => handleChange('email', v)}
                  onBlur={() => handleBlur('email')}
                  error={touched.email && errors.email}
                  valid={isValid('email')}
                  t={t} placeholder="you@domain.com"
                  type="email" inputMode="email" autoComplete="email" />
                <Field label="PHONE (OPTIONAL)" value={form.phone}
                  onChange={(v) => handleChange('phone', v)}
                  onBlur={() => handleBlur('phone')}
                  error={touched.phone && errors.phone}
                  valid={isValid('phone')}
                  t={t} placeholder="(808) 555-0100"
                  type="tel" inputMode="tel" autoComplete="tel" />
                <Field label="AGE" required value={form.age}
                  onChange={(v) => handleChange('age', v)}
                  onBlur={() => handleBlur('age')}
                  error={touched.age && errors.age}
                  valid={isValid('age')}
                  t={t} placeholder="18"
                  type="number" inputMode="numeric" autoComplete="bday-year" />

                <SelectField label="HOW DID YOU HEAR ABOUT US?"
                  value={form.source} options={SOURCE_OPTIONS}
                  onChange={(v) => handleChange('source', v)} t={t} />

                <PillGroup label="WORKING WITH A RECRUITER?"
                  options={['Yes', 'No']}
                  value={form.recruiter}
                  onChange={(v) => handleChange('recruiter', v)}
                  t={t} />

                <ChipGroup label="CAREER FIELDS OF INTEREST"
                  options={CAREER_OPTIONS}
                  values={form.careers}
                  onToggle={toggleCareer}
                  t={t} />

                <Field label="MEDICAL / INJURIES" value={form.medical}
                  onChange={(v) => handleChange('medical', v)}
                  onBlur={() => {}}
                  t={t} placeholder="Optional" />
                <TextareaField label="ANYTHING ELSE?" value={form.notes}
                  onChange={(v) => handleChange('notes', v)}
                  t={t} placeholder="Optional" />

                <WaiverBox checked={form.waiver}
                  onToggle={() => handleChange('waiver', !form.waiver)}
                  error={errors.waiver && touched.waiver}
                  t={t} />

                {!user && (
                  <div style={{ marginTop: 12 }}>
                    <div
                      onClick={() => handleChange('saveProfile', !form.saveProfile)}
                      style={{
                        display: 'flex', gap: 12, alignItems: 'center', padding: '12px 14px',
                        cursor: 'pointer', background: form.saveProfile ? t.accentBg : 'transparent',
                        border: `1px solid ${form.saveProfile ? t.brass : t.line}`,
                        transition: 'all 0.15s',
                      }}>
                      <div style={{
                        width: 16, height: 16, flexShrink: 0,
                        border: `1.5px solid ${form.saveProfile ? t.brass : t.dim}`,
                        background: form.saveProfile ? t.brass : 'transparent',
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                      }}>
                        {form.saveProfile && (
                          <svg viewBox="0 0 24 24" style={{ width: 10, height: 10, fill: '#0F1114' }}>
                            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" />
                          </svg>
                        )}
                      </div>
                      <div style={{
                        fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 12,
                        color: t.fg, lineHeight: 1.4,
                      }}>
                        <strong style={{ color: form.saveProfile ? t.brass : t.fg }}>Save my info</strong>
                        <span style={{ color: t.dim, display: 'block', fontSize: 10, marginTop: 2, letterSpacing: '0.05em' }}>
                          Skip the form on future events. No password needed.
                        </span>
                      </div>
                    </div>
                    <div style={{
                      fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 10,
                      color: t.dim, marginTop: 8, textAlign: 'center', letterSpacing: '0.1em',
                    }}>
                      Already have an account?{' '}
                      <span onClick={onOpenAuth} style={{
                        color: t.brass, cursor: 'pointer', textDecoration: 'underline',
                      }}>SIGN IN</span>
                    </div>
                  </div>
                )}
                {user && (
                  <div style={{
                    marginTop: 12, padding: '10px 12px',
                    background: t.accentBg, border: `1px solid ${t.line}`,
                    fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 11,
                    color: t.dim, letterSpacing: '0.05em',
                  }}>
                    <span style={{ color: t.brass }}>◉</span> Signed in as <strong style={{ color: t.fg }}>{user.email}</strong>
                  </div>
                )}

                <button type="submit" disabled={submitting} style={{
                  width: '100%', padding: '18px',
                  background: submitting ? t.accentBg : t.brass,
                  color: submitting ? t.dim : '#0F1114', border: 'none',
                  fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 14,
                  letterSpacing: '0.3em',
                  cursor: submitting ? 'wait' : 'pointer',
                  opacity: submitting ? 0.6 : 1,
                  marginTop: 14, transition: 'opacity 0.15s',
                }}
                onMouseEnter={e => !submitting && (e.target.style.opacity = '0.85')}
                onMouseLeave={e => !submitting && (e.target.style.opacity = '1')}
                >{submitting ? 'SUBMITTING...' : (isFull ? 'JOIN WAITLIST' : 'RESERVE MY SPOT')}</button>

                <div style={{
                  fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
                  color: t.dim, marginTop: 14, letterSpacing: '0.1em',
                  lineHeight: 1.5, textAlign: 'center',
                }}>By signing up you accept the event standards. No-shows forfeit future priority.</div>
              </form>
              </>)}
            </div>
          </div>
        </div>
      </div>

      {/* Sticky mobile CTA — per brief Section 5.4 */}
      {!existingReg && !isFull && (
        <div style={{
          position: 'fixed', bottom: 0, left: 0, right: 0, zIndex: 40,
          background: t.bg, borderTop: `1px solid ${t.lineStrong}`,
          padding: '10px 16px', display: 'flex', gap: 12, alignItems: 'center',
          transform: stickyVisible ? 'translateY(0)' : 'translateY(100%)',
          transition: 'transform 0.25s ease-out',
          boxShadow: stickyVisible ? '0 -8px 24px rgba(0,0,0,0.35)' : 'none',
        }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{
              fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 13,
              color: t.fg, letterSpacing: '0.08em',
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>{event.title}</div>
            <div style={{
              fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
              color: t.dim, letterSpacing: '0.1em', marginTop: 2,
            }}>{event.time} · {event.location.split(',')[0]}</div>
          </div>
          <button onClick={scrollToForm} style={{
            padding: '12px 20px', minHeight: 44,
            background: t.brass, color: '#0F1114', border: 'none',
            fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 12,
            letterSpacing: '0.25em', cursor: 'pointer', whiteSpace: 'nowrap',
          }}>RESERVE →</button>
        </div>
      )}
    </div>
  );
}

function SpecCell({ label, value, t }) {
  return (
    <div style={{
      padding: '18px 22px',
      borderRight: `1px solid ${t.line}`,
      borderBottom: `1px solid ${t.line}`,
    }}>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 10,
        letterSpacing: '0.3em', color: t.dim, marginBottom: 6,
      }}>{label}</div>
      <div style={{
        fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 16,
        color: t.fg, letterSpacing: '0.03em', lineHeight: 1.2,
      }}>{value}</div>
    </div>
  );
}

function SectionLabel({ children, t }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 18 }}>
      <span style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 600, fontSize: 11,
        letterSpacing: '0.35em', color: t.brass,
      }}>{children}</span>
      <span style={{ flex: 1, height: 1, background: t.lineStrong }} />
    </div>
  );
}

function Field({ label, value, onChange, onBlur, error, valid, t, placeholder, type = 'text', inputMode, autoComplete, required }) {
  const [focus, setFocus] = useStateS(false);
  const errRed = '#d06a4a';
  const greenOk = '#7aa86b';
  const borderColor = error ? errRed : (valid ? greenOk : (focus ? t.brass : t.lineStrong));
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 10,
        letterSpacing: '0.3em',
        color: error ? errRed : (focus ? t.brass : t.dim),
        marginBottom: 6, transition: 'color 0.15s',
      }}>{label}{required && <span style={{ color: t.brass, marginLeft: 4 }}>*</span>}</div>
      <div style={{ position: 'relative' }}>
        <input
          type={type} value={value}
          onChange={(e) => onChange(e.target.value)}
          onFocus={() => setFocus(true)}
          onBlur={() => { setFocus(false); onBlur && onBlur(); }}
          placeholder={placeholder}
          inputMode={inputMode}
          autoComplete={autoComplete}
          aria-invalid={error ? 'true' : 'false'}
          style={{
            width: '100%', padding: '10px 24px 10px 0', background: 'transparent', border: 'none',
            borderBottom: `1px solid ${borderColor}`,
            fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 16,
            color: t.fg, outline: 'none', transition: 'border-color 0.15s',
            boxSizing: 'border-box', minHeight: 44,
          }}
        />
        {valid && !error && (
          <svg viewBox="0 0 24 24" style={{
            position: 'absolute', right: 2, top: '50%', transform: 'translateY(-50%)',
            width: 16, height: 16, fill: greenOk, pointerEvents: 'none',
          }}>
            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" />
          </svg>
        )}
      </div>
      {error && (
        <div style={{
          fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 11,
          color: errRed, marginTop: 4, letterSpacing: '0.05em',
        }}>{error}</div>
      )}
    </div>
  );
}

function SelectField({ label, value, options, onChange, t }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 10,
        letterSpacing: '0.3em', color: t.dim, marginBottom: 6,
      }}>{label}</div>
      <select value={value} onChange={(e) => onChange(e.target.value)}
        style={{
          width: '100%', padding: '10px 0', background: 'transparent',
          border: 'none', borderBottom: `1px solid ${t.lineStrong}`,
          fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 16,
          color: value ? t.fg : t.dim, outline: 'none',
          appearance: 'none', cursor: 'pointer',
          backgroundImage: `linear-gradient(45deg, transparent 50%, ${t.dim} 50%), linear-gradient(135deg, ${t.dim} 50%, transparent 50%)`,
          backgroundPosition: 'calc(100% - 12px) 50%, calc(100% - 6px) 50%',
          backgroundSize: '6px 6px, 6px 6px',
          backgroundRepeat: 'no-repeat',
          paddingRight: 24,
        }}>
        <option value="" style={{ background: t.cellBg, color: t.dim }}>SELECT</option>
        {options.map(o => (
          <option key={o} value={o} style={{ background: t.cellBg, color: t.fg }}>{o}</option>
        ))}
      </select>
    </div>
  );
}

function PillGroup({ label, options, value, onChange, t }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 10,
        letterSpacing: '0.3em', color: t.dim, marginBottom: 8,
      }}>{label}</div>
      <div style={{ display: 'flex', gap: 8 }}>
        {options.map(o => {
          const active = value === o;
          return (
            <button key={o} type="button" onClick={() => onChange(o)}
              style={{
                flex: 1, padding: '10px 0', cursor: 'pointer',
                background: active ? t.accentBg : 'transparent',
                border: `1px solid ${active ? t.brass : t.lineStrong}`,
                color: active ? t.brass : t.fg,
                fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 12,
                letterSpacing: '0.2em', transition: 'all 0.15s',
              }}>{o.toUpperCase()}</button>
          );
        })}
      </div>
    </div>
  );
}

function ChipGroup({ label, options, values, onToggle, t }) {
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 10,
        letterSpacing: '0.3em', color: t.dim, marginBottom: 8,
      }}>{label}</div>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
        {options.map(o => {
          const active = values.includes(o);
          return (
            <button key={o} type="button" onClick={() => onToggle(o)}
              style={{
                padding: '7px 12px', cursor: 'pointer',
                background: active ? t.accentBg : 'transparent',
                border: `1px solid ${active ? t.brass : t.lineStrong}`,
                color: active ? t.brass : t.fg,
                fontFamily: 'Oswald, sans-serif', fontWeight: 600, fontSize: 11,
                letterSpacing: '0.2em', transition: 'all 0.15s',
              }}>{o.toUpperCase()}</button>
          );
        })}
      </div>
    </div>
  );
}

function TextareaField({ label, value, onChange, t, placeholder }) {
  const [focus, setFocus] = useStateS(false);
  return (
    <div style={{ marginBottom: 18 }}>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 10,
        letterSpacing: '0.3em', color: focus ? t.brass : t.dim,
        marginBottom: 6, transition: 'color 0.15s',
      }}>{label}</div>
      <textarea value={value}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        placeholder={placeholder} rows={3}
        style={{
          width: '100%', padding: '10px 0', background: 'transparent',
          border: 'none', borderBottom: `1px solid ${focus ? t.brass : t.lineStrong}`,
          fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 15,
          color: t.fg, outline: 'none', resize: 'vertical',
          transition: 'border-color 0.15s', boxSizing: 'border-box',
        }} />
    </div>
  );
}

function WaiverBox({ checked, onToggle, error, t }) {
  const errRed = '#d06a4a';
  return (
    <div
      onClick={onToggle}
      style={{
        display: 'flex', gap: 12, alignItems: 'flex-start',
        padding: '14px 16px', marginTop: 8, cursor: 'pointer',
        background: checked ? t.accentBg : 'transparent',
        border: `1px solid ${error ? errRed : (checked ? t.brass : t.lineStrong)}`,
        transition: 'all 0.15s',
      }}>
      <div style={{
        width: 18, height: 18, flexShrink: 0, marginTop: 2,
        border: `1.5px solid ${checked ? t.brass : (error ? errRed : t.dim)}`,
        background: checked ? t.brass : 'transparent',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {checked && (
          <svg viewBox="0 0 24 24" style={{ width: 12, height: 12, fill: '#0F1114' }}>
            <path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z" />
          </svg>
        )}
      </div>
      <div style={{
        fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 11,
        color: t.fg, opacity: 0.85, lineHeight: 1.5,
      }}>
        I understand participation involves inherent risk. I am in good physical condition
        and will sign a <strong style={{ color: t.brass }}>Liability Release & Express
        Assumption of Risk</strong> waiver in person before participating.
      </div>
    </div>
  );
}

window.EventDetail = EventDetail;
window.Field = Field;
window.SelectField = SelectField;
window.PillGroup = PillGroup;
window.ChipGroup = ChipGroup;
window.TextareaField = TextareaField;
window.WaiverBox = WaiverBox;
window.SpecCell = SpecCell;
window.SectionLabel = SectionLabel;
