/* Application / Apply modal for Rep by Rep.
   ============================================================
   Opens when any "Apply" CTA is clicked.

   LOCKED DECISION (2026-05-20, Master Decisions Log):
   - Application form gates a Cal.com calendar.
   - The calendar is BLURRED behind an overlay until the form is complete.
   - A radio lets the applicant choose how to start:
       "Schedule a call directly" → blur lifts, they pick a time
       "Email me first"           → they submit, JP reaches out within 24h
   - Form fields: Name, Email, Age, Training experience, Primary goal,
     Training availability, 3-month commitment confirmation, How'd you
     hear about us, Additional notes (optional).

   This file REPLACES the old 3-step wizard (expectations → calendar →
   confirm). The blur-to-unlock model is the locked design.

   Brand discipline: no em dashes in client copy (periods/commas instead),
   no exclamation marks, sapphire as the only accent.
   ============================================================ */

// ── MailerLite apply-path group tagging ──────────────────────────────────
// One group per path. Do not let either fire for the other.
//   email-first  → source::apply-email-first  (fires automation 189201233924326952)
//   call         → source::discovery-call     (fires automation 189201255363511420)
//                  Call tag fires on bookingSuccessful only — not on path selection.
const ML_GROUPS = {
  emailFirst:      '189201167161492983',
  discoveryCall:   '188557302026995140',
  getfitafter40:   '191261376391415160',
};

async function addToMailerLiteGroup(groupId, subscriber) {
  try {
    await fetch('/api/subscribe', {
      method:  'POST',
      headers: { 'Content-Type': 'application/json' },
      body:    JSON.stringify({ email: subscriber.email, name: subscriber.name || '', groupId }),
    });
  } catch (e) {
    console.error('ML group tag error:', e);
  }
}
// ─────────────────────────────────────────────────────────────────────────

