/* Corsa Privata — "Su brief privado": a 7-step qualification brief.
 * It collects intention, not components: no prices, no quote, no brands.
 * Flow: intro → 7 steps (Paso n de 7) → contact → result. Answers are stored
 * as ids (language-switch safe); labels are always read from the active
 * language, except the transmitted brief, which is composed with the Spanish
 * labels so it maps 1:1 onto the internal Excel (01_Respuestas columns).
 * Delivery: window.cpSubmitBrief (app/submit.js); the brief is also attached
 * to the #begin form via the 'cp:circuit' event as an always-on fallback. */
const { Card, Button, Input } = window.CorsaPrivataDesignSystem_94a5c9;
const CfgIcon = window.Icon;

const CFG_STEPS = [
  { key: 'usage', type: 'single' },
  { key: 'driving', type: 'multi', max: 2 },
  { key: 'platform', type: 'single' },
  { key: 'pilots', type: 'single' },
  { key: 'motion', type: 'single' },
  { key: 'visual', type: 'single' },
  { key: 'project', type: 'composite' },
];

/* Icons only — every label/phrase lives in i18n. All names verified against
 * the pinned lucide@0.544.0 UMD. Platform icons stay generic: no brand marks. */
const CFG_ICONS = {
  usage: { personal: 'armchair', hobby: 'repeat', competition: 'timer', content: 'clapperboard' },
  driving: { formula: 'zap', gt: 'car-front', rally: 'trees', varied: 'shuffle' },
  platform: { playstation: 'gamepad-2', xbox: 'gamepad', pc: 'pc-case', guidance: 'compass' },
  pilots: { one: 'user-round', shared: 'users', family: 'users-round', team: 'graduation-cap' },
  motion: { static: 'circle-dot', motion3dof: 'move-3d', compare: 'scale', guidance: 'compass' },
  visual: { near: 'monitor', curved: 'gallery-horizontal', triple: 'columns-3', guidance: 'circle-help' },
  location: { residence: 'home', office: 'briefcase', commercial: 'store', undecided: 'map-pin' },
  size: { compact: 'square-dashed', defined: 'ruler', ample: 'expand', unknown: 'circle-help' },
  level: { essential: 'circle-check', performance: 'gauge', flagship: 'crown', guidance: 'compass' },
};

const cfgFill = (tpl, slots) => String(tpl || '').replace(/\{(\w+)\}/g, (_, k) => (slots[k] != null ? String(slots[k]) : ''));

