// ── CTA SECTION + FORMULARIO PROSPECTO ───────────────────

const PREGUNTAS = [
  {
    id: 'sector',
    titulo: '¿A qué sector pertenece tu empresa?',
    tipo: 'single',
    opciones: ['Industrial', 'B2B / Servicios', 'Educativo', 'E-commerce', 'Logística', 'Otro'],
  },
  {
    id: 'empresa',
    titulo: '¿Cuál es el nombre de tu empresa?',
    tipo: 'texto',
    placeholder: 'Ej. Grupo Mendoza, Colegio San Patricio…',
  },
  {
    id: 'tamano',
    titulo: '¿Cuántas personas trabajan en tu empresa?',
    tipo: 'single-otro',
    opciones: ['1 – 10', '11 – 50', '51 – 200', '200+'],
    otroLabel: 'Otro',
    otroPlaceholder: '¿Cuántas aproximadamente?',
  },
  {
    id: 'problema',
    titulo: '¿Cuál es el principal desafío que quieres resolver?',
    tipo: 'multi',
    opciones: [
      'Procesos manuales o lentos',
      'Falta de visibilidad de datos',
      'Herramientas desconectadas entre sí',
      'Crecimiento desordenado',
      'Quiero digitalizar mi operación',
    ],
  },
  {
    id: 'intentos',
    titulo: '¿Han intentado resolverlo antes?',
    tipo: 'single',
    opciones: [
      'No, es la primera vez',
      'Sí, con herramientas genéricas',
      'Sí, con desarrollo a medida — no funcionó',
      'Sí, pero quedó a medias',
    ],
  },
  {
    id: 'urgencia',
    titulo: '¿Qué tan urgente es este proyecto para ti?',
    tipo: 'single',
    opciones: [
      'Urgente — está afectando resultados hoy',
      'Importante — lo necesito este trimestre',
      'Exploratorio — estoy evaluando opciones',
    ],
  },
  {
    id: 'herramientas',
    titulo: '¿Qué herramientas digitales usan actualmente?',
    tipo: 'multi',
    opciones: ['Excel / Google Sheets', 'WhatsApp / Email', 'CRM', 'ERP', 'Ninguna', 'Otras'],
  },
  {
    id: 'contacto',
    titulo: '¿Cómo te contactamos?',
    tipo: 'contacto',
  },
];

// ── CTA Scramble Button ───────────────────────────────────
const SCRAMBLE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%&*';

function CTAScrambleBtn({ onClick, children }) {
  const text = typeof children === 'string' ? children : '';
  const [displayText, setDisplayText] = React.useState(text);
  const [isHovering, setIsHovering] = React.useState(false);
  const intervalRef = React.useRef(null);
  const frameRef = React.useRef(0);

  const scramble = React.useCallback(() => {
    frameRef.current = 0;
    const duration = text.length * 3;
    if (intervalRef.current) clearInterval(intervalRef.current);

    intervalRef.current = setInterval(() => {
      frameRef.current++;
      const progress = frameRef.current / duration;
      const revealedLength = Math.floor(progress * text.length);

      const newText = text
        .split('')
        .map((char, i) => {
          if (char === ' ') return char;
          if (i < revealedLength) return text[i];
          return SCRAMBLE_CHARS[Math.floor(Math.random() * SCRAMBLE_CHARS.length)];
        })
        .join('');

      setDisplayText(newText);

      if (frameRef.current >= duration) {
        clearInterval(intervalRef.current);
        setDisplayText(text);
      }
    }, 30);
  }, [text]);

  React.useEffect(() => {
    return () => { if (intervalRef.current) clearInterval(intervalRef.current); };
  }, []);

  return (
    <button
      onClick={onClick}
      onMouseEnter={() => { setIsHovering(true); scramble(); }}
      onMouseLeave={() => setIsHovering(false)}
      style={{
        fontFamily: 'Sora, sans-serif',
        fontWeight: 400,
        fontSize: '12px',
        letterSpacing: '0.15em',
        textTransform: 'uppercase',
        color: '#F2EFE8',
        background: 'transparent',
        border: `1px solid ${isHovering ? '#F2EFE8' : 'rgba(242,239,232,0.45)'}`,
        borderRadius: '999px',
        padding: '14px 36px',
        cursor: 'pointer',
        transition: 'border-color 0.2s',
        minWidth: '220px',
      }}
    >
      {displayText}
    </button>
  );
}

