// apply.jsx — Every Man's Health · Apply for Membership.
// Conversion endpoint for a limited-panel concierge practice. Selective,
// calm, premium, physician-led — not a sales funnel, not a generic contact
// page. Form is a membership inquiry, NOT a medical intake.
//
// Responsive: useViewport() tier hook (shared.jsx). PX = horizontal padding,
// SY = scaled vertical padding. Above 1024px = original desktop design.

const PX = (vp) => vp.pad;
const SY = (vp, n) => Math.round(n * (vp.isPhone ? 0.5 : vp.isMobile ? 0.6 : vp.isTablet ? 0.8 : 1));

// ── Form options ────────────────────────────────────────────────────────
// Option VALUES must match the backend Worker validation exactly. Labels may
// be friendlier for display; the value sent in the payload is the backend token.
const AGE_RANGES = ['30–44', '45–59', '60+', 'Prefer not to say'];
const CONTACT_METHODS = ['Email', 'Phone', 'Text message'];
const IN_PERSON_EVALUATION_OPTIONS = [
  { value: 'Yes — local', label: 'Yes — I live in the Ocala / Florida area' },
  { value: 'Yes — can travel', label: 'Yes — I can travel to Florida for an initial visit' },
  { value: 'Not sure yet', label: 'Not sure yet' },
  { value: 'No', label: 'No' },
];
// Florida first, then alphabetical. Values are full state names.
const US_STATES = ['Florida', 'Alabama', 'Alaska', 'Arizona', 'Arkansas', 'California', 'Colorado', 'Connecticut', 'Delaware', 'District of Columbia', 'Georgia', 'Hawaii', 'Idaho', 'Illinois', 'Indiana', 'Iowa', 'Kansas', 'Kentucky', 'Louisiana', 'Maine', 'Maryland', 'Massachusetts', 'Michigan', 'Minnesota', 'Mississippi', 'Missouri', 'Montana', 'Nebraska', 'Nevada', 'New Hampshire', 'New Jersey', 'New Mexico', 'New York', 'North Carolina', 'North Dakota', 'Ohio', 'Oklahoma', 'Oregon', 'Pennsylvania', 'Rhode Island', 'South Carolina', 'South Dakota', 'Tennessee', 'Texas', 'Utah', 'Vermont', 'Virginia', 'Washington', 'West Virginia', 'Wisconsin', 'Wyoming'];

const AFTER_STEPS = [
  { n: '01', t: 'Submit a brief inquiry', body: 'A short note about who you are and what you\'re hoping to address. No medical detail required at this stage.' },
  { n: '02', t: 'Introductory conversation', body: 'A brief, no-pressure conversation about your goals and whether our model is the right fit for you.' },
  { n: '03', t: 'In-person physician evaluation', body: 'If it\'s a fit, we schedule your first long visit at our Florida practice — the real beginning of the relationship.' },
  { n: '04', t: 'Membership decision & care plan', body: 'After the evaluation, we decide together whether ongoing membership is appropriate, and your physician outlines a plan.' },
];

const NOT_THIS = [
  'This is not an emergency contact pathway.',
  'This form is not for urgent symptoms or acute medical concerns.',
  'Submitting this form does not establish a physician-patient relationship.',
  'Detailed medical intake occurs later, through a secure and appropriate process.',
];