function CfgOption({ icon, label, phrase, on, dimmed, compact, onClick }) {
  return (
    <button type="button" onClick={onClick} className="cp-opt" aria-pressed={on}
      style={{
        textAlign: 'left', cursor: 'pointer', display: 'flex', alignItems: 'flex-start', gap: compact ? 12 : 14,
        background: 'var(--surface-card)', borderRadius: 'var(--radius-md)',
        border: '1px solid', borderColor: on ? 'var(--cp-gold-500)' : 'var(--border-default)',
        boxShadow: on ? 'var(--shadow-sm)' : 'none', padding: compact ? '13px 14px' : '16px 18px',
        opacity: dimmed ? 0.45 : 1,
        transition: 'border-color var(--dur-fast) var(--ease-standard), box-shadow var(--dur-fast) var(--ease-standard), opacity var(--dur-fast) var(--ease-standard)',
      }}>
      <span style={{ width: compact ? 32 : 38, height: compact ? 32 : 38, borderRadius: 'var(--radius-sm)', flex: 'none', display: 'flex', alignItems: 'center', justifyContent: 'center', background: on ? 'rgba(194,161,101,0.12)' : 'var(--surface-sunken)', border: '1px solid', borderColor: on ? 'rgba(194,161,101,0.3)' : 'var(--border-hairline)' }}>
        <CfgIcon name={icon} size={compact ? 16 : 18} stroke={1.5} color={on ? 'var(--cp-gold-700)' : 'var(--text-muted)'} />
      </span>
      <span style={{ flex: 1, minWidth: 0 }}>
        <span style={{ display: 'block', fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-semibold)', fontSize: compact ? 14.5 : 16, color: 'var(--text-strong)', letterSpacing: '-0.01em' }}>{label}</span>
        {phrase && <span style={{ display: 'block', fontFamily: 'var(--font-body)', fontSize: 13.5, lineHeight: 1.5, color: 'var(--text-muted)', marginTop: 4 }}>{phrase}</span>}
      </span>
      <span style={{ width: 20, height: 20, borderRadius: '50%', flex: 'none', marginTop: 2, border: '1px solid', borderColor: on ? 'var(--cp-gold-500)' : 'var(--border-default)', background: on ? 'var(--accent)' : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        {on && <CfgIcon name="check" size={12} stroke={2.4} color="var(--text-on-gold)" />}
      </span>
    </button>
  );
}

/* The design system has no Textarea; this mirrors its Input field exactly. */
function CfgTextarea({ label, error, id, style, ...rest }) {
  const [focus, setFocus] = React.useState(false);
  const areaId = id || React.useId();
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      {label && <label htmlFor={areaId} style={{ fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 'var(--fw-medium)', textTransform: 'uppercase', letterSpacing: 'var(--ls-wide)', color: 'var(--text-muted)' }}>{label}</label>}
      <textarea id={areaId} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
        style={{
          fontFamily: 'var(--font-body)', fontSize: 15, color: 'var(--text-strong)', background: 'var(--surface-raised)',
          padding: '12px 14px', borderRadius: 'var(--radius-sm)', resize: 'vertical', minHeight: 96,
          border: `1px solid ${error ? 'var(--cp-danger)' : focus ? 'var(--cp-gold-500)' : 'var(--border-default)'}`,
          boxShadow: focus ? '0 0 0 3px var(--focus-ring)' : 'none', outline: 'none',
          transition: 'border-color var(--dur-fast) var(--ease-standard), box-shadow var(--dur-fast) var(--ease-standard)',
          ...style,
        }} {...rest} />
      {error && <span style={{ fontSize: 12, color: 'var(--cp-danger)' }}>{error}</span>}
    </div>
  );
}
window.CPTextarea = CfgTextarea;

function Configurator({ go, t, lang }) {
  const c = t.configurator;
  const [phase, setPhase] = React.useState('intro'); // intro | steps | contact | result
  const [stepIdx, setStepIdx] = React.useState(0);
  const [answers, setAnswers] = React.useState({
    usage: null, driving: [], platform: null, pilots: null, motion: null, visual: null,
    location: null, size: null, widthCm: '', lengthCm: '', level: null,
  });
  const [contact, setContact] = React.useState({ name: '', email: '', phone: '', city: '', comment: '' });
  const [errors, setErrors] = React.useState({});
  const [sending, setSending] = React.useState(false);
  const [sendFailed, setSendFailed] = React.useState(false);
  const [sentVia, setSentVia] = React.useState(null); // 'endpoint' | 'attached'
  const sectionRef = React.useRef(null);

  /* When a taller screen is swapped for a shorter one, keep the section pinned. */
  const repin = () => {
    window.requestAnimationFrame(() => {
      const el = sectionRef.current;
      if (el && el.getBoundingClientRect().top < 0) el.scrollIntoView({ block: 'start' });
    });
  };

  const setField = (field, value) => setAnswers((a) => ({ ...a, [field]: value }));
  const toggleDriving = (id) => setAnswers((a) => {
    if (a.driving.includes(id)) return { ...a, driving: a.driving.filter((x) => x !== id) };
    if (a.driving.length >= 2) return a;
    return { ...a, driving: [...a.driving, id] };
  });

  const def = CFG_STEPS[stepIdx];
  const stepValid = (d) =>
    d.key === 'driving' ? answers.driving.length >= 1 :
    d.key === 'project' ? !!(answers.location && answers.size && answers.level) :
    !!answers[d.key];

  const next = () => {
    if (stepIdx < CFG_STEPS.length - 1) setStepIdx((i) => i + 1);
    else setPhase('contact');
    repin();
  };
  const back = () => {
    if (phase === 'contact') setPhase('steps');
    else if (stepIdx > 0) setStepIdx((i) => i - 1);
    else setPhase('intro');
    repin();
  };

  /* Transmitted brief: Spanish labels always, mirroring the Excel columns. */
  /* The cm fields only apply to "Espacio definido"; values typed under it are
   * kept in state (so toggling back restores them) but never transmitted for
   * any other space answer. */
  const dims = () => (answers.size === 'defined' ? { w: answers.widthCm.trim(), l: answers.lengthCm.trim() } : { w: '', l: '' });

  const composeBrief = (esC) => {
    const st = esC.steps, cols = esC.brief.cols;
    const opt = (group, id) => (id && st[group].options[id] ? st[group].options[id].label : '');
    const sub = (block, id) => (id && st.project[block].options[id] ? st.project[block].options[id].label : '');
    const lines = [
      [cols.usage, opt('usage', answers.usage)],
      [cols.d1, opt('driving', answers.driving[0])],
      [cols.d2, opt('driving', answers.driving[1])],
      [cols.platform, opt('platform', answers.platform)],
      [cols.pilots, opt('pilots', answers.pilots)],
      [cols.motion, opt('motion', answers.motion)],
      [cols.visual, opt('visual', answers.visual)],
      [cols.locationType, sub('location', answers.location)],
      [cols.space, sub('size', answers.size)],
      [cols.width, dims().w],
      [cols.length, dims().l],
      [cols.level, sub('level', answers.level)],
      [cols.comment, contact.comment.trim()],
      [cols.name, contact.name.trim()],
      [cols.email, contact.email.trim()],
      [cols.whatsapp, contact.phone.trim()],
      [cols.city, contact.city.trim()],
    ];
    return esC.brief.intro + '\n' + lines.filter(([, v]) => v).map(([k, v]) => k + ': ' + v).join('\n');
  };

  const buildSentence = () => {
    const f = c.result.fragments;
    return cfgFill(c.result.sentence, {
      driving: answers.driving.map((id) => f.driving[id]).join(c.result.joiner),
      usage: f.usage[answers.usage],
      pilots: f.pilots[answers.pilots],
      visual: f.visual[answers.visual],
    });
  };

  const submitBrief = async () => {
    const er = {};
    if (!contact.name.trim()) er.name = c.contact.nameErr;
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(contact.email)) er.email = c.contact.emailErr;
    setErrors(er);
    if (Object.keys(er).length) return;

    const esC = (window.CP_I18N && window.CP_I18N.es && window.CP_I18N.es.configurator) || c;
    const briefText = composeBrief(esC);

    /* Always attach to the #begin form: it is the fallback if delivery is off. */
    const detail = { summary: briefText, name: contact.name.trim(), email: contact.email.trim() };
    window.cpCircuit = detail;
    window.dispatchEvent(new CustomEvent('cp:circuit', { detail }));

    setSending(true);
    setSendFailed(false);
    const st = esC.steps;
    const opt = (group, id) => (id && st[group].options[id] ? st[group].options[id].label : '');
    const sub = (block, id) => (id && st.project[block].options[id] ? st.project[block].options[id].label : '');
    const r = await (window.cpSubmitBrief
      ? window.cpSubmitBrief({
          _subject: esC.brief.intro,
          _replyto: contact.email.trim(),
          name: contact.name.trim(),
          email: contact.email.trim(),
          whatsapp: contact.phone.trim(),
          ciudad_pais: contact.city.trim(),
          comentario: contact.comment.trim(),
          uso: opt('usage', answers.usage),
          disciplina_1: opt('driving', answers.driving[0]),
          disciplina_2: opt('driving', answers.driving[1]),
          plataforma: opt('platform', answers.platform),
          pilotos: opt('pilots', answers.pilots),
          movimiento: opt('motion', answers.motion),
          visualizacion: opt('visual', answers.visual),
          tipo_de_espacio: sub('location', answers.location),
          espacio: sub('size', answers.size),
          ancho_cm: dims().w,
          largo_cm: dims().l,
          nivel_de_proyecto: sub('level', answers.level),
          brief: briefText,
          idioma: lang,
        })
      : Promise.resolve({ ok: false, skipped: true }));
    setSending(false);
    if (!r.ok && !r.skipped) { setSendFailed(true); return; }
    setSentVia(r.ok ? 'endpoint' : 'attached');
    setPhase('result');
    repin();
  };

  /* ---------- screens (render helpers, not components: inputs keep focus) ---------- */

  const renderIntro = () => (
    <div className="cp-cfg-step" style={{ padding: 'clamp(40px, 6vw, 72px) clamp(24px, 4vw, 48px)', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center' }}>
      <span style={{ width: 52, height: 52, borderRadius: 'var(--radius-md)', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--cp-gold-050)', border: '1px solid rgba(194,161,101,0.35)' }}>
        <CfgIcon name="route" size={24} stroke={1.4} color="var(--cp-gold-700)" />
      </span>
      <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, marginTop: 22, fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 'var(--fw-medium)', letterSpacing: 'var(--ls-wide)', textTransform: 'uppercase', color: 'var(--text-muted)' }}>
        <CfgIcon name="timer" size={14} stroke={1.6} color="var(--cp-gold-700)" /> {c.intro.time}
      </div>
      <div style={{ marginTop: 24 }}>
        <Button size="lg" onClick={() => { setPhase('steps'); repin(); }}>{c.intro.start}</Button>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 18 }}>
        <CfgIcon name="lock" size={13} stroke={1.6} color="var(--text-faint)" />
        <span style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--text-faint)' }}>{c.intro.confidential}</span>
      </div>
    </div>
  );

  const renderNav = (nextDisabled, nextLabel, onNext) => (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 28, gap: 12 }}>
      <Button variant="ghost" onClick={back} style={{ paddingLeft: 0 }}>&larr;&nbsp; {c.back}</Button>
      <Button onClick={onNext || next} disabled={nextDisabled}>{nextLabel || c.next}&nbsp; &rarr;</Button>
    </div>
  );

  const renderGroup = (groupKey, groupTxt, selected, onPick, opts) => (
    <div className="cp-cfg-opts" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: (opts && opts.tight) ? 14 : 24 }}>
      {Object.keys(groupTxt.options).map((id) => {
        const ot = groupTxt.options[id];
        const on = Array.isArray(selected) ? selected.includes(id) : selected === id;
        const dimmed = Array.isArray(selected) && !on && selected.length >= 2;
        return (
          <CfgOption key={id} icon={CFG_ICONS[groupKey][id]} label={ot.label} phrase={ot.phrase}
            on={on} dimmed={dimmed} compact={opts && opts.compact} onClick={() => onPick(id)} />
        );
      })}
    </div>
  );

  const renderStep = () => {
    const st = c.steps[def.key];
    return (
      <div key={def.key} className="cp-cfg-step" style={{ padding: 'clamp(24px, 3.5vw, 40px)' }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 12, flexWrap: 'wrap' }}>
          <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-semibold)', fontSize: 'clamp(22px,2.4vw,28px)', letterSpacing: '-0.02em', color: 'var(--text-strong)', margin: 0, textWrap: 'balance' }}>{st.title}</h3>
          {st.hint && <span style={{ fontFamily: 'var(--font-display)', fontSize: 10.5, fontWeight: 'var(--fw-medium)', letterSpacing: 'var(--ls-wide)', textTransform: 'uppercase', color: 'var(--cp-gold-700)', whiteSpace: 'nowrap' }}>{st.hint}</span>}
        </div>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 15, lineHeight: 1.55, color: 'var(--text-muted)', margin: '10px 0 0', maxWidth: '52ch' }}>{st.note}</p>

        {def.key === 'project' ? (
          <div>
            {[
              { block: 'location', iconKey: 'location', field: 'location', compact: true },
              { block: 'size', iconKey: 'size', field: 'size', compact: true },
              { block: 'level', iconKey: 'level', field: 'level', compact: true },
            ].map(({ block, iconKey, field, compact }) => {
              const q = st[block];
              return (
                <div key={block} style={{ marginTop: 26 }}>
                  <div style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-semibold)', fontSize: 16.5, letterSpacing: '-0.01em', color: 'var(--text-strong)' }}>{q.q}</div>
                  {renderGroup(iconKey, q, answers[field], (id) => setField(field, id), { compact, tight: true })}
                  {block === 'size' && answers.size === 'defined' && (
                    <div style={{ marginTop: 14 }}>
                      <span style={{ fontFamily: 'var(--font-display)', fontSize: 10.5, fontWeight: 'var(--fw-medium)', letterSpacing: 'var(--ls-wide)', textTransform: 'uppercase', color: 'var(--text-faint)' }}>{st.size.optionalTag}</span>
                      <div className="cp-form-row" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 8 }}>
                        <Input label={st.size.widthLabel} type="number" min="0" inputMode="numeric" value={answers.widthCm} onChange={(e) => setField('widthCm', e.target.value)} />
                        <Input label={st.size.lengthLabel} type="number" min="0" inputMode="numeric" value={answers.lengthCm} onChange={(e) => setField('lengthCm', e.target.value)} />
                      </div>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        ) : def.type === 'multi' ? (
          renderGroup(def.key, st, answers.driving, toggleDriving)
        ) : (
          renderGroup(def.key, st, answers[def.key], (id) => setField(def.key, id))
        )}

        {renderNav(!stepValid(def))}
      </div>
    );
  };

  const renderContact = () => (
    <div className="cp-cfg-step" style={{ padding: 'clamp(24px, 3.5vw, 40px)' }}>
      <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-semibold)', fontSize: 'clamp(22px,2.4vw,28px)', letterSpacing: '-0.02em', color: 'var(--text-strong)', margin: 0, textWrap: 'balance' }}>{c.contact.title}</h3>
      <p style={{ fontFamily: 'var(--font-body)', fontSize: 15, lineHeight: 1.55, color: 'var(--text-muted)', margin: '10px 0 0', maxWidth: '52ch' }}>{c.contact.body}</p>
      <form onSubmit={(e) => { e.preventDefault(); submitBrief(); }} style={{ display: 'flex', flexDirection: 'column', gap: 16, marginTop: 24 }}>
        <div className="cp-form-row" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Input label={c.contact.name} placeholder={c.contact.namePh} value={contact.name} onChange={(e) => setContact((p) => ({ ...p, name: e.target.value }))} error={errors.name} />
          <Input label={c.contact.email} type="email" placeholder={c.contact.emailPh} value={contact.email} onChange={(e) => setContact((p) => ({ ...p, email: e.target.value }))} error={errors.email} />
        </div>
        <div className="cp-form-row" style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
          <Input label={c.contact.phone} placeholder={c.contact.phonePh} value={contact.phone} onChange={(e) => setContact((p) => ({ ...p, phone: e.target.value }))} />
          <Input label={c.contact.city} placeholder={c.contact.cityPh} value={contact.city} onChange={(e) => setContact((p) => ({ ...p, city: e.target.value }))} />
        </div>
        <CfgTextarea label={c.contact.comment} placeholder={c.contact.commentPh} rows={3} value={contact.comment} onChange={(e) => setContact((p) => ({ ...p, comment: e.target.value }))} />
        {sendFailed && <span style={{ fontFamily: 'var(--font-body)', fontSize: 13, lineHeight: 1.5, color: 'var(--cp-danger)' }}>{c.contact.sendErr}</span>}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
          <Button variant="ghost" onClick={back} type="button" style={{ paddingLeft: 0 }}>&larr;&nbsp; {c.back}</Button>
          <Button type="submit" disabled={sending}>{c.contact.submit}</Button>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, justifyContent: 'center' }}>
          <CfgIcon name="lock" size={13} stroke={1.6} color="var(--text-faint)" />
          <span style={{ fontFamily: 'var(--font-body)', fontSize: 12, color: 'var(--text-faint)' }}>{c.contact.fine}</span>
        </div>
      </form>
    </div>
  );

  const renderResult = () => {
    const gridRows = [
      ['usage', c.steps.usage.options[answers.usage]],
      ['driving', { label: answers.driving.map((id) => c.steps.driving.options[id].label).join(' · ') }],
      ['platform', c.steps.platform.options[answers.platform]],
      ['pilots', c.steps.pilots.options[answers.pilots]],
      ['motion', c.steps.motion.options[answers.motion]],
      ['visual', c.steps.visual.options[answers.visual]],
    ];
    return (
      <div className="cp-cfg-step" style={{ padding: 'clamp(28px, 4vw, 48px)' }}>
        <span style={{ width: 46, height: 46, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center', background: 'var(--cp-gold-050)', border: '1px solid rgba(194,161,101,0.35)' }}>
          <CfgIcon name="check" size={20} stroke={2} color="var(--cp-gold-700)" />
        </span>
        <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-semibold)', fontSize: 'clamp(23px,2.6vw,30px)', letterSpacing: '-0.02em', color: 'var(--text-strong)', margin: '18px 0 0', textWrap: 'balance', maxWidth: '24ch' }}>{c.result.title}</h3>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 'clamp(15.5px,1.35vw,17px)', lineHeight: 1.62, color: 'var(--text-body)', margin: '16px 0 0', maxWidth: '58ch', textWrap: 'pretty' }}>{buildSentence()}</p>
        <p style={{ fontFamily: 'var(--font-body)', fontSize: 14, lineHeight: 1.6, color: 'var(--text-muted)', margin: '12px 0 0', maxWidth: '58ch' }}>{c.result.followup}</p>

        <div className="cp-cfg-result" style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: '0 28px', marginTop: 28 }}>
          {gridRows.map(([key, o]) => (
            <div key={key} style={{ borderTop: '1px solid var(--border-hairline)', padding: '12px 0 14px' }}>
              <div style={{ fontFamily: 'var(--font-display)', fontSize: 10, fontWeight: 'var(--fw-medium)', letterSpacing: 'var(--ls-wide)', textTransform: 'uppercase', color: 'var(--text-faint)' }}>{c.result.grid[key]}</div>
              <div style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-semibold)', fontSize: 14.5, color: 'var(--text-strong)', letterSpacing: '-0.01em', marginTop: 5 }}>{o ? o.label : '—'}</div>
            </div>
          ))}
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 20 }}>
          <CfgIcon name={sentVia === 'endpoint' ? 'send' : 'route'} size={14} stroke={1.6} color="var(--cp-gold-700)" />
          <span style={{ fontFamily: 'var(--font-body)', fontSize: 13, color: 'var(--text-muted)' }}>
            {sentVia === 'endpoint' ? c.result.sent : c.result.attachedNote}
          </span>
        </div>

        <div style={{ marginTop: 30, paddingTop: 26, borderTop: '1px solid var(--border-hairline)' }}>
          <span aria-hidden="true" style={{ display: 'block', width: 28, height: 2, background: 'var(--cp-gold-500)' }} />
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-semibold)', fontSize: 'clamp(19px,2vw,23px)', letterSpacing: '-0.015em', color: 'var(--text-strong)', marginTop: 16, textWrap: 'balance' }}>
            {c.result.closing1}
          </div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-semibold)', fontSize: 'clamp(19px,2vw,23px)', letterSpacing: '-0.015em', color: 'var(--cp-gold-700)', marginTop: 4, textWrap: 'balance' }}>
            {c.result.closing2}
          </div>
          <div style={{ marginTop: 22 }}>
            <Button onClick={() => go('begin')}>{c.result.cta}</Button>
          </div>
        </div>
      </div>
    );
  };

  const progressPct = phase === 'steps' ? ((stepIdx + 1) / CFG_STEPS.length) * 100 : phase === 'intro' ? 0 : 100;

  return (
    <section id="configure" ref={sectionRef} style={{ background: 'var(--surface-sunken)', scrollMarginTop: 72 }}>
      <div style={{ maxWidth: 'var(--container-max)', margin: '0 auto', padding: 'clamp(72px, 9vw, 112px) 32px' }}>
        <div className="cp-reveal" style={{ maxWidth: 680 }}>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-bold)', fontSize: 'clamp(32px,4vw,48px)', lineHeight: 1.06, letterSpacing: '-0.03em', color: 'var(--text-strong)', margin: 0, textWrap: 'balance' }}>
            {c.intro.title}
          </h2>
          <p style={{ fontFamily: 'var(--font-body)', fontSize: 'clamp(16px,1.4vw,18px)', lineHeight: 1.6, color: 'var(--text-body)', margin: '16px 0 0', maxWidth: '58ch', textWrap: 'pretty' }}>
            {c.intro.body}
          </p>
        </div>

        <div className="cp-reveal" style={{ marginTop: 40, maxWidth: 860 }}>
          <Card padding="0" style={{ overflow: 'hidden' }}>
            {phase !== 'intro' && (
              <div>
                {phase === 'steps' && (
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12, padding: '15px clamp(24px, 3.5vw, 40px)' }}>
                    <span style={{ fontFamily: 'var(--font-display)', fontSize: 11, fontWeight: 'var(--fw-medium)', letterSpacing: 'var(--ls-wider)', textTransform: 'uppercase', color: 'var(--cp-gold-700)' }}>
                      {cfgFill(c.progress, { n: stepIdx + 1, total: CFG_STEPS.length })}
                    </span>
                    <span aria-hidden="true" style={{ fontFamily: 'var(--font-display)', fontWeight: 'var(--fw-bold)', fontSize: 18, letterSpacing: '-0.02em', color: 'var(--cp-ink-100)' }}>
                      {String(stepIdx + 1).padStart(2, '0') + ' / ' + String(CFG_STEPS.length).padStart(2, '0')}
                    </span>
                  </div>
                )}
                <div style={{ height: 2, background: 'var(--border-hairline)' }}>
                  <div style={{ height: 2, width: progressPct + '%', background: 'var(--cp-gold-500)', transition: 'width var(--dur-base) var(--ease-standard)' }} />
                </div>
              </div>
            )}
            {phase === 'intro' && renderIntro()}
            {phase === 'steps' && renderStep()}
            {phase === 'contact' && renderContact()}
            {phase === 'result' && renderResult()}
          </Card>
        </div>
      </div>
    </section>
  );
}

window.Configurator = Configurator;
