// Interactive 60-second diagnostic.
// User answers 4 questions, each option contributes weighted scores to
// up to four offerings. At the end we surface the highest-scored one.
function Diagnostico() {
  const [lang] = useLang();
  const C = window.FUSE_CONTENT.diagnostico;
  const OFERTAS = window.FUSE_CONTENT.ofertas.items;

  const questions = C.questions[lang];
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState([]);

  const total = questions.length;
  const done = step >= total;

  // Aggregate weights to pick top offering
  const winner = React.useMemo(() => {
    if (!done) return null;
    const score = { diagnostico: 0, motor: 0, infra: 0, retainer: 0 };
    answers.forEach(a => {
      Object.entries(a.weight).forEach(([k, v]) => { score[k] = (score[k] || 0) + v; });
    });
    const sorted = Object.entries(score).sort((a, b) => b[1] - a[1]);
    const topId = sorted[0][0];
    const topOferta = OFERTAS.find(o => o.id === topId);
    return { score, topId, topOferta };
  }, [done, answers]);

  const choose = (opt) => {
    setAnswers(prev => [...prev, opt]);
    setStep(s => s + 1);
  };

  const reset = () => { setStep(0); setAnswers([]); };

  // Custom rationale strings
  const rationale = (id) => {
    const map = {
      es: {
        diagnostico: 'Antes de invertir en construir, te conviene entender qué tenés y qué te falta. El diagnóstico es de baja fricción y la mayoría de los clientes lo usan como entrada.',
        motor: 'Tus pérdidas más costosas están del lado comercial. El motor comercial sistematiza captación, calificación, seguimiento y propuestas — en 6–8 semanas, funcionando.',
        infra: 'El conocimiento y los procesos operacionales son el cuello de botella. Conocimiento estructurado + copilots específicos + automatización crítica, opcionalmente con RAG privado.',
        retainer: 'Ya tenés el sistema funcionando. Lo que necesitás es iteración sostenida, mejoras incrementales y acceso directo para lo urgente.',
      },
      en: {
        diagnostico: 'Before investing in building, it pays to understand what you have and what\'s missing. The diagnostic is low-friction and most clients use it as the entry point.',
        motor: 'Your costliest leaks are on the commercial side. The commercial engine systematizes capture, qualification, follow-up and proposals — in 6–8 weeks, running.',
        infra: 'Knowledge and operational processes are the bottleneck. Structured knowledge + firm-specific copilots + critical automation, optionally with private RAG.',
        retainer: 'You already have the system running. What you need is sustained iteration, incremental improvements, and direct access for the urgent stuff.',
      },
    };
    return map[lang][id];
  };

  return (
    <section id="diagnostico" className="section" style={{ background: 'var(--bone)', borderTop: '1px solid var(--border)' }} data-screen-label="diagnostico">
      <div className="container">
        <header className="reveal" style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 64, alignItems: 'end', marginBottom: 40 }}>
          <div>
            <div className="kicker kicker-accent">{C.kicker[lang]}</div>
            <h2 className="h-section" style={{ marginTop: 12 }}>
              {C.h2[lang][0]} <span className="mk-emph">{C.h2[lang][1]}</span>{C.h2[lang][2]}
            </h2>
          </div>
          <p className="lead" style={{ color: 'var(--fg-2)' }}>{C.body[lang]}</p>
        </header>

        <div className="diag-wrap reveal" data-delay="1">
          {/* Progress bar */}
          <div className="diag-progress" aria-hidden>
            {questions.map((_, i) => (
              <span key={i} className={i < step ? 'done' : (i === step ? 'now' : '')} />
            ))}
          </div>

          {!done && (
            <div key={step}>
              <div className="diag-counter">
                {lang === 'es' ? 'Pregunta' : 'Question'} {String(step + 1).padStart(2, '0')} / {String(total).padStart(2, '0')}
              </div>
              <h3 className="diag-q">{questions[step].q}</h3>
              <ul className="diag-options">
                {questions[step].options.map((opt, i) => (
                  <li key={i}>
                    <button className="diag-option" onClick={() => choose(opt)}>
                      <span>{opt.label}</span>
                      <span className="arrow">→</span>
                    </button>
                  </li>
                ))}
              </ul>
              {step > 0 && (
                <button
                  onClick={() => { setStep(s => s - 1); setAnswers(a => a.slice(0, -1)); }}
                  style={{
                    marginTop: 28, background: 'transparent', border: 'none',
                    fontFamily: 'var(--font-mono)', fontSize: 12, letterSpacing: '0.06em', textTransform: 'uppercase',
                    color: 'var(--fg-mute)', cursor: 'pointer',
                  }}
                >
                  ← {lang === 'es' ? 'Volver' : 'Back'}
                </button>
              )}
            </div>
          )}

          {done && winner && (
            <div className="diag-result">
              <div className="diag-counter">
                {C.result[lang].intro}
              </div>
              <div className="diag-result-card">
                <div className="dr-kicker">
                  {lang === 'es' ? 'Para tu firma, empezaría con' : 'For your firm, I\'d start with'}
                </div>
                <h3>
                  {winner.topOferta.num} — <em>{winner.topOferta.title[lang]}</em>
                </h3>
                <p style={{ fontSize: 16 }}>{rationale(winner.topId)}</p>
                <div style={{ display: 'flex', gap: 24, alignItems: 'flex-end', flexWrap: 'wrap', marginTop: 8 }}>
                  <div>
                    <div className="dr-kicker" style={{ marginBottom: 6 }}>{lang === 'es' ? 'Duración' : 'Duration'}</div>
                    <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 20, color: 'var(--bone)' }}>
                      {winner.topOferta.duration[lang]}
                    </div>
                  </div>
                  <div>
                    <div className="dr-kicker" style={{ marginBottom: 6 }}>{lang === 'es' ? 'Precio (Latam)' : 'Price (Latam)'}</div>
                    <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 20, color: 'var(--ochre)' }}>
                      {winner.topOferta.price.latam}
                    </div>
                  </div>
                  <div>
                    <div className="dr-kicker" style={{ marginBottom: 6 }}>{lang === 'es' ? 'Precio (US)' : 'Price (US)'}</div>
                    <div style={{ fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 20, color: 'var(--ochre)' }}>
                      {winner.topOferta.price.us}
                    </div>
                  </div>
                </div>
                <div className="dr-actions">
                  <a href="#cta" className="btn btn-on-dark">{C.result[lang].cta} →</a>
                  <button onClick={reset}>{C.result[lang].reset}</button>
                </div>
              </div>

              {/* Mini breakdown */}
              <div style={{ marginTop: 32, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
                {OFERTAS.map(o => {
                  const v = winner.score[o.id] || 0;
                  const max = Math.max(...Object.values(winner.score), 1);
                  const pct = (v / max) * 100;
                  const isTop = o.id === winner.topId;
                  return (
                    <div key={o.id} style={{
                      padding: 16,
                      borderRadius: 8,
                      background: isTop ? 'var(--bone-2)' : 'transparent',
                      border: `1px solid ${isTop ? 'var(--border-strong)' : 'var(--border)'}`,
                    }}>
                      <div className="kicker" style={{ marginBottom: 8, color: isTop ? 'var(--accent)' : 'var(--fg-mute)' }}>
                        {o.num} · {o.title[lang]}
                      </div>
                      <div style={{ height: 4, background: 'var(--border)', borderRadius: 2, overflow: 'hidden' }}>
                        <div style={{
                          width: `${pct}%`, height: '100%',
                          background: isTop ? 'var(--accent)' : 'var(--stone)',
                          transition: 'width 600ms var(--ease-out)',
                        }} />
                      </div>
                    </div>
                  );
                })}
              </div>

              <p className="caption" style={{ marginTop: 20, color: 'var(--fg-mute)', textAlign: 'center' }}>
                {lang === 'es'
                  ? 'Esto es indicativo, no un contrato. Lo confirmamos en la primera conversación.'
                  : 'This is indicative, not a contract. We confirm it in the first conversation.'}
              </p>
            </div>
          )}
        </div>
      </div>

      <style>{`
        @media (max-width: 820px) {
          #diagnostico header { grid-template-columns: 1fr !important; gap: 24px !important; }
          .diag-result > div[style*="grid-template-columns: repeat(4"] { grid-template-columns: repeat(2, 1fr) !important; }
        }
      `}</style>
    </section>
  );
}

window.Diagnostico = Diagnostico;