const ApplyModal = ({ open, onClose }) => {
  const BLANK = {
    name: '', email: '', age: '',
    experience: '', goal: '', availability: '',
    commit: false, source: '', notes: '',
  };
  const [form, setForm] = React.useState(BLANK);
  const [startMode, setStartMode] = React.useState(null); // 'call' | 'email' | null
  const [selectedDate, setSelectedDate] = React.useState(null);
  const [selectedTime, setSelectedTime] = React.useState(null);
  const [result, setResult] = React.useState(null); // 'booked' | 'emailed' | null

  // Reset when closed
  React.useEffect(() => {
    if (!open) {
      const t = setTimeout(() => {
        setForm(BLANK);
        setStartMode(null);
        setSelectedDate(null);
        setSelectedTime(null);
        setResult(null);
      }, 300);
      return () => clearTimeout(t);
    }
  }, [open]);

  // Lock body scroll while open
  React.useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  // Required-field validation. Commitment checkbox is a hard gate.
  const emailValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email);
  const formComplete =
    form.name.trim() &&
    emailValid &&
    form.age.trim() &&
    form.experience &&
    form.goal &&
    form.availability &&
    form.commit;

  // The calendar unlocks only when the form is complete AND they chose
  // the "schedule directly" path.
  const calendarUnlocked = formComplete && startMode === 'call';

  if (!open) return null;

  return (
    <div
      role="dialog"
      aria-modal="true"
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        background: 'rgba(17,20,24,0.85)',
        display: 'flex', alignItems: 'flex-start', justifyContent: 'center',
        padding: '48px 24px', overflowY: 'auto',
        animation: 'rxrFadeIn 200ms cubic-bezier(.16,1,.3,1)',
      }}
    >
      <style>{`
        @keyframes rxrFadeIn { from { opacity: 0; } to { opacity: 1; } }
        @keyframes rxrSlideUp { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
        @keyframes rxrUnlock { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
      `}</style>

      <div style={{
        background: '#fff', borderRadius: 6,
        maxWidth: 760, width: '100%', position: 'relative',
        animation: 'rxrSlideUp 300ms cubic-bezier(.16,1,.3,1)',
      }}>
        {/* Close */}
        <button
          onClick={onClose}
          aria-label="Close"
          style={{
            position: 'absolute', top: 18, right: 18,
            background: '#fff', border: 0, cursor: 'pointer',
            color: 'var(--fg-3)', padding: 8, borderRadius: 4,
            transition: 'all 150ms cubic-bezier(.16,1,.3,1)', display: 'flex', zIndex: 20,
            boxShadow: '0 1px 3px rgba(0,0,0,0.08)',
          }}
          onMouseEnter={e => { e.currentTarget.style.background = 'var(--rxr-haze)'; e.currentTarget.style.color = 'var(--fg)'; }}
          onMouseLeave={e => { e.currentTarget.style.background = '#fff'; e.currentTarget.style.color = 'var(--fg-3)'; }}
        >
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.75" strokeLinecap="round">
            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        </button>

        {result
          ? <ApplyConfirmed result={result} form={form} selectedDate={selectedDate} selectedTime={selectedTime} onClose={onClose} />
          : (
            <>
              {/* Header */}
              <div style={{ padding: '32px 40px 24px', borderBottom: '1px solid var(--border)' }}>
                <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--accent)' }}>
                  Apply for Coaching
                </div>
                <h2 style={{
                  fontFamily: 'var(--font-display)', fontSize: 36, lineHeight: 1,
                  letterSpacing: '-0.01em', color: 'var(--fg)', margin: '10px 0 8px',
                  textTransform: 'uppercase',
                }}>
                  Tell me where you&apos;re at.
                </h2>
                <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--fg-2)', margin: 0, maxWidth: '58ch' }}>
                  This is how I learn whether coaching is the right fit for both of us. Honest answers only. The highlight reel doesn&apos;t help either of us.
                </p>
              </div>

              {/* Body */}
              <div style={{ padding: 40 }}>
                <ApplyForm form={form} setForm={setForm} />

                {/* Start mode */}
                <div style={{ marginTop: 32, paddingTop: 28, borderTop: '1px solid var(--border)' }}>
                  <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 4 }}>
                    How do you want to start
                  </div>
                  <p style={{ fontSize: 13, color: 'var(--fg-3)', margin: '0 0 16px' }}>
                    Both paths reach the same place. Pick what fits how you like to move.
                  </p>
                  <div className="m-1" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                    <StartChoice
                      active={startMode === 'call'}
                      disabled={!formComplete}
                      title="Schedule a call directly"
                      sub="Pick a time now. We talk this week."
                      onClick={() => setStartMode('call')}
                    />
                    <StartChoice
                      active={startMode === 'email'}
                      disabled={!formComplete}
                      title="Email me first"
                      sub="I reach out within 24 hours, then we find a time."
                      onClick={() => setStartMode('email')}
                    />
                  </div>
                </div>

                {/* Bottom panel — blurred calendar / live calendar / email path */}
                <div style={{ marginTop: 28, position: 'relative' }}>
                  {startMode === 'email' && formComplete ? (
                    <EmailPath form={form} onSubmit={() => setResult('emailed')} />
                  ) : (
                    <div style={{ position: 'relative' }}>
                      <div style={{
                        filter: calendarUnlocked ? 'none' : 'blur(5px)',
                        opacity: calendarUnlocked ? 1 : 0.55,
                        pointerEvents: calendarUnlocked ? 'auto' : 'none',
                        transition: 'filter 400ms cubic-bezier(.16,1,.3,1), opacity 400ms cubic-bezier(.16,1,.3,1)',
                        userSelect: calendarUnlocked ? 'auto' : 'none',
                      }}>
                        <CalendarPanel
                          name={form.name}
                          email={form.email}
                          source={form.source}
                          onConfirm={() => setResult('booked')}
                        />
                      </div>

                      {/* Lock overlay */}
                      {!calendarUnlocked && (
                        <div style={{
                          position: 'absolute', inset: 0,
                          display: 'flex', flexDirection: 'column',
                          alignItems: 'center', justifyContent: 'center',
                          textAlign: 'center', padding: 24,
                          background: 'rgba(255,255,255,0.4)',
                        }}>
                          <div style={{
                            width: 40, height: 40, borderRadius: 20,
                            background: 'var(--rxr-charcoal)',
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            marginBottom: 16,
                          }}>
                            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                              <rect x="3" y="11" width="18" height="11" rx="2"/>
                              <path d="M7 11V7a5 5 0 0 1 10 0v4"/>
                            </svg>
                          </div>
                          <div style={{
                            fontFamily: 'var(--font-headline)', fontWeight: 600, fontSize: 17,
                            textTransform: 'uppercase', letterSpacing: '0.02em', color: 'var(--fg)',
                            marginBottom: 6, maxWidth: '30ch',
                          }}>
                            {startMode === 'email'
                              ? 'You chose email. No calendar needed.'
                              : !formComplete
                                ? 'Complete the form to unlock your time.'
                                : 'Choose how you want to start.'}
                          </div>
                          <div style={{ fontSize: 13, color: 'var(--fg-2)', maxWidth: '40ch', lineHeight: 1.5 }}>
                            {startMode === 'email'
                              ? 'Use the button below to send your application.'
                              : !formComplete
                                ? 'Fill in every required field above, including the 3-month commitment, and the calendar opens.'
                                : 'Pick "Schedule a call directly" above to open the calendar.'}
                          </div>
                        </div>
                      )}
                    </div>
                  )}
                </div>
              </div>
            </>
          )}
      </div>
    </div>
  );
};

