(function($){
let localStream=null;
let currentSession=null;

window.startCam=async function(slot){
  try{
    localStream=await navigator.mediaDevices.getUserMedia({video:true,audio:true});
    const v=document.createElement('video');
    v.autoplay=true;v.muted=true;v.srcObject=localStream;
    $('#slot-'+slot).html(v);
  }catch(e){alert('Camera denied');}
};

window.loadTokens=async function(){
  const r=await fetch(SCP_DATA.rest+'tokens/get');
  const j=await r.json();
  $('#scp-balance').text(j.balance);
};

window.buyTokens=async function(amount){
  const r=await fetch(SCP_DATA.rest+'tokens/add',{
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({amount:amount})
  });
  const j=await r.json();
  $('#scp-balance').text(j.balance);
};

window.sendTip=async function(modelId,amount){
  const r=await fetch(SCP_DATA.rest+'billing/tip',{
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({to:modelId,amount:amount})
  });
  const j=await r.json();
  if(j.remaining!==undefined){
    $('#scp-balance').text(j.remaining);
    alert('Tip sent. Remaining: '+j.remaining);
  }else if(j.code){ alert(j.message); }
};

window.startSession=async function(modelId,roomType,rate){
  const r=await fetch(SCP_DATA.rest+'billing/start',{
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({model:modelId,room_type:roomType,rate_per_min:rate})
  });
  const j=await r.json();
  if(j.id){
    currentSession=j;
    $('#scp-session-info').text('Session '+j.id+' active ('+roomType+', '+rate+' tokens/min)');
    if(rate>0){
      setInterval(async()=>{ if(currentSession) await tickSession(); },60000);
    }
  }
};

async function tickSession(){
  const r=await fetch(SCP_DATA.rest+'billing/tick',{
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({session_id:currentSession.id})
  });
  const j=await r.json();
  if(j.code){
    alert('Session stopped: '+j.message);
    currentSession=null;
    $('#scp-session-info').text('No active session');
  }else{
    $('#scp-session-info').text('Session '+currentSession.id+' spent '+j.total_spent+' tokens');
    if(j.remaining_tokens!==undefined) $('#scp-balance').text(j.remaining_tokens);
  }
}

window.endSession=async function(){
  if(!currentSession) return;
  const r=await fetch(SCP_DATA.rest+'billing/end',{
    method:'POST',
    headers:{'Content-Type':'application/json'},
    body:JSON.stringify({session_id:currentSession.id})
  });
  const j=await r.json();
  alert('Session ended. Total spent: '+j.total_spent+' tokens');
  currentSession=null;
  $('#scp-session-info').text('No active session');
};

window.loadUsers=async function(){
  const r=await fetch(SCP_DATA.rest+'users');
  const arr=await r.json();
  let html='';
  arr.forEach(u=>{
    html+=`<div class="scp-row">${u.name} (${u.role}) [ID ${u.id}]
      <button class="scp-btn" onclick="sendTip(${u.id},10)">Tip 10</button>
      <button class="scp-btn" onclick="startSession(${u.id},'private',20)">Private 20/min</button>
    </div>`;
  });
  $('#scp-users').html(html);
};

window.loadRooms=async function(){
  const r=await fetch(SCP_DATA.rest+'rooms');
  const arr=await r.json();
  let html='';
  arr.forEach(room=>{
    html+=`<div class="scp-row">${room.name} – type: ${room.type} – rate: ${room.rate_per_min}/min</div>`;
  });
  $('#scp-rooms').html(html);
};

$(function(){
  if($('#scp-balance').length) loadTokens();
  if($('#scp-users').length) loadUsers();
  if($('#scp-rooms').length) loadRooms();
  if($('#scp-session-info').length) $('#scp-session-info').text('No active session');
});
})(jQuery);