// quiz.jsx — Multi-step eligibility quiz modal

const QUIZ_STEPS = [
  {
    id: 'goal', kind: 'choice',
    q: '¿Cuál es tu objetivo principal hoy?',
    sub: 'Esto guía qué protocolos te pueden funcionar.',
    options: [
      { v: 'metabolic', l: 'Bajar de peso y mejorar mi metabolismo', i: 'pulse' },
      { v: 'longevity', l: 'Sentirme con más energía y prevenir el envejecimiento', i: 'dna' },
      { v: 'hormones',  l: 'Ajustar mis hormonas (TRT, tiroides, menopausia)', i: 'shield' },
      { v: 'sleep',     l: 'Dormir mejor y reducir mi estrés', i: 'brain' },
    ],
  },
  {
    id: 'sex', kind: 'choice',
    q: '¿Cuál es tu sexo biológico?',
    sub: 'Determina qué hormonas y dosis son apropiadas.',
    options: [
      { v: 'm', l: 'Hombre' },
      { v: 'f', l: 'Mujer' },
      { v: 'i', l: 'Intersex / prefiero no decir' },
    ],
  },
  {
    id: 'age', kind: 'slider',
    q: '¿Qué edad tienes?',
    sub: 'Necesitamos al menos 21 años para iniciar tratamiento.',
    min: 18, max: 75, def: 38, unit: 'años',
  },
  {
    id: 'weight', kind: 'choice',
    q: '¿Has intentado bajar de peso antes?',
    sub: 'Tu historial nos ayuda a personalizar tu protocolo.',
    options: [
      { v: 'never', l: 'Nunca lo he intentado seriamente' },
      { v: 'diet',  l: 'Sí, con dietas o ejercicio' },
      { v: 'meds',  l: 'Sí, con medicamentos (incluido GLP‑1)' },
      { v: 'surg',  l: 'Sí, con cirugía bariátrica' },
    ],
  },
  {
    id: 'conditions', kind: 'multi',
    q: '¿Tienes alguna de estas condiciones?',
    sub: 'Selecciona todas las que apliquen. Ninguna te excluye automáticamente.',
    options: [
      { v: 'dm',   l: 'Diabetes tipo 2' },
      { v: 'htn',  l: 'Hipertensión' },
      { v: 'thy',  l: 'Tiroides (hipo o hiper)' },
      { v: 'chol', l: 'Colesterol alto' },
      { v: 'preg', l: 'Embarazo o lactancia' },
      { v: 'none', l: 'Ninguna de las anteriores' },
    ],
  },
  {
    id: 'country', kind: 'choice',
    q: '¿Desde dónde nos contactas?',
    sub: 'Operamos en estos países hoy.',
    options: [
      { v: 'mx', l: '🇲🇽 México' },
      { v: 'co', l: '🇨🇴 Colombia' },
      { v: 'do', l: '🇩🇴 República Dominicana' },
      { v: 'ar', l: '🇦🇷 Argentina' },
      { v: 'cl', l: '🇨🇱 Chile' },
      { v: 'pe', l: '🇵🇪 Perú' },
      { v: 'es', l: '🇪🇸 España' },
    ],
  },
  {
    id: 'email', kind: 'email',
    q: 'Envíame mi plan personalizado',
    sub: 'Crearemos tu cuenta y guardaremos tu progreso. Cero spam.',
  },
];