// ---------------- Application form ----------------
const ApplyForm = ({ form, setForm }) => {
  const set = (k) => (v) => setForm({ ...form, [k]: v });
  return (
    <div>
      <div className="m-1" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
        <ApField label="Full Name" required value={form.name} onChange={set('name')} />
        <ApField label="Email" required type="email" value={form.email} onChange={set('email')} />
        <ApField label="Age" required type="text" value={form.age} onChange={set('age')} placeholder="e.g. 38" />
        <ApSelect label="Training Experience" required value={form.experience} onChange={set('experience')}
          options={['', 'Under 1 year', '1 to 3 years', '3 to 5 years', '5 to 10 years', '10+ years']} />
        <ApSelect label="Primary Goal" required value={form.goal} onChange={set('goal')}
          options={['', 'General coaching', 'Lean bulk / recomp', 'Cut to maintenance', 'Contest Prep', 'Not sure yet']} />
        <ApSelect label="Training Availability" required value={form.availability} onChange={set('availability')}
          options={['', '2 days / week', '3 days / week', '4 days / week', '5 days / week', '6+ days / week']} />
      </div>

      <div style={{ marginTop: 18 }}>
        <ApSelect label="How did you hear about us" value={form.source} onChange={set('source')} optional
          options={['', 'Instagram', 'YouTube', 'A current or former client', 'Search', 'The 3-Week Reset', { value: 'getfitafter40', label: 'getfitafter40.com' }, 'Other']} />
      </div>

      <div style={{ marginTop: 18 }}>
        <ApField label="Anything I should know going in" optional textarea value={form.notes} onChange={set('notes')} />
      </div>

      {/* 3-month commitment — required gate */}
      <label style={{
        display: 'flex', alignItems: 'flex-start', gap: 12, marginTop: 22,
        padding: '16px 18px', borderRadius: 6, cursor: 'pointer',
        border: '1px solid ' + (form.commit ? 'var(--accent)' : 'var(--border-strong)'),
        background: form.commit ? 'var(--rxr-sapphire-wash)' : '#fff',
        transition: 'all 150ms cubic-bezier(.16,1,.3,1)',
      }}>
        <input
          type="checkbox"
          checked={form.commit}
          onChange={e => set('commit')(e.target.checked)}
          style={{ marginTop: 2, width: 18, height: 18, accentColor: 'var(--accent)', flexShrink: 0, cursor: 'pointer' }}
        />
        <div>
          <div style={{ fontSize: 14, fontWeight: 600, color: 'var(--fg)', lineHeight: 1.4 }}>
            I understand coaching starts with a 3-month commitment.
          </div>
          <div style={{ fontSize: 13, color: 'var(--fg-2)', marginTop: 4, lineHeight: 1.5 }}>
            Real change takes a full training block. After 3 months it moves to month-to-month. This is required to apply.
          </div>
        </div>
      </label>
    </div>
  );
};

