// variation-a.jsx — Centered minimal B2B SaaS
// One question at a time, dead-centered, generous whitespace, top stepper.

const VA_C = {
  bg: '#0a0a0b',
  panel: '#0f1011',
  border: 'rgba(255,255,255,0.08)',
  borderStrong: 'rgba(255,255,255,0.16)',
  text: '#f4f4f5',
  textDim: 'rgba(244,244,245,0.6)',
  textMute: 'rgba(244,244,245,0.4)',
};

function VAStepper({ ob, accent, onJumpSection, mobile = false }) {
  // Section-aware progress: one segment per section, with the active
  // section showing internal step progress.
  const currentSec = ob.sectionOf(ob.stepIdx);
  const activeW = mobile ? 26 : 44;
  const inactiveW = mobile ? 12 : 22;
  const gap = mobile ? 3 : 5;
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap }}>
      {ATLAS_SECTION_INDICES.map((sec) => {
        const idxs = sec.stepIndices;
        if (!idxs.length) return null;
        const firstIdx = idxs[0];
        const lastIdx = idxs[idxs.length - 1];
        const isCurrent = ob.stepIdx >= firstIdx && ob.stepIdx <= lastIdx && !ob.done;
        const isPast = ob.stepIdx > lastIdx || ob.done;
        // For the current section, compute fill ratio inside it.
        const localPos = (ob.stepIdx - firstIdx) / Math.max(1, idxs.length - 1);
        const fillRatio = isPast ? 1 : isCurrent ? localPos : 0;
        return (
          <button key={sec.id}
            onClick={() => onJumpSection && onJumpSection(firstIdx)}
            style={{
              appearance: 'none', border: 0, padding: 0, cursor: 'pointer',
              height: 4, width: isCurrent ? activeW : inactiveW, borderRadius: 2,
              background: 'rgba(255,255,255,0.08)',
              position: 'relative', overflow: 'hidden',
              transition: 'width .35s cubic-bezier(.2,.7,.3,1)',
              flexShrink: 0,
            }}>
            <div style={{
              position: 'absolute', inset: 0,
              width: `${fillRatio * 100}%`,
              background: accent,
              opacity: isPast ? 0.5 : 1,
              transition: 'width .4s cubic-bezier(.2,.7,.3,1)',
            }}/>
          </button>
        );
      })}
    </div>
  );
}

function VAOtherInput({ value, onChange, accent }) {
  const [focused, setFocused] = React.useState(false);
  const filled = (value || '').trim().length > 0;
  const live = focused || filled;
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center',
      borderRadius: 999,
      background: live ? `color-mix(in oklab, ${accent} 8%, transparent)` : 'transparent',
      border: `1px solid ${live ? accent : VA_C.border}`,
      padding: '6px 10px 6px 14px', gap: 10,
      transition: 'background .15s, border-color .15s',
      maxWidth: 520, alignSelf: 'flex-start',
    }}>
      <span style={{
        fontSize: 13, fontWeight: 500,
        color: live ? accent : VA_C.textDim,
        letterSpacing: '0.01em',
      }}>Other</span>
      <span style={{
        width: 1, height: 16, background: live ? accent : VA_C.border, opacity: 0.5,
      }} />
      <input
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        placeholder="add your own"
        style={{
          appearance: 'none', background: 'transparent', border: 'none',
          padding: '4px 4px 4px 0', color: VA_C.text, fontSize: 14,
          fontFamily: 'inherit', outline: 'none',
          minWidth: 220, flex: 1,
        }}
      />
    </div>
  );
}

function VAChip({ label, active, onClick, accent }) {
  return (
    <button onClick={onClick} style={{
      appearance: 'none', cursor: 'pointer',
      padding: '10px 16px', borderRadius: 999,
      fontFamily: 'inherit', fontSize: 14, fontWeight: 500,
      background: active ? accent : 'transparent',
      color: active ? '#0a0a0b' : VA_C.text,
      border: `1px solid ${active ? accent : VA_C.border}`,
      transition: 'background .15s, border-color .15s, color .15s',
    }}>{label}</button>
  );
}

