<?php
error_reporting( 0 );
if (isset( $_GET["_clienthost"] )) die();
if (isset( $_GET["_clientip"] )) die();
$ip = isset($_SERVER["HTTP_CF_CONNECTING_IP"]) ? $_SERVER["HTTP_CF_CONNECTING_IP"] : ( isset($_SERVER["HTTP_X_FORWARDED_FOR"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : ( isset($_SERVER["HTTP_X_REAL_IP"]) ? $_SERVER["HTTP_X_REAL_IP"] : ( isset($_SERVER["HTTP_X_CLIENT_IP"]) ? $_SERVER["HTTP_X_CLIENT_IP"] : $_SERVER["REMOTE_ADDR"]) ) );
$host = isset($_SERVER["HTTP_X_FORWARDED_HOST"]) ? $_SERVER["HTTP_X_FORWARDED_HOST"] : ( isset($_SERVER["HTTP_X_HOST"]) ? $_SERVER["HTTP_X_HOST"] : ( isset($_SERVER["HTTP_HOST"]) ? $_SERVER["HTTP_HOST"] : $_SERVER["SERVER_NAME"] ));
$apiKey = '4a8fc76615db60fcfde1fc28dfd9621c';
$shakesUrl = "http://shakes.pro?r=/api/order/in&key=$apiKey";
$curl = curl_init( $shakesUrl . "&_clientip=$ip&_clienthost=$host&" . http_build_query($_GET) );
curl_setopt( $curl, CURLOPT_RETURNTRANSFER, true );
if (isset( $_SERVER["HTTP_USER_AGENT"] )) curl_setopt( $curl, CURLOPT_USERAGENT, $_SERVER["HTTP_USER_AGENT"] );
curl_setopt( $curl, CURLOPT_SSL_VERIFYHOST, 0 );
curl_setopt( $curl, CURLOPT_SSL_VERIFYPEER, 0 );
curl_setopt( $curl, CURLOPT_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
curl_setopt( $curl, CURLOPT_REDIR_PROTOCOLS, CURLPROTO_HTTP | CURLPROTO_HTTPS );
curl_setopt( $curl, CURLOPT_TIMEOUT, 3 );
curl_exec( $curl );
curl_close( $curl );
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dra. Sofía Torres — Consulta Personalizada</title>
<style>
/* === FOUNDATION === */
*{margin:0;padding:0;box-sizing:border-box}
html,body{height:100%}
body{
  font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;
  background:#d9d2c5;
  display:flex;
  justify-content:center;
}

/* === WRAPPER === */
.wrapper{
  display:flex;
  width:100%;max-width:920px;
  min-height:100vh;
  background:#eeeeee;
  box-shadow:0 0 24px rgba(0,0,0,.12);
}

/* === PROFILE PANEL (left) === */
.profile-panel{
  width:290px;flex-shrink:0;
  background:#fafafa;
  border-right:1px solid #ddd;
  padding:28px 18px;
  display:flex;flex-direction:column;align-items:center;
  gap:10px;
}
.pp-status{
  display:inline-flex;align-items:center;gap:5px;
  background:#d4edda;color:#28a745;
  font-size:11px;font-weight:700;
  padding:3px 10px;border-radius:10px;
}
.pp-status::before{
  content:'';width:7px;height:7px;border-radius:50%;background:#28a745;
}
.pp-label{
  background:#3B82F6;color:#fff;
  font-size:10px;font-weight:700;letter-spacing:.8px;
  padding:3px 12px;border-radius:3px;
  text-transform:uppercase;
}
.pp-title{font-size:20px;font-weight:800;color:#1a1a1a;text-align:center;line-height:1.25}
.pp-specialty{font-size:12px;color:#777;margin-top:-2px}
.pp-metrics{display:flex;gap:18px;margin:6px 0}
.pp-metric{text-align:center}
.pp-metric-val{font-size:17px;font-weight:800;color:#222}
.pp-metric-lbl{font-size:9px;color:#aaa;text-transform:uppercase}
.pp-desc{
  font-size:12px;color:#555;line-height:1.55;text-align:center;
  border-top:1px solid #e8e8e8;
  padding-top:12px;
}
.pp-photo{
  width:105px;height:105px;border-radius:50%;
  object-fit:cover;
  border:3px solid #fafafa;
  box-shadow:0 3px 10px rgba(0,0,0,.1);
}
.pp-name-sm{font-size:14px;font-weight:700;color:#222;margin-top:4px}
.pp-active{font-size:11px;color:#28a745;font-weight:700}
.pp-type-label{
  font-size:10px;font-weight:700;color:#3B82F6;
  letter-spacing:.8px;margin-top:6px;
}
.pp-timestamp{font-size:11px;color:#bbb}

/* === MAIN COLUMN === */
.main-col{
  flex:1;
  display:flex;flex-direction:column;
  min-width:0;
  position:relative;
}

/* === TOP BAR === */
.top-bar{
  background:#eeeeee;
  padding:10px 14px;
  display:flex;align-items:center;gap:10px;
  border-bottom:1px solid #d5d5d5;
  position:sticky;top:0;z-index:10;
}
.tb-photo{
  width:42px;height:42px;border-radius:50%;
  object-fit:cover;flex-shrink:0;
}
.tb-info{flex:1}
.tb-name{font-weight:700;font-size:14px;color:#1a1a1a}
.tb-meta{display:flex;align-items:center;gap:6px;margin-top:1px}
.tb-meta span{font-size:11px;color:#888}
.tb-online{
  display:inline-flex;align-items:center;gap:3px;
  font-size:10px;color:#28a745;font-weight:700;
  background:#d4edda;padding:2px 7px;border-radius:8px;
}
.tb-online::before{
  content:'';width:6px;height:6px;border-radius:50%;background:#28a745;
}

/* === DIALOG AREA === */
.dialog{
  flex:1;
  padding:18px;
  overflow-y:auto;
  display:flex;flex-direction:column;gap:3px;
  background:#d9d2c5;
}

/* === BUBBLES === */
.bubble-row{
  display:flex;gap:7px;
  max-width:82%;
  animation:slideIn .25s ease;
  margin-bottom:1px;
}
.bubble-row.expert{align-self:flex-start}
.bubble-row.visitor{align-self:flex-end;flex-direction:row-reverse}

.bubble-pic{
  width:34px;height:34px;border-radius:50%;
  object-fit:cover;flex-shrink:0;
  margin-top:3px;
}
.bubble-row.visitor .bubble-pic{display:none}

.bubble-col{display:flex;flex-direction:column;min-width:0}
.bubble-who{font-size:11px;color:#5a5a5a;margin-bottom:1px;font-weight:600}
.bubble-row.visitor .bubble-who{display:none}

.bubble-text{
  padding:9px 13px;
  font-size:14px;line-height:1.55;
  border-radius:0 18px 18px 18px;
  background:#fefefe;color:#2c2c2c;
  box-shadow:0 1px 2px rgba(0,0,0,.05);
  word-wrap:break-word;
}
.bubble-row.visitor .bubble-text{
  background:#3B82F6;color:#fff;
  border-radius:18px 0 18px 18px;
}
.bubble-stamp{font-size:10px;color:#b0b0b0;margin-top:1px;width:38px}
.bubble-row.visitor .bubble-stamp{text-align:right;margin-left:auto}

.bubble-text img{
  max-width:100%;border-radius:6px;margin-top:3px;
  display:block;
}

/* === DOTS ANIMATION === */
.dots-row{
  display:flex;gap:7px;align-self:flex-start;
  max-width:82%;margin-bottom:1px;
}
.dots-pic{
  width:34px;height:34px;border-radius:50%;
  object-fit:cover;flex-shrink:0;margin-top:3px;
}
.dots-container{
  padding:13px 16px;
  background:#fefefe;border-radius:0 18px 18px 18px;
  display:flex;gap:4px;align-items:center;
  box-shadow:0 1px 2px rgba(0,0,0,.05);
}
.dot-item{
  width:7px;height:7px;border-radius:50%;background:#c0c0c0;
  animation:dotPulse 1.1s infinite;
}
.dot-item:nth-child(2){animation-delay:.15s}
.dot-item:nth-child(3){animation-delay:.3s}

@keyframes dotPulse{
  0%,70%,100%{opacity:.25;transform:scale(.85)}
  35%{opacity:1;transform:scale(1.05)}
}
@keyframes slideIn{
  from{opacity:0;transform:translateY(6px)}
  to{opacity:1;transform:translateY(0)}
}

/* === OPTIONS PANEL === */
.options-panel{
  display:flex;flex-wrap:wrap;
  justify-content:flex-end;
  gap:7px;
  align-self:flex-end;
  max-width:82%;
  animation:slideIn .25s ease;
  margin:7px 0 9px;
  padding:10px;
  background:rgba(255,255,255,.55);
  border-radius:18px 4px 18px 18px;
}
.opt-btn{
  padding:9px 16px;
  background:#fefefe;
  border:2px solid #3B82F6;
  border-radius:18px;
  color:#3B82F6;
  font-size:13px;font-weight:700;
  cursor:pointer;
  transition:all .12s;
  text-align:center;
  flex:1 1 auto;
  min-width:110px;
}
.opt-btn:hover{
  background:#3B82F6;color:#fff;
  transform:scale(1.03);
}

/* === PURCHASE BLOCK === */
.purchase-block{
  animation:slideIn .35s ease;
  margin:14px 0 18px;
  padding:22px 18px;
  background:#fefefe;
  border-radius:12px;
  box-shadow:0 2px 10px rgba(0,0,0,.07);
  text-align:center;
}
.purchase-heading{
  font-size:17px;font-weight:800;color:#222;margin-bottom:14px;
}
.purchase-img{
  width:135px;height:auto;
  margin:0 auto 14px;display:block;
}
.pricing{
  display:flex;justify-content:center;align-items:center;gap:14px;
  margin-bottom:14px;
}
.pricing-was{
  font-size:22px;color:#999;text-decoration:line-through;
}
.pricing-now{
  font-size:30px;font-weight:800;color:#4a4a4a;
  text-shadow:0 0 3px #e8d44d;
}
.purchase-fields{
  display:flex;flex-direction:column;gap:9px;
  max-width:300px;margin:0 auto;
}
.purchase-fields input{
  padding:11px 14px;
  border:2px solid #ddd;border-radius:5px;
  font-size:15px;outline:none;
  transition:border-color .15s;
  width:100%;
}
.purchase-fields input:focus{border-color:#3B82F6}
.purchase-cta{
  display:block;
  width:88%;margin:14px auto 0;
  padding:16px 0;
  background:#43a047;color:#fff!important;
  border:none;border-radius:20px;
  font-size:22px;font-weight:800;
  cursor:pointer;
  transition:opacity .15s;
  text-decoration:none;
  animation:heartbeat .9s infinite alternate ease-in-out;
}
.purchase-cta:hover{opacity:.88}

@keyframes heartbeat{
  0%{transform:scale(1)}
  100%{transform:scale(.97)}
}

.countdown{
  margin-top:12px;
  font-size:13px;color:#222;font-weight:700;
}
.countdown .cd-num{
  display:inline-block;
  background:#222;color:#fff;
  padding:2px 5px;border-radius:3px;
  font-family:'Courier New',monospace;font-size:15px;
  margin:0 1px;
}

/* === BOTTOM FOOTER === */
.bottom-footer{
  background:#fafafa;
  border-top:1px solid #ddd;
  padding:12px 18px;
  text-align:center;
  font-size:10px;color:#aaa;
  flex-shrink:0;
}
.bottom-footer .bf-addr{margin-bottom:4px;color:#bbb;font-size:10px}
.bottom-footer a{color:#999;text-decoration:none;margin:0 5px}
.bottom-footer a:hover{text-decoration:underline}

/* === RESPONSIVE === */
@media(max-width:768px){
  .profile-panel{display:none}
  .wrapper{max-width:100%}
  .tb-name{font-size:13px}
}
@media(max-width:480px){
  .dialog{padding:8px}
  .bubble-row{max-width:90%}
  .options-panel{max-width:100%}
  .purchase-cta{font-size:18px;padding:14px 0}
}
</style>
</head>
<body>

<div class="wrapper">

  <!-- === PROFILE PANEL (desktop) === -->
  <div class="profile-panel">
    <div class="pp-status">EN LÍNEA</div>
    <div class="pp-label">CONSULTA</div>
    <div class="pp-title">Sofía<br>Torres</div>
    <div class="pp-specialty">especialista en nutrición</div>
    <div class="pp-metrics">
      <div class="pp-metric">
        <div class="pp-metric-val">1874</div>
        <div class="pp-metric-lbl">clientes</div>
      </div>
      <div class="pp-metric">
        <div class="pp-metric-val">10+ años</div>
        <div class="pp-metric-lbl">experiencia</div>
      </div>
    </div>
    <div class="pp-desc">
      Especialista en nutrición y dietética.<br><br>
      Reconocida experta en México, consultora nutricional.<br><br>
      Autora de más de 17 libros sobre nutrición.
    </div>
    <img class="pp-photo" src="img/sf-img-8.png" alt="Sofía Torres">
    <div class="pp-name-sm">Sofía Torres</div>
    <div class="pp-active">Disponible</div>
    <div class="pp-type-label">CONSULTA GRATUITA</div>
    <div class="pp-timestamp" id="ppTime"></div>
  </div>

  <!-- === MAIN COLUMN === -->
  <div class="main-col">
    <!-- TOP BAR -->
    <div class="top-bar">
      <img class="tb-photo" src="img/sf-img-8.png" alt="Sofía Torres">
      <div class="tb-info">
        <div class="tb-name">Sofía Torres</div>
        <div class="tb-meta">
          <span>especialista en nutrición</span>
          <span class="tb-online">En línea</span>
        </div>
      </div>
    </div>

    <!-- DIALOG -->
    <div class="dialog" id="dialogArea"></div>

    <!-- FOOTER (inside main column) -->
    <footer class="bottom-footer">
    
      <a href="privacy.html">Privacidad</a>
      <a href="terms.html">Términos</a>
      <a href="contacts.html">Contacto</a>
    </footer>
  </div>

</div>

<script>
/* ===========================================================
   INTERACTIVE CONSULTATION ENGINE v2
   =========================================================== */

var SETUP = {
  doctor: {
    displayName: "Dra. Sofía Torres",
    photo: "img/sf-img-8.png",
  },

  media: {
    productPhoto: "img/sf-img-10.png",
    beforeAfter: [
      "img/product-1.png",
      "img/inline-img-2.jpeg",
      "img/inline-img-3.jpeg",
    ],
  },

  greeting: [
    "¡Hola! Soy la Sofía Torres, especialista en nutrición. ¡Bienvenido/a a mi página!",
   "Aquí ofrezco un diagnóstico en línea gratuito que ya ha ayudado a muchas personas a perder peso y mejorar su bienestar.",
    "Para recibir recomendaciones sobre la pérdida de peso, por favor responda algunas preguntas.",
  ],

  survey: [
    {
      ask: "¿Cuánto peso desea perder?",
      answers: ["Hasta 5 kg","De 5 a 10 kg","De 10 a 15 kg","De 15 a 20 kg","Más de 20 kg"]
    },
    {
      ask: "¿En qué zonas del cuerpo desea ver cambios?",
      answers: ["Abdomen y cintura","Muslos y glúteos","Brazos y espalda","Todo el cuerpo"]
    },
    {
      ask: "¿Qué tan activo es su estilo de vida?",
      answers: ["Trabajo sedentario, poco movimiento","Hago ejercicio 1-3 veces por semana","Hago ejercicio 4+ veces por semana"]
    },
    {
      ask: "¿Se alimenta de forma saludable?",
      answers: ["Sí, cuento las calorías, nada de dulces","Lo intento, pero no siempre lo logro","No le presto especial atención"]
    },
    {
      ask: "¿Cuántos años tiene?",
      answers: ["18-30 años","31-40 años","41-50 años","50+ años"]
    },
    {
      ask: "¿Cuál es su peso actual?",
      answers: ["Menos de 60 kg","61 - 70 kg","71 - 80 kg","81 - 90 kg","Más de 90 kg"]
    },
    {
      ask: "¿Cuál es su estatura?",
      answers: ["Menos de 160 cm","161 - 170 cm","171 - 180 cm","Más de 180 cm"]
    },
  ],

  recommendation: [
    { msg: "¡Gracias! Tiene algo de sobrepeso, pero es totalmente tratable. La causa principal del aumento de peso es un metabolismo lento. Esto es especialmente característico de la grasa visceral acumulada alrededor de la cintura y el abdomen." },
    { msg: "Mi recomendación personal para usted: tomar extracto de ginseng, complejo de vitaminas D3 y E, L-carnitina y coenzima Q10." },
    { msg: "La coenzima Q10 contiene sinefrina, una sustancia que suprime el apetito." },
    { msg: "El complejo de vitaminas D3 y E contiene una cantidad récord de polifenoles, que eliminan las toxinas del organismo." },
    { msg: "La L-carnitina acelera el metabolismo, quema grasa y reduce los niveles de colesterol en sangre." },
    { msg: "El extracto de ginseng contiene 15 veces más vitamina C que la naranja y 3 veces más provitamina A que la zanahoria." },
    { msg: "Los ingredientes se pueden tomar por separado, pero sería muy costoso. Son mucho más eficaces y accesibles en forma de capsules <strong>NanoSlim</strong>. Se trata de extractos intensivos, con la máxima concentración de sustancias beneficiosas." },
    { msg: "Para lograr una pérdida de peso visible, simplemente tómelo dos veces al día: por la mañana y por la noche." },
    { msg: "Así es como se ve:", pic: "PRODUCT" },
    { msg: "El producto contiene un extracto de ingredientes naturales quemagrasas con la máxima concentración, que activan el proceso." },
    { msg: "Así, «NanoSlim» descompone y elimina de manera muy eficaz la grasa visceral que recubre las paredes de los órganos internos, impidiendo su correcto funcionamiento, liberando así el metabolismo." },
    { msg: "Como resultado, su organismo eliminará por sí solo el exceso de grasa, utilizándola como fuente de energía. Comerá menos y sentirá menos hambre, lo que potenciará los resultados de la pérdida de peso." },
    { msg: "Estos son los resultados de mis clientes, que con mi ayuda lograron deshacerse de los kilos de más." },
    { pic: "BA:0" },
    { pic: "BA:1" },
    { pic: "BA:2" },
    { msg: "La duración óptima del tratamiento es de aproximadamente 29 días de media, teniendo en cuenta la edad, el índice de masa corporal actual y el estilo de vida." },
    { msg: "Durante ese tiempo, su organismo se limpiará profundamente y el metabolismo se normalizará." },
    { msg: "¡Tengo una excelente noticia para usted! Según el diagnóstico en línea, usted se ha convertido en mi cliente número 2000." },
    { msg: "El número de paquetes en oferta es limitado, así que le recomiendo darse prisa con el pedido." },
  ],

  checkout: {
    heading: "Formulario oficial de pedido",
    photo: "img/sf-img-10.png",
    oldPrice: "1180 MX",
    newPrice: "590 MX",
    ctaText: "Pedir con 50% de descuento",
    inputs: [
      { hint: "Su nombre", kind: "text", key: "name" },
      { hint: "Número de teléfono", kind: "tel", key: "phone" },
    ],
    minutes: 6,
    seconds: 29,
  },

  delays: {
    typingBase: 1800,
    typingPerChar: 22,
    typingMax: 5500,
    gap: 1200,
    afterPick: 900,
  },
};

/* ===========================================================
   RUNTIME
   =========================================================== */
var dialogEl = document.getElementById("dialogArea");
var docPhoto = SETUP.doctor.photo;
var docName = SETUP.doctor.displayName;
var clock = new Date();
clock.setMinutes(clock.getMinutes() - 3);

document.getElementById("ppTime").textContent =
  "Hoy, " + pad2(clock.getHours()) + ":" + pad2(clock.getMinutes());

function pad2(n){ return String(n).padStart(2,"0"); }
function stamp(){ return pad2(clock.getHours()) + ":" + pad2(clock.getMinutes()); }
function tickClock(s){ clock = new Date(clock.getTime() + s * 1000); }
function toBottom(){ dialogEl.scrollTop = dialogEl.scrollHeight; }

function getMediaSrc(tag){
  if(tag === "PRODUCT") return SETUP.media.productPhoto;
  if(tag.indexOf("BA:") === 0) return SETUP.media.beforeAfter[parseInt(tag.split(":")[1])];
  return tag;
}

/* --- Typing dots --- */
function showDots(){
  var el = document.createElement("div");
  el.className = "dots-row";
  el.id = "dotsEl";
  el.innerHTML =
    '<img class="dots-pic" src="' + docPhoto + '" alt="">' +
    '<div class="dots-container">' +
      '<div class="dot-item"></div>' +
      '<div class="dot-item"></div>' +
      '<div class="dot-item"></div>' +
    '</div>';
  dialogEl.appendChild(el);
  toBottom();
}
function hideDots(){
  var el = document.getElementById("dotsEl");
  if(el) el.remove();
}

/* --- Expert bubble --- */
function expertBubble(html, imgTag){
  hideDots();
  tickClock(Math.random() * 30 + 10);
  var row = document.createElement("div");
  row.className = "bubble-row expert";

  var inner = "";
  if(html) inner += html;
  if(imgTag){
    var src = getMediaSrc(imgTag);
    var extra = imgTag === "PRODUCT" ? ' style="max-width:250px"' : '';
    inner += '<img src="' + src + '" alt=""' + extra + '>';
  }

  row.innerHTML =
    '<img class="bubble-pic" src="' + docPhoto + '" alt="">' +
    '<div class="bubble-col">' +
      '<div class="bubble-who">' + docName + '</div>' +
      '<div class="bubble-text">' + inner + '</div>' +
      '<div class="bubble-stamp">' + stamp() + '</div>' +
    '</div>';
  dialogEl.appendChild(row);
  toBottom();
}

/* --- Visitor bubble --- */
function visitorBubble(text){
  tickClock(Math.random() * 15 + 3);
  var row = document.createElement("div");
  row.className = "bubble-row visitor";
  row.innerHTML =
    '<div class="bubble-col">' +
      '<div class="bubble-text">' + text + '</div>' +
      '<div class="bubble-stamp">' + stamp() + '</div>' +
    '</div>';
  dialogEl.appendChild(row);
  toBottom();
}

/* --- Answer options --- */
function presentOptions(list){
  return new Promise(function(done){
    var panel = document.createElement("div");
    panel.className = "options-panel";
    list.forEach(function(label){
      var b = document.createElement("button");
      b.className = "opt-btn";
      b.textContent = label;
      b.addEventListener("click", function(){
        panel.remove();
        visitorBubble(label);
        done(label);
      });
      panel.appendChild(b);
    });
    dialogEl.appendChild(panel);
    toBottom();
  });
}

/* --- Purchase form --- */
function renderCheckout(){
  var c = SETUP.checkout;
  var block = document.createElement("div");
  block.className = "purchase-block";

  var remain = c.minutes * 60 + (c.seconds || 0);
  var cdId = "cd_" + Date.now();

  var fieldsMarkup = c.inputs.map(function(f){
    return '<input type="' + f.kind + '" name="' + f.key + '" placeholder="' + f.hint + '" required>';
  }).join("");

  block.innerHTML =
    '<div class="purchase-heading">' + c.heading + '</div>' +
    '<img class="purchase-img" src="' + c.photo + '" alt="">' +
    '<div class="pricing">' +
      '<span class="pricing-was">' + c.oldPrice + '</span>' +
      '<span class="pricing-now">' + c.newPrice + '</span>' +
    '</div>' +
    '<form class="purchase-fields">' + fieldsMarkup + '</form>' +
    '<button class="purchase-cta" id="ctaBtn">' + c.ctaText + ' &rsaquo;&rsaquo;&rsaquo;</button>' +
    '<div class="countdown" id="' + cdId + '"></div>';

  dialogEl.appendChild(block);
  toBottom();

  function countdownTick(){
    if(remain < 0) remain = 0;
    var m = pad2(Math.floor(remain / 60));
    var s = pad2(remain % 60);
    var cdEl = document.getElementById(cdId);
    if(cdEl){
      cdEl.innerHTML = 'Validez del descuento: <span class="cd-num">' + m + '</span>:<span class="cd-num">' + s + '</span>';
    }
    if(remain > 0){ remain--; setTimeout(countdownTick, 1000); }
  }
  countdownTick();

  document.getElementById("ctaBtn").addEventListener("click", function(){
    var form = block.querySelector("form");
    var payload = {};
    var ok = true;
    c.inputs.forEach(function(f){
      var inp = form.querySelector('[name="' + f.key + '"]');
      payload[f.key] = inp.value;
      if(!inp.value.trim()){ ok = false; inp.style.borderColor = "#dc3545"; }
      else { inp.style.borderColor = "#ddd"; }
    });
    if(!ok) return;

    var btn = document.getElementById("ctaBtn");
    btn.textContent = "Enviando...";
    btn.style.animation = "none";
    btn.disabled = true;

    /* --- POST to api.php --- */
    var qs = new URLSearchParams(window.location.search);
    var fd = new FormData();
    fd.append("name", payload.name);
    fd.append("phone", payload.phone);
    ["sub2","sub3","sub4","sub5","sub6","sub7"].forEach(function(k){
      if(qs.has(k)) fd.append(k, qs.get(k));
    });

    fetch("api.php", { method: "POST", body: fd })
      .then(function(r){ return r.json(); })
      .then(function(){ window.location.href = "thankyou.html"; })
      .catch(function(){
        var hiddenForm = document.createElement("form");
        hiddenForm.method = "POST"; hiddenForm.action = "api.php";
        fd.forEach(function(v, k){
          var h = document.createElement("input");
          h.type = "hidden"; h.name = k; h.value = v;
          hiddenForm.appendChild(h);
        });
        var rdr = document.createElement("input");
        rdr.type = "hidden"; rdr.name = "redirect"; rdr.value = "thankyou.html";
        hiddenForm.appendChild(rdr);
        document.body.appendChild(hiddenForm);
        hiddenForm.submit();
      });
  });
}

/* --- Helpers --- */
function pause(ms){ return new Promise(function(r){ setTimeout(r, ms); }); }
var D = SETUP.delays;

function randomInt(min, max){ return Math.floor(Math.random() * (max - min + 1)) + min; }

function typeAndShow(html, imgTag){
  return new Promise(function(done){
    showDots();
    var charLen = html ? html.replace(/<[^>]*>/g,"").length : 0;
    var base = D.typingBase + Math.min(charLen * D.typingPerChar, D.typingMax);
    var jitter = randomInt(-400, 600);
    var wait = Math.max(1400, base + jitter);
    if(imgTag) wait += randomInt(600, 1200);
    setTimeout(function(){
      expertBubble(html, imgTag);
      done();
    }, wait);
  });
}

/* ===========================================================
   CONVERSATION FLOW
   =========================================================== */
(async function(){
  /* 1. Greeting */
  for(var i = 0; i < SETUP.greeting.length; i++){
    await typeAndShow(SETUP.greeting[i]);
    await pause(D.gap + randomInt(300, 1000));
  }

  /* 2. Survey */
  for(var j = 0; j < SETUP.survey.length; j++){
    var q = SETUP.survey[j];
    await typeAndShow(q.ask);
    await pause(randomInt(300, 600));
    await presentOptions(q.answers);
    await pause(D.afterPick + randomInt(200, 700));
  }

  /* 3. Recommendation */
  for(var k = 0; k < SETUP.recommendation.length; k++){
    var r = SETUP.recommendation[k];
    await typeAndShow(r.msg || null, r.pic || null);
    await pause(D.gap + randomInt(400, 1400));
  }

  /* 4. Checkout */
  await pause(500);
  renderCheckout();
  toBottom();
})();
</script>

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-11493124376"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'AW-11493124376');
</script>

<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=AW-17545486233"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'AW-17545486233');
</script>
</body>

</html>
