Aucune description
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

share.html 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1">
  6. <title>BizGaze Support — Share your screen</title>
  7. <style>
  8. :root{ --brand:#FFC708; --brand-d:#E0AC00; --blue:#1F3B73; --blue-d:#16294f; --blue-soft:#EAF0FB; --ink:#1f2430; --muted:#6b7280; --bg:#f6f8fb; --card:#ffffff; --line:#e6e9ef; }
  9. *{box-sizing:border-box;}
  10. body{font-family:'Segoe UI',system-ui,sans-serif;background:var(--bg);color:var(--ink);margin:0;}
  11. .stage{display:flex;min-height:100vh;}
  12. .brandpanel{flex:1;background:linear-gradient(160deg,var(--blue),var(--blue-d));color:#fff;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center;padding:2.5rem;}
  13. .mark{width:88px;height:88px;border-radius:22px;background:var(--brand);display:grid;place-items:center;font-weight:800;font-size:2.6rem;color:var(--blue);margin-bottom:1.2rem;box-shadow:0 12px 30px rgba(0,0,0,.25);}
  14. .wordmark{font-size:2.2rem;font-weight:800;letter-spacing:.01em;}
  15. .wordmark span{color:var(--brand);}
  16. .tagline{color:#cdd7ee;margin-top:.6rem;font-size:1rem;max-width:300px;line-height:1.5;}
  17. .panelside{flex:1;display:flex;align-items:center;justify-content:center;padding:2rem;}
  18. .card{background:var(--card);border:1px solid var(--line);border-radius:18px;padding:2.4rem;max-width:440px;width:100%;text-align:center;box-shadow:0 10px 30px rgba(20,30,60,.06);}
  19. h1{font-size:1.45rem;margin:.2rem 0 .4rem;color:var(--blue);}
  20. .sub{color:var(--muted);font-size:.97rem;line-height:1.5;margin-bottom:1.6rem;}
  21. .codewrap{background:#fffdf2;border:2px dashed var(--brand);border-radius:14px;padding:1.2rem;}
  22. .codelabel{font-size:.78rem;letter-spacing:.08em;text-transform:uppercase;color:var(--muted);margin-bottom:.3rem;}
  23. .code{font-size:clamp(1.9rem,12vw,3rem);letter-spacing:clamp(.18rem,3vw,.5rem);font-weight:800;color:var(--ink);white-space:nowrap;overflow:hidden;text-overflow:clip;}
  24. .status{margin-top:1.3rem;padding:.7rem 1rem;border-radius:10px;background:#f1f5f9;color:#475569;font-size:.92rem;}
  25. .status.on{background:#ecfdf3;color:#15803d;}
  26. .consent{margin-top:1.3rem;border:1px solid #c7d6f0;background:var(--blue-soft);border-left:5px solid var(--blue);border-radius:12px;padding:1.3rem;text-align:left;color:var(--blue-d);}
  27. .consent .who{font-weight:700;color:var(--blue);}
  28. .btns{margin-top:1rem;display:flex;gap:.6rem;}
  29. button{flex:1;padding:.8rem 1rem;border:none;border-radius:10px;font-weight:700;font-size:.98rem;cursor:pointer;}
  30. .grant{background:var(--brand);color:var(--ink);} .grant:hover{background:var(--brand-d);}
  31. .deny{background:#fff;color:var(--blue);border:1px solid #c7d6f0;} .deny:hover{background:#f3f6fc;}
  32. .foot{color:var(--muted);font-size:.8rem;margin-top:1.4rem;}
  33. .indicator{position:fixed;top:0;left:0;right:0;background:#dc2626;color:#fff;text-align:center;padding:.5rem;font-size:.9rem;display:none;font-weight:600;z-index:9;}
  34. .indicator.show{display:block;}
  35. /* Embedded inside the home shell: hide own chrome (the shell provides it). */
  36. html.embed .brandpanel{display:none!important;}
  37. html.embed #homeLink{display:none!important;}
  38. html.embed .panelside{flex:1;}
  39. @media(max-width:860px){ .stage{flex-direction:column;} .brandpanel{padding:2rem;min-height:auto;} .mark{width:60px;height:60px;border-radius:16px;font-size:1.8rem;margin-bottom:.7rem;} .wordmark{font-size:1.5rem;} .tagline{display:none;} }
  40. .profile{position:relative}
  41. .profile .pbtn{display:flex;align-items:center;gap:.4rem;background:rgba(255,255,255,.14);color:#fff;border:1px solid #46598c;border-radius:10px;padding:.45rem .85rem;font-weight:600;font-size:.88rem;cursor:pointer}
  42. .profile .pbtn:hover{background:rgba(255,255,255,.24)}
  43. .profile .pmenu{position:absolute;right:0;top:calc(100% + 6px);background:#fff;border:1px solid #e6e9ef;border-radius:10px;box-shadow:0 10px 28px rgba(0,0,0,.18);min-width:190px;overflow:hidden;z-index:5000;display:none}
  44. .profile .pmenu.open{display:block}
  45. .profile .pmenu a{display:block;padding:.6rem .9rem;color:#1f2430;text-decoration:none;font-size:.9rem;cursor:pointer}
  46. .profile .pmenu a:hover{background:#f1f5f9}
  47. .profile .pmenu a.danger{color:#b91c1c;border-top:1px solid #eef1f6}
  48. </style>
  49. </head>
  50. <body>
  51. <script>if(new URLSearchParams(location.search).get('embed')==='1')document.documentElement.classList.add('embed');</script>
  52. <div class="indicator" id="indicator">● Your screen is being shared — close this tab anytime to stop</div>
  53. <a href="/" id="homeLink" style="position:fixed;top:14px;left:16px;z-index:50;display:inline-flex;align-items:center;gap:6px;background:rgba(255,255,255,.92);color:#1F3B73;text-decoration:none;font-weight:600;font-size:.86rem;padding:.45rem .8rem;border-radius:10px;box-shadow:0 4px 12px rgba(0,0,0,.15)">&#8592; Home</a>
  54. <div class="stage">
  55. <div class="brandpanel">
  56. <img src="/logo.png" alt="" style="width:88px;height:88px;border-radius:22px;object-fit:contain;margin-bottom:1.2rem;background:#fff;padding:8px;box-shadow:0 12px 30px rgba(0,0,0,.25)" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'mark',textContent:'B'}))">
  57. <div class="wordmark">BizGaze <span>Support</span></div>
  58. <div class="tagline">Secure, instant remote support — no downloads, you stay in control.</div>
  59. </div>
  60. <div class="panelside">
  61. <div class="card">
  62. <h1>Let's get you connected</h1>
  63. <div class="sub">Share the code below with your BizGaze support agent.</div>
  64. <div class="codewrap">
  65. <div class="codelabel">Your session code</div>
  66. <div style="display:flex;align-items:center;justify-content:center;gap:.7rem">
  67. <div class="code" id="code">······</div>
  68. <button id="copyBtn" title="Click to copy" aria-label="Click to copy" style="flex:0 0 auto;width:38px;height:38px;padding:0;background:#fff;border:1px solid var(--brand);color:var(--blue);border-radius:8px;cursor:pointer;display:inline-flex;align-items:center;justify-content:center"><svg id="copyIcon" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg></button>
  69. </div>
  70. </div>
  71. <div id="status" class="status">Preparing your code…</div>
  72. <div id="consentBox"></div>
  73. <div class="foot">🔒 You stay in control. The agent can only see your screen after you tap Allow, and you can stop anytime.</div>
  74. </div>
  75. </div>
  76. </div>
  77. <script>
  78. let ICE={iceServers:[{urls:'stun:stun.l.google.com:19302'}]};
  79. let SHARER_NAME='Customer';
  80. try{fetch('/api/me').then(r=>r.ok?r.json():null).then(m=>{if(m&&(m.name||m.email))SHARER_NAME=m.name||m.email;}).catch(()=>{});}catch(_){}
  81. const IS_MOBILE=/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini|Mobile/i.test(navigator.userAgent||'');
  82. let __icePromise=Promise.resolve();try{__icePromise=fetch('/api/ice').then(r=>r.ok?r.json():null).then(c=>{if(c&&c.iceServers)ICE=c;}).catch(()=>{});}catch(_){}
  83. async function ensureIce(){try{await __icePromise;}catch(_){}return ICE;}
  84. function pEsc(s){return String(s==null?'':s).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));}
  85. // When embedded in the home shell, tell the parent when a session is live so the
  86. // rail can show a "return here" indicator.
  87. function bzcSession(active){try{if(window.parent&&window.parent!==window)window.parent.postMessage({type:'bzc-session',flow:'share',active:!!active},location.origin);}catch(_){}}
  88. function profileHTML(name){return '<div class="profile"><button class="pbtn" id="pbtn">'+pEsc(name)+' <span style="font-size:.65rem">&#9662;</span></button><div class="pmenu" id="pmenu"><a href="/home">Home</a><a href="/dashboard">Dashboard</a><a id="plogout" class="danger">Logout</a></div></div>';}
  89. function wireProfile(){const btn=document.getElementById('pbtn'),menu=document.getElementById('pmenu');if(!btn)return;btn.onclick=(e)=>{e.stopPropagation();menu.classList.toggle('open');};document.addEventListener('click',()=>menu.classList.remove('open'));const lo=document.getElementById('plogout');if(lo)lo.onclick=async()=>{try{await fetch('/api/logout',{method:'POST'});}catch(_){}location.href='/';};}
  90. function makeBrandClickable(){document.querySelectorAll('.brandrow,.wordmark').forEach(el=>{el.style.cursor='pointer';el.addEventListener('click',()=>{location.href='/';});});}
  91. makeBrandClickable();
  92. const codeEl=document.getElementById('code'), statusEl=document.getElementById('status'),
  93. consentBox=document.getElementById('consentBox'), indicator=document.getElementById('indicator');
  94. const setStatus=(t,c='')=>{statusEl.textContent=t;statusEl.className='status '+c;};
  95. document.getElementById('copyBtn').onclick=async()=>{
  96. const code=codeEl.textContent.trim();
  97. if(!/^\d{6}$/.test(code)) return;
  98. try{ await navigator.clipboard.writeText(code); }
  99. catch(e){ const ta=document.createElement('textarea');ta.value=code;document.body.appendChild(ta);ta.select();document.execCommand('copy');ta.remove(); }
  100. const b=document.getElementById('copyBtn'); const old=b.innerHTML;
  101. b.innerHTML='<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#16a34a" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg>';
  102. setTimeout(()=>{b.innerHTML=old;},1500);
  103. };
  104. let ws,pc,localStream,chatChannel,sessionId;
  105. ws=new WebSocket((location.protocol==='https:'?'wss://':'ws://')+location.host+'/ws');
  106. ws.onopen=()=>ws.send(JSON.stringify({type:'share-create'}));
  107. ws.onmessage=async(e)=>{const m=JSON.parse(e.data);switch(m.type){
  108. case 'share-code': codeEl.textContent=m.code; setStatus('Waiting for your agent to enter the code…'); break;
  109. case 'share-request': onAgentConnected(m); break;
  110. case 'start-stream': sessionId=m.sessionId; await startStreaming(); break;
  111. case 'answer': if(pc) await pc.setRemoteDescription(new RTCSessionDescription(m.sdp)); break;
  112. case 'ice-candidate': if(m.candidate&&pc) await pc.addIceCandidate(new RTCIceCandidate(m.candidate)); break;
  113. case 'recording': recNotice(m.on); if(m.on) startCustTranscription(); else stopCustTranscription(); break;
  114. case 'session-ended': endShareSession('Your support agent ended the session. Tap below for a new code if you still need help.'); break;
  115. case 'error': setStatus(m.message,''); break;
  116. }};
  117. ws.onclose=()=>{ if(document.getElementById('sessionBar')||localStream){ /* keep the live session: media flows independently of signaling. a real end is detected via pc 'failed' or an explicit session-ended message. */ } else { setStatus('Connection closed. Refresh the page to start again.'); } };
  118. function onAgentConnected(m){
  119. const cw=document.querySelector('.codewrap');
  120. if(cw) cw.style.display='none';
  121. setStatus('Your agent has connected. Please respond below.','on');
  122. showConsent(m);
  123. }
  124. function showConsent(m){
  125. const name=(m.technician&&m.technician.trim())?m.technician:'Your support agent';
  126. consentBox.innerHTML='<div class="consent">Your support agent <span class="who">'+esc(name)+'</span> would like to view your screen to help you.'+
  127. '<div class="btns"><button class="grant" id="g">Allow</button><button class="deny" id="d">Not now</button></div></div>';
  128. const allow=async()=>{
  129. document.removeEventListener('keydown',onKey);
  130. setStatus('Opening the screen picker — choose your screen and tap Share / Start.','on');
  131. const ok=await beginCapture();
  132. if(!ok){ consentBox.innerHTML=''; try{ws.send(JSON.stringify({type:'consent',sessionId:m.sessionId,granted:false}));}catch(_){} setStatus('Screen share was cancelled. Refresh this page if you need a new code.'); return; }
  133. consentBox.innerHTML='';
  134. try{ws.send(JSON.stringify({type:'consent',sessionId:m.sessionId,granted:true}));}catch(_){}
  135. };
  136. const onKey=(e)=>{if(e.key==='Enter'){e.preventDefault();allow();}};
  137. document.addEventListener('keydown',onKey);
  138. document.getElementById('g').onclick=allow;
  139. document.getElementById('d').onclick=()=>{consentBox.innerHTML='';document.removeEventListener('keydown',onKey);ws.send(JSON.stringify({type:'consent',sessionId:m.sessionId,granted:false}));setStatus('Connection declined. Refresh this page if you need a new code.');};
  140. }
  141. // Capture the screen (+mic) DIRECTLY from the Allow tap. Mobile browsers reject
  142. // getDisplayMedia unless it is called from a user gesture, so this must not run
  143. // after a server round-trip. getDisplayMedia is called first to keep the gesture.
  144. async function beginCapture(){
  145. try{ localStream=await navigator.mediaDevices.getDisplayMedia({video:{displaySurface:'monitor',frameRate:{ideal:30}},audio:false,monitorTypeSurfaces:'include'}); }
  146. catch(err){ return false; }
  147. try{ const mic=await navigator.mediaDevices.getUserMedia({audio:true}); window.__mic=mic; mic.getAudioTracks().forEach(t=>localStream.addTrack(t)); }catch(e){}
  148. try{ ensureIce(); }catch(_){}
  149. return true;
  150. }
  151. async function startStreaming(){
  152. // If the Allow tap already captured the screen (mobile path), reuse it.
  153. if(!localStream){
  154. await ensureIce();
  155. let mic=null; try{ mic=await navigator.mediaDevices.getUserMedia({audio:true}); }catch(e){ mic=null; }
  156. setStatus('In the popup: choose your screen, then tap Share / Start.','on');
  157. try{ localStream=await navigator.mediaDevices.getDisplayMedia({video:{displaySurface:'monitor',frameRate:{ideal:30}},audio:false,monitorTypeSurfaces:'include'}); }
  158. catch(err){ if(mic){try{mic.getTracks().forEach(t=>t.stop());}catch(_){}} try{ws.send(JSON.stringify({type:'end-session',sessionId,reason:'share-cancelled'}));}catch(e){} setStatus('Screen share was cancelled. Refresh the page to try again.'); return; }
  159. if(mic){ window.__mic=mic; try{mic.getAudioTracks().forEach(t=>localStream.addTrack(t));}catch(_){} }
  160. }
  161. await ensureIce();
  162. indicator.classList.add('show'); setStatus('You are now sharing your screen with your agent.','on'); bzcSession(true);
  163. { const hl=document.getElementById('homeLink'); if(hl) hl.style.display='none'; }
  164. window.onbeforeunload=function(){ if((localStream||document.getElementById('sessionBar'))&&!sessionOver){ return 'Leaving or refreshing this page will end your screen sharing session.'; } };
  165. pc=new RTCPeerConnection(ICE);
  166. buildBar();
  167. localStream.getTracks().forEach(t=>pc.addTrack(t,localStream));
  168. pc.ondatachannel=(ev)=>{ev.channel.onmessage=()=>{};};
  169. pc.ontrack=(ev)=>{ if(ev.track.kind==='audio'){ let a=document.getElementById('remoteAudio'); if(!a){a=document.createElement('audio');a.id='remoteAudio';a.autoplay=true;document.body.appendChild(a);} a.srcObject=ev.streams[0]; } };
  170. pc.onicecandidate=(ev)=>{if(ev.candidate)ws.send(JSON.stringify({type:'ice-candidate',sessionId,candidate:ev.candidate}));};
  171. pc.onconnectionstatechange=()=>{ if(pc&&pc.connectionState==='failed'){ try{ws.send(JSON.stringify({type:'end-session',sessionId,reason:'customer-ended'}));}catch(_){} endShareSession('The connection was lost. Tap below for a new code if you still need help.'); } };
  172. chatChannel=pc.createDataChannel('chat',{ordered:true});
  173. chatChannel.onmessage=(e)=>{try{addChat(JSON.parse(e.data));}catch(_){}};
  174. const offer=await pc.createOffer(); await pc.setLocalDescription(offer);
  175. ws.send(JSON.stringify({type:'offer',sessionId,sdp:pc.localDescription}));
  176. localStream.getVideoTracks()[0].onended=()=>{ws.send(JSON.stringify({type:'end-session',sessionId,reason:'customer-ended'}));teardown();};
  177. }
  178. const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
  179. let crecog=null, crecogActive=false, sessionOver=false;
  180. function startCustTranscription(){
  181. if(!SR){ return; }
  182. try{
  183. crecog=new SR(); crecog.continuous=true; crecog.interimResults=false; crecog.lang='en-US';
  184. crecog.onresult=(e)=>{ for(let i=e.resultIndex;i<e.results.length;i++){ if(e.results[i].isFinal){ const txt=(e.results[i][0].transcript||'').trim(); if(txt){ try{ws.send(JSON.stringify({type:'transcript',sessionId,role:'customer',name:SHARER_NAME,text:txt,chat:false}));}catch(_){} } } } };
  185. crecog.onerror=()=>{};
  186. crecog.onend=()=>{ if(crecogActive){ try{crecog.start();}catch(_){} } };
  187. crecogActive=true; crecog.start();
  188. }catch(e){}
  189. }
  190. function stopCustTranscription(){ crecogActive=false; if(crecog){ try{crecog.stop();}catch(_){} crecog=null; } }
  191. let recTimerInt=null, recStartTs=0;
  192. function fmtElapsed(ms){const s=Math.max(0,Math.floor(ms/1000));return String(Math.floor(s/60)).padStart(2,'0')+':'+String(s%60).padStart(2,'0');}
  193. function recNotice(on){
  194. if(on&&sessionOver) return;
  195. let n=document.getElementById('recNotice');
  196. if(on){
  197. if(!n){ n=document.createElement('div'); n.id='recNotice';
  198. n.style.cssText='position:fixed;top:14px;left:50%;transform:translateX(-50%);z-index:2147483600;background:#b91c1c;color:#fff;font-weight:600;font-size:.9rem;padding:.5rem 1rem;border-radius:999px;box-shadow:0 6px 18px rgba(0,0,0,.3);display:flex;align-items:center;gap:.5rem';
  199. n.innerHTML='<span style="width:10px;height:10px;border-radius:50%;background:#fff;display:inline-block;animation:recPulse 1.2s infinite"></span> This session is being recorded \u00b7 <span id="recTimeVal">00:00</span>';
  200. document.body.appendChild(n);
  201. if(!document.getElementById('recPulseStyle')){const st=document.createElement('style');st.id='recPulseStyle';st.textContent='@keyframes recPulse{0%,100%{opacity:1}50%{opacity:.25}}';document.head.appendChild(st);}
  202. }
  203. recStartTs=Date.now(); clearInterval(recTimerInt);
  204. const upd=()=>{ const t=document.getElementById('recTimeVal'); if(t) t.textContent=fmtElapsed(Date.now()-recStartTs); };
  205. upd(); recTimerInt=setInterval(upd,1000);
  206. } else { clearInterval(recTimerInt); recTimerInt=null; if(n) n.remove(); }
  207. }
  208. function endShareSession(msgText){
  209. sessionOver=true; window.onbeforeunload=null; bzcSession(false); { const hl=document.getElementById('homeLink'); if(hl) hl.style.display=''; } try{recNotice(false);stopCustTranscription();}catch(_){}
  210. removeSessionUI();
  211. indicator.classList.remove('show');
  212. if(window.__mic){try{window.__mic.getTracks().forEach(t=>t.stop());}catch(_){}window.__mic=null;}
  213. if(localStream){try{localStream.getTracks().forEach(t=>t.stop());}catch(_){}localStream=null;}
  214. if(pc){try{pc.close();}catch(_){}pc=null;}
  215. var card=document.querySelector('.panelside .card');
  216. if(card){ card.innerHTML='<h1 style="color:var(--blue)">Session ended</h1><div class="sub">'+esc(msgText||'The session has ended.')+'</div><button onclick="location.reload()" style="width:100%;margin-top:.4rem">Get a new code</button>'; }
  217. }
  218. function teardown(){sessionOver=true;window.onbeforeunload=null;bzcSession(false);{const hl=document.getElementById('homeLink');if(hl)hl.style.display='';}try{recNotice(false);stopCustTranscription();}catch(_){}indicator.classList.remove('show');removeSessionUI();if(window.__mic){window.__mic.getTracks().forEach(t=>t.stop());window.__mic=null;}if(localStream){localStream.getTracks().forEach(t=>t.stop());localStream=null;}if(pc){pc.close();pc=null;}consentBox.innerHTML='';setStatus('Session ended. Refresh this page to get a new code.');}
  219. let chatOpen=false;
  220. const SVG_MIC='<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="2" width="6" height="11" rx="3"/><path d="M5 10a7 7 0 0 0 14 0"/><line x1="12" y1="19" x2="12" y2="22"/></svg>';
  221. const SVG_MICOFF='<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="3" y1="3" x2="21" y2="21"/><path d="M9 9v4a3 3 0 0 0 5 2.2"/><path d="M5 10a7 7 0 0 0 10.9 5.6"/><line x1="12" y1="19" x2="12" y2="22"/></svg>';
  222. const SVG_CHAT='<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/></svg>';
  223. const SVG_END='<svg viewBox="0 0 24 24" width="17" height="17" fill="#fff"><rect x="5" y="5" width="14" height="14" rx="2.5"/></svg>';
  224. function _btn(id,svg,label,bg){const b=document.createElement('button');b.id=id;b.innerHTML='<span style="display:inline-flex">'+svg+'</span><span>'+label+'</span>';b.style.cssText='display:inline-flex;align-items:center;gap:7px;border:none;border-radius:12px;padding:.62rem 1rem;font-weight:600;font-size:.9rem;cursor:pointer;color:#fff;background:'+bg+';transition:background .15s,transform .08s';b.onmouseenter=()=>b.style.transform='translateY(-1px)';b.onmouseleave=()=>b.style.transform='none';return b;}
  225. function buildBar(){
  226. if(document.getElementById('sessionBar'))return;
  227. const bar=document.createElement('div'); bar.id='sessionBar';
  228. bar.style.cssText='position:fixed;right:18px;bottom:18px;z-index:2147483000;display:flex;gap:10px;align-items:center;background:rgba(15,23,42,.94);padding:8px 12px;border-radius:16px;box-shadow:0 10px 28px rgba(0,0,0,.35)';
  229. const mic=_btn('micBtn',SVG_MIC,'Mic','#2563eb');
  230. const chat=_btn('chatBtn',SVG_CHAT,'Chat','#475569');
  231. const end=_btn('endBtn2',SVG_END,'Stop','#dc2626');
  232. bar.appendChild(mic);bar.appendChild(chat);bar.appendChild(end);
  233. document.body.appendChild(bar);
  234. mic.onclick=()=>{const m=window.__mic;if(!m)return;const t=m.getAudioTracks()[0];if(!t)return;t.enabled=!t.enabled;mic.innerHTML='<span style="display:inline-flex">'+(t.enabled?SVG_MIC:SVG_MICOFF)+'</span><span>'+(t.enabled?'Mic':'Muted')+'</span>';mic.style.background=t.enabled?'#2563eb':'#6b7280';};
  235. chat.onclick=toggleChat;
  236. end.onclick=()=>{ try{ws.send(JSON.stringify({type:'end-session',sessionId,reason:'customer-ended'}));}catch(_){} teardown(); };
  237. buildChatPanel();
  238. document.addEventListener('pointerdown',ensureAudio,{once:true});
  239. document.addEventListener('keydown',ensureAudio,{once:true});
  240. if('Notification' in window && Notification.permission==='default'){ try{Notification.requestPermission();}catch(_){}}
  241. }
  242. function buildChatPanel(){
  243. if(document.getElementById('chatPanel'))return;
  244. const p=document.createElement('div'); p.id='chatPanel';
  245. p.style.cssText='position:fixed;right:18px;bottom:84px;width:300px;max-width:92vw;height:360px;max-height:62vh;z-index:2147483001;background:#fff;border:1px solid #e6e9ef;border-radius:16px;box-shadow:0 14px 34px rgba(0,0,0,.28);display:none;flex-direction:column;overflow:hidden';
  246. p.innerHTML='<div style="background:#1F3B73;color:#fff;padding:.6rem .85rem;font-weight:600;font-size:.92rem;display:flex;justify-content:space-between;align-items:center">Chat <span id="chatClose" style="cursor:pointer;opacity:.85">&#10005;</span></div><div id="chatMsgs" style="flex:1;overflow-y:auto;padding:.6rem;display:flex;flex-direction:column;gap:.4rem;font-size:.85rem"></div><div style="display:flex;gap:.4rem;padding:.5rem;border-top:1px solid #e6e9ef"><input id="chatInput" placeholder="Type a message..." style="flex:1;padding:.5rem;border:1px solid #e6e9ef;border-radius:8px;font-size:.85rem;outline:none"><button id="chatSend" style="background:#FFC708;border:none;border-radius:8px;padding:.5rem .85rem;font-weight:700;cursor:pointer">Send</button></div>';
  247. document.body.appendChild(p);
  248. document.getElementById('chatSend').onclick=sendChat;
  249. document.getElementById('chatClose').onclick=toggleChat;
  250. document.getElementById('chatInput').addEventListener('keydown',e=>{if(e.key==='Enter')sendChat();});
  251. }
  252. function toggleChat(){const p=document.getElementById('chatPanel');if(!p)return;chatOpen=!chatOpen;p.style.display=chatOpen?'flex':'none';const b=document.getElementById('chatBtn');if(chatOpen){b&&(b.style.background='#475569');const i=document.getElementById('chatInput');if(i)setTimeout(()=>i.focus(),50);}}
  253. function addChat(msg){const c=document.getElementById('chatMsgs');if(!c)return;const mine=msg.from==='__self';const w=document.createElement('div');w.style.cssText='max-width:85%;padding:.4rem .6rem;border-radius:10px;'+(mine?'align-self:flex-end;background:#EAF0FB;color:#16294f':'align-self:flex-start;background:#f1f5f9;color:#1f2430');w.innerHTML='<div style="font-size:.7rem;opacity:.65;margin-bottom:2px">'+esc(msg.name||'')+'</div>'+esc(msg.text);c.appendChild(w);c.scrollTop=c.scrollHeight;if(!mine)notifyMsg(msg);}
  254. function notifyMsg(msg){const b=document.getElementById('chatBtn');if(b&&!chatOpen){b.style.background='#FFC708';b.style.color='#1f2430';}toast((msg.name||'Message')+': '+msg.text);try{beep();}catch(_){}if('Notification' in window && Notification.permission==='granted' && (document.hidden||!chatOpen)){try{new Notification('New message from '+(msg.name||'support'),{body:msg.text});}catch(_){}}}
  255. function toast(text){let t=document.getElementById('msgToast');if(!t){t=document.createElement('div');t.id='msgToast';t.style.cssText='position:fixed;top:18px;left:50%;transform:translateX(-50%);z-index:2147483600;background:#16a34a;color:#fff;padding:.7rem 1.1rem;border-radius:12px;box-shadow:0 10px 26px rgba(0,0,0,.35);font-size:.92rem;font-weight:600;border:2px solid #0c7a36;max-width:82vw;transition:opacity .4s';document.body.appendChild(t);}t.innerHTML='\ud83d\udcac '+text;t.style.opacity='1';clearTimeout(window.__toastT);window.__toastT=setTimeout(()=>{t.style.opacity='0';},2800);}
  256. let __ac=null;
  257. function ensureAudio(){try{__ac=__ac||new (window.AudioContext||window.webkitAudioContext)();if(__ac.state==='suspended')__ac.resume();}catch(_){}}
  258. function beep(){ensureAudio();if(!__ac)return;try{const o=__ac.createOscillator(),g=__ac.createGain();o.type='sine';o.connect(g);g.connect(__ac.destination);const t0=__ac.currentTime;o.frequency.setValueAtTime(880,t0);o.frequency.setValueAtTime(660,t0+0.09);g.gain.setValueAtTime(0.0001,t0);g.gain.exponentialRampToValueAtTime(0.12,t0+0.02);g.gain.exponentialRampToValueAtTime(0.0001,t0+0.22);o.start(t0);o.stop(t0+0.24);}catch(_){}}
  259. try{['pointerdown','keydown','touchstart','click'].forEach(ev=>document.addEventListener(ev,ensureAudio,{passive:true}));}catch(_){}
  260. function sendChat(){const i=document.getElementById('chatInput');if(!i)return;const t=i.value.trim();if(!t)return;if(chatChannel&&chatChannel.readyState==='open'){chatChannel.send(JSON.stringify({name:SHARER_NAME,text:t}));}addChat({from:'__self',name:'You',text:t});i.value='';}
  261. function removeSessionUI(){['sessionBar','chatPanel','remoteAudio','muteBtn','msgToast'].forEach(id=>{const e=document.getElementById(id);if(e)e.remove();});}
  262. function esc(s){return String(s).replace(/[&<>"]/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));}
  263. </script>
  264. </body>
  265. </html>