<?php
if (count(get_included_files()) === 1) { http_response_code(403); exit('Forbidden'); }

$page_title = 'Configurá tu Vale';
$lang       = $lang    ?? 'es';
$channel    = $channel ?? 'web';
$tenantName = $_SESSION['tenant_name'] ?? '';
// Nombre limpio para el arranque (si viene del wizard ya está en DB)
$initName   = ($tenantName && $tenantName !== 'Mi Negocio' && $tenantName !== 'My Business')
    ? $tenantName : '';
?>
<!DOCTYPE html>
<html lang="<?= $lang ?>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, interactive-widget=resizes-content">
<title><?= htmlspecialchars($page_title) ?></title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,500;9..144,600;9..144,700&family=Hanken+Grotesk:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
:root{
  --bg:#F4EDE3;--card:#FFFDF9;--coffee:#3B2F27;--rust:#A8331A;--rust-d:#8F2712;
  --gold:#D99A4E;--ok:#3F7A52;--ink:#3A332E;--muted:#8A7E73;--line:#E7DDD0;
}
*{box-sizing:border-box;margin:0;padding:0;-webkit-tap-highlight-color:transparent}
html,body{overflow-x:hidden}
html{height:100%}
body{
  font-family:'Hanken Grotesk',sans-serif;color:var(--ink);
  min-height:100dvh;width:100%;
  background:radial-gradient(130% 80% at 50% -10%,#FBF5EC,var(--bg) 55%,#DDD0BE);
  display:flex;flex-direction:column;-webkit-font-smoothing:antialiased;
}
.page{flex:1;display:flex;flex-direction:column;align-items:center;padding:16px 12px 0;width:100%}
.top-bar{
  width:100%;max-width:960px;
  display:flex;align-items:center;justify-content:space-between;padding:0 0 16px;gap:8px;
}
.top-bar img{height:26px;width:auto;flex:none}
.top-bar-right{font-size:12px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0}

/* Layout: columna en mobile, 2 col en desktop */
.main{width:100%;max-width:960px;display:flex;flex-direction:column;align-items:center;gap:0;flex:1}
@media(min-width:720px){.main{flex-direction:row;gap:48px;align-items:flex-start}}

/* Value prop (desktop only) */
.vp{flex:1;padding:24px 0 40px;display:none}
@media(min-width:720px){.vp{display:flex;flex-direction:column}}
.vp-eyebrow{font-size:11px;font-weight:700;letter-spacing:2.5px;text-transform:uppercase;color:var(--rust);margin-bottom:14px}
.vp-h{font-family:'Fraunces',serif;font-weight:700;font-size:clamp(26px,3vw,36px);line-height:1.06;letter-spacing:-.7px;color:var(--coffee);margin-bottom:10px}
.vp-h em{font-style:italic;color:var(--rust)}
.vp-lead{font-size:15px;color:var(--muted);line-height:1.65;margin-bottom:24px;max-width:22em}
.step-list{list-style:none;display:flex;flex-direction:column;gap:10px}
.step-item{display:flex;align-items:center;gap:11px;font-size:13.5px;padding:10px 13px;border-radius:12px;background:rgba(255,255,255,.5);border:1px solid var(--line);transition:.2s}
.step-item.done{background:rgba(63,122,82,.06);border-color:rgba(63,122,82,.2)}
.step-item.active{background:rgba(168,51,26,.06);border-color:rgba(168,51,26,.25);font-weight:600}
.step-num{width:26px;height:26px;border-radius:99px;display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;flex:none}
.step-num.done{background:#3F7A52;color:#fff}
.step-num.active{background:var(--rust);color:#fff}
.step-num.pending{background:var(--line);color:var(--muted)}
.vp-note{margin-top:20px;font-size:12.5px;color:var(--muted);line-height:1.5}

/* Chat col: full width en mobile, fijo en desktop */
.chat-col{width:100%;max-width:100%;padding-bottom:16px}
@media(min-width:720px){.chat-col{flex:0 0 400px;width:400px;max-width:420px;padding-bottom:24px}}

.frame{
  width:100%;
  height:min(600px,80dvh);
  background:var(--card);border-radius:20px;
  display:flex;flex-direction:column;overflow:hidden;
  box-shadow:0 20px 50px -16px rgba(60,35,20,.35),0 0 0 1px rgba(255,255,255,.55);
}
@media(min-width:720px){.frame{border-radius:26px;height:min(620px,84dvh)}}
.ch{background:var(--coffee);color:#fff;display:flex;align-items:center;gap:12px;padding:14px 16px;flex:none}
.ch-av{width:40px;height:40px;border-radius:50%;flex:none;background:linear-gradient(145deg,#E7B568,var(--gold));display:flex;align-items:center;justify-content:center;overflow:hidden}
.ch-name{font-family:'Fraunces',serif;font-weight:600;font-size:17px;color:var(--gold);line-height:1}
.ch-sub{font-size:11px;color:rgba(255,255,255,.55);margin-top:2px;display:flex;align-items:center;gap:5px}
.ch-dot{width:6px;height:6px;border-radius:50%;background:#4ad07f;flex:none;animation:pulse 2s infinite}
@keyframes pulse{0%,100%{opacity:1}50%{opacity:.4}}

.msgs{flex:1;overflow-y:auto;overflow-x:hidden;padding:14px;display:flex;flex-direction:column;gap:9px;scroll-behavior:smooth}
.msgs::-webkit-scrollbar{width:0}
.bv,.bu{
  max-width:88%;padding:10px 13px;font-size:13.5px;line-height:1.55;
  animation:mpop .3s cubic-bezier(.2,.8,.2,1) both;
  word-break:break-word;overflow-wrap:break-word;
}
.bv{align-self:flex-start;background:var(--coffee);color:#f3e7d8;border-radius:15px 15px 15px 3px}
.bu{align-self:flex-end;background:var(--rust);color:#fff;border-radius:15px 15px 3px 15px}
@keyframes mpop{from{opacity:0;transform:translateY(6px) scale(.97)}to{opacity:1;transform:none}}

.typing{align-self:flex-start;background:var(--coffee);border-radius:15px 15px 15px 3px;padding:12px 14px;display:flex;gap:5px;align-items:center}
.typing b{width:6px;height:6px;border-radius:50%;background:rgba(255,255,255,.4);display:inline-block;animation:tdot 1.1s infinite ease}
.typing b:nth-child(2){animation-delay:.18s}
.typing b:nth-child(3){animation-delay:.36s}
@keyframes tdot{0%,60%,100%{transform:translateY(0)}30%{transform:translateY(-5px)}}

/* Chips de opciones — dinámicos desde Gemini */
.opts{align-self:flex-start;display:flex;flex-wrap:wrap;gap:6px;max-width:100%;animation:mpop .3s ease both}
.opt{
  background:var(--card);border:1.5px solid var(--line);border-radius:18px;
  padding:7px 12px;font-family:inherit;font-size:13px;font-weight:600;
  color:var(--ink);cursor:pointer;transition:.15s;
}
.opt:hover{border-color:var(--rust);color:var(--rust);transform:translateY(-1px)}
.opt:active{transform:scale(.97)}
.opt:disabled{opacity:.35;cursor:not-allowed;transform:none}

/* CTA final */
.cta-done{
  align-self:center;margin-top:6px;
  background:var(--ok);color:#fff;border:none;
  border-radius:12px;padding:13px 26px;
  font-family:inherit;font-size:15px;font-weight:700;cursor:pointer;
  box-shadow:0 6px 18px rgba(63,122,82,.3);transition:.15s;animation:mpop .3s ease both;
}
.cta-done:hover{background:#2E6040;transform:translateY(-1px)}

/* Input bar — font-size 16px evita el zoom de iOS al enfocar */
.input-bar{flex:none;padding:10px 12px 14px;border-top:1px solid var(--line);background:var(--card);display:flex;gap:8px;align-items:center}
.input-bar input{flex:1;background:#F6EFE6;border:none;border-radius:99px;padding:11px 15px;font-family:inherit;font-size:16px;color:var(--ink);outline:none;transition:.15s;min-width:0}
.input-bar input:focus{box-shadow:0 0 0 2px rgba(168,51,26,.15)}
.input-bar input::placeholder{color:var(--muted)}
.input-bar input:disabled{opacity:.5}
.send{width:40px;height:40px;border-radius:50%;background:var(--rust);border:none;display:flex;align-items:center;justify-content:center;cursor:pointer;flex:none;transition:.15s;box-shadow:0 4px 10px -5px rgba(168,51,26,.6)}
.send:hover{background:var(--rust-d)}
.send:disabled{background:#ccc;box-shadow:none;cursor:not-allowed}
.send svg{width:16px;height:16px;stroke:#fff;stroke-width:2.2;fill:none;stroke-linecap:round;stroke-linejoin:round}

footer{text-align:center;padding:12px;font-size:12px;color:var(--muted)}
footer a{color:var(--muted);text-decoration:underline;text-underline-offset:2px}
footer .sep{margin:0 7px;opacity:.4}
</style>
</head>
<body>
<div class="page">
  <div class="top-bar">
    <img src="/img/logo.png" alt="Vale">
    <span class="top-bar-right">
      <?= $lang === 'en' ? 'Setting up your' : 'Configurando' ?> <strong><?= htmlspecialchars($tenantName ?: 'tu negocio') ?></strong>
    </span>
  </div>

  <div class="main">
    <!-- Value prop: progress steps (desktop) -->
    <div class="vp">
      <div class="vp-eyebrow"><?= $lang === 'en' ? 'Setup' : 'Configuración' ?></div>
      <h1 class="vp-h">
        <?= $lang === 'en' ? 'Vale is getting<br><em>to know you.</em>' : 'Vale está<br><em>conociéndote.</em>' ?>
      </h1>
      <p class="vp-lead">
        <?= $lang === 'en'
          ? 'A few questions and Vale will be ready to attend your clients, book appointments and grow your business.'
          : 'Unas preguntas y Vale estará lista para atender clientes, agendar citas y hacer crecer tu negocio.' ?>
      </p>
      <ul class="step-list" id="stepList">
        <li class="step-item active" data-step="servicios">
          <div class="step-num active">1</div>
          <span><?= $lang === 'en' ? 'Services you offer' : 'Servicios que ofrecés' ?></span>
        </li>
        <li class="step-item" data-step="horarios">
          <div class="step-num pending">2</div>
          <span><?= $lang === 'en' ? 'Business hours' : 'Horarios de atención' ?></span>
        </li>
        <li class="step-item" data-step="ciudad">
          <div class="step-num pending">3</div>
          <span><?= $lang === 'en' ? 'Location' : 'Ubicación' ?></span>
        </li>
        <li class="step-item" data-step="calendar">
          <div class="step-num pending">4</div>
          <span>Google Calendar</span>
        </li>
      </ul>
      <p class="vp-note"><?= $lang === 'en' ? 'Everything you tell Vale is saved automatically. No forms.' : 'Todo lo que le contás a Vale se guarda automáticamente. Sin formularios.' ?></p>
    </div>

    <!-- Chat col -->
    <div class="chat-col">
      <div class="frame">
        <div class="ch">
          <div class="ch-av"><img src="/img/icon.png" alt="Vale" style="width:80%;height:80%;object-fit:contain;"></div>
          <div>
            <div class="ch-name">Vale</div>
            <div class="ch-sub"><span class="ch-dot"></span><span><?= $lang === 'en' ? 'setting up your business' : 'configurando tu negocio' ?></span></div>
          </div>
        </div>
        <div class="msgs" id="msgs"></div>
        <div class="input-bar" id="inputBar">
          <input id="msgIn" type="text"
                 placeholder="<?= $lang === 'en' ? 'Type your message…' : 'Escribí tu mensaje…' ?>"
                 autocomplete="off" autocorrect="off" spellcheck="false" disabled>
          <button class="send" id="sendBtn" disabled>
            <svg viewBox="0 0 24 24"><path d="M22 2L11 13M22 2l-7 20-4-9-9-4z"/></svg>
          </button>
        </div>
      </div>
    </div>
  </div>
</div>

<footer>
  <span>Hecho por <a href="https://supraide.com" target="_blank" rel="noopener">Supraide</a></span>
  <span class="sep">·</span>
  <a href="/privacy"><?= $lang === 'en' ? 'Privacy' : 'Privacidad' ?></a>
  <span class="sep">·</span>
  <a href="mailto:hola@valeai.app"><?= $lang === 'en' ? 'Contact' : 'Contacto' ?></a>
</footer>

<script>
var LANG        = <?= json_encode($lang) ?>;
var CHANNEL     = <?= json_encode($channel) ?>;
var INITNAME    = <?= json_encode($initName) ?>;
var CALENDAR_OK = <?= json_encode(isset($_GET['calendar']) && $_GET['calendar'] === 'ok') ?>;

var msgs    = document.getElementById('msgs');
var msgIn   = document.getElementById('msgIn');
var sendBtn = document.getElementById('sendBtn');
var chatHistory = [];
var busy    = false;
var done    = false;

// ── Activar / desactivar input ────────────────────────────────────────────────
msgIn.addEventListener('input',   function(){ sendBtn.disabled = !msgIn.value.trim() || busy || done; });
msgIn.addEventListener('keydown', function(e){ if(e.key === 'Enter' && !e.shiftKey){ e.preventDefault(); trySend(); } });
sendBtn.addEventListener('click', trySend);

// ── DOM helpers ────────────────────────────────────────────────────────────────
function scroll(){ msgs.scrollTop = msgs.scrollHeight; }

function addMsg(cls, text){
  var d = document.createElement('div');
  d.className = cls;
  if(cls === 'bv'){ d.innerHTML = text.replace(/\n/g,'<br>'); }
  else { d.textContent = text; }
  msgs.appendChild(d); scroll(); return d;
}

function addTyping(){
  var t = document.createElement('div');
  t.className = 'typing'; t.innerHTML = '<b></b><b></b><b></b>';
  msgs.appendChild(t); scroll(); return t;
}

// Chips de opciones (vienen de la API en data.options)
function addOpts(options, onPick){
  if(!options || !options.length) return;
  var row = document.createElement('div');
  row.className = 'opts';
  options.forEach(function(opt){
    var b = document.createElement('button');
    b.className = 'opt'; b.textContent = opt;
    b.onclick = function(){
      row.querySelectorAll('.opt').forEach(function(x){ x.disabled = true; });
      row.style.opacity = '.5';
      onPick(opt);
    };
    row.appendChild(b);
  });
  msgs.appendChild(row); scroll();
}

// Botón de fin de onboarding
function addDone(){
  var btn = document.createElement('button');
  btn.className = 'cta-done';
  btn.textContent = LANG === 'en' ? 'Go to my dashboard →' : 'Ir a mi panel →';
  btn.onclick = function(){ window.location.href = '/inicio'; };
  msgs.appendChild(btn); scroll();
}

// Marcar paso activo en la columna izquierda
function markStep(stepName){
  document.querySelectorAll('.step-item').forEach(function(li){
    var s = li.getAttribute('data-step');
    var num = li.querySelector('.step-num');
    if(s === stepName){
      li.className = 'step-item active'; num.className = 'step-num active';
    } else if(li.previousElementSibling && li.previousElementSibling.classList.contains('active') || li.classList.contains('done')){
      li.className = 'step-item done'; num.className = 'step-num done'; num.textContent = '✓';
    } else {
      li.className = 'step-item'; num.className = 'step-num pending';
    }
  });
}

// ── API call ──────────────────────────────────────────────────────────────────
function removeTyping(t){ try { msgs.removeChild(t); } catch(_){} }

function callVale(userText, callback){
  var t = addTyping();
  setBusy(true);

  fetch('/onboarding/message', {
    method: 'POST',
    headers: {'Content-Type':'application/json'},
    body: JSON.stringify({ message: userText, history: chatHistory })
  })
  .then(function(r){
    var status = r.status;
    return r.json().then(function(data){ return {status: status, data: data}; });
  })
  .then(function(resp){
    removeTyping(t);
    var data   = resp.data;
    var isErr  = resp.status !== 200 || data.error;
    var reply  = data.reply || (LANG === 'en' ? 'One moment…' : 'Un momento…');

    if(isErr){
      // Error del servidor: mostrar mensaje pero NO contaminar el historial
      addMsg('bv', reply);
      setBusy(false);
      if(callback) callback(data);
      return;
    }

    // Solo agregar al historial cuando la respuesta es válida
    chatHistory.push({role:'user',  text: userText});
    chatHistory.push({role:'model', text: reply});

    addMsg('bv', reply);

    // Chips de opciones (servicios, confirmación, etc.)
    if(data.options && data.options.length){
      addOpts(data.options, function(chosen){
        addMsg('bu', chosen);
        callVale(chosen, null);
      });
    }

    // Detectar paso actual para actualizar el sidebar
    var replyL = reply.toLowerCase();
    if(/servicio|service/i.test(replyL))  markStep('servicios');
    if(/horario|hour|abrís|open/i.test(replyL)) markStep('horarios');
    if(/ciudad|city|dónde|where/i.test(replyL)) markStep('ciudad');
    if(/calendar|agenda|google/i.test(replyL))  markStep('calendar');

    if(data.done){
      done = true; setBusy(true);
      document.querySelectorAll('.step-num').forEach(function(n){ n.className='step-num done'; n.textContent='✓'; });
      document.querySelectorAll('.step-item').forEach(function(li){ li.className='step-item done'; });
      setTimeout(addDone, 500);
    } else {
      setBusy(false);
    }
    if(callback) callback(data);
  })
 .catch(function(err){
    removeTyping(t);
    setBusy(false);
    addMsg('bv', LANG === 'en' ? 'Connection error. Please try again.' : 'Error de conexión. Intentá de nuevo.');
    console.error('[Onboarding error]:', err);
  });
}

function setBusy(val){
  busy = val;
  sendBtn.disabled = val || done || !msgIn.value.trim();
  msgIn.disabled   = val || done;
  if(!val && !done) setTimeout(function(){ msgIn.focus(); }, 80);
}

function trySend(){
  var txt = msgIn.value.trim();
  if(!txt || busy || done) return;
  msgIn.value = ''; sendBtn.disabled = true;
  addMsg('bu', txt);
  callVale(txt, null);
}

// ── Arranque ──────────────────────────────────────────────────────────────────
function start(){
  setBusy(true);
  var starter;
  if (CALENDAR_OK) {
    // Usuario vuelve de conectar Google Calendar — decírselo a Vale para que avance al resumen
    starter = LANG === 'en'
      ? 'Hi Vale, I just connected Google Calendar successfully.'
      : 'Hola Vale, acabo de conectar Google Calendar exitosamente.';
  } else if (INITNAME) {
    starter = LANG === 'en'
      ? 'Hi Vale, my business name is "' + INITNAME + '".'
      : 'Hola Vale, el nombre de mi negocio es "' + INITNAME + '".';
  } else {
    starter = LANG === 'en' ? 'Hi Vale, I just registered.' : 'Hola Vale, acabo de registrarme.';
  }
  callVale(starter, null);
}

setTimeout(start, 400);
</script>
</body>
</html>