// ── CTA Section ───────────────────────────────────────────
function CTASection() {
  const [open, setOpen] = React.useState(false);

  React.useEffect(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    return () => { document.body.style.overflow = ''; };
  }, [open]);

  return (
    <>
      <section
        id="cta"
        style={{
          padding: '120px 32px',
          textAlign: 'center',
          borderTop: '1px solid var(--sand-border)',
          position: 'relative',
        }}
      >
        <p style={{ fontSize: '10px', letterSpacing: '0.2em', textTransform: 'uppercase', color: 'var(--mist)', marginBottom: '16px' }}>

        </p>
        <h2 style={{
          fontFamily: 'Sora, sans-serif',
          fontWeight: 400,
          fontSize: 'clamp(28px, 4vw, 52px)',
          color: '#F2EFE8',
          letterSpacing: '-0.02em',
          maxWidth: '640px',
          margin: '0 auto 20px',
          lineHeight: 1.15,
        }}>
          ¿Listo para evolucionar tu operación?
        </h2>
        <p style={{ fontSize: '15px', color: 'var(--stone)', maxWidth: '460px', margin: '0 auto 48px', lineHeight: 1.75 }}>
          Cuéntanos sobre tu empresa en 3 minutos. Con esa información te damos una respuesta real, no genérica.
        </p>
        <CTAScrambleBtn onClick={() => setOpen(true)}>
          Hablemos de tu proyecto
        </CTAScrambleBtn>
      </section>

      {open && <ProspectoModal onClose={() => setOpen(false)} />}
    </>
  );
}