function VACard({ option, active, onClick, accent, idx }) {
  return (
    <button onClick={onClick} style={{
      appearance: 'none', cursor: 'pointer', textAlign: 'left',
      padding: '18px 20px', borderRadius: 12,
      background: active ? `color-mix(in oklab, ${accent} 12%, ${VA_C.panel})` : VA_C.panel,
      border: `1px solid ${active ? accent : VA_C.border}`,
      color: VA_C.text, display: 'flex', alignItems: 'center', gap: 16,
      transition: 'all .18s cubic-bezier(.2,.7,.3,1)',
      fontFamily: 'inherit',
    }}>
      <div style={{
        width: 28, height: 28, borderRadius: 6,
        background: active ? accent : 'rgba(255,255,255,0.04)',
        color: active ? '#0a0a0b' : VA_C.textDim,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 12, fontWeight: 600, fontFamily: 'ui-monospace, SFMono-Regular, monospace',
        flexShrink: 0,
      }}>{idx + 1}</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 2 }}>{option.label}</div>
        <div style={{ fontSize: 13, color: VA_C.textDim }}>{option.detail}</div>
      </div>
      <div style={{
        width: 18, height: 18, borderRadius: '50%',
        border: `1px solid ${active ? accent : VA_C.borderStrong}`,
        background: active ? accent : 'transparent',
        flexShrink: 0, position: 'relative',
      }}>
        {active && (
          <svg viewBox="0 0 18 18" width="18" height="18" style={{ position: 'absolute', inset: 0 }}>
            <path d="M5 9.5l3 2.5 5-5.5" stroke="#0a0a0b" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        )}
      </div>
    </button>
  );
}

function VATextField({ field, value, onChange, accent, autoFocus }) {
  const [focused, setFocused] = React.useState(false);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <label style={{ fontSize: 12, color: VA_C.textDim, fontWeight: 500, letterSpacing: '0.02em', textTransform: 'uppercase' }}>
        {field.label}{field.optional && <span style={{ textTransform: 'none', opacity: 0.6, marginLeft: 6, letterSpacing: 0 }}>(optional)</span>}
      </label>
      <input
        autoFocus={autoFocus}
        type={field.type || 'text'}
        value={value || ''}
        onChange={(e) => onChange(e.target.value)}
        onFocus={() => setFocused(true)}
        onBlur={() => setFocused(false)}
        placeholder={field.placeholder}
        style={{
          appearance: 'none', background: VA_C.panel,
          border: `1px solid ${focused ? accent : VA_C.border}`,
          borderRadius: 10, padding: '14px 16px',
          color: VA_C.text, fontSize: 16, fontFamily: 'inherit',
          outline: 'none', transition: 'border-color .15s',
          width: '100%', boxSizing: 'border-box',
        }}
      />
    </div>
  );
}

function VATextarea({ field, value, onChange, accent, autoFocus }) {
  const [focused, setFocused] = React.useState(false);
  return (
    <textarea
      autoFocus={autoFocus}
      value={value || ''}
      onChange={(e) => onChange(e.target.value)}
      onFocus={() => setFocused(true)}
      onBlur={() => setFocused(false)}
      placeholder={field.placeholder}
      rows={field.rows || 4}
      style={{
        appearance: 'none', background: VA_C.panel,
        border: `1px solid ${focused ? accent : VA_C.border}`,
        borderRadius: 10, padding: '14px 16px',
        color: VA_C.text, fontSize: 15, fontFamily: 'inherit',
        outline: 'none', transition: 'border-color .15s',
        width: '100%', boxSizing: 'border-box',
        resize: 'vertical', lineHeight: 1.5, minHeight: 100,
      }}
    />
  );
}