// ---------------- Start-mode choice card ----------------
const StartChoice = ({ active, disabled, title, sub, onClick }) => (
  <button
    onClick={onClick}
    disabled={disabled}
    style={{
      textAlign: 'left', padding: '16px 18px', borderRadius: 6, cursor: disabled ? 'not-allowed' : 'pointer',
      border: '1px solid ' + (active ? 'var(--accent)' : 'var(--border-strong)'),
      background: active ? 'var(--rxr-sapphire-wash)' : '#fff',
      opacity: disabled ? 0.45 : 1,
      transition: 'all 150ms cubic-bezier(.16,1,.3,1)',
      display: 'flex', gap: 12, alignItems: 'flex-start',
    }}
    onMouseEnter={e => { if (!disabled && !active) e.currentTarget.style.borderColor = 'var(--fg)'; }}
    onMouseLeave={e => { if (!disabled && !active) e.currentTarget.style.borderColor = 'var(--border-strong)'; }}
  >
    <div style={{
      width: 18, height: 18, borderRadius: 9, flexShrink: 0, marginTop: 1,
      border: '2px solid ' + (active ? 'var(--accent)' : 'var(--border-strong)'),
      background: active ? 'var(--accent)' : '#fff',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      transition: 'all 150ms cubic-bezier(.16,1,.3,1)',
    }}>
      {active && <div style={{ width: 6, height: 6, borderRadius: 3, background: '#fff' }} />}
    </div>
    <div>
      <div style={{ fontFamily: 'var(--font-headline)', fontWeight: 600, fontSize: 14, textTransform: 'uppercase', letterSpacing: '0.02em', color: 'var(--fg)' }}>{title}</div>
      <div style={{ fontSize: 12.5, color: 'var(--fg-2)', marginTop: 3, lineHeight: 1.45 }}>{sub}</div>
    </div>
  </button>
);

// ---------------- Email path ----------------
const EmailPath = ({ form, onSubmit }) => {
  const [sending, setSending] = React.useState(false);

  const handleSend = async () => {
    setSending(true);
    try {
      await fetch('https://formspree.io/f/xwvzgjvv', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify({
          _subject:     'New Coaching Application — ' + (form.name || 'Unknown'),
          name:         form.name,
          email:        form.email,
          age:          form.age,
          experience:   form.experience,
          goal:         form.goal,
          availability: form.availability,
          source:       form.source || '—',
          notes:        form.notes || '—',
          path:         'email-first',
        }),
      });
      // Tag to source::apply-email-first — email path only
      await addToMailerLiteGroup(ML_GROUPS.emailFirst, { email: form.email, name: form.name });
      if (form.source === 'getfitafter40') {
        await addToMailerLiteGroup(ML_GROUPS.getfitafter40, { email: form.email, name: form.name });
      }
    } catch (err) {
      console.error('Application submit error:', err);
    }
    onSubmit();
  };

  return (
    <div style={{
      border: '1px solid var(--border)', borderRadius: 6, padding: 28,
      background: 'var(--rxr-snow)', animation: 'rxrUnlock 300ms cubic-bezier(.16,1,.3,1)',
    }}>
      <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 10 }}>
        Email First
      </div>
      <div style={{ fontFamily: 'var(--font-headline)', fontWeight: 600, fontSize: 20, textTransform: 'uppercase', letterSpacing: '0.02em', color: 'var(--fg)', marginBottom: 10 }}>
        Send your application.
      </div>
      <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--fg-2)', margin: '0 0 20px', maxWidth: '54ch' }}>
        I read every application myself. Expect a reply at <strong style={{ color: 'var(--fg)' }}>{form.email || 'your email'}</strong> within 24 hours. We take it from there and find a time that works.
      </p>
      <button onClick={handleSend} disabled={sending} className="btn btn-primary" style={{ padding: '14px 24px', opacity: sending ? 0.6 : 1 }}>
        {sending ? 'Sending…' : 'Send Application →'}
      </button>
    </div>
  );
};