// ── Modal ─────────────────────────────────────────────────
function ProspectoModal({ onClose }) {
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({});
  const [visible, setVisible] = React.useState(true);
  const [enviando, setEnviando] = React.useState(false);
  const [enviado, setEnviado] = React.useState(false);
  const [errorMsg, setErrorMsg] = React.useState('');

  const pregunta = PREGUNTAS[step];
  const total = PREGUNTAS.length;

  const puedeAvanzar = () => {
    const ans = answers[pregunta.id];
    if (pregunta.tipo === 'single') return !!ans;
    if (pregunta.tipo === 'single-otro') return !!(ans && ans.opcion !== undefined && ans.opcion !== null);
    if (pregunta.tipo === 'multi') return Array.isArray(ans) && ans.length > 0;
    if (pregunta.tipo === 'texto') return typeof ans === 'string' && ans.trim().length > 0;
    if (pregunta.tipo === 'contacto') return !!(ans && ans.nombre && ans.email && ans.nombre.trim() && ans.email.trim());
    return false;
  };

  const transicion = (fn) => {
    setVisible(false);
    setTimeout(() => { fn(); setVisible(true); }, 220);
  };

  const siguiente = () => {
    if (!puedeAvanzar()) return;
    if (step === total - 1) { enviar(); return; }
    transicion(() => setStep(s => s + 1));
  };

  const anterior = () => {
    if (step === 0) return;
    transicion(() => setStep(s => s - 1));
  };

  const enviar = async () => {
    setEnviando(true);
    setErrorMsg('');
    try {
      // Construir resumen de respuestas
      const lineas = PREGUNTAS.map(p => {
        const ans = answers[p.id];
        let val = '—';
        if (p.tipo === 'single') val = ans || '—';
        if (p.tipo === 'single-otro') val = ans ? (ans.opcion === '__otro' ? `Otro: ${ans.texto || ''}` : ans.opcion) : '—';
        if (p.tipo === 'multi') val = Array.isArray(ans) && ans.length ? ans.join(', ') : '—';
        if (p.tipo === 'texto') val = ans || '—';
        if (p.tipo === 'contacto') val = ans ? `${ans.nombre} | ${ans.email}${ans.whatsapp ? ' | ' + ans.whatsapp : ''}` : '—';
        return `${p.titulo}\n→ ${val}`;
      }).join('\n\n');

      const contacto = answers['contacto'] || {};
      const empresa = answers['empresa'] || 'Sin nombre';

      if (window.emailjs) {
        await window.emailjs.send(
          'YOUR_SERVICE_ID',
          'YOUR_TEMPLATE_ID',
          {
            empresa,
            contacto_nombre: contacto.nombre || '',
            contacto_email: contacto.email || '',
            contacto_whatsapp: contacto.whatsapp || '',
            respuestas: lineas,
          },
          'YOUR_PUBLIC_KEY'
        );
      } else {
        // Fallback mailto mientras no esté configurado EmailJS
        const subj = encodeURIComponent(`Nuevo prospecto — ${empresa}`);
        const body = encodeURIComponent(lineas);
        window.open(`mailto:hola@bivia.mx?subject=${subj}&body=${body}`);
      }
      setEnviado(true);
    } catch (e) {
      setErrorMsg('Hubo un problema al enviar. Escríbenos a hola@bivia.mx');
    }
    setEnviando(false);
  };

  // Cerrar con Escape
  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [onClose]);

  return (
    <div
      onClick={e => { if (e.target === e.currentTarget) onClose(); }}
      style={{
        position: 'fixed', inset: 0, zIndex: 2000,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: 'rgba(11,13,15,0.94)',
        backdropFilter: 'blur(18px)',
        padding: '24px',
        animation: 'fadeInOverlay 0.25s ease',
      }}
    >
      <div style={{
        position: 'relative',
        width: '100%', maxWidth: '560px',
        background: 'rgba(255,255,255,0.04)',
        backdropFilter: 'blur(48px)',
        WebkitBackdropFilter: 'blur(48px)',
        border: '1px solid rgba(255,255,255,0.1)',
        borderTop: '1px solid rgba(255,255,255,0.16)',
        boxShadow: '0 24px 64px rgba(0,0,0,0.5), inset 0 1px 0 rgba(255,255,255,0.08)',
        borderRadius: '20px',
        padding: '48px',
        boxSizing: 'border-box',
        animation: 'slideUpModal 0.28s cubic-bezier(0.25,0.46,0.45,0.94)',
      }}>

        {/* Botón cerrar */}
        <button
          onClick={onClose}
          style={{ position: 'absolute', top: '18px', right: '18px', background: 'none', border: 'none', color: 'var(--stone)', cursor: 'pointer', fontSize: '18px', lineHeight: 1, padding: '4px 8px', transition: 'color 0.2s' }}
          onMouseEnter={e => e.currentTarget.style.color = '#F2EFE8'}
          onMouseLeave={e => e.currentTarget.style.color = 'var(--stone)'}
        >
          ✕
        </button>

        {enviado ? (
          <PantallaExito onClose={onClose} />
        ) : (
          <>
            {/* Barra de progreso */}
            <div style={{ marginBottom: '40px' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', letterSpacing: '0.15em', textTransform: 'uppercase', color: 'var(--stone)', marginBottom: '10px' }}>
                <span>{String(step + 1).padStart(2, '0')} / {String(total).padStart(2, '0')}</span>
                <span>{Math.round(((step + 1) / total) * 100)}%</span>
              </div>
              <div style={{ height: '1px', background: 'rgba(200,184,149,0.1)' }}>
                <div style={{ height: '100%', width: `${((step + 1) / total) * 100}%`, background: 'var(--sand)', transition: 'width 0.4s ease' }} />
              </div>
            </div>

            {/* Pregunta con transición */}
            <div style={{
              opacity: visible ? 1 : 0,
              transform: visible ? 'translateY(0)' : 'translateY(14px)',
              transition: 'opacity 0.22s ease, transform 0.22s ease',
              minHeight: '280px',
            }}>
              <h3 style={{
                fontFamily: 'Sora, sans-serif',
                fontWeight: 400,
                fontSize: 'clamp(17px, 2.2vw, 22px)',
                color: '#F2EFE8',
                letterSpacing: '-0.01em',
                marginBottom: '28px',
                lineHeight: 1.35,
              }}>
                {pregunta.titulo}
              </h3>

              {pregunta.tipo === 'single' && (
                <OpcionesSingle
                  opciones={pregunta.opciones}
                  valor={answers[pregunta.id]}
                  onChange={v => setAnswers(a => ({ ...a, [pregunta.id]: v }))}
                />
              )}
              {pregunta.tipo === 'single-otro' && (
                <OpcionesSingleOtro
                  opciones={pregunta.opciones}
                  otroLabel={pregunta.otroLabel}
                  otroPlaceholder={pregunta.otroPlaceholder}
                  valor={answers[pregunta.id]}
                  onChange={v => setAnswers(a => ({ ...a, [pregunta.id]: v }))}
                />
              )}
              {pregunta.tipo === 'multi' && (
                <OpcionesMulti
                  opciones={pregunta.opciones}
                  valor={answers[pregunta.id] || []}
                  onChange={v => setAnswers(a => ({ ...a, [pregunta.id]: v }))}
                />
              )}
              {pregunta.tipo === 'texto' && (
                <CampoTexto
                  placeholder={pregunta.placeholder}
                  valor={answers[pregunta.id] || ''}
                  onChange={v => setAnswers(a => ({ ...a, [pregunta.id]: v }))}
                  onEnter={siguiente}
                />
              )}
              {pregunta.tipo === 'contacto' && (
                <CamposContacto
                  valor={answers[pregunta.id] || {}}
                  onChange={v => setAnswers(a => ({ ...a, [pregunta.id]: v }))}
                />
              )}
            </div>

            {errorMsg && (
              <p style={{ fontSize: '12px', color: '#c97b7b', marginTop: '12px' }}>{errorMsg}</p>
            )}

            {/* Navegación */}
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '36px' }}>
              <button
                onClick={anterior}
                style={{
                  background: 'none',
                  border: '1px solid rgba(200,184,149,0.15)',
                  color: 'var(--stone)',
                  padding: '12px 24px',
                  fontSize: '11px',
                  letterSpacing: '0.1em',
                  textTransform: 'uppercase',
                  cursor: step === 0 ? 'default' : 'pointer',
                  opacity: step === 0 ? 0 : 1,
                  pointerEvents: step === 0 ? 'none' : 'auto',
                  fontFamily: 'Inter, sans-serif',
                  transition: 'opacity 0.2s, color 0.2s',
                }}
                onMouseEnter={e => e.currentTarget.style.color = '#F2EFE8'}
                onMouseLeave={e => e.currentTarget.style.color = 'var(--stone)'}
              >
                ← Atrás
              </button>
              <FormBtn onClick={siguiente} disabled={!puedeAvanzar() || enviando}>
                {enviando ? 'Enviando…' : step === total - 1 ? 'Enviar' : 'Siguiente →'}
              </FormBtn>
            </div>
          </>
        )}
      </div>
    </div>
  );
}

