// Block 6 — Secondary CTA + Form anchor section (for Phase 2 layout)
// Reuses the Field / PillGroup / ChipGroup / WaiverBox / TextareaField / SelectField
// components defined in event-detail.jsx (loaded globally before this file).

const SOURCE_OPTIONS_V2 = ['Instagram', 'School / Coach referral', 'Recruiter', 'Friend / Word of mouth', 'Other'];
const CAREER_OPTIONS_V2 = ['PJ', 'CCT', 'SR', 'TACP', 'EOD', 'SERE', 'Unsure'];

function EventSignupSection({ event, t, user, onSubmit, onOpenAuth, existingReg, onViewConfirmation, isFull, spotsLeft }) {
  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] = React.useState({
    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] = React.useState({});
  const [touched, setTouched] = React.useState({});

  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 is optional. If provided, must look like a US phone: 10 digits,
    // optionally with a leading 1 (11 digits total). Formatting chars ok.
    if (f.phone && f.phone.trim()) {
      const digits = f.phone.replace(/\D/g, '');
      if (digits.length < 10 || digits.length > 11) {
        e.phone = 'Enter a 10-digit US phone number.';
      } else if (digits.length === 11 && digits[0] !== '1') {
        e.phone = 'Enter a 10-digit US phone number.';
      }
    }
    const ageNum = parseInt(f.age, 10);
    if (!f.age) e.age = 'Please enter your age.';
    else if (isNaN(ageNum) || ageNum < 18 || ageNum > 39) e.age = 'Age must be 18–39. Under-18 candidates cannot attend events (contact a recruiter).';
    if (!f.waiver) e.waiver = 'Please acknowledge the waiver to continue.';
    return e;
  };
  const isValid = (k) => {
    if (!touched[k]) return false;
    const errs = validate(form);
    if (errs[k]) return false;
    const v = form[k];
    return typeof v === 'string' ? v.trim().length > 0 : !!v;
  };

  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; // belt-and-suspenders against double-fire
    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 {
      // If parent flipped the view to confirmation, this component is already
      // unmounting and this setState is a no-op. If parent threw or stayed,
      // we reset so the candidate can try again.
      setSubmitting(false);
    }
  };

  // Already registered — show confirmation panel instead of form
  if (existingReg) {
    return (
      <section style={{ background: t.cellBg, padding: '56px 24px', borderTop: `4px solid ${t.brass}` }}>
        <div style={{ maxWidth: 640, margin: '0 auto' }}>
          <div style={{
            fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 11,
            color: t.brass, letterSpacing: '0.35em', marginBottom: 10,
          }}>// BLOCK 06 · STATUS</div>
          <div style={{
            padding: '28px 28px', background: t.bg,
            border: `1px solid ${t.line}`, textAlign: 'center',
          }}>
            <div style={{
              fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 30,
              color: '#7aa86b', letterSpacing: '0.08em', marginBottom: 10,
            }}>✓ LOCKED IN</div>
            <div style={{
              fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 14,
              color: t.fg, marginBottom: 22, lineHeight: 1.5,
            }}>You're confirmed for this event. Show up on time and ready.</div>
            <button onClick={onViewConfirmation} style={{
              padding: '14px 28px', minHeight: 48,
              background: t.brass, color: '#0F1114', border: 'none',
              fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 13,
              letterSpacing: '0.25em', cursor: 'pointer',
            }}>VIEW CONFIRMATION →</button>
          </div>
        </div>
      </section>
    );
  }

  return (
    <section style={{ background: t.cellBg, padding: '56px 24px 100px', borderTop: `4px solid ${t.brass}` }}>
      <div style={{ maxWidth: 640, margin: '0 auto' }}>
        <div style={{
          fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 11,
          color: t.brass, letterSpacing: '0.35em', marginBottom: 10,
        }}>// BLOCK 06</div>
        <h2 style={{
          fontFamily: 'Bebas Neue, sans-serif', fontWeight: 400,
          fontSize: 'clamp(28px, 4vw, 44px)', lineHeight: 1,
          color: t.fg, margin: '0 0 8px', letterSpacing: '0.02em',
        }}>{isFull ? 'WAITLIST' : 'RESERVE MY SPOT'}</h2>
        <div style={{
          fontFamily: 'Barlow, sans-serif', fontWeight: 300, fontSize: 13,
          color: t.dim, marginBottom: 10, lineHeight: 1.55,
        }}>
          {isFull
            ? 'This event is full. Add your name to the waitlist. We release spots as no-shows cancel.'
            : '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: 24, letterSpacing: '0.2em',
        }}><span style={{ color: t.brass }}>*</span> REQUIRED FIELD</div>

        <div style={{
          padding: 24, background: t.bg, border: `1px solid ${t.line}`,
        }}>
          <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 }}>
              <window.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" />
              <window.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>
            <window.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" />
            <window.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" />
            <window.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" />

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

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

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

            <window.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: 10, textAlign: 'center', letterSpacing: '0.15em',
                }}>
                  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: '20px', minHeight: 56,
              background: t.brass, color: '#0F1114', border: 'none',
              fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 15,
              letterSpacing: '0.3em',
              cursor: submitting ? 'wait' : 'pointer',
              opacity: submitting ? 0.6 : 1,
              marginTop: 16, 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>

        {/* POC fallback */}
        <div style={{
          marginTop: 24, padding: '16px 20px',
          background: t.bg, border: `1px dashed ${t.line}`,
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          gap: 14, flexWrap: 'wrap',
        }}>
          <div>
            <div style={{
              fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 10,
              color: t.dim, letterSpacing: '0.25em', marginBottom: 4,
            }}>QUESTIONS?</div>
            <div style={{
              fontFamily: 'Barlow, sans-serif', fontWeight: 400, fontSize: 13,
              color: t.fg,
            }}>DM @pacific.afsws — we respond within a day.</div>
          </div>
          <a href="https://instagram.com/pacific.afsws" target="_blank" rel="noreferrer"
            style={{
              padding: '8px 14px', border: `1px solid ${t.brass}`,
              color: t.brass, textDecoration: 'none',
              fontFamily: 'Oswald, sans-serif', fontWeight: 700, fontSize: 11,
              letterSpacing: '0.25em',
            }}>OPEN DM →</a>
        </div>
      </div>
    </section>
  );
}

window.EventSignupSection = EventSignupSection;