function VARoleField({ value, onChange, accent }) {
  const isPreset = !value || ATLAS_ROLES.includes(value);
  const [customMode, setCustomMode] = React.useState(!isPreset);
  React.useEffect(() => { if (!isPreset) setCustomMode(true); }, [isPreset]);

  if (customMode) {
    return (
      <div style={{ flex: 1.2, display: 'flex', gap: 6, minWidth: 0 }}>
        <input
          value={value || ''}
          onChange={(e) => onChange(e.target.value)}
          placeholder="Custom role"
          autoFocus
          style={{
            flex: 1, appearance: 'none', background: VA_C.panel,
            border: `1px solid ${VA_C.border}`, borderRadius: 8,
            padding: '12px 14px', color: VA_C.text, fontSize: 14,
            fontFamily: 'inherit', outline: 'none', minWidth: 0,
          }}
        />
        <button
          onClick={() => { setCustomMode(false); onChange(''); }}
          title="Use preset list"
          style={{
            appearance: 'none', cursor: 'pointer', fontFamily: 'inherit',
            background: 'transparent', border: `1px solid ${VA_C.border}`,
            color: VA_C.textMute, borderRadius: 8, padding: '0 10px',
            fontSize: 11, flexShrink: 0,
          }}>List</button>
      </div>
    );
  }
  return (
    <div style={{
      flex: 1.2, position: 'relative', minWidth: 0,
      display: 'flex',
    }}>
      <select
        value={value || ''}
        onChange={(e) => {
          if (e.target.value === '__custom__') { setCustomMode(true); onChange(''); }
          else onChange(e.target.value);
        }}
        style={{
          flex: 1, appearance: 'none', WebkitAppearance: 'none', MozAppearance: 'none',
          background: VA_C.panel,
          border: `1px solid ${VA_C.border}`, borderRadius: 8,
          padding: '12px 36px 12px 14px', color: value ? VA_C.text : VA_C.textMute,
          fontSize: 14, fontFamily: 'inherit', outline: 'none',
          minWidth: 0, width: '100%', cursor: 'pointer',
        }}
      >
        <option value="" disabled>Role</option>
        {ATLAS_ROLES.map((r) => <option key={r} value={r}>{r}</option>)}
        <option value="__custom__">Other / custom…</option>
      </select>
      <span style={{
        position: 'absolute', right: 14, top: '50%', transform: 'translateY(-50%)',
        pointerEvents: 'none', color: VA_C.textMute, fontSize: 10,
      }}>▾</span>
    </div>
  );
}

function VARoster({ rows, onSet, onAdd, onRemove, accent }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {(rows || []).map((r, i) => (
        <div key={i} style={{ display: 'flex', gap: 8, alignItems: 'stretch' }}>
          <input
            value={r.name || ''}
            onChange={(e) => onSet(i, { name: e.target.value })}
            placeholder="Name"
            style={{
              flex: 1, appearance: 'none', background: VA_C.panel,
              border: `1px solid ${VA_C.border}`, borderRadius: 8,
              padding: '12px 14px', color: VA_C.text, fontSize: 14,
              fontFamily: 'inherit', outline: 'none', minWidth: 0,
            }}
          />
          <VARoleField
            value={r.role}
            onChange={(role) => onSet(i, { role })}
            accent={accent}
          />
          <button onClick={() => onRemove(i)}
            style={{
              appearance: 'none', cursor: 'pointer', fontFamily: 'inherit',
              background: 'transparent', border: `1px solid ${VA_C.border}`,
              color: VA_C.textMute, borderRadius: 8, width: 38,
              fontSize: 16, flexShrink: 0,
            }}>×</button>
        </div>
      ))}
      <button onClick={onAdd}
        style={{
          appearance: 'none', cursor: 'pointer', fontFamily: 'inherit',
          background: 'transparent', border: `1px dashed ${VA_C.borderStrong}`,
          color: accent, borderRadius: 8, padding: '10px 14px',
          fontSize: 13, fontWeight: 500,
        }}>+ Add another</button>
    </div>
  );
}

// People-picker, multi-select cards built from the team roster.
// Falls back to a soft prompt if the roster is empty.
function VARosterPick({ roster, value, onToggle, accent }) {
  const valid = (roster || []).filter((r) => (r.name || '').trim() || (r.role || '').trim());
  if (!valid.length) {
    return (
      <div style={{
        padding: '18px 20px', borderRadius: 12,
        background: 'rgba(255,255,255,0.02)',
        border: `1px dashed ${VA_C.border}`,
        color: VA_C.textDim, fontSize: 13, lineHeight: 1.55,
      }}>
        Add a few teammates in the previous step first, we’ll show them here as picks.
      </div>
    );
  }
  return (
    <div style={{
      display: 'grid', gap: 8,
      gridTemplateColumns: 'repeat(auto-fit, minmax(180px, 1fr))',
      width: '100%', minWidth: 0,
    }}>
      {valid.map((r, i) => {
        const id = `${(r.name || '').trim()}|${(r.role || '').trim()}|${i}`;
        const active = (value || []).includes(id);
        const initials = ((r.name || '').trim().split(/\s+/).map(w => w[0]).join('').slice(0, 2) || '?').toUpperCase();
        return (
          <button key={id} onClick={() => onToggle(id)} style={{
            appearance: 'none', cursor: 'pointer', textAlign: 'left',
            padding: '14px 14px', borderRadius: 12,
            background: active ? `color-mix(in oklab, ${accent} 12%, ${VA_C.panel})` : VA_C.panel,
            border: `1px solid ${active ? accent : VA_C.border}`,
            color: VA_C.text, display: 'flex', alignItems: 'center', gap: 12,
            transition: 'all .18s cubic-bezier(.2,.7,.3,1)',
            fontFamily: 'inherit',
          }}>
            <div style={{
              width: 32, height: 32, borderRadius: '50%',
              background: active ? accent : 'rgba(255,255,255,0.06)',
              color: active ? '#0a0a0b' : VA_C.text,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 12, fontWeight: 600, flexShrink: 0,
              fontFamily: 'ui-monospace, SFMono-Regular, monospace',
            }}>{initials}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontSize: 14, fontWeight: 600,
                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
              }}>{(r.name || '').trim() || 'Unnamed'}</div>
              <div style={{
                fontSize: 12, color: VA_C.textDim,
                whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
              }}>{(r.role || '').trim() || ' '}</div>
            </div>
            <div style={{
              width: 18, height: 18, borderRadius: 5,
              border: `1px solid ${active ? accent : VA_C.borderStrong}`,
              background: active ? accent : 'transparent',
              flexShrink: 0, position: 'relative',
            }}>
              {active && (
                <svg viewBox="0 0 18 18" width="18" height="18" style={{ position: 'absolute', inset: 0, display: 'block' }}>
                  <path d="M4.5 9.5L7.5 12.5L13.5 6" stroke="#0a0a0b" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
              )}
            </div>
          </button>
        );
      })}
    </div>
  );
}