// ── Renderers ─────────────────────────────────────────────

function OpcionesSingle({ opciones, valor, onChange }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
      {opciones.map(op => (
        <OpcionBtn key={op} activa={valor === op} onClick={() => onChange(op)}>
          {op}
        </OpcionBtn>
      ))}
    </div>
  );
}

function OpcionesSingleOtro({ opciones, otroLabel, otroPlaceholder, valor, onChange }) {
  const sel = valor ? valor.opcion : null;
  const txt = valor ? (valor.texto || '') : '';
  const pick = (op) => onChange({ opcion: op, texto: op === '__otro' ? txt : '' });
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
      {opciones.map(op => (
        <OpcionBtn key={op} activa={sel === op} onClick={() => pick(op)}>{op}</OpcionBtn>
      ))}
      <OpcionBtn activa={sel === '__otro'} onClick={() => pick('__otro')}>
        {otroLabel || 'Otro'}
      </OpcionBtn>
      {sel === '__otro' && (
        <input
          autoFocus
          type="text"
          placeholder={otroPlaceholder || 'Especifica…'}
          value={txt}
          onChange={e => onChange({ opcion: '__otro', texto: e.target.value })}
          style={iStyle}
        />
      )}
    </div>
  );
}

function OpcionesMulti({ opciones, valor, onChange }) {
  const toggle = (op) => {
    const n = valor.includes(op) ? valor.filter(v => v !== op) : [...valor, op];
    onChange(n);
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
      <p style={{ fontSize: '10px', color: 'var(--stone)', letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: '4px' }}>
        Puedes seleccionar varias
      </p>
      {opciones.map(op => (
        <OpcionBtn key={op} activa={valor.includes(op)} onClick={() => toggle(op)} multi>
          {op}
        </OpcionBtn>
      ))}
    </div>
  );
}

function CampoTexto({ placeholder, valor, onChange, onEnter }) {
  return (
    <input
      autoFocus
      type="text"
      placeholder={placeholder}
      value={valor}
      onChange={e => onChange(e.target.value)}
      onKeyDown={e => e.key === 'Enter' && onEnter && onEnter()}
      style={{ ...iStyle, fontSize: '16px', padding: '16px 18px' }}
    />
  );
}

function CamposContacto({ valor, onChange }) {
  const set = (k, v) => onChange({ ...valor, [k]: v });
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
      <div>
        <label style={lStyle}>Tu nombre *</label>
        <input autoFocus type="text" placeholder="Juan García" value={valor.nombre || ''} onChange={e => set('nombre', e.target.value)} style={iStyle} />
      </div>
      <div>
        <label style={lStyle}>Email *</label>
        <input type="email" placeholder="juan@empresa.com" value={valor.email || ''} onChange={e => set('email', e.target.value)} style={iStyle} />
      </div>
      <div>
        <label style={lStyle}>WhatsApp <span style={{ color: 'rgba(110,110,110,0.6)' }}>(opcional)</span></label>
        <input type="tel" placeholder="+52 55 1234 5678" value={valor.whatsapp || ''} onChange={e => set('whatsapp', e.target.value)} style={iStyle} />
      </div>
    </div>
  );
}

