/* Vale web chat widget — embeddable, vanilla JS.
 * Usage: <script src="https://YOUR-HOST/js/widget.js" data-vale-key="PUBLIC_KEY"></script>
 */
(function () {
  'use strict';

  var script = document.currentScript;
  var valeKey = script && script.dataset ? script.dataset.valeKey : '';
  if (!valeKey) {
    console.error('[Vale] missing data-vale-key on widget script tag');
    return;
  }
  var apiBase = new URL(script.src).origin;
  var cookieName = 'vale_visitor_' + valeKey.slice(0, 8);

  function getCookie(name) {
    var match = document.cookie.match(new RegExp('(?:^|; )' + name + '=([^;]*)'));
    return match ? decodeURIComponent(match[1]) : '';
  }
  function setCookie(name, value) {
    var oneYear = 365 * 24 * 60 * 60;
    document.cookie = name + '=' + encodeURIComponent(value) + '; max-age=' + oneYear + '; path=/; SameSite=Lax';
  }

  var visitorId = getCookie(cookieName);

  // --- Styles ---
  var style = document.createElement('style');
  style.textContent =
    '.vale-launcher{position:fixed;bottom:20px;right:20px;width:56px;height:56px;border-radius:50%;' +
    'background:#A8331A;color:#FBF6EE;border:none;cursor:pointer;font-size:24px;box-shadow:0 4px 14px rgba(0,0,0,.25);z-index:2147483000}' +
    '.vale-panel{position:fixed;bottom:88px;right:20px;width:340px;max-width:calc(100vw - 40px);height:460px;max-height:calc(100vh - 120px);' +
    'background:#FBF6EE;border-radius:14px;box-shadow:0 10px 40px rgba(0,0,0,.3);display:none;flex-direction:column;overflow:hidden;z-index:2147483000;font-family:system-ui,sans-serif}' +
    '.vale-panel.open{display:flex}' +
    '.vale-head{background:#A8331A;color:#FBF6EE;padding:12px 16px;font-weight:600}' +
    '.vale-head small{display:block;font-weight:400;opacity:.85;font-size:11px}' +
    '.vale-msgs{flex:1;overflow-y:auto;padding:12px;display:flex;flex-direction:column;gap:8px}' +
    '.vale-bubble{max-width:80%;padding:8px 12px;border-radius:12px;font-size:14px;line-height:1.35;white-space:pre-wrap;word-wrap:break-word}' +
    '.vale-in{align-self:flex-start;background:#fff;color:#221C18;border:1px solid #eadfce}' +
    '.vale-out{align-self:flex-end;background:#E0A33E;color:#221C18}' +
    '.vale-form{display:flex;border-top:1px solid #eadfce}' +
    '.vale-form input{flex:1;border:none;padding:12px;font-size:14px;background:transparent;outline:none}' +
    '.vale-form button{border:none;background:#A8331A;color:#FBF6EE;padding:0 16px;cursor:pointer;font-weight:600}' +
    '.vale-opts{display:flex;flex-wrap:wrap;gap:6px;padding:2px 2px 6px}' +
    '.vale-opt{background:#fff;border:1.5px solid #A8331A;color:#A8331A;border-radius:16px;padding:6px 12px;font-size:13px;cursor:pointer;font-weight:600;font-family:system-ui,sans-serif}';
  document.head.appendChild(style);

  // --- DOM ---
  var launcher = document.createElement('button');
  launcher.className = 'vale-launcher';
  launcher.setAttribute('aria-label', 'Abrir chat');
  launcher.textContent = '💬';

  var panel = document.createElement('div');
  panel.className = 'vale-panel';
  panel.innerHTML =
    '<div class="vale-head">Vale<small>Asistente virtual con IA</small></div>' +
    '<div class="vale-msgs"></div>' +
    '<form class="vale-form"><input type="text" placeholder="Escribí tu mensaje…" autocomplete="off"/><button type="submit">→</button></form>';

  document.body.appendChild(launcher);
  document.body.appendChild(panel);

  var msgs = panel.querySelector('.vale-msgs');
  var form = panel.querySelector('.vale-form');
  var input = panel.querySelector('input');
  var greeted = false;

  function addBubble(text, kind) {
    var b = document.createElement('div');
    b.className = 'vale-bubble ' + (kind === 'out' ? 'vale-out' : 'vale-in');
    b.textContent = text;
    msgs.appendChild(b);
    msgs.scrollTop = msgs.scrollHeight;
    return b;
  }

  function clearOptions() {
    var prev = msgs.querySelector('.vale-opts');
    if (prev) prev.remove();
  }

  function addOptions(opts) {
    clearOptions();
    if (!opts || !opts.length) return;
    var wrap = document.createElement('div');
    wrap.className = 'vale-opts';
    opts.forEach(function (o) {
      var btn = document.createElement('button');
      btn.className = 'vale-opt';
      btn.textContent = o;
      btn.addEventListener('click', function () { clearOptions(); sendMessage(o); });
      wrap.appendChild(btn);
    });
    msgs.appendChild(wrap);
    msgs.scrollTop = msgs.scrollHeight;
  }

  launcher.addEventListener('click', function () {
    panel.classList.toggle('open');
    if (panel.classList.contains('open')) {
      input.focus();
      if (!greeted) {
        greeted = true;
        addBubble('¡Hola! Soy Vale, la asistente virtual. ¿En qué te puedo ayudar?', 'in');
      }
    }
  });

  function sendMessage(text) {
    clearOptions();
    addBubble(text, 'out');
    var typing = addBubble('…', 'in');
    fetch(apiBase + '/agent/web', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ key: valeKey, visitorId: visitorId, message: text })
    })
      .then(function (r) { return r.json(); })
      .then(function (data) {
        typing.remove();
        if (data.visitorId) {
          visitorId = data.visitorId;
          setCookie(cookieName, visitorId);
        }
        addBubble(data.reply || 'No pude responder ahora mismo.', 'in');
        addOptions(data.options || []);
      })
      .catch(function () {
        typing.remove();
        addBubble('Hubo un problema de conexión. Intentá de nuevo.', 'in');
      });
  }

  form.addEventListener('submit', function (e) {
    e.preventDefault();
    var text = input.value.trim();
    if (!text) return;
    input.value = '';
    sendMessage(text);
  });
})();