function VAStages({ stages, value, onSet, accent }) {
  const v = value || {};
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {stages.map((st, i) => (
        <div key={st.key} style={{
          display: 'flex', gap: 12, alignItems: 'flex-start',
        }}>
          <div style={{
            flexShrink: 0, paddingTop: 10, width: 72,
            display: 'flex', flexDirection: 'column', alignItems: 'flex-start', gap: 4,
          }}>
            <div style={{
              fontFamily: 'ui-monospace, SFMono-Regular, monospace',
              fontSize: 11, color: accent, letterSpacing: '0.05em',
              textTransform: 'uppercase', fontWeight: 600,
            }}>{st.label}</div>
            {i < stages.length - 1 && (
              <div style={{
                width: 1, flex: 1, minHeight: 16,
                background: VA_C.border, marginLeft: 6, marginTop: 2,
              }}/>
            )}
          </div>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 4 }}>
            <input
              value={v[st.key] || ''}
              onChange={(e) => onSet(st.key, e.target.value)}
              placeholder={st.placeholder}
              style={{
                appearance: 'none', background: VA_C.panel,
                border: `1px solid ${VA_C.border}`, borderRadius: 8,
                padding: '12px 14px', color: VA_C.text, fontSize: 14,
                fontFamily: 'inherit', outline: 'none',
              }}
            />
            <div style={{ fontSize: 11, color: VA_C.textMute, paddingLeft: 2 }}>{st.hint}</div>
          </div>
        </div>
      ))}
    </div>
  );
}

// Atlas wordmark, simple type lockup, no SVG icon
function AtlasMark({ accent, size = 'sm' }) {
  const isLg = size === 'lg';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
      <div style={{
        width: isLg ? 22 : 18, height: isLg ? 22 : 18, borderRadius: 4,
        background: accent, position: 'relative', flexShrink: 0,
      }}>
        <div style={{
          position: 'absolute', inset: '20% 20% 20% 20%',
          border: '1.5px solid #0a0a0b', borderRadius: 1,
          borderTop: 0, borderLeft: 0,
        }}/>
      </div>
      <span style={{
        fontFamily: '"Instrument Serif", Georgia, serif',
        fontSize: isLg ? 22 : 18, fontWeight: 400, color: VA_C.text,
        letterSpacing: '-0.01em',
      }}>Atlas</span>
    </div>
  );
}

