// ===== Quiz: conversational tire advisor =====
const Quiz = ({ navigate, addToCart }) => {
  const questions = [
  {
    q: 'Hola 👋 Soy RAY, tu asesor RUTA. ¿Cuál es tu prioridad #1 al manejar?',
    options: [
    { lbl: 'Que aguanten mucho tiempo', ico: '⏳', tag: 'life' },
    { lbl: 'Sentir el coche en curvas', ico: '🏁', tag: 'sport' },
    { lbl: 'Manejar tranquilo y silencioso', ico: '🤫', tag: 'comfort' },
    { lbl: 'Que rindan gasolina', ico: '⛽', tag: 'fuel' }]

  },
  {
    q: '¿Dónde manejas más?',
    options: [
    { lbl: 'Ciudad (CDMX, tráfico, topes)', ico: '🏙️', tag: 'city' },
    { lbl: 'Carretera (largos viajes)', ico: '🛣️', tag: 'highway' },
    { lbl: 'Off-road / terracería', ico: '🏔️', tag: 'offroad' },
    { lbl: 'Mixto', ico: '🔀', tag: 'mix' }]

  },
  {
    q: 'En tu zona, ¿llueve seguido?',
    options: [
    { lbl: 'Mucho — temporada de lluvias intensa', ico: '🌧️', tag: 'wet-high' },
    { lbl: 'Normal — algunas tormentas', ico: '☁️', tag: 'wet-med' },
    { lbl: 'Casi nunca llueve', ico: '☀️', tag: 'wet-low' }]

  },
  {
    q: '¿Qué tan importante es el silencio dentro del coche?',
    options: [
    { lbl: 'Crítico — escucho podcasts/llamadas', ico: '🎧', tag: 'quiet-high' },
    { lbl: 'Lo normal', ico: '🎵', tag: 'quiet-med' },
    { lbl: 'No me importa el ruido', ico: '🔊', tag: 'quiet-low' }]

  },
  {
    q: '¿Cuál es tu rango de presupuesto por llanta?',
    options: [
    { lbl: 'Menos de $3,000', ico: '💵', tag: 'budget-low' },
    { lbl: '$3,000 — $5,000', ico: '💸', tag: 'budget-med' },
    { lbl: 'Más de $5,000 — quiero lo mejor', ico: '💎', tag: 'budget-high' }]

  },
  {
    q: 'Última: ¿cuántos km haces al año?',
    options: [
    { lbl: 'Menos de 10,000 (fines de semana)', ico: '🐢', tag: 'low-km' },
    { lbl: '10,000 — 25,000 km', ico: '🚗', tag: 'med-km' },
    { lbl: 'Más de 25,000 (uber / vendedor)', ico: '🏎️', tag: 'high-km' }]

  }];


  const [answers, setAnswers] = useState([]);
  const [currentQ, setCurrentQ] = useState(0);
  const [typing, setTyping] = useState(true);
  const scrollRef = useRef(null);

  useEffect(() => {
    setTyping(true);
    const t = setTimeout(() => setTyping(false), 800);
    return () => clearTimeout(t);
  }, [currentQ]);

  useEffect(() => {
    scrollRef.current?.scrollTo({ top: 99999, behavior: 'smooth' });
  });

  const pick = (opt) => {
    const newAnswers = [...answers, { qIdx: currentQ, ...opt }];
    setAnswers(newAnswers);
    if (currentQ < questions.length - 1) {
      setTimeout(() => setCurrentQ(currentQ + 1), 400);
    } else {
      setTimeout(() => setCurrentQ(currentQ + 1), 400); // -> results
    }
  };

  const done = currentQ >= questions.length;

  // Score recommendation based on answers
  const recommendation = useMemo(() => {
    if (!done) return null;
    const tags = answers.map((a) => a.tag);
    const score = (t) => {
      let s = 0;
      // budget
      if (tags.includes('budget-low') && t.price > 3000) s -= 2;
      if (tags.includes('budget-high') && t.price < 4500) s -= 1;
      // use
      if (tags.includes('sport') && t.use === 'sport') s += 4;
      if (tags.includes('comfort') && t.dna.noise > 80) s += 3;
      if (tags.includes('life') && t.dna.life > 85) s += 3;
      if (tags.includes('fuel') && t.dna.fuel > 85) s += 3;
      if (tags.includes('offroad') && t.use === 'offroad') s += 5;
      if (tags.includes('city') && t.use === 'city') s += 2;
      if (tags.includes('highway') && (t.use === 'highway' || t.dna.life > 85)) s += 2;
      if (tags.includes('wet-high') && t.dna.wet > 88) s += 3;
      if (tags.includes('quiet-high') && t.dna.noise > 85) s += 2;
      return s;
    };
    return [...TIRES].map((t) => ({ t, s: score(t) })).sort((a, b) => b.s - a.s).slice(0, 3);
  }, [done, answers]);

  return (
    <div className="page-fade quiz-shell" data-comment-anchor="4372c50781-div-108-5">
      <div style={{ textAlign: 'center', marginBottom: 24 }}>
        <div className="eyebrow">— ASESOR CONVERSACIONAL · RAY</div>
        <h1 className="display" style={{ fontSize: 48, margin: '8px 0 0' }}>NO SÉ NADA DE LLANTAS</h1>
        <p style={{ color: 'var(--text-mute)', margin: '8px 0 0' }}>90 segundos. Sin tecnicismos. Te recomiendo tu match.</p>
      </div>

      {!done &&
      <div className="quiz-progress">
          <div className="num">PREGUNTA {currentQ + 1} / {questions.length}</div>
          <div className="bar"><div className="bar-f" style={{ width: (currentQ + 1) / questions.length * 100 + '%' }}></div></div>
        </div>
      }

      <div ref={scrollRef} style={{ maxHeight: 'calc(100vh - 280px)', overflowY: 'auto', paddingRight: 8 }}>
        {/* Initial greeting */}
        {answers.map((a, i) => {
          const q = questions[a.qIdx];
          return (
            <React.Fragment key={i}>
              <div className="quiz-bubble">
                <div className="quiz-avatar">R</div>
                <div className="quiz-msg">{q.q}</div>
              </div>
              <div className="quiz-bubble user">
                <div className="quiz-avatar">{(localStorage.getItem('userInitial') || 'T').toUpperCase()}</div>
                <div className="quiz-msg">{a.ico} {a.lbl}</div>
              </div>
            </React.Fragment>);

        })}

        {/* Current question */}
        {currentQ < questions.length &&
        <>
            <div className="quiz-bubble">
              <div className="quiz-avatar">R</div>
              <div className="quiz-msg">
                {typing ?
              <div className="quiz-typing"><span></span><span></span><span></span></div> :

              questions[currentQ].q
              }
              </div>
            </div>

            {!typing &&
          <div className="quiz-options">
                {questions[currentQ].options.map((opt, i) =>
            <button key={i} className="quiz-option" onClick={() => pick(opt)}>
                    <span className="ico">{opt.ico}</span>
                    <span>{opt.lbl}</span>
                  </button>
            )}
              </div>
          }
          </>
        }

        {/* Results */}
        {done && recommendation &&
        <div style={{ animation: 'pageFade 600ms ease both', marginTop: 32 }}>
            <div className="quiz-bubble">
              <div className="quiz-avatar">R</div>
              <div className="quiz-msg" style={{ maxWidth: '100%' }}>
                <div className="display" style={{ fontSize: 28, marginBottom: 8 }}>¡TENGO TU MATCH! 🎯</div>
                Basado en tus respuestas, estas son las 3 llantas que mejor encajan con tu manejo:
              </div>
            </div>

            <div style={{ margin: '32px 0 16px 0', display: 'grid', gridTemplateColumns: '1fr', gap: 12 }}>
              {recommendation.map((rec, i) =>
            <div key={rec.t.id} className="card" style={{ padding: 20, display: 'grid', gridTemplateColumns: 'auto 1fr auto', gap: 20, alignItems: 'center', borderColor: i === 0 ? 'var(--accent)' : 'var(--line)', position: 'relative' }}>
                  {i === 0 && <span className="chip chip-accent" style={{ position: 'absolute', top: -10, left: 20 }}>★ TU MATCH PERFECTO</span>}
                  <div style={{ width: 88, height: 88, background: 'var(--bg-elev-2)', borderRadius: 10, display: 'grid', placeItems: 'center' }}>
                    <TireSVG size={78} brand={rec.t.brand.substring(0, 4).toUpperCase()} spec="" accent={rec.t.accent} />
                  </div>
                  <div>
                    <div style={{ fontFamily: 'var(--font-mono)', fontSize: 10, color: 'var(--text-mute)', textTransform: 'uppercase', letterSpacing: '0.12em' }}>{rec.t.brand}</div>
                    <div className="display" style={{ fontSize: 24, lineHeight: 1, margin: '4px 0' }}>{rec.t.name}</div>
                    <div style={{ fontSize: 13, color: 'var(--text-mute)', margin: '4px 0 6px' }}>{rec.t.tagline}</div>
                    <DnaMini dna={rec.t.dna} />
                  </div>
                  <div style={{ textAlign: 'right', display: 'flex', flexDirection: 'column', gap: 8, alignItems: 'flex-end' }}>
                    <div className="price"><span className="from">DESDE</span><span className="currency">$</span>{rec.t.price.toLocaleString('es-MX')}</div>
                    <button className="btn btn-primary" onClick={() => navigate('product', { id: rec.t.id })}>
                      VER <Icon name="arrow" size={14} />
                    </button>
                  </div>
                </div>
            )}
            </div>

            <div style={{ display: 'flex', gap: 8, marginLeft: 52 }}>
              <button className="btn btn-ghost" onClick={() => {setAnswers([]);setCurrentQ(0);}}>
                <Icon name="arrowL" size={14} /> EMPEZAR DE NUEVO
              </button>
              <button className="btn btn-ghost" onClick={() => navigate('catalog')}>
                VER CATÁLOGO COMPLETO
              </button>
            </div>
          </div>
        }
      </div>
    </div>);

};

Object.assign(window, { Quiz });