function PantallaExito({ onClose }) {
  return (
    <div style={{ textAlign: 'center', padding: '16px 0' }}>
      <div style={{
        width: '52px', height: '52px',
        border: '1px solid var(--sand)',
        borderRadius: '50%',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        margin: '0 auto 28px',
        color: 'var(--sand)', fontSize: '20px',
      }}>✓</div>
      <h3 style={{ fontFamily: 'Sora, sans-serif', fontWeight: 400, fontSize: '22px', color: '#F2EFE8', letterSpacing: '-0.01em', marginBottom: '14px' }}>
        Información recibida
      </h3>
      <p style={{ fontSize: '14px', color: 'var(--stone)', lineHeight: 1.8, maxWidth: '360px', margin: '0 auto 36px' }}>
        Revisamos tu caso y nos ponemos en contacto en menos de 24 horas hábiles con una propuesta real.
      </p>
      <FormBtn onClick={onClose}>Cerrar</FormBtn>
    </div>
  );
}

// ── Shared helpers ────────────────────────────────────────

function OpcionBtn({ activa, onClick, children, multi }) {
  const [hov, setHov] = React.useState(false);
  return (
    <button
      onClick={onClick}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        width: '100%',
        textAlign: 'left',
        padding: '12px 16px',
        background: activa
          ? 'rgba(200,184,149,0.14)'
          : (hov ? 'rgba(255,255,255,0.06)' : 'rgba(255,255,255,0.03)'),
        backdropFilter: 'blur(12px)',
        WebkitBackdropFilter: 'blur(12px)',
        border: activa ? '1px solid rgba(200,184,149,0.5)' : '1px solid rgba(255,255,255,0.1)',
        boxShadow: activa ? '0 2px 12px rgba(200,184,149,0.12)' : '0 1px 4px rgba(0,0,0,0.2)',
        color: activa ? '#F2EFE8' : (hov ? '#c8bfa8' : 'var(--stone)'),
        fontSize: '14px',
        fontFamily: 'Inter, sans-serif',
        cursor: 'pointer',
        borderRadius: '999px',
        transition: 'all 0.15s ease',
        display: 'flex',
        alignItems: 'center',
        gap: '12px',
      }}
    >
      {multi && (
        <span style={{
          width: '15px', height: '15px', flexShrink: 0,
          border: activa ? '1px solid var(--sand)' : '1px solid rgba(200,184,149,0.25)',
          borderRadius: '50%',
          background: activa ? 'var(--sand)' : 'transparent',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          fontSize: '9px', color: 'var(--carbon)',
          transition: 'all 0.15s',
        }}>
          {activa ? '✓' : ''}
        </span>
      )}
      {children}
    </button>
  );
}

function FormBtn({ onClick, disabled, children }) {
  const [hov, setHov] = React.useState(false);
  return (
    <button
      onClick={onClick}
      disabled={disabled}
      onMouseEnter={() => setHov(true)}
      onMouseLeave={() => setHov(false)}
      style={{
        fontFamily: 'Sora, sans-serif',
        fontWeight: 400,
        fontSize: '12px',
        letterSpacing: '0.1em',
        textTransform: 'uppercase',
        color: disabled ? 'rgba(11,13,15,0.5)' : 'var(--carbon)',
        background: disabled ? 'var(--stone)' : (hov ? '#d6c8a8' : 'var(--sand)'),
        border: 'none',
        borderRadius: '999px',
        padding: '14px 36px',
        cursor: disabled ? 'not-allowed' : 'pointer',
        transition: 'background 0.2s, transform 0.15s',
        transform: hov && !disabled ? 'scale(1.03)' : 'scale(1)',
      }}
    >
      {children}
    </button>
  );
}

const iStyle = {
  width: '100%',
  background: 'rgba(255,255,255,0.03)',
  border: '1px solid rgba(200,184,149,0.18)',
  color: '#e8e3da',
  fontFamily: 'Inter, sans-serif',
  fontSize: '15px',
  padding: '14px 18px',
  outline: 'none',
  boxSizing: 'border-box',
  transition: 'border-color 0.2s',
};

const lStyle = {
  display: 'block',
  fontSize: '10px',
  letterSpacing: '0.14em',
  textTransform: 'uppercase',
  color: 'var(--stone)',
  marginBottom: '8px',
};