// ── Page ────────────────────────────────────────────────────────────────
function ApplyPage() {
  const [t, setTweak] = useTweaks(window.TWEAK_DEFAULTS);
  const vp = useViewport();
  const p = PALETTES[t.palette];
  const T = TYPES[t.typePair];
  const tc = toneCopy(t.tone);

  const S = {
    base:      { background: p.cream, color: p.ink, fontFamily: T.body, fontSize: 15.5, lineHeight: 1.55, letterSpacing: '-0.005em' },
    display:   { fontFamily: T.display, fontWeight: T.displayWeight, letterSpacing: T.displayTracking, color: p.ink },
    mono:      { fontFamily: T.mono, letterSpacing: '0.14em', textTransform: 'uppercase' },
    container: { padding: `0 ${PX(vp)}px`, position: 'relative', maxWidth: 1440, margin: '0 auto' },
  };

  return (
    <div style={S.base}>
      <ANav p={p} T={T} S={S} vp={vp} />
      <AHero p={p} T={T} S={S} vp={vp} />
      <AWhyLimited p={p} T={T} S={S} vp={vp} />
      <AAfter p={p} T={T} S={S} vp={vp} />
      <AForm p={p} T={T} S={S} vp={vp} />
      <ANotThis p={p} T={T} S={S} vp={vp} />
      <AContact p={p} T={T} S={S} vp={vp} />
      <APrivacy p={p} T={T} S={S} vp={vp} />
      <ACTA p={p} T={T} S={S} vp={vp} />
      <AFooter p={p} T={T} S={S} vp={vp} />

      <TweaksPanel title="Tweaks">
        <TweakSection label="Palette">
          <TweakColor label="Theme" value={t.palette}
            options={[
              ['#0E1E3A', '#F2EBDD', '#B8965B'],
              ['#0A1628', '#ECE6D9', '#3FB6C2'],
              ['#142244', '#EFE4D0', '#7A8F6E'],
            ]}
            onChange={(v) => {
              const map = { '["#0e1e3a","#f2ebdd","#b8965b"]': 'marine',
                            '["#0a1628","#ece6d9","#3fb6c2"]': 'graphite',
                            '["#142244","#efe4d0","#7a8f6e"]': 'atlantic' };
              setTweak('palette', map[JSON.stringify(v).toLowerCase()] || 'marine');
            }} />
        </TweakSection>
        <TweakSection label="Typography">
          <TweakRadio label="Pairing" value={t.typePair}
            options={[{ value: 'editorial', label: 'Editorial' },
                     { value: 'clinical',  label: 'Clinical' },
                     { value: 'technical', label: 'Technical' }]}
            onChange={(v) => setTweak('typePair', v)} />
        </TweakSection>
        <TweakSection label="Tone">
          <TweakSlider label="Clinical ↔ Consumer" value={t.tone}
            min={1} max={10} step={1}
            onChange={(v) => setTweak('tone', v)} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

// ── NAV ─────────────────────────────────────────────────────────────────
function ANav({ p, T, S, vp }) {
  const [hover, setHover] = React.useState(null);
  const [open, setOpen] = React.useState(false);
  const items = [
    { label: 'The Practice', href: 'EMH_05_The_Practice.html' },
    { label: 'Care Model',   href: 'EMH_03_Care_Model.html' },
    { label: 'Membership',   href: 'EMH_04_Membership.html' },
    { label: 'Insights',     href: 'EMH_13_Insights.html' },
  ];
  const applyBtn = (
    <a href="#apply" style={{ fontFamily: T.body, fontSize: 13.5, fontWeight: 500, padding: '10px 18px', background: p.ink, color: p.cream, border: 'none', borderRadius: 2, cursor: 'pointer', whiteSpace: 'nowrap', textDecoration: 'none', display: 'inline-block' }}>Apply for membership</a>
  );

  if (vp.isMobile) {
    return (
      <div style={{ position: 'sticky', top: 0, zIndex: 20, background: `${p.cream}f5`, backdropFilter: 'blur(10px)', borderBottom: `1px solid ${p.ink}1a` }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: `14px ${PX(vp)}px`, gap: 14 }}>
          <a href="EMH_02_Florida_Concierge_Homepage_Current.html" style={{ display: 'flex', alignItems: 'center', gap: 10, textDecoration: 'none', color: 'inherit', minWidth: 0 }}>
            <EMHMark color={p.ink} size={24} />
            <div style={{ fontFamily: T.display, fontWeight: 500, fontSize: 15.5, letterSpacing: '-0.012em', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Every Man's Health</div>
          </a>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0 }}>
            <button onClick={() => setOpen((o) => !o)} aria-expanded={open} aria-label="Menu"
              style={{ fontFamily: T.body, fontSize: 13, fontWeight: 500, padding: '9px 12px', background: 'transparent', color: p.ink, border: `1px solid ${p.ink}33`, borderRadius: 2, cursor: 'pointer', display: 'inline-flex', alignItems: 'center', gap: 6 }}>
              Menu<span style={{ display: 'inline-block', transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .18s', fontSize: 9 }}>▾</span>
            </button>
            {!vp.isPhone && applyBtn}
          </div>
        </div>
        {open && (
          <div style={{ borderTop: `1px solid ${p.ink}14`, padding: `8px ${PX(vp)}px 16px`, display: 'flex', flexDirection: 'column' }}>
            {items.map(({ label, href }) => (
              <a key={label} href={href} onClick={() => setOpen(false)}
                 style={{ fontSize: 15, color: p.ink, textDecoration: 'none', padding: '13px 0', borderBottom: `1px solid ${p.ink}10` }}>
                {label}
              </a>
            ))}
            <a href="https://www.yourhealthfile.com/portal/login.jsp" target="_blank" rel="noopener noreferrer" style={{ fontSize: 15, color: p.inkSoft, textDecoration: 'none', padding: '13px 0' }}>Patient Portal</a>
            <div style={{ marginTop: 10 }}>{applyBtn}</div>
          </div>
        )}
      </div>
    );
  }

  return (
    <div style={{ position: 'sticky', top: 0, zIndex: 10, background: `${p.cream}f0`, backdropFilter: 'blur(10px)', borderBottom: `1px solid ${p.ink}1a` }}>
      <div style={{ ...S.container, display: 'flex', alignItems: 'center', padding: `20px ${PX(vp)}px`, gap: vp.isTablet ? 24 : 40 }}>
        <a href="EMH_02_Florida_Concierge_Homepage_Current.html" style={{ display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none', color: 'inherit' }}>
          <EMHMark color={p.ink} size={26} />
          <div style={{ fontFamily: T.display, fontWeight: 500, fontSize: 17, letterSpacing: '-0.012em', whiteSpace: 'nowrap' }}>Every Man's Health</div>
        </a>
        <div style={{ flex: 1, display: 'flex', justifyContent: 'center', gap: vp.isTablet ? 22 : 32 }}>
          {items.map(({ label, href }) => (
            <a key={label} href={href} onMouseEnter={() => setHover(label)} onMouseLeave={() => setHover(null)}
               style={{ fontSize: 13.5, color: hover === label ? p.ink : p.inkSoft, textDecoration: 'none', transition: 'color .12s', position: 'relative', padding: '4px 0', whiteSpace: 'nowrap' }}>
              {label}
              {hover === label && <span style={{ position: 'absolute', left: 0, right: 0, bottom: -2, height: 1, background: p.accent }} />}
            </a>
          ))}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          {!vp.isTablet && <a href="https://www.yourhealthfile.com/portal/login.jsp" target="_blank" rel="noopener noreferrer" style={{ fontSize: 13.5, color: p.inkSoft, textDecoration: 'none', whiteSpace: 'nowrap' }}>Patient Portal</a>}
          {applyBtn}
        </div>
      </div>
    </div>
  );
}

// ── HERO ────────────────────────────────────────────────────────────────
function AHero({ p, T, S, vp }) {
  return (
    <section style={{ ...S.container, padding: `${SY(vp, 96)}px ${PX(vp)}px ${SY(vp, 80)}px`, borderBottom: `1px solid ${p.ink}14` }}>
      <div style={{ ...S.mono, fontSize: 11, color: p.accent, marginBottom: 24, display: 'inline-flex', alignItems: 'center', gap: 10 }}>
        <span style={{ width: 5, height: 5, borderRadius: 3, background: p.accent }} />
        By application · Limited panel · Florida
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: vp.isMobile ? '1fr' : '1.3fr 1fr', gap: vp.isMobile ? 28 : 80, alignItems: vp.isMobile ? 'start' : 'end' }}>
        <h1 style={{ ...S.display, fontSize: vp.isPhone ? 38 : vp.isMobile ? 52 : vp.isTablet ? 58 : 66, lineHeight: 1.05, margin: 0, textWrap: 'balance' }}>
          Apply for <span style={{ fontStyle: T.name === 'Editorial' ? 'italic' : 'normal', color: p.inkSoft }}>membership</span>.
        </h1>
        <p style={{ fontSize: 17, lineHeight: 1.6, color: p.inkSoft, margin: 0, maxWidth: 460 }}>
          Every Man's Health is a limited-panel Florida concierge practice for men seeking a more deliberate, physician-led approach to long-term health, function, vitality, and resilience. Membership begins with a conversation.
        </p>
      </div>
      <div style={{ display: 'flex', gap: 14, alignItems: 'stretch', marginTop: 48, flexWrap: 'wrap', flexDirection: vp.isPhone ? 'column' : 'row' }}>
        <a href="#apply" style={{ fontFamily: T.body, fontSize: 14.5, fontWeight: 500, padding: '15px 26px', background: p.ink, color: p.cream, border: 'none', borderRadius: 2, cursor: 'pointer', textDecoration: 'none', display: 'inline-block', textAlign: 'center' }}>Begin your application ↓</a>
        <a href="EMH_04_Membership.html" style={{ fontFamily: T.body, fontSize: 14.5, fontWeight: 500, padding: '15px 22px', background: 'transparent', color: p.ink, border: `1px solid ${p.ink}44`, borderRadius: 2, cursor: 'pointer', textDecoration: 'none', textAlign: 'center' }}>Review membership</a>
      </div>
    </section>
  );
}

// ── WHY APPLICATION MATTERS ─────────────────────────────────────────────
function AWhyLimited({ p, T, S, vp }) {
  return (
    <section style={{ ...S.container, padding: `${SY(vp, 104)}px ${PX(vp)}px`, borderBottom: `1px solid ${p.ink}14` }}>
      <div style={{ display: 'grid', gridTemplateColumns: vp.isMobile ? '1fr' : '1.4fr 1fr', gap: vp.isMobile ? 32 : 80 }}>
        <p style={{ ...S.display, fontSize: vp.isPhone ? 25 : vp.isMobile ? 28 : 32, lineHeight: 1.26, margin: 0, color: p.ink, fontWeight: T.displayWeight, letterSpacing: T.displayTracking, textWrap: 'pretty' }}>
          Membership is intentionally limited — so that care remains <em style={{ color: p.inkSoft, fontStyle: T.name === 'Editorial' ? 'italic' : 'normal' }}>personal, longitudinal, and physician-led</em>.
        </p>
        <div>
          <p style={{ fontSize: 16, lineHeight: 1.65, color: p.inkSoft, margin: 0, marginBottom: 18 }}>
            A physician can only truly know so many patients. We keep our panel small on purpose — to preserve access to your physician, continuity across the years, and the time that individualized care actually requires.
          </p>
          <p style={{ fontSize: 16, lineHeight: 1.65, color: p.inkSoft, margin: 0 }}>
            Because of that, membership is by application. It begins with a conversation and a physician's review — not an automatic online purchase.
          </p>
        </div>
      </div>
    </section>
  );
}

// ── WHAT HAPPENS AFTER YOU APPLY ────────────────────────────────────────
function AAfter({ p, T, S, vp }) {
  const cols = vp.isPhone ? 1 : vp.isMobile ? 2 : 4;
  return (
    <section style={{ ...S.container, padding: `${SY(vp, 104)}px ${PX(vp)}px`, borderBottom: `1px solid ${p.ink}14`, background: p.paper }}>
      <div style={{ display: 'flex', alignItems: vp.isMobile ? 'flex-start' : 'baseline', justifyContent: 'space-between', marginBottom: vp.isMobile ? 40 : 56, gap: vp.isMobile ? 16 : 40, flexDirection: vp.isMobile ? 'column' : 'row' }}>
        <div>
          <div style={{ ...S.mono, fontSize: 11, color: p.accent, marginBottom: 20 }}>What happens after you apply</div>
          <h2 style={{ ...S.display, fontSize: vp.isPhone ? 32 : 42, lineHeight: 1.06, margin: 0, textWrap: 'balance' }}>A considered sequence, not a checkout.</h2>
        </div>
        <div style={{ ...S.mono, fontSize: 10.5, color: p.muted, alignSelf: vp.isMobile ? 'flex-start' : 'flex-end', flexShrink: 0 }}>Four steps · No obligation</div>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${cols}, 1fr)`, borderTop: `1px solid ${p.ink}22` }}>
        {AFTER_STEPS.map((s, i) => {
          const colInRow = i % cols;
          return (
          <div key={s.n} style={{ padding: '32px 28px 36px', borderRight: colInRow < cols - 1 ? `1px solid ${p.ink}1a` : 'none', borderBottom: vp.isMobile && i < AFTER_STEPS.length - (AFTER_STEPS.length % cols || cols) ? `1px solid ${p.ink}14` : 'none' }}>
            <div style={{ ...S.mono, fontSize: 10.5, color: p.accent, marginBottom: 22 }}>{s.n}</div>
            <h3 style={{ ...S.display, fontSize: 20, margin: 0, marginBottom: 14, lineHeight: 1.2 }}>{s.t}</h3>
            <p style={{ fontSize: 14, lineHeight: 1.6, color: p.inkSoft, margin: 0 }}>{s.body}</p>
          </div>
        );})}
      </div>
      <p style={{ marginTop: 32, fontSize: 13.5, lineHeight: 1.6, color: p.muted, maxWidth: 720 }}>
        Applying does not automatically establish a physician-patient relationship or guarantee membership. Both are determined after the introductory conversation and in-person evaluation.
      </p>
    </section>
  );
}

// ── APPLICATION FORM ────────────────────────────────────────────────────
function AField({ label, children, p, T, S, optional }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <span style={{ ...S.mono, fontSize: 10, color: p.muted }}>
        {label}{optional && <span style={{ color: `${p.muted}`, opacity: 0.7 }}> · optional</span>}
      </span>
      {children}
    </label>
  );
}

const APPLY_ENDPOINT = '/api/apply';
const APPLY_INITIAL = {
  firstName: '', lastName: '', ageRange: '', city: '', state: '',
  phone: '', email: '', preferredContactMethod: '', preferredContactTime: '',
  inPersonEvaluationAvailability: '', applicantGoalStatement: '',
  consentAcknowledgment: false, honeypot: '',
};

function AForm({ p, T, S, vp }) {
  const [form, setForm] = React.useState(APPLY_INITIAL);
  const [submitting, setSubmitting] = React.useState(false);
  const [sent, setSent] = React.useState(false);
  const [error, setError] = React.useState('');

  const inputStyle = {
    fontFamily: T.body, fontSize: 15, color: p.ink, background: p.cream,
    border: `1px solid ${p.ink}33`, borderRadius: 2, padding: '12px 14px', outline: 'none', width: '100%', boxSizing: 'border-box',
  };
  const selectStyle = { ...inputStyle, appearance: 'none', backgroundImage: `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'><path fill='%235B6783' d='M0 0h10L5 6z'/></svg>")`, backgroundRepeat: 'no-repeat', backgroundPosition: 'right 14px center' };
  const onFocus = (e) => { e.target.style.borderColor = p.accent; };
  const onBlur = (e) => { e.target.style.borderColor = `${p.ink}33`; };
  const fieldCols = vp.isPhone ? '1fr' : '1fr 1fr';
  const fullSpan = vp.isPhone ? 'auto' : 'span 2';

  // Controlled-field setter. Checkbox uses .checked; everything else .value.
  const set = (key) => (e) => {
    const v = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
    setForm((f) => ({ ...f, [key]: v }));
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    if (submitting) return;
    setError('');
    setSubmitting(true);
    try {
      const params = new URLSearchParams(window.location.search);
      const payload = {
        firstName: form.firstName.trim(),
        lastName: form.lastName.trim(),
        ageRange: form.ageRange,
        city: form.city.trim(),
        state: form.state,
        phone: form.phone.trim(),
        email: form.email.trim(),
        preferredContactMethod: form.preferredContactMethod,
        preferredContactTime: form.preferredContactTime.trim(),
        inPersonEvaluationAvailability: form.inPersonEvaluationAvailability,
        applicantGoalStatement: form.applicantGoalStatement.trim(),
        consentAcknowledgment: form.consentAcknowledgment,
        honeypot: form.honeypot,
        sourcePage: 'apply',
        referrer: document.referrer || '',
        utmSource: params.get('utm_source') || '',
        utmMedium: params.get('utm_medium') || '',
        utmCampaign: params.get('utm_campaign') || '',
      };
      const res = await fetch(APPLY_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error('Request failed: ' + res.status);
      setSent(true);
    } catch (err) {
      setError('We weren\u2019t able to submit your inquiry just now. Please try again in a moment \u2014 or email membership@everymanshealth.com and we\u2019ll follow up.');
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section id="apply" style={{ ...S.container, padding: `${SY(vp, 112)}px ${PX(vp)}px`, borderBottom: `1px solid ${p.ink}14`, scrollMarginTop: 80 }}>
      <div style={{ display: 'grid', gridTemplateColumns: vp.isMobile ? '1fr' : '360px 1fr', gap: vp.isMobile ? 36 : 80, alignItems: 'start' }}>
        <div style={{ position: vp.isMobile ? 'static' : 'sticky', top: 100 }}>
          <div style={{ ...S.mono, fontSize: 11, color: p.accent, marginBottom: 20 }}>Membership inquiry</div>
          <h2 style={{ ...S.display, fontSize: vp.isPhone ? 30 : 38, lineHeight: 1.07, margin: 0, marginBottom: 22, textWrap: 'balance' }}>
            Begin your application.
          </h2>
          <p style={{ fontSize: 15.5, lineHeight: 1.65, color: p.inkSoft, margin: 0, marginBottom: 18 }}>
            A few details to start the conversation. This is a membership inquiry — not a medical intake — so please keep it brief.
          </p>
          <p style={{ fontSize: 13.5, lineHeight: 1.6, color: p.muted, margin: 0 }}>
            Please don't include medical history, medications, lab results, insurance details, or sensitive information here. If your application proceeds, a secure intake process follows.
          </p>
        </div>

        <div style={{ background: p.paper, border: `1px solid ${p.ink}1f`, padding: vp.isPhone ? '28px 22px 32px' : '40px 40px 44px' }}>
          {sent ? (
            <div style={{ padding: '40px 0', textAlign: 'center' }}>
              <div style={{ ...S.mono, fontSize: 10.5, color: p.accent, marginBottom: 16 }}>Inquiry received</div>
              <h3 style={{ ...S.display, fontSize: 28, margin: 0, marginBottom: 14 }}>Thank you.</h3>
              <p style={{ fontSize: 15.5, lineHeight: 1.65, color: p.inkSoft, margin: '0 auto', maxWidth: 440 }}>
                We've received your inquiry. A member of our team will review it and reach out if membership appears to be a good fit. This does not establish a physician-patient relationship. If you are experiencing a medical emergency, call 911 or go to your nearest emergency department.
              </p>
            </div>
          ) : (
            <form onSubmit={onSubmit}>
              {/* Honeypot — visually hidden, off-screen, not tabbable. Real users leave it blank. */}
              <div aria-hidden="true" style={{ position: 'absolute', left: '-9999px', top: 'auto', width: 1, height: 1, overflow: 'hidden' }}>
                <label>Company
                  <input type="text" tabIndex={-1} autoComplete="off" value={form.honeypot} onChange={set('honeypot')} />
                </label>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: fieldCols, gap: 22 }}>
                <AField label="FIRST NAME" p={p} T={T} S={S}>
                  <input type="text" required placeholder="First name" value={form.firstName} onChange={set('firstName')} style={inputStyle} onFocus={onFocus} onBlur={onBlur} />
                </AField>
                <AField label="LAST NAME" p={p} T={T} S={S}>
                  <input type="text" required placeholder="Last name" value={form.lastName} onChange={set('lastName')} style={inputStyle} onFocus={onFocus} onBlur={onBlur} />
                </AField>
                <AField label="AGE RANGE" p={p} T={T} S={S}>
                  <select required value={form.ageRange} onChange={set('ageRange')} style={selectStyle} onFocus={onFocus} onBlur={onBlur}>
                    <option value="" disabled>Select</option>
                    {AGE_RANGES.map((a) => <option key={a} value={a}>{a}</option>)}
                  </select>
                </AField>
                <AField label="CITY" p={p} T={T} S={S}>
                  <input type="text" placeholder="City" value={form.city} onChange={set('city')} style={inputStyle} onFocus={onFocus} onBlur={onBlur} />
                </AField>
                <AField label="STATE" p={p} T={T} S={S}>
                  <select value={form.state} onChange={set('state')} style={selectStyle} onFocus={onFocus} onBlur={onBlur}>
                    <option value="" disabled>Select</option>
                    {US_STATES.map((s) => <option key={s} value={s}>{s}</option>)}
                  </select>
                </AField>
                <AField label="PHONE" p={p} T={T} S={S}>
                  <input type="tel" required placeholder="(000) 000-0000" value={form.phone} onChange={set('phone')} style={inputStyle} onFocus={onFocus} onBlur={onBlur} />
                </AField>
                <AField label="EMAIL" p={p} T={T} S={S}>
                  <input type="email" required placeholder="you@email.com" value={form.email} onChange={set('email')} style={inputStyle} onFocus={onFocus} onBlur={onBlur} />
                </AField>
                <AField label="PREFERRED CONTACT METHOD" p={p} T={T} S={S}>
                  <select value={form.preferredContactMethod} onChange={set('preferredContactMethod')} style={selectStyle} onFocus={onFocus} onBlur={onBlur}>
                    <option value="" disabled>Select</option>
                    {CONTACT_METHODS.map((m) => <option key={m} value={m}>{m}</option>)}
                  </select>
                </AField>
                <AField label="PREFERRED TIME TO BE CONTACTED" p={p} T={T} S={S} optional>
                  <input type="text" placeholder="e.g. weekday mornings" value={form.preferredContactTime} onChange={set('preferredContactTime')} style={inputStyle} onFocus={onFocus} onBlur={onBlur} />
                </AField>
                <div style={{ gridColumn: fullSpan }}>
                  <AField label="ARE YOU ABLE TO COME TO OUR OCALA, FLORIDA OFFICE FOR AN INITIAL IN-PERSON EVALUATION?" p={p} T={T} S={S}>
                    <select required value={form.inPersonEvaluationAvailability} onChange={set('inPersonEvaluationAvailability')} style={selectStyle} onFocus={onFocus} onBlur={onBlur}>
                      <option value="" disabled>Select</option>
                      {IN_PERSON_EVALUATION_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}
                    </select>
                  </AField>
                </div>
                <div style={{ gridColumn: fullSpan }}>
                  <AField label="WHAT ARE YOU HOPING TO IMPROVE OR BETTER UNDERSTAND?" p={p} T={T} S={S} optional>
                    <textarea rows={4} placeholder="A sentence or two is plenty. Please don't include sensitive medical detail." value={form.applicantGoalStatement} onChange={set('applicantGoalStatement')} style={{ ...inputStyle, resize: 'vertical', lineHeight: 1.55 }} onFocus={onFocus} onBlur={onBlur} />
                  </AField>
                </div>
              </div>

              {/* Required acknowledgment */}
              <label style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginTop: 24, cursor: 'pointer' }}>
                <input type="checkbox" required checked={form.consentAcknowledgment} onChange={set('consentAcknowledgment')}
                  style={{ marginTop: 3, width: 16, height: 16, accentColor: p.ink, flexShrink: 0 }} />
                <span style={{ fontSize: 13.5, lineHeight: 1.6, color: p.inkSoft }}>
                  I understand this is a membership inquiry only, is not for urgent or emergency medical concerns, and submitting this form does not establish a physician-patient relationship.
                </span>
              </label>

              {error && (
                <div role="alert" style={{ marginTop: 22, padding: '14px 16px', background: `${p.accent}14`, border: `1px solid ${p.accent}55`, borderRadius: 2, fontSize: 13.5, lineHeight: 1.6, color: p.ink }}>
                  {error}
                </div>
              )}

              <div style={{ marginTop: 28, display: 'flex', alignItems: 'center', gap: 20, flexWrap: 'wrap' }}>
                <button type="submit" disabled={submitting} style={{ fontFamily: T.body, fontSize: 15, fontWeight: 500, padding: '15px 30px', background: p.ink, color: p.cream, border: 'none', borderRadius: 2, cursor: submitting ? 'default' : 'pointer', opacity: submitting ? 0.6 : 1, width: vp.isPhone ? '100%' : 'auto' }}>
                  {submitting ? 'Submitting…' : 'Submit inquiry →'}
                </button>
                <p style={{ fontSize: 12.5, lineHeight: 1.55, color: p.muted, margin: 0, maxWidth: 360 }}>
                  Submitting does not establish a physician-patient relationship or guarantee membership.
                </p>
              </div>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}

// ── WHAT THIS FORM IS NOT ───────────────────────────────────────────────
function ANotThis({ p, T, S, vp }) {
  return (
    <section style={{ ...S.container, padding: `${SY(vp, 96)}px ${PX(vp)}px`, borderBottom: `1px solid ${p.ink}14`, background: p.paper }}>
      <div style={{ display: 'grid', gridTemplateColumns: vp.isMobile ? '1fr' : '320px 1fr', gap: vp.isMobile ? 28 : 80 }}>
        <div>
          <div style={{ ...S.mono, fontSize: 11, color: p.accent, marginBottom: 20 }}>Please note</div>
          <h2 style={{ ...S.display, fontSize: vp.isPhone ? 28 : 34, lineHeight: 1.08, margin: 0, textWrap: 'balance' }}>
            What this form is not.
          </h2>
        </div>
        <div style={{ borderTop: `1px solid ${p.ink}22` }}>
          {NOT_THIS.map((item, i) => (
            <div key={item} style={{ display: 'grid', gridTemplateColumns: '40px 1fr', gap: 20, padding: '20px 0', borderBottom: i < NOT_THIS.length - 1 ? `1px solid ${p.ink}12` : 'none', alignItems: 'baseline' }}>
              <span style={{ ...S.mono, fontSize: 10.5, color: p.accent }}>{String(i + 1).padStart(2, '0')}</span>
              <span style={{ fontSize: 16.5, lineHeight: 1.5, color: p.ink, fontFamily: T.display, fontWeight: T.displayWeight }}>{item}</span>
            </div>
          ))}
        </div>
      </div>
      <div style={{ marginTop: 32, background: p.cream, border: `1px solid ${p.accent}44`, padding: '20px 24px', display: 'flex', alignItems: 'flex-start', gap: 16, maxWidth: 880 }}>
        <span style={{ ...S.mono, fontSize: 9.5, color: p.accent, padding: '3px 7px', border: `1px solid ${p.accent}66`, flexShrink: 0, marginTop: 2 }}>URGENT?</span>
        <p style={{ fontSize: 14, lineHeight: 1.6, color: p.ink, margin: 0 }}>
          If you are experiencing a medical emergency, call 911 or go to your nearest emergency department. This inquiry form is not monitored for urgent concerns.
        </p>
      </div>
    </section>
  );
}

// ── GENERAL CONTACT ─────────────────────────────────────────────────────
function AContact({ p, T, S, vp }) {
  const details = [
    ['Office', '9401 SW Highway 200, STE 502\nOcala, FL 34481-9650'],
    ['Phone & fax', 'Tel (352) 861-2115\nFax (352) 854-5726'],
    ['Email', 'membership@everymanshealth.com'],
    ['Office hours', 'Monday – Thursday\n8:00 AM – 3:30 PM'],
  ];
  const cols = vp.isPhone ? 2 : 4;
  return (
    <section style={{ ...S.container, padding: `${SY(vp, 104)}px ${PX(vp)}px`, borderBottom: `1px solid ${p.ink}14` }}>
      <div style={{ display: 'grid', gridTemplateColumns: vp.isMobile ? '1fr' : '320px 1fr', gap: vp.isMobile ? 28 : 80, marginBottom: vp.isMobile ? 36 : 48 }}>
        <div>
          <div style={{ ...S.mono, fontSize: 11, color: p.accent, marginBottom: 20 }}>General contact</div>
          <h2 style={{ ...S.display, fontSize: vp.isPhone ? 30 : 38, lineHeight: 1.06, margin: 0, textWrap: 'balance' }}>
            Other ways to reach us.
          </h2>
        </div>
        <p style={{ fontSize: 16, lineHeight: 1.6, color: p.inkSoft, marginTop: 8, maxWidth: 540 }}>
          The application above is the best way to begin. For existing members, professional inquiries, or general questions, you can also reach the practice directly.
        </p>
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${cols}, 1fr)`, borderTop: `1px solid ${p.ink}22` }}>
        {details.map(([k, v], i) => {
          const colInRow = i % cols;
          return (
          <div key={k} style={{ padding: '28px 24px 32px', borderRight: colInRow < cols - 1 ? `1px solid ${p.ink}1a` : 'none', borderBottom: (vp.isPhone && i < 2) ? `1px solid ${p.ink}1a` : 'none' }}>
            <div style={{ ...S.mono, fontSize: 10, color: p.accent, marginBottom: 14 }}>{k.toUpperCase()}</div>
            <div style={{ fontSize: 14.5, lineHeight: 1.55, color: p.inkSoft, whiteSpace: 'pre-line' }}>{v}</div>
          </div>
        );})}
      </div>
      <div style={{ display: 'flex', gap: vp.isPhone ? 16 : 40, marginTop: 32, flexWrap: 'wrap', flexDirection: vp.isPhone ? 'column' : 'row' }}>
        <a href="https://www.yourhealthfile.com/portal/login.jsp" target="_blank" rel="noopener noreferrer" style={{ fontFamily: T.body, fontSize: 14, color: p.ink, textDecoration: 'none', borderBottom: `1px solid ${p.accent}66`, paddingBottom: 3 }}>Existing patient · Patient Portal →</a>
        <a href="mailto:membership@everymanshealth.com" style={{ fontFamily: T.body, fontSize: 14, color: p.inkSoft, textDecoration: 'none', borderBottom: `1px solid ${p.ink}33`, paddingBottom: 3 }}>Professional & media inquiries →</a>
      </div>
    </section>
  );
}

// ── PRIVACY / COMMUNICATION NOTE ────────────────────────────────────────
function APrivacy({ p, T, S, vp }) {
  return (
    <section style={{ ...S.container, padding: `${SY(vp, 64)}px ${PX(vp)}px`, borderBottom: `1px solid ${p.ink}14`, background: p.paper }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 18, maxWidth: 920 }}>
        <span style={{ ...S.mono, fontSize: 9.5, color: p.muted, padding: '3px 7px', border: `1px solid ${p.muted}55`, flexShrink: 0, marginTop: 3 }}>PRIVACY</span>
        <p style={{ fontSize: 14, lineHeight: 1.65, color: p.inkSoft, margin: 0 }}>
          Please do not submit urgent medical concerns or highly sensitive medical information through this initial inquiry form. A secure intake process will be provided if your application proceeds. We treat the information you share with discretion and use it only to evaluate fit and contact you about membership.
        </p>
      </div>
    </section>
  );
}

// ── FINAL CTA ───────────────────────────────────────────────────────────
function ACTA({ p, T, S, vp }) {
  return (
    <section style={{ ...S.container, padding: `${SY(vp, 96)}px ${PX(vp)}px`, borderBottom: `1px solid ${p.ink}14` }}>
      <div style={{ display: 'flex', alignItems: vp.isMobile ? 'flex-start' : 'center', justifyContent: 'space-between', gap: vp.isMobile ? 28 : 48, flexDirection: vp.isMobile ? 'column' : 'row' }}>
        <div>
          <div style={{ ...S.mono, fontSize: 11, color: p.accent, marginBottom: 16 }}>Begin</div>
          <h2 style={{ ...S.display, fontSize: vp.isPhone ? 32 : 46, lineHeight: 1.04, margin: 0, textWrap: 'balance' }}>Begin with a conversation.</h2>
          <p style={{ fontSize: 17, color: p.inkSoft, marginTop: 14, marginBottom: 0, maxWidth: 600 }}>
            A short inquiry, an introductory conversation, then your in-person evaluation in Florida. We decide together from there.
          </p>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, flexShrink: 0, alignItems: 'stretch', width: vp.isMobile ? '100%' : 'auto' }}>
          <a href="#apply" style={{ fontFamily: T.body, fontSize: 15, fontWeight: 500, padding: '16px 28px', background: p.ink, color: p.cream, border: 'none', borderRadius: 2, cursor: 'pointer', textDecoration: 'none', textAlign: 'center' }}>Begin your application ↑</a>
          <a href="EMH_03_Care_Model.html" style={{ fontFamily: T.body, fontSize: 15, fontWeight: 500, padding: '15px 26px', background: 'transparent', color: p.ink, border: `1px solid ${p.ink}44`, borderRadius: 2, cursor: 'pointer', textDecoration: 'none', textAlign: 'center' }}>Review the care model</a>
        </div>
      </div>
    </section>
  );
}

// ── FOOTER ──────────────────────────────────────────────────────────────
function AFooter({ p, T, S, vp }) {
  const cols = [
    ['Practice',  ['The Practice', 'Care model', 'Membership', 'Insights']],
    ['Care',      ['Preventive', 'Hormone health', 'Metabolic', 'Sexual', 'Cognitive', 'Longevity']],
    ['Resources', ['Care model', 'Membership', 'Apply', 'FAQ']],
    ['Company',   ['The Practice', 'Careers', 'Press', 'Apply']],
  ];
  const gridCols = vp.isPhone ? '1fr 1fr' : vp.isMobile ? 'repeat(3, 1fr)' : '1.4fr repeat(4, 1fr)';
  return (
    <footer style={{ background: p.cream, padding: `${SY(vp, 72)}px ${PX(vp)}px 36px`, maxWidth: 1440, margin: '0 auto' }}>
      <div style={{ display: 'grid', gridTemplateColumns: gridCols, gap: vp.isMobile ? 32 : 48, marginBottom: vp.isMobile ? 40 : 60 }}>
        <div style={{ gridColumn: vp.isMobile ? '1 / -1' : 'auto' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 18 }}>
            <EMHMark color={p.ink} size={26} />
            <span style={{ fontFamily: T.display, fontSize: 17, fontWeight: 500 }}>Every Man's Health</span>
          </div>
          <p style={{ fontSize: 13.5, lineHeight: 1.6, color: p.inkSoft, maxWidth: 280, margin: 0 }}>
            A Florida concierge men's health practice. Physician-led, lab-guided, data-informed — by application.
          </p>
          <div style={{ marginTop: 18, fontSize: 12.5, lineHeight: 1.7, color: p.inkSoft }}>
            9401 SW Highway 200, STE 502<br />Ocala, FL 34481-9650<br />
            <span style={{ color: p.muted }}>Tel</span> (352) 861-2115 &nbsp;·&nbsp; <span style={{ color: p.muted }}>Fax</span> (352) 854-5726<br />
            <span style={{ color: p.muted }}>Mon–Thu</span> 8:00 AM – 3:30 PM<br />
            <a href="mailto:membership@everymanshealth.com" style={{ color: 'inherit', textDecoration: 'none' }}>membership@everymanshealth.com</a>
          </div>
        </div>
        {cols.map(([title, items]) => (
          <div key={title}>
            <div style={{ ...S.mono, fontSize: 10, color: p.muted, marginBottom: 14 }}>{title}</div>
            <ul style={{ listStyle: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 8 }}>
              {items.map((i) => <li key={i} style={{ fontSize: 13.5, color: p.inkSoft }}>{i}</li>)}
            </ul>
          </div>
        ))}
      </div>
      <div style={{ borderTop: `1px solid ${p.ink}1a`, paddingTop: 24, display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 32, flexDirection: vp.isMobile ? 'column' : 'row' }}>
        <p style={{ fontSize: 11.5, lineHeight: 1.55, color: p.muted, margin: 0, maxWidth: 760 }}>
          Information presented on this site is for educational purposes and does not constitute medical advice. Submitting an inquiry does not establish a physician-patient relationship. Routine blood and biomarker testing is coordinated through trusted laboratory partners; specialized pathology and molecular diagnostic testing may be supported through affiliated CAP/CLIA laboratory infrastructure when clinically indicated. Technology, including AI-assisted organization of laboratory and health data, supports physician review; clinical interpretation and treatment decisions are made by licensed physicians on a case-by-case basis. Compounded medications, when used, are dispensed by 503A pharmacies in compliance with applicable regulations. Practice based in Florida; telehealth follow-up available where licensed.
        </p>
        <div style={{ ...S.mono, fontSize: 10, color: p.muted, textAlign: vp.isMobile ? 'left' : 'right' }}>
          © 2026 Every Man's Health. All rights reserved.<br /><a href="EMH_07_Privacy_Policy.html" style={{ color: 'inherit', textDecoration: 'none' }}>Privacy Policy</a> · <a href="EMH_08_Terms_Of_Use.html" style={{ color: 'inherit', textDecoration: 'none' }}>Terms of Use</a> · <a href="EMH_09_HIPAA_Notice.html" style={{ color: 'inherit', textDecoration: 'none' }}>HIPAA Notice</a><br /><a href="EMH_10_Accessibility_Statement.html" style={{ color: 'inherit', textDecoration: 'none' }}>Accessibility</a> · <a href="EMH_11_Website_Disclaimer.html" style={{ color: 'inherit', textDecoration: 'none' }}>Website Disclaimer</a> · <a href="EMH_12_Electronic_Communications.html" style={{ color: 'inherit', textDecoration: 'none' }}>Electronic Communications</a>
        </div>
      </div>
    </footer>
  );
}

// Wait for shared/tweaks globals before mounting.
function __mountA() {
  if (window.PALETTES && window.TYPES && window.useTweaks && window.TweaksPanel && window.EMHMark && window.toneCopy && window.useViewport) {
    try {
      ReactDOM.createRoot(document.getElementById('root')).render(<ApplyPage />);
    } catch (e) {
      document.getElementById('root').innerHTML = '<pre style="padding:24px;color:#900;white-space:pre-wrap;font:12px ui-monospace">' + (e && e.stack || e) + '</pre>';
      throw e;
    }
  } else {
    setTimeout(__mountA, 30);
  }
}
__mountA();