// ---------------- Calendar panel — Cal.com inline embed ----------------
const CalendarPanel = ({ name, email, source, onConfirm }) => {
  const containerRef = React.useRef(null);
  const initialized  = React.useRef(false);

  React.useEffect(() => {
    if (initialized.current || !window.Cal || !containerRef.current) return;
    initialized.current = true;

    Cal('inline', {
      elementOrSelector: containerRef.current,
      calLink: 'jasonrxr/discovery',
      layout: 'month_view',
      config: { name: name || '', email: email || '' },
    });
    Cal('ui', { theme: 'light', hideEventTypeDetails: false, layout: 'month_view' });

    // Fire on confirmed booking only — not on path selection
    const handleMsg = (e) => {
      if (e.data && e.data.type === 'bookingSuccessful') {
        addToMailerLiteGroup(ML_GROUPS.discoveryCall, { email: email, name: name });
        if (source === 'getfitafter40') {
          addToMailerLiteGroup(ML_GROUPS.getfitafter40, { email: email, name: name });
        }
        onConfirm && onConfirm();
      }
    };
    window.addEventListener('message', handleMsg);
    return () => window.removeEventListener('message', handleMsg);
  }, []);

  return (
    <div>
      <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 12 }}>
        Pick a time · ~30 min · Free
      </div>
      <div ref={containerRef} style={{ width: '100%', height: 550, overflow: 'auto', borderRadius: 6, border: '1px solid var(--border)' }} />
    </div>
  );
};

// ---------------- Confirmation ----------------
const ApplyConfirmed = ({ result, form, selectedDate, selectedTime, onClose }) => {
  const formattedDate = selectedDate
    ? new Date(selectedDate.year, selectedDate.month, selectedDate.day).toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric' })
    : '';
  const booked = result === 'booked';
  return (
    <div style={{ padding: '48px 40px' }}>
      <div style={{ width: 48, height: 48, borderRadius: 24, background: 'var(--rxr-volt)', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', marginBottom: 22 }}>
        <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
      </div>

      <div style={{ fontSize: 11, fontWeight: 600, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 10 }}>
        {booked ? 'You\u2019re booked' : 'Application received'}
      </div>
      <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 38, lineHeight: 1, letterSpacing: '-0.01em', color: 'var(--fg)', margin: '0 0 16px', textTransform: 'uppercase' }}>
        {booked
          ? (formattedDate
              ? (<>{formattedDate}.<br/>{selectedTime}.</>)
              : (<>You&apos;re booked,<br/>{(form.name || '').split(' ')[0] || 'lifter'}.</>))
          : (<>Talk soon,<br/>{(form.name || '').split(' ')[0] || 'lifter'}.</>)}
      </h2>

      {booked ? (
        <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--fg-2)', margin: '0 0 24px', maxWidth: '56ch' }}>
          Confirmation is on the way to <strong style={{ color: 'var(--fg)' }}>{form.email}</strong> with the call link. Put it on your calendar. I never miss a call, and I expect the same from you.
        </p>
      ) : (
        <p style={{ fontSize: 15, lineHeight: 1.6, color: 'var(--fg-2)', margin: '0 0 24px', maxWidth: '56ch' }}>
          I read every application myself. Expect a reply at <strong style={{ color: 'var(--fg)' }}>{form.email}</strong> within 24 hours. We find a time from there.
        </p>
      )}

      <div style={{ background: 'var(--rxr-haze)', padding: '20px 24px', borderRadius: 6 }}>
        <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.22em', textTransform: 'uppercase', color: 'var(--accent)' }}>Before we talk</div>
        <ul style={{ listStyle: 'none', padding: 0, margin: '12px 0 0', display: 'flex', flexDirection: 'column', gap: 8 }}>
          {[
            'Think about what success looks like for you in 6 months. Be specific.',
            'Have your current training and nutrition top of mind. We review both.',
            'Bring the honest questions about the process and the cost.',
          ].map(t => (
            <li key={t} style={{ fontSize: 13, color: 'var(--fg)', display: 'flex', gap: 10, lineHeight: 1.5 }}>
              <span style={{ color: 'var(--accent)', fontWeight: 600, flexShrink: 0 }}>—</span>{t}
            </li>
          ))}
        </ul>
      </div>

      <div style={{ marginTop: 28, paddingTop: 20, borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 14, flexWrap: 'wrap' }}>
        <div style={{ fontSize: 13, color: 'var(--fg-2)' }}>
          Questions? <a href="mailto:JP@repxrep.fit" style={{ color: 'var(--accent)', fontWeight: 600 }}>JP@repxrep.fit</a>
        </div>
        <button onClick={onClose} className="btn btn-primary" style={{ padding: '12px 22px' }}>Done</button>
      </div>
    </div>
  );
};