function Quiz({ open, onClose }) {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [done, setDone] = React.useState(false);

  React.useEffect(() => {
    if (open) { setStep(0); setAnswers({}); setDone(false); }
  }, [open]);

  if (!open) return null;
  const s = QUIZ_STEPS[step];
  const total = QUIZ_STEPS.length;
  const pct = Math.round(((step + (done ? 1 : 0)) / total) * 100);

  const setAns = (v) => setAnswers({ ...answers, [s.id]: v });
  const next = () => {
    if (step < total - 1) setStep(step + 1);
    else setDone(true);
  };
  const canNext = answers[s?.id] !== undefined &&
    (s.kind !== 'multi' || (answers[s.id] && answers[s.id].length));

  const iconFor = (key) => ({ pulse: Icon.pulse, dna: Icon.dna, shield: Icon.shield, brain: Icon.brain }[key] || Icon.spark);

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(6,35,31,0.55)',
      backdropFilter: 'blur(8px)', WebkitBackdropFilter: 'blur(8px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
      animation: 'fadeIn .25s ease',
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 720, background: '#fff', borderRadius: 24,
        overflow: 'hidden', boxShadow: '0 40px 100px rgba(0,0,0,0.4)',
        animation: 'slideUp .35s cubic-bezier(.2,.9,.3,1.2)',
        fontFamily: POPPINS, position: 'relative',
      }}>
        {/* header */}
        <div style={{
          padding: '20px 28px', display: 'flex', alignItems: 'center',
          justifyContent: 'space-between', borderBottom: `1px solid ${M.rule}`,
        }}>
          <Wordmark size={16}/>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            {!done && <span style={{ fontSize: 12, color: M.ink3 }}>Paso {step + 1} de {total}</span>}
            <button onClick={onClose} style={{
              width: 32, height: 32, borderRadius: 99, border: 'none',
              background: M.creamSoft, cursor: 'pointer', fontSize: 18, color: M.ink2,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>×</button>
          </div>
        </div>

        {/* progress */}
        <div style={{ height: 3, background: M.ruleSoft }}>
          <div style={{
            width: `${pct}%`, height: '100%',
            background: `linear-gradient(90deg, ${M.primary}, ${M.primaryHi})`,
            transition: 'width .4s ease',
          }}/>
        </div>

        {/* body */}
        {!done ? (
          <div key={step} style={{ padding: 40, animation: 'fadeUp .3s ease' }}>
            <h3 style={{
              fontFamily: POPPINS, fontSize: 30, fontWeight: 600,
              letterSpacing: '-0.025em', lineHeight: 1.1, margin: '0 0 8px', color: M.ink,
              textWrap: 'balance',
            }}>{s.q}</h3>
            <p style={{ fontSize: 15, color: M.ink2, margin: '0 0 28px', lineHeight: 1.5 }}>{s.sub}</p>

            {s.kind === 'choice' && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {s.options.map(o => {
                  const sel = answers[s.id] === o.v;
                  return (
                    <button key={o.v} onClick={() => setAns(o.v)} style={{
                      padding: '18px 20px', borderRadius: 14, textAlign: 'left',
                      background: sel ? 'rgba(14,122,101,0.08)' : '#fff',
                      border: `1.5px solid ${sel ? M.primary : M.rule}`,
                      cursor: 'pointer', fontFamily: POPPINS, fontSize: 16,
                      color: M.ink, fontWeight: 500,
                      display: 'flex', alignItems: 'center', gap: 14,
                      transition: 'all .15s ease',
                    }}>
                      {o.i && (
                        <div style={{
                          width: 40, height: 40, borderRadius: 10, flexShrink: 0,
                          background: sel ? M.primary : 'rgba(14,122,101,0.08)',
                          color: sel ? '#fff' : M.primary,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                        }}>{React.cloneElement(iconFor(o.i)(sel ? '#fff' : M.primary), { width: 22, height: 22 })}</div>
                      )}
                      <span style={{ flex: 1 }}>{o.l}</span>
                      <span style={{
                        width: 22, height: 22, borderRadius: 99,
                        background: sel ? M.primary : 'transparent',
                        border: sel ? 'none' : `1.5px solid ${M.rule}`,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                      }}>{sel && React.cloneElement(Icon.check('#fff'), { width: 14, height: 14 })}</span>
                    </button>
                  );
                })}
              </div>
            )}

            {s.kind === 'multi' && (
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                {s.options.map(o => {
                  const arr = answers[s.id] || [];
                  const sel = arr.includes(o.v);
                  return (
                    <button key={o.v} onClick={() => {
                      let next = sel ? arr.filter(x => x !== o.v) : [...arr, o.v];
                      if (o.v === 'none') next = sel ? [] : ['none'];
                      else next = next.filter(x => x !== 'none');
                      setAns(next);
                    }} style={{
                      padding: '14px 18px', borderRadius: 14, textAlign: 'left',
                      background: sel ? 'rgba(14,122,101,0.08)' : '#fff',
                      border: `1.5px solid ${sel ? M.primary : M.rule}`,
                      cursor: 'pointer', fontFamily: POPPINS, fontSize: 15,
                      color: M.ink, fontWeight: 500,
                      display: 'flex', alignItems: 'center', gap: 12,
                    }}>
                      <span style={{
                        width: 20, height: 20, borderRadius: 5, flexShrink: 0,
                        background: sel ? M.primary : 'transparent',
                        border: sel ? 'none' : `1.5px solid ${M.rule}`,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                      }}>{sel && React.cloneElement(Icon.check('#fff'), { width: 12, height: 12 })}</span>
                      {o.l}
                    </button>
                  );
                })}
              </div>
            )}

            {s.kind === 'slider' && (
              <div>
                <div style={{
                  textAlign: 'center', fontFamily: POPPINS, fontSize: 72, fontWeight: 600,
                  letterSpacing: '-0.04em', color: M.primary, margin: '20px 0 8px', lineHeight: 1,
                }}>{answers[s.id] ?? s.def}</div>
                <div style={{ textAlign: 'center', color: M.ink3, marginBottom: 24, fontSize: 14 }}>{s.unit}</div>
                <input type="range" min={s.min} max={s.max} value={answers[s.id] ?? s.def}
                  onChange={e => setAns(parseInt(e.target.value))}
                  style={{ width: '100%', accentColor: M.primary }}/>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10, color: M.ink3, fontSize: 12 }}>
                  <span>{s.min}</span><span>{s.max}</span>
                </div>
              </div>
            )}

            {s.kind === 'email' && (
              <div>
                <input type="email" placeholder="tu@correo.com" autoFocus
                  value={answers[s.id] || ''}
                  onChange={e => setAns(e.target.value)}
                  style={{
                    width: '100%', padding: '18px 20px', borderRadius: 14,
                    border: `1.5px solid ${M.rule}`, fontFamily: POPPINS,
                    fontSize: 18, color: M.ink, outline: 'none', boxSizing: 'border-box',
                  }}
                  onFocus={e => e.currentTarget.style.borderColor = M.primary}
                  onBlur={e => e.currentTarget.style.borderColor = M.rule}/>
                <div style={{
                  marginTop: 14, padding: 14, borderRadius: 12,
                  background: M.creamSoft, fontSize: 12, color: M.ink2, lineHeight: 1.5,
                  display: 'flex', gap: 10,
                }}>
                  {Icon.lock(M.primary)}
                  <span>Tus datos están cifrados de extremo a extremo. Nunca los compartimos con farmacéuticas, aseguradoras ni anunciantes.</span>
                </div>
              </div>
            )}
          </div>
        ) : (
          // Result
          <div style={{ padding: 48, textAlign: 'center' }}>
            <div style={{
              width: 72, height: 72, borderRadius: 99, margin: '0 auto 24px',
              background: `linear-gradient(135deg, ${M.primary}, ${M.primaryHi})`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              animation: 'pop .4s cubic-bezier(.2,.9,.3,1.4)',
            }}>{React.cloneElement(Icon.check('#fff'), { width: 36, height: 36 })}</div>
            <h3 style={{
              fontFamily: POPPINS, fontSize: 32, fontWeight: 600,
              letterSpacing: '-0.025em', lineHeight: 1.1, margin: '0 0 12px', color: M.ink,
            }}>Calificas para Medicya.</h3>
            <p style={{
              fontFamily: POPPINS, fontSize: 16, color: M.ink2,
              lineHeight: 1.55, margin: '0 0 28px', maxWidth: 480, marginInline: 'auto',
            }}>
              Según tus respuestas, recomendamos el protocolo de{' '}
              <strong style={{ color: M.primary }}>
                {(TREATMENTS_NAME[answers.goal] || 'medicina personalizada')}
              </strong>. Un médico revisará tu caso y te contactará en menos de 24 horas.
            </p>
            <div style={{
              display: 'inline-flex', gap: 32, padding: '20px 28px',
              background: M.creamSoft, borderRadius: 16, marginBottom: 28,
              fontFamily: POPPINS,
            }}>
              <div>
                <div style={{ fontSize: 11, color: M.ink3, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Costo estimado</div>
                <div style={{ fontSize: 22, fontWeight: 600, color: M.ink, marginTop: 4 }}>$1,890 MXN/mes</div>
              </div>
              <div style={{ width: 1, background: M.rule }}/>
              <div>
                <div style={{ fontSize: 11, color: M.ink3, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Inicio</div>
                <div style={{ fontSize: 22, fontWeight: 600, color: M.ink, marginTop: 4 }}>3‑5 días hábiles</div>
              </div>
            </div>
            <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
              <Btn kind="dark" size="lg">Reservar consulta médica</Btn>
              <Btn kind="ghost" size="lg" onClick={onClose}>Cerrar</Btn>
            </div>
          </div>
        )}

        {/* footer */}
        {!done && (
          <div style={{
            padding: '20px 28px', display: 'flex', justifyContent: 'space-between',
            alignItems: 'center', borderTop: `1px solid ${M.rule}`, background: M.creamSoft,
          }}>
            <button onClick={() => step > 0 && setStep(step - 1)} style={{
              padding: '12px 18px', borderRadius: 99, border: 'none',
              background: 'transparent', cursor: step > 0 ? 'pointer' : 'not-allowed',
              fontFamily: POPPINS, fontSize: 14, fontWeight: 500,
              color: step > 0 ? M.ink : M.ink3,
            }}>← Atrás</button>
            <Btn kind="dark" size="md" onClick={canNext ? next : undefined}
              style={{ opacity: canNext ? 1 : 0.4, pointerEvents: canNext ? 'auto' : 'none' }}>
              {step === total - 1 ? 'Ver mi plan' : 'Continuar'} →
            </Btn>
          </div>
        )}
      </div>
    </div>
  );
}

const TREATMENTS_NAME = {
  metabolic: 'optimización metabólica',
  longevity: 'longevidad & vitalidad',
  hormones: 'equilibrio hormonal',
  sleep: 'sueño & estrés',
};

Object.assign(window, { Quiz });
