// Pantalla 8 — Resultado personalizado.
// Densidad de info + storytelling + screenshot-friendly. Reveal por bloques.

window.S8Result = function S8Result({ state, restart, openDashboard, openDemo }) {
  const niche = window.NICHOS.find(n => n.id === state.nicho) || window.NICHOS[0];
  const escala = window.ESCALAS.find(e => e.id === state.escala) || window.ESCALAS[1];
  const impacto = window.IMPACTOS.find(i => i.id === state.impacto) || window.IMPACTOS[0];
  const areasData = niche.areas || niche.dolores || [];
  const dolores = (state.dolores || [])
    .map(id => areasData.find(d => d.id === id))
    .filter(Boolean);
  const mainDolor = dolores[0] || areasData[0] || { titulo: 'proceso crítico', sub: '' };
  const temp = window.calcTemperatura(state.urgencia, state.presupuesto);

  // Coherent impact estimate based on declared inputs
  const est = window.estimarImpacto({ nicho: state.nicho, escala: state.escala, maduracion: state.maduracion, areas: state.dolores||[] });
  const madurezScore = est ? est.madurez : window.calcMadurez({ maduracion: state.maduracion, escala: state.escala, areas: state.dolores||[] });
  const madurezPct = Math.round((parseFloat(madurezScore) / 5) * 100);
  const horasMin = est ? est.horasMin : 0;
  const horasMax = est ? est.horasMax : 0;
  const copMin = est ? est.copMmMin : 0;
  const copMax = est ? est.copMmMax : 0;
  const personasAfectadas = est ? est.personasAfectadas : 0;
  const personasRango = est ? est.personasRango : null;

  // CTA copy by temperature
  const ctaPrimary = {
    caliente: { label: 'Agenda diagnóstico profundo (30 min)', icon: 'whatsapp' },
    tibio: { label: 'Hablar con un especialista en tu industria', icon: 'whatsapp' },
    frio: { label: 'Ver cómo funciona (demo de 2 min)', icon: 'eye' },
  }[temp];
  const ctaSecondary = {
    caliente: { label: 'Recibir propuesta por email' },
    tibio: { label: 'Enviarme este diagnóstico' },
    frio: { label: 'Enviarme el diagnóstico' },
  }[temp];

  // WhatsApp deep link with niche-specific prefilled message
  const wspMessage = encodeURIComponent(
    `Hola, soy ${state.nombre || ''} de ${state.empresa || ''}. Acabo de hacer el diagnóstico en AI First Business. Mi problema principal es "${mainDolor.titulo}". ¿Podemos hablar?`
  );
  const wspUrl = `https://wa.me/${window.WSP_NUMBER}?text=${wspMessage}`;

  const dolorIc = {
    trazabilidad: 'list', reportes: 'book', vencimientos: 'clock', auditoria: 'shield',
    quiebre: 'store', forecast: 'trend', devoluciones: 'arrowL', mostrador: 'users',
    rutas: 'truck', conciliacion: 'check', rastreo: 'eye', temperatura: 'fire',
    dispensacion: 'cross', his: 'chart', duplicadas: 'list', cierres: 'clock',
    postventa: 'users', garantias: 'shield', sanitario: 'shield', cotizaciones: 'dollar',
    manual: 'list', datos: 'chart', errores: 'shield',
    otro: 'sparkle',
  };

  return (
    <div style={{ height: '100%', display: 'flex', flexDirection: 'column', position: 'relative' }}>
      <window.PremiumBg accent={{ glow: 'var(--accent-glow)' }} />

      {/* Top bar */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: '60px 20px 12px', position: 'relative', zIndex: 2,
      }}>
        <window.Wordmark size={11} />
        <div style={{ display: 'flex', gap: 6 }}>
          <window.TempChip temp={temp} />
        </div>
      </div>

      <div style={{ flex: 1, overflowY: 'auto', position: 'relative', zIndex: 2 }}>
        <div style={{ padding: '8px 20px 24px', display: 'flex', flexDirection: 'column', gap: 14 }}>

          {/* BLOQUE A — Diagnóstico */}
          <window.Reveal delay={60}>
            <div style={{
              fontSize: 11, color: 'var(--accent-solid)', fontWeight: 600,
              letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8,
            }}>Diagnóstico personalizado</div>
            <h1 style={{
              fontSize: 24, fontWeight: 600, letterSpacing: '-0.02em', lineHeight: 1.2,
              margin: 0, color: window.THEME.text, textWrap: 'pretty',
            }}>
              {(state.nombre || '').split(' ')[0] || 'Hola'}, esto es lo que identificamos en <span style={{ color: 'var(--accent-solid)' }}>{state.empresa || 'tu empresa'}</span>
            </h1>
          </window.Reveal>

          {/* Dolor identificado */}
          <window.Reveal delay={140}>
            <div style={{
              padding: 18, borderRadius: 16,
              background: window.THEME.bgCard,
              border: `1px solid ${window.THEME.border}`,
              backdropFilter: 'blur(12px)',
            }}>
              <div style={{ display: 'flex', gap: 12, alignItems: 'flex-start' }}>
                <div style={{
                  width: 40, height: 40, borderRadius: 10, flexShrink: 0,
                  background: 'var(--accent-soft)', color: 'var(--accent-solid)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <window.Icon name={dolorIc[mainDolor.id] || 'sparkle'} size={20} strokeWidth={1.8} />
                </div>
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontSize: 16, fontWeight: 600, color: window.THEME.text, lineHeight: 1.25 }}>
                    {mainDolor.id === 'otro' && state.dolorOtro ? state.dolorOtro : mainDolor.titulo}
                  </div>
                  <div style={{ fontSize: 13, color: window.THEME.textMuted, marginTop: 6, lineHeight: 1.45 }}>
                    {mainDolor.sub}. En operaciones {labelEscala(state.escala)} este dolor multiplica costo de coordinación y se traduce en horas que tu equipo no recupera.
                  </div>
                </div>
              </div>

              {/* Impact estimate — methodology grounded in declared inputs */}
              <div style={{
                marginTop: 14, padding: 14, borderRadius: 12,
                background: 'rgba(20,22,30,0.04)', border: `1px solid ${window.THEME.border}`,
              }}>
                <div style={{ fontSize: 10, color: window.THEME.textDim, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8 }}>
                  Estimación · basada en tus respuestas
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                  <div>
                    <div style={{ fontSize: 22, fontWeight: 600, color: window.THEME.text, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>
                      <window.Counter value={horasMin} />–<window.Counter value={horasMax} />
                    </div>
                    <div style={{ fontSize: 10.5, color: window.THEME.textMuted, marginTop: 4 }}>horas/semana del equipo</div>
                  </div>
                  <div>
                    <div style={{ fontSize: 22, fontWeight: 600, color: window.THEME.text, lineHeight: 1, fontVariantNumeric: 'tabular-nums' }}>
                      $<window.Counter value={copMin} />–<window.Counter value={copMax} />M
                    </div>
                    <div style={{ fontSize: 10.5, color: window.THEME.textMuted, marginTop: 4 }}>COP/mes en costo oculto</div>
                  </div>
                </div>
                {personasAfectadas > 0 && (
                  <div style={{ fontSize: 10.5, color: window.THEME.textDim, marginTop: 10, lineHeight: 1.5 }}>
                    ≈ {personasAfectadas} personas afectadas en una operación de {personasRango.min}–{personasRango.max}, a {est.horasPorPersona.min}–{est.horasPorPersona.max} h/persona/semana. Rango orientativo, validable en sesión.
                  </div>
                )}

                {/* Medidor de madurez operativa */}
                <div style={{ marginTop: 14, paddingTop: 14, borderTop: `1px solid ${window.THEME.border}` }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                    <div style={{ fontSize: 10, color: window.THEME.textDim, fontWeight: 600, letterSpacing: '0.08em', textTransform: 'uppercase' }}>
                      Madurez operativa digital
                    </div>
                    <div style={{ fontSize: 18, fontWeight: 700, color: 'var(--accent-solid)' }}>
                      {madurezScore}<span style={{ fontSize: 12, fontWeight: 400, color: window.THEME.textMuted }}>/5</span>
                    </div>
                  </div>
                  <div style={{ height: 6, borderRadius: 99, background: 'rgba(20,22,30,0.08)', overflow: 'hidden' }}>
                    <div style={{
                      height: '100%', borderRadius: 99,
                      width: `${madurezPct}%`,
                      background: `linear-gradient(90deg, var(--accent-solid), #8b5cf6)`,
                      transition: 'width 1s ease',
                    }} />
                  </div>
                  <div style={{ fontSize: 10.5, color: window.THEME.textDim, marginTop: 6, lineHeight: 1.4 }}>
                    {parseFloat(madurezScore) < 2 ? 'Operación con alto potencial de automatización — base sólida para transformar rápido.' :
                     parseFloat(madurezScore) < 3 ? 'Tienes herramientas básicas. La brecha hacia la automatización inteligente es alcanzable en semanas.' :
                     parseFloat(madurezScore) < 4 ? 'Buena base tecnológica. La oportunidad está en conectar los puntos y eliminar el trabajo manual que persiste.' :
                     'Operación avanzada. La oportunidad está en inteligencia predictiva y automatización de decisiones.'}
                  </div>
                </div>
              </div>
            </div>
          </window.Reveal>

          {/* BLOQUE B — Solución */}
          <window.Reveal delay={220}>
            <div style={{
              padding: 18, borderRadius: 16,
              background: 'linear-gradient(180deg, var(--accent-soft) 0%, transparent 90%)',
              border: '1px solid var(--accent-soft)',
            }}>
              <div style={{
                fontSize: 11, color: 'var(--accent-solid)', fontWeight: 600,
                letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 8,
                display: 'flex', alignItems: 'center', gap: 6,
              }}>
                <window.Icon name="sparkle" size={12} strokeWidth={2} />
                Existe una solución específica para esto
              </div>
              <div style={{ fontSize: 17, fontWeight: 600, color: window.THEME.text, lineHeight: 1.25 }}>
                {niche.solucion ? niche.solucion.titulo : "Solución personalizada para tu operación"}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 14 }}>
                {(niche.solucion ? niche.solucion.bullets : ["Automatización de procesos operativos críticos", "Visibilidad en tiempo real para tomar mejores decisiones", "Herramientas específicas para cada actor de tu operación"]).map((b, i) => (
                  <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                    <div style={{
                      width: 18, height: 18, borderRadius: 99, flexShrink: 0, marginTop: 1,
                      background: 'var(--accent-solid)', display: 'flex', alignItems: 'center', justifyContent: 'center',
                      color: '#fff',
                    }}>
                      <window.Icon name="check" size={11} strokeWidth={3.5} />
                    </div>
                    <div style={{ fontSize: 13, color: window.THEME.text, lineHeight: 1.45 }}>{b}</div>
                  </div>
                ))}
              </div>
              <div style={{ display: 'flex', gap: 6, marginTop: 14, flexWrap: 'wrap' }}>
                <window.Chip tone="ok"><window.Icon name="check" size={11} strokeWidth={3} />Implementable en Colombia</window.Chip>
                <window.Chip tone="ok"><window.Icon name="check" size={11} strokeWidth={3} />Sin reemplazar tu ERP</window.Chip>
              </div>
            </div>
          </window.Reveal>

          {/* BLOQUE C — Pilares de valor (sin casos placeholders) */}
          <window.Reveal delay={300}>
            <div>
              <div style={{
                fontSize: 11, color: window.THEME.textMuted, fontWeight: 600,
                letterSpacing: '0.08em', textTransform: 'uppercase', marginBottom: 10,
              }}>
                Lo que cambia en tu operación
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
                {[
                  { icon: 'trend', label: 'Vender más', sub: 'sin contratar más' },
                  { icon: 'clock', label: 'Optimizar tiempos', sub: 'horas que vuelven al equipo' },
                  { icon: 'list', label: 'Orden y control', sub: 'todo en un solo lugar' },
                  { icon: 'sparkle', label: 'Decisiones inteligentes', sub: 'con datos en tiempo real' },
                ].map((p, i) => (
                  <div key={i} style={{
                    padding: 12, borderRadius: 12,
                    background: window.THEME.bgCard,
                    border: `1px solid ${window.THEME.border}`,
                  }}>
                    <div style={{ color: 'var(--accent-solid)', marginBottom: 8 }}>
                      <window.Icon name={p.icon} size={16} strokeWidth={1.8} />
                    </div>
                    <div style={{ fontSize: 12.5, fontWeight: 600, color: window.THEME.text, lineHeight: 1.25 }}>{p.label}</div>
                    <div style={{ fontSize: 11, color: window.THEME.textMuted, marginTop: 3, lineHeight: 1.35 }}>{p.sub}</div>
                  </div>
                ))}
              </div>
            </div>
          </window.Reveal>

          {/* BLOQUE E — Urgencia real (solo caliente) */}
          {state.urgencia === 'activa' && (
            <window.Reveal delay={360}>
              <div style={{
                padding: 14, borderRadius: 12,
                background: 'rgba(239,68,68,0.08)',
                border: '1px solid rgba(239,68,68,0.25)',
                display: 'flex', gap: 12, alignItems: 'flex-start',
              }}>
                <div style={{ color: '#FCA5A5', flexShrink: 0, marginTop: 2 }}>
                  <window.Icon name="fire" size={18} strokeWidth={1.8} />
                </div>
                <div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: '#FCA5A5', lineHeight: 1.3 }}>
                    Agenda esta semana
                  </div>
                  <div style={{ fontSize: 12, color: window.THEME.textMuted, marginTop: 4, lineHeight: 1.45 }}>
                    Tenemos cupos limitados de diagnóstico profundo. Si quieres uno esta semana, escríbenos ahora.
                  </div>
                </div>
              </div>
            </window.Reveal>
          )}

          {/* BLOQUE D — CTA */}
          <window.Reveal delay={420}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 4 }}>
              {/* CTA primario — WhatsApp para caliente/tibio, demo para frío */}
              <a href={wspUrl} target="_blank" rel="noopener noreferrer" className="cu-btn-primary" style={{
                width: '100%', padding: '16px 18px', borderRadius: 14, boxSizing: 'border-box',
                background: 'var(--accent-solid)', color: '#fff', textDecoration: 'none',
                fontSize: 15, fontWeight: 600, letterSpacing: '-0.005em',
                display: temp === 'frio' ? 'none' : 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                boxShadow: '0 8px 24px var(--accent-glow), 0 0 0 1px rgba(255,255,255,0.2) inset',
                textWrap: 'pretty', textAlign: 'center',
              }}>
                <window.Icon name={ctaPrimary.icon} size={18} strokeWidth={2} />
                {ctaPrimary.label}
              </a>

              {/* Demo — disponible para TODOS los leads */}
              <button onClick={openDemo} style={{
                width: '100%', padding: temp === 'frio' ? '16px 18px' : '13px 18px',
                borderRadius: 14, border: temp === 'frio' ? 'none' : `1px solid var(--accent-solid)`,
                background: temp === 'frio' ? 'var(--accent-solid)' : 'transparent',
                color: temp === 'frio' ? '#fff' : 'var(--accent-solid)',
                fontSize: temp === 'frio' ? 15 : 14, fontWeight: 600,
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                boxShadow: temp === 'frio' ? '0 8px 24px var(--accent-glow)' : 'none',
                cursor: 'pointer', fontFamily: 'inherit',
              }}>
                <window.Icon name="sparkle" size={temp === 'frio' ? 18 : 16} strokeWidth={2} />
                {temp === 'frio' ? 'Ver cómo quedaría tu operación' : 'Ver demo de tu operación con IA'}
              </button>
              <button style={{
                width: '100%', padding: '14px 18px', borderRadius: 14,
                background: 'rgba(20,22,30,0.04)',
                border: `1px solid ${window.THEME.border}`,
                color: window.THEME.text, fontSize: 14, fontWeight: 500,
                cursor: 'pointer', fontFamily: 'inherit',
              }}>{ctaSecondary.label}</button>
              {temp === 'frio' && (
                <div style={{ textAlign: 'center', fontSize: 11, color: window.THEME.textDim, marginTop: 4 }}>
                  Sin compromiso. Solo para que veas si aplica a tu caso.
                </div>
              )}
            </div>
          </window.Reveal>

          <window.Reveal delay={500}>
            <div style={{
              marginTop: 20, paddingTop: 18, borderTop: `1px solid ${window.THEME.border}`,
              display: 'flex', alignItems: 'center', justifyContent: 'space-between',
              fontSize: 11, color: window.THEME.textDim,
            }}>
              <button onClick={restart} style={{
                background: 'transparent', border: 0, color: window.THEME.textMuted,
                fontSize: 11, fontFamily: 'inherit', cursor: 'pointer', padding: 0,
              }}>← Empezar de nuevo</button>
              <button onClick={openDashboard} style={{
                background: 'transparent', border: 0, color: window.THEME.textDim,
                fontSize: 11, fontFamily: 'inherit', cursor: 'pointer', padding: 0,
              }}>Stand</button>
            </div>
            <div style={{ fontSize: 10, color: window.THEME.textDim, marginTop: 16, textAlign: 'center', lineHeight: 1.5 }}>
              {window.AGENCY_TAGLINE}
            </div>
          </window.Reveal>
        </div>
      </div>
    </div>
  );
};

function labelEscala(id) {
  const map = { xs: 'pequeñas', s: 'medianas', m: 'grandes', l: 'a escala empresarial' };
  return map[id] || 'medianas';
}