// ---------------- Form primitives ----------------
const ApField = ({ label, required, optional, type = 'text', textarea, value, onChange, placeholder }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
    <label style={{ fontSize: 10, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.18em', color: 'var(--fg-3)' }}>
      {label}{required && <span style={{ marginLeft: 3, color: 'var(--accent)' }}>*</span>}{optional && <span style={{ marginLeft: 8, color: 'var(--fg-4)', letterSpacing: '0.1em' }}>OPTIONAL</span>}
    </label>
    {textarea ? (
      <textarea value={value} onChange={e => onChange(e.target.value)} rows={3}
        style={{ fontFamily: 'var(--font-body)', fontSize: 14, padding: '11px 12px', borderRadius: 6, border: '1px solid var(--border-strong)', background: '#fff', color: 'var(--fg)', resize: 'vertical', minHeight: 64 }} />
    ) : (
      <input type={type} value={value} placeholder={placeholder || ''} onChange={e => onChange(e.target.value)}
        style={{ fontFamily: 'var(--font-body)', fontSize: 14, padding: '11px 12px', borderRadius: 6, border: '1px solid var(--border-strong)', background: '#fff', color: 'var(--fg)' }} />
    )}
  </div>
);

const ApSelect = ({ label, required, optional, value, onChange, options }) => (
  <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
    <label style={{ fontSize: 10, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.18em', color: 'var(--fg-3)' }}>
      {label}{required && <span style={{ marginLeft: 3, color: 'var(--accent)' }}>*</span>}{optional && <span style={{ marginLeft: 8, color: 'var(--fg-4)', letterSpacing: '0.1em' }}>OPTIONAL</span>}
    </label>
    <select value={value} onChange={e => onChange(e.target.value)}
      style={{ fontFamily: 'var(--font-body)', fontSize: 14, padding: '11px 12px', borderRadius: 6, border: '1px solid var(--border-strong)', background: '#fff', color: value ? 'var(--fg)' : 'var(--fg-4)' }}>
      {options.map((o, i) => {
        const val = o && typeof o === 'object' ? o.value : o;
        const lbl = o && typeof o === 'object' ? o.label : o;
        return <option key={i} value={val}>{lbl || 'Choose one…'}</option>;
      })}
    </select>
  </div>
);

Object.assign(window, { ApplyModal });
