// init_session.js
(function(){
  var baseUrl = "https:\/\/calls.magicful.ai";
  var callBase = "tel:+12342193998";
  var existingSid = "40";
  var telDisplay = "+12342193998";
  var sessionTtl = 172800;
  window.wsPublic = { key: "e3b277de8bf28747315e", cluster: "us2", authEndpoint: baseUrl + '/api/ws_auth.php' };
  window.vaBaseUrl = baseUrl;
  var callLinkId = 'call-link';
  function ready(fn){ if(document.readyState !== 'loading'){ fn(); } else { document.addEventListener('DOMContentLoaded', fn); } }
  function applySid(sid){
    if(!sid) return;
    window.sessionId = sid;
    try { localStorage.setItem('VA_SESSION_ID', sid); } catch(e) {}
    try {
      var cookieStr = 'VA_SESSION_ID=' + sid + ';path=/;max-age=' + sessionTtl + ';SameSite=Lax';
      if (window.location.protocol === 'https:') cookieStr += ';Secure';
      document.cookie = cookieStr;
    } catch(e) {}
    var link = document.getElementById(callLinkId);
    if(link) { link.setAttribute('href', callBase + ',,' + sid); link.dataset.vaReady = '1'; }
  }
  ready(function(){
    var link = document.getElementById(callLinkId);
    if (!link) {
      if (existingSid) { applySid(existingSid); }
      return;
    }
    if(!link.hasAttribute('href')) link.setAttribute('href', callBase);
    var storedSid = '';
    try { storedSid = localStorage.getItem('VA_SESSION_ID') || ''; } catch(e) {}
    if (!existingSid && storedSid && /^[1-9]\d{1}$/.test(storedSid)) {
      existingSid = storedSid;
    }
    if (existingSid) {
      applySid(existingSid);
      return;
    }
    link.addEventListener('click', function(ev){
      if (window.sessionId) return;
      ev.preventDefault();
      if (link.dataset.vaFetching === '1') return;
      link.dataset.vaFetching = '1';
      fetch(baseUrl + '/api/start_call.php', {
        method: 'POST',
        credentials: 'include',
        headers: { 'Content-Type': 'application/json' },
        body: '{}'
      }).then(function(resp){
        if (!resp.ok) throw new Error('status ' + resp.status);
        return resp.json();
      }).then(function(data){
        if (!data || !data.sid || !data.call_href) throw new Error('bad payload');
        applySid(data.sid);
        window.location.href = data.call_href;
      }).catch(function(err){
        console.warn('VA start_call failed', err);
        window.location.href = callBase;
      }).finally(function(){
        link.dataset.vaFetching = '';
      });
    }, { capture: true });
  });
})();