function VariationA({ accent = '#14b8a6', mobile = false, density = 'regular', atmosphere = 'minimal' }) {
  const ob = useOnboarding();
  const obRef = React.useRef(ob);
  React.useEffect(() => { obRef.current = ob; });
  const containerRef = React.useRef(null);
  const [stepKey, setStepKey] = React.useState(0);

  // Keyboard nav: 1/2/3/4 select cards/chips, Enter advances.
  // For textareas, Cmd/Ctrl+Enter advances; plain Enter inserts a newline.
  React.useEffect(() => {
    const onKey = (e) => {
      const tag = e.target && e.target.tagName;
      if (tag === 'TEXTAREA') {
        if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); ob.next(); }
        return;
      }
      if (tag === 'INPUT') {
        if (e.key === 'Enter') { e.preventDefault(); ob.next(); }
        return;
      }
      if (ob.done) return;
      const s = ob.step;
      if (e.key === 'Enter') { ob.next(); return; }
      if (e.key === 'Backspace' && ob.stepIdx > 0) { ob.prev(); return; }
      const n = parseInt(e.key, 10);
      if (!isNaN(n) && n >= 1) {
        if (s.kind === 'cards' && s.options[n - 1]) {
          ob.setField(s.fieldKey, s.options[n - 1].value);
          setTimeout(() => obRef.current.next(), 650);
        } else if (s.kind === 'chips' && s.options[n - 1]) {
          ob.toggleMulti(s.fieldKey, s.options[n - 1]);
        }
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [ob]);

  React.useEffect(() => { setStepKey((k) => k + 1); }, [ob.stepIdx, ob.done]);

  React.useEffect(() => {
    if (ob.done && containerRef.current) fireConfetti(containerRef.current, accent);
  }, [ob.done, accent]);

  const pad = mobile ? 20 : (density === 'compact' ? 28 : density === 'comfy' ? 56 : 40);

  return (
    <div ref={containerRef} style={{
      width: '100%', height: '100%', position: 'relative',
      background: VA_C.bg, color: VA_C.text,
      fontFamily: '"Inter", ui-sans-serif, system-ui, -apple-system, sans-serif',
      display: 'flex', flexDirection: 'column', overflow: 'hidden',
    }}>
      <Atmosphere mode={atmosphere} accent={accent} mobile={mobile} />
      {/* Top bar */}
      <header style={{
        position: 'relative', zIndex: 1,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: `${mobile ? 14 : 22}px ${pad}px`,
        paddingTop: mobile ? 64 : 22,
        gap: mobile ? 10 : 0,
        flexShrink: 0,
      }}>
        <AtlasMark accent={accent} size="sm" />
        <div style={{ flex: 1, display: 'flex', justifyContent: 'center', minWidth: 0 }}>
          {!ob.done && <VAStepper ob={ob} accent={accent} mobile={mobile} onJumpSection={(i) => i <= ob.stepIdx && ob.setStepIdx(i)} />}
        </div>
        <button onClick={ob.reset} style={{
          appearance: 'none', background: 'transparent', border: 0,
          color: VA_C.textMute, fontSize: 13, cursor: 'pointer',
          fontFamily: 'inherit', fontWeight: 500, whiteSpace: 'nowrap',
          flexShrink: 0,
        }}>{ob.done ? 'Restart' : (mobile ? 'Exit' : 'Save & exit')}</button>
      </header>

      {/* Body */}
      <main style={{
        position: 'relative', zIndex: 1,
        flex: 1, display: 'flex', flexDirection: 'column',
        alignItems: 'center',
        justifyContent: mobile ? 'flex-start' : 'safe center',
        padding: `${mobile ? 8 : 16}px ${pad}px ${pad}px`,
        minHeight: 0, overflowY: 'auto', overflowX: 'hidden',
      }}>
        <div style={{
          width: '100%', display: 'flex', flexDirection: 'column',
          alignItems: 'center',
          margin: mobile ? '0' : 'auto 0',
        }}>
        {!ob.done ? (
          ob.step.kind === 'welcome' ? (
            <div key={stepKey} style={{
              width: '100%', maxWidth: 560,
              animation: 'va-rise .55s cubic-bezier(.2,.7,.3,1) both',
            }}>
              <div style={{
                fontFamily: 'ui-monospace, SFMono-Regular, monospace',
                fontSize: 11, color: accent, letterSpacing: '0.08em',
                textTransform: 'uppercase', marginBottom: 18,
              }}>{ob.step.eyebrow}</div>
              <h1 style={{
                fontFamily: '"Instrument Serif", Georgia, serif',
                fontSize: mobile ? 40 : 64, fontWeight: 400,
                lineHeight: 1.02, letterSpacing: '-0.025em',
                margin: 0, marginBottom: mobile ? 14 : 18, color: VA_C.text,
                textWrap: 'balance',
              }}>{ob.step.title}</h1>
              <p style={{
                fontSize: mobile ? 14 : 16, color: VA_C.textDim,
                lineHeight: 1.55, margin: 0, marginBottom: mobile ? 28 : 36,
                maxWidth: 480, textWrap: 'pretty',
              }}>{ob.step.helper}</p>
              <ul style={{
                listStyle: 'none', padding: 0, margin: 0,
                display: 'flex', flexDirection: 'column', gap: 10,
                fontSize: mobile ? 13 : 14,
              }}>
                {[
                  ['01', 'Your gym & contact'],
                  ['02', 'Members, tiers, software'],
                  ['03', 'Staff & roles'],
                  ['04', 'How members move through your gym'],
                  ['05', 'Where things slip & priorities'],
                ].map(([n, label]) => (
                  <li key={n} style={{ display: 'flex', alignItems: 'baseline', gap: 14 }}>
                    <span style={{
                      fontFamily: 'ui-monospace, SFMono-Regular, monospace',
                      fontSize: 10, color: VA_C.textMute, letterSpacing: '0.08em',
                      width: 22,
                    }}>{n}</span>
                    <span style={{ color: VA_C.text }}>{label}</span>
                  </li>
                ))}
              </ul>

              {!mobile && (
                <div style={{
                  display: 'flex', alignItems: 'center', gap: 14,
                  marginTop: 36,
                }}>
                  <button onClick={ob.next}
                    style={{
                      appearance: 'none', cursor: 'pointer',
                      background: accent, color: '#0a0a0b',
                      border: 0, padding: '14px 26px',
                      borderRadius: 8, fontSize: 15, fontFamily: 'inherit', fontWeight: 600,
                    }}>Begin →</button>
                  <span style={{
                    fontFamily: 'ui-monospace, SFMono-Regular, monospace',
                    fontSize: 11, color: VA_C.textMute, letterSpacing: '0.05em',
                  }}>
                    or press <kbd style={kbdStyle}>↵</kbd>
                  </span>
                </div>
              )}
            </div>
          ) : (
          <div key={stepKey} style={{
            width: '100%', maxWidth: 540,
            animation: 'va-rise .42s cubic-bezier(.2,.7,.3,1) both',
          }}>
            <div style={{
              fontFamily: 'ui-monospace, SFMono-Regular, monospace',
              fontSize: 11, color: accent, letterSpacing: '0.08em',
              textTransform: 'uppercase', marginBottom: 14,
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <span>{ob.step.eyebrow}</span>
              {ob.step.optional && (
                <span style={{ color: VA_C.textMute, letterSpacing: '0.05em' }}>· Optional</span>
              )}
            </div>
            <h1 style={{
              fontFamily: '"Instrument Serif", Georgia, serif',
              fontSize: mobile ? 28 : 38, fontWeight: 400,
              lineHeight: 1.1, letterSpacing: '-0.015em',
              margin: 0, marginBottom: 12, color: VA_C.text,
              textWrap: 'balance',
            }}>{ob.step.title}</h1>
            <p style={{
              fontSize: mobile ? 13 : 14, color: VA_C.textDim,
              lineHeight: 1.55, margin: 0, marginBottom: mobile ? 22 : 32,
              maxWidth: 460, textWrap: 'pretty',
            }}>{ob.step.helper}</p>

            {/* Field */}
            {ob.step.kind === 'text' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                {ob.step.fields.map((f, i) => (
                  <VATextField key={f.key} field={f}
                    value={ob.answers[f.key]}
                    onChange={(v) => ob.setField(f.key, v)}
                    accent={accent} autoFocus={!mobile && i === 0} />
                ))}
              </div>
            )}
            {ob.step.kind === 'longtext' && (
              <VATextarea field={ob.step.field}
                value={ob.answers[ob.step.field.key]}
                onChange={(v) => ob.setField(ob.step.field.key, v)}
                accent={accent} autoFocus={!mobile} />
            )}
            {ob.step.kind === 'stages' && (
              <VAStages
                stages={ob.step.stages}
                value={ob.answers[ob.step.fieldKey]}
                onSet={(stKey, val) => ob.setField(ob.step.fieldKey, {
                  ...(ob.answers[ob.step.fieldKey] || {}), [stKey]: val,
                })}
                accent={accent}
              />
            )}
            {ob.step.kind === 'roster' && (
              <VARoster
                rows={ob.answers[ob.step.fieldKey]}
                onSet={(i, p) => ob.setRosterRow(ob.step.fieldKey, i, p)}
                onAdd={() => ob.addRosterRow(ob.step.fieldKey)}
                onRemove={(i) => ob.removeRosterRow(ob.step.fieldKey, i)}
                accent={accent}
              />
            )}
            {ob.step.kind === 'cards' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {ob.step.options.map((o, i) => (
                  <VACard key={o.value} option={o} idx={i} accent={accent}
                    active={ob.answers[ob.step.fieldKey] === o.value}
                    onClick={() => {
                      ob.setField(ob.step.fieldKey, o.value);
                      setTimeout(() => obRef.current.next(), 650);
                    }} />
                ))}
              </div>
            )}
            {ob.step.kind === 'rosterPick' && (
              <VARosterPick
                roster={ob.answers[ob.step.sourceKey || 'roster']}
                value={ob.answers[ob.step.fieldKey]}
                onToggle={(id) => ob.toggleMulti(ob.step.fieldKey, id)}
                accent={accent}
              />
            )}
            {ob.step.kind === 'chips' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                  {ob.step.options.map((o) => (
                    <VAChip key={o} label={o} accent={accent}
                      active={(ob.answers[ob.step.fieldKey] || []).includes(o)}
                      onClick={() => ob.toggleMulti(ob.step.fieldKey, o)} />
                  ))}
                </div>
                {ob.step.allowOther && (
                  <VAOtherInput
                    value={ob.answers[ob.step.fieldKey + '_other'] || ''}
                    onChange={(v) => ob.setField(ob.step.fieldKey + '_other', v)}
                    accent={accent}
                  />
                )}
              </div>
            )}

            {/* Inline action row (desktop only) */}
            {!mobile && (() => {
              const isOptional = ob.step?.optional;
              const isEmpty = isOptional && (() => {
                const s = ob.step;
                if (s.kind === 'longtext') return !(ob.answers[s.field.key] || '').trim();
                if (s.kind === 'cards') return !ob.answers[s.fieldKey];
                if (s.kind === 'chips') return !(ob.answers[s.fieldKey] || []).length;
                return true;
              })();
              const label = ob.step?.kind === 'welcome' ? 'Begin →' : ob.stepIdx === ob.total - 1 ? 'Finish' : isEmpty ? 'Skip →' : 'Continue →';
              return (
                <div style={{
                  display: 'flex', alignItems: 'center', gap: 14,
                  marginTop: 28,
                }}>
                  <button onClick={ob.next} disabled={!ob.canAdvance}
                    style={{
                      appearance: 'none', cursor: ob.canAdvance ? 'pointer' : 'default',
                      background: ob.canAdvance ? accent : 'rgba(255,255,255,0.06)',
                      color: ob.canAdvance ? '#0a0a0b' : VA_C.textMute,
                      border: 0, padding: '12px 22px',
                      borderRadius: 8, fontSize: 14, fontFamily: 'inherit', fontWeight: 600,
                      transition: 'background .15s, transform .15s',
                    }}>{label}</button>
                  <span style={{
                    fontFamily: 'ui-monospace, SFMono-Regular, monospace',
                    fontSize: 11, color: VA_C.textMute, letterSpacing: '0.05em',
                  }}>
                    or press <kbd style={kbdStyle}>↵</kbd>
                  </span>
                </div>
              );
            })()}
          </div>
          )
        ) : (
          <div key="done" style={{
            textAlign: 'center', maxWidth: 480,
            animation: 'va-rise .5s cubic-bezier(.2,.7,.3,1) both',
          }}>
            <div style={{
              fontFamily: 'ui-monospace, SFMono-Regular, monospace',
              fontSize: 11, color: accent, letterSpacing: '0.1em',
              textTransform: 'uppercase', marginBottom: 14,
            }}>Brief complete</div>
            <h1 style={{
              fontFamily: '"Instrument Serif", Georgia, serif',
              fontSize: mobile ? 32 : 44, fontWeight: 400, lineHeight: 1.05,
              letterSpacing: '-0.02em', margin: 0, marginBottom: 16,
              color: VA_C.text,
            }}>Thanks{ob.answers.gymName ? `,` : '.'} <br/>
              {ob.answers.gymName && (
                <span style={{ color: accent, fontStyle: 'italic' }}>{ob.answers.gymName}</span>
              )}
            </h1>
            <p style={{
              fontSize: 14, color: VA_C.textDim, lineHeight: 1.55,
              margin: '0 auto 28px', maxWidth: 420,
            }}>
              We’ll review {ob.answers.gymName ? `${ob.answers.gymName}’s` : 'your'} brief and reach out at{' '}
              <span style={{ color: VA_C.text }}>{ob.answers.contactEmail || 'your email'}</span> shortly.
            </p>
            <div style={{
              fontFamily: 'ui-monospace, SFMono-Regular, monospace',
              fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase',
              marginBottom: 24,
              color: ob.submitState === 'sent' ? accent
                : ob.submitState === 'error' ? '#ff8a80'
                : VA_C.textMute,
            }}>
              {ob.submitState === 'sending' && 'Saving your responses\u2026'}
              {ob.submitState === 'sent' && '\u2713 Responses saved'}
              {ob.submitState === 'error' && 'Save failed \u2014 please email us your answers'}
              {ob.submitState === 'idle' && ' '}
            </div>
            <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
              <button onClick={ob.reset} style={{
                appearance: 'none', cursor: 'pointer', fontFamily: 'inherit',
                background: 'transparent', color: VA_C.text,
                border: `1px solid ${VA_C.border}`, fontWeight: 500,
                padding: '12px 22px', borderRadius: 10, fontSize: 14,
              }}>Start over</button>
            </div>
          </div>
        )}
        </div>
      </main>

      {/* Footer */}
      {!ob.done && (
        <footer style={{
          position: 'relative', zIndex: 1,
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          padding: `${mobile ? 16 : 22}px ${pad}px`,
          paddingBottom: mobile ? 38 : 22,
          borderTop: `1px solid ${VA_C.border}`,
          flexShrink: 0,
        }}>
          <button onClick={ob.prev} disabled={ob.stepIdx === 0}
            style={{
              appearance: 'none', cursor: ob.stepIdx === 0 ? 'default' : 'pointer',
              background: 'transparent', color: ob.stepIdx === 0 ? VA_C.textMute : VA_C.text,
              border: `1px solid ${VA_C.border}`, padding: '10px 16px',
              borderRadius: 8, fontSize: 13, fontFamily: 'inherit', fontWeight: 500,
              opacity: ob.stepIdx === 0 ? 0.4 : 1,
            }}>← Back</button>

          <div style={{
            fontFamily: 'ui-monospace, SFMono-Regular, monospace',
            fontSize: 11, color: VA_C.textMute, letterSpacing: '0.05em',
          }}>
            {ob.stepIdx + 1} / {ob.total}
          </div>

          {(() => {
            if (!mobile) {
              return <div style={{ width: 1 }} />;
            }
            const isOptional = ob.step?.optional;
            const isEmpty = isOptional && (() => {
              const s = ob.step;
              if (s.kind === 'longtext') return !(ob.answers[s.field.key] || '').trim();
              if (s.kind === 'cards') return !ob.answers[s.fieldKey];
              if (s.kind === 'chips') return !(ob.answers[s.fieldKey] || []).length;
              return true;
            })();
            const label = ob.step?.kind === 'welcome' ? 'Begin →' : ob.stepIdx === ob.total - 1 ? 'Finish' : isEmpty ? 'Skip →' : 'Continue →';
            return (
              <button onClick={ob.next} disabled={!ob.canAdvance}
                style={{
                  appearance: 'none', cursor: ob.canAdvance ? 'pointer' : 'default',
                  background: ob.canAdvance ? accent : 'rgba(255,255,255,0.06)',
                  color: ob.canAdvance ? '#0a0a0b' : VA_C.textMute,
                  border: 0, padding: '10px 18px',
                  borderRadius: 8, fontSize: 13, fontFamily: 'inherit', fontWeight: 600,
                  transition: 'background .15s',
                }}>{label}</button>
            );
          })()}
        </footer>
      )}
    </div>
  );
}

const kbdStyle = {
  fontFamily: 'ui-monospace, SFMono-Regular, monospace',
  fontSize: 10, padding: '1px 5px', borderRadius: 3,
  background: 'rgba(255,255,255,0.08)', border: '1px solid rgba(255,255,255,0.12)',
  color: 'rgba(244,244,245,0.7)',
};

// Animation keyframes (one-shot inject)
if (typeof document !== 'undefined' && !document.getElementById('va-anim')) {
  const s = document.createElement('style');
  s.id = 'va-anim';
  s.textContent = `
    @keyframes va-rise {
      from { opacity: 0; transform: translateY(8px); }
      to { opacity: 1; transform: translateY(0); }
    }
  `;
  document.head.appendChild(s);
}

Object.assign(window, { VariationA, AtlasMark });
