sls/resources/views/interview/candidate_room.blade.php
2026-08-03 13:46:39 +05:30

2061 lines
96 KiB
PHP

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Live Assessment Room - {{ $interview->candidate_name }} | SingleLogin</title>
@vite(['resources/css/app.css', 'resources/js/app.js'])
<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=Fira+Code:wght@400;500;600&family=Instrument+Sans:wght@400;500;600;700&family=Outfit:wght@500;600;700&display=swap" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<!-- Monaco Code Editor Loader & PeerJS Realtime WebRTC Call & SweetAlert2 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs/loader.min.js"></script>
<script src="https://unpkg.com/peerjs@1.5.2/dist/peerjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
<style>
:root {
--bg-color: #080c14;
--card-bg: #0f172a;
--card-border: rgba(255, 255, 255, 0.15);
--accent-primary: #6366f1;
}
/* Modern Custom Scrollbars */
html, body, *, ::-webkit-scrollbar {
scrollbar-width: thin;
scrollbar-color: rgba(255, 255, 255, 0.4) rgba(15, 23, 42, 0.35);
}
::-webkit-scrollbar {
width: 5px;
height: 5px;
}
::-webkit-scrollbar-track {
background: rgba(15, 23, 42, 0.35);
}
::-webkit-scrollbar-thumb {
background: rgba(255, 255, 255, 0.4);
border-radius: 10px;
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: 'Instrument Sans', sans-serif;
background-color: var(--bg-color);
color: white;
height: 100vh;
display: flex;
flex-direction: column;
overflow: hidden;
}
.ide-header {
height: 60px;
background: #0d1322;
border-bottom: 1px solid var(--card-border);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 20px;
}
.ide-layout {
display: grid;
grid-template-columns: 1fr 340px;
height: calc(100vh - 60px);
width: 100%;
}
.editor-section {
display: flex;
flex-direction: column;
border-right: 1px solid var(--card-border);
height: 100%;
}
#monaco-editor-container {
flex: 1;
width: 100%;
height: 100%;
}
.terminal-section {
height: 220px;
background: #050811;
border-top: 1px solid var(--card-border);
display: flex;
flex-direction: column;
}
.terminal-header {
height: 36px;
background: #090e1a;
border-bottom: 1px solid rgba(255,255,255,0.08);
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 16px;
font-size: 0.75rem;
color: #94a3b8;
font-weight: 600;
}
#terminal-output {
flex: 1;
padding: 12px 16px;
font-family: 'Fira Code', monospace;
font-size: 0.8rem;
color: #34d399;
overflow-y: auto;
white-space: pre-wrap;
}
.proctor-sidebar {
background: #0d1322;
padding: 16px;
display: flex;
flex-direction: column;
gap: 16px;
overflow-y: auto;
}
.webcam-box {
width: 100%;
height: 180px;
min-height: 180px;
flex-shrink: 0;
background: #000;
border-radius: 12px;
border: 2px solid var(--card-border);
overflow: hidden;
position: relative;
}
#webcam {
width: 100%;
height: 100%;
object-fit: cover;
}
.btn-ide {
padding: 8px 16px;
border-radius: 8px;
font-weight: 600;
font-size: 0.8rem;
cursor: pointer;
border: 1px solid var(--card-border);
background: rgba(255,255,255,0.05);
color: white;
transition: all 0.2s ease;
}
.btn-ide-primary {
background: #10b981;
border-color: #10b981;
color: white;
}
.btn-ide-run {
background: #6366f1;
border-color: #6366f1;
color: white;
}
/* Warning Popup Overlay */
#warning-banner {
position: fixed;
top: 70px;
left: 50%;
transform: translateX(-50%);
background: rgba(239, 68, 68, 0.95);
color: white;
padding: 12px 24px;
border-radius: 12px;
font-weight: 700;
font-size: 0.9rem;
box-shadow: 0 10px 30px rgba(239, 68, 68, 0.5);
z-index: 9999;
display: none;
backdrop-filter: blur(10px);
}
</style>
</head>
<body>
<!-- IDE Header Bar -->
<header class="ide-header">
<div style="display: flex; align-items: center; gap: 12px;">
<div style="font-weight: 700; font-family: 'Outfit', sans-serif; font-size: 1.05rem; color: white;">
Candidate Assessment Room
</div>
<code style="background: rgba(255,255,255,0.06); padding: 4px 10px; border-radius: 6px; color: #38bdf8; font-size: 0.75rem;">
ID: {{ $interview->submission_unique_id }}
</code>
</div>
<div style="display: flex; align-items: center; gap: 14px;">
<button onclick="toggleNotepadModal()" class="btn-ide" style="background: rgba(99,102,241,0.2); border-color: #6366f1;">
📝 Open Notepad
</button>
<button onclick="toggleDrawingModal()" class="btn-ide" style="background: rgba(6,182,212,0.2); border-color: #06b6d4;">
🎨 Open Drawing
</button>
<div style="display: flex; align-items: center; gap: 8px;">
<label style="font-size: 0.75rem; color: #94a3b8; font-weight: 500;">Language:</label>
<select id="language-select" class="btn-ide" style="background: #151b2c;">
<option value="python" {{ strtolower($interview->language) === 'python' ? 'selected' : '' }}>Python 3</option>
<option value="cpp" {{ strtolower($interview->language) === 'cpp' ? 'selected' : '' }}>C++ (GCC)</option>
<option value="c" {{ strtolower($interview->language) === 'c' ? 'selected' : '' }}>C (GCC)</option>
<option value="java" {{ strtolower($interview->language) === 'java' ? 'selected' : '' }}>Java 15</option>
<option value="php" {{ strtolower($interview->language) === 'php' ? 'selected' : '' }}>PHP 8.2 / Laravel</option>
<option value="javascript" {{ strtolower($interview->language) === 'javascript' ? 'selected' : '' }}>JavaScript (Node.js)</option>
</select>
</div>
<button onclick="runCode()" class="btn-ide btn-ide-run">
Run Code
</button>
<button onclick="submitSolution()" class="btn-ide btn-ide-primary">
Submit Final Solution
</button>
<button onclick="candidateLogoutAction()" class="btn-ide" style="background: rgba(239,68,68,0.2); border-color: #ef4444; color: #fca5a5; font-weight: 700;">
🚪 Logout
</button>
</div>
</header>
<!-- Candidate Notepad Modal -->
<div id="notepad-modal" style="position: fixed; top: 70px; right: 360px; width: 420px; height: 350px; background: #0f172a; border: 1.5px solid #6366f1; border-radius: 16px; box-shadow: 0 20px 40px rgba(0,0,0,0.6); display: none; flex-direction: column; z-index: 1000; overflow: hidden;">
<div style="background: #1e293b; padding: 10px 16px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(255,255,255,0.1);">
<div style="font-weight: 700; font-size: 0.85rem; color: white;">📝 Candidate Notepad (Synced)</div>
<button onclick="toggleNotepadModal()" style="background: none; border: none; color: #94a3b8; font-size: 1.2rem; cursor: pointer;">&times;</button>
</div>
<textarea id="notepad-textarea" oninput="saveNotepadContent()" placeholder="Type rough notes, pseudo-code, or thoughts here..." style="flex: 1; width: 100%; padding: 14px; background: #0b0f19; color: #e2e8f0; border: none; outline: none; font-family: 'Fira Code', monospace; font-size: 0.85rem; resize: none;">{{ $interview->candidate_notes }}</textarea>
<div style="padding: 6px 12px; background: #0d1322; font-size: 0.65rem; color: #34d399; text-align: right;">
Auto-saved to interviewer portal
</div>
</div>
<!-- Candidate Canvas Drawing Modal -->
<div id="drawing-modal" style="position: fixed; top: 70px; right: 360px; width: 550px; height: 420px; background: #0f172a; border: 1.5px solid #06b6d4; border-radius: 16px; box-shadow: 0 20px 40px rgba(0,0,0,0.6); display: none; flex-direction: column; z-index: 1000; overflow: hidden;">
<div style="background: #1e293b; padding: 10px 16px; display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid rgba(255,255,255,0.1);">
<div style="font-weight: 700; font-size: 0.85rem; color: white;">🎨 Candidate Live Drawing Board</div>
<div style="display: flex; gap: 8px; align-items: center;">
<input type="color" id="draw-color" value="#38bdf8" style="width: 26px; height: 26px; border: none; border-radius: 50%; cursor: pointer;">
<button onclick="clearCanvasDraw()" class="btn-ide" style="padding: 2px 8px; font-size: 0.7rem;">Clear</button>
<button onclick="toggleDrawingModal()" style="background: none; border: none; color: #94a3b8; font-size: 1.2rem; cursor: pointer;">&times;</button>
</div>
</div>
<div style="flex: 1; background: #050811; position: relative;">
<canvas id="drawing-canvas" width="550" height="340" style="cursor: crosshair; display: block; width: 100%; height: 100%;"></canvas>
</div>
<div style="padding: 6px 12px; background: #0d1322; font-size: 0.65rem; color: #38bdf8; text-align: right;">
🎨 Draw architecture / logic diagrams (Auto-synced to Interviewer)
</div>
</div>
<!-- IDE Room Layout -->
<div class="ide-layout">
<!-- Main Editor & Terminal Area -->
<div class="editor-section">
<div id="monaco-editor-container"></div>
<div class="terminal-section">
<div class="terminal-header">
<span>EXECUTION OUTPUT TERMINAL (STDOUT / STDERR)</span>
<span id="run-status" style="color: #94a3b8;">Ready</span>
</div>
<div id="terminal-output">// Press 'Run Code' to execute candidate solution live...</div>
</div>
</div>
@php
$words = preg_split('/\s+/', trim($interview->candidate_name));
if (count($words) >= 2) {
$candInitials = strtoupper(substr($words[0], 0, 1) . substr(end($words), 0, 1));
} else {
$nameStr = trim($interview->candidate_name);
$candInitials = strtoupper(substr($nameStr, 0, 1) . (strlen($nameStr) > 1 ? substr($nameStr, -1) : ''));
}
@endphp
<!-- Sidebar: Real-Time 2-Way Interview Call & Screen Share -->
<div class="proctor-sidebar">
<!-- Candidate Camera Feed -->
<div class="webcam-box" style="position: relative;">
<video id="webcam" autoplay muted playsinline style="width: 100%; height: 100%; object-fit: cover;"></video>
<div id="webcam-avatar-placeholder" style="position: absolute; inset: 0; display: none; flex-direction: column; align-items: center; justify-content: center; background: #0f172a; color: white; z-index: 5;">
<div style="width: 60px; height: 60px; border-radius: 50%; background: linear-gradient(135deg, #6366f1 0%, #0078d4 100%); display: flex; align-items: center; justify-content: center; font-size: 1.5rem; font-weight: 800; font-family: 'Outfit', sans-serif; box-shadow: 0 0 15px rgba(99,102,241,0.4);">
{{ $candInitials }}
</div>
<div style="font-size: 0.7rem; color: #94a3b8; margin-top: 6px;">Camera Disabled</div>
</div>
<div style="position: absolute; bottom: 8px; left: 8px; background: rgba(0,0,0,0.6); padding: 2px 8px; border-radius: 4px; font-size: 0.65rem; color: #34d399; font-weight: 600; z-index: 10;">
📷 Candidate Camera
</div>
</div>
<!-- Remote Interviewer Video Feed (Live 2-Way Call) -->
<div class="webcam-box" style="position: relative; border-color: #6366f1;">
<video id="interviewer-video" autoplay playsinline style="width: 100%; height: 100%; object-fit: cover; background: #050811;"></video>
<div id="interviewer-video-placeholder" style="position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; background: rgba(15,23,42,0.95); color: #94a3b8; font-size: 0.75rem; text-align: center; padding: 10px; z-index: 5;">
<div id="interviewer-avatar-circle" style="width: 60px; height: 60px; border-radius: 50%; background: linear-gradient(135deg, #38bdf8 0%, #6366f1 100%); display: flex; align-items: center; justify-content: center; font-size: 1.5rem; font-weight: 800; font-family: 'Outfit', sans-serif; color: white; margin-bottom: 6px; box-shadow: 0 0 15px rgba(56,189,248,0.4);">
IV
</div>
<div id="call-status-sub" style="font-size: 0.7rem; color: #e2e8f0; font-weight: 600;">Interviewer Video Feed</div>
<div style="font-size: 0.65rem; color: #38bdf8; margin-top: 2px;">Waiting for panelist to join call...</div>
</div>
<div style="position: absolute; bottom: 8px; left: 8px; background: rgba(99,102,241,0.8); padding: 2px 8px; border-radius: 4px; font-size: 0.65rem; color: white; font-weight: 600; z-index: 10;">
🎙️ Interviewer / Panelist
</div>
</div>
<canvas id="proctor-canvas" style="display: none;" width="320" height="240"></canvas>
<!-- Candidate Profile Info -->
<div style="background: rgba(255,255,255,0.03); border: 1px solid var(--card-border); border-radius: 12px; padding: 14px; font-size: 0.8rem;">
<div style="font-weight: 700; color: white; margin-bottom: 6px;">Candidate Profile</div>
<div style="color: #94a3b8;">Name: <strong style="color: white;">{{ $interview->candidate_name }}</strong></div>
<div style="color: #94a3b8;">Email: <span style="color: white;">{{ $interview->candidate_email }}</span></div>
<div style="color: #94a3b8; margin-top: 6px;">Access Expires: <span style="color: #fca5a5;">{{ $interview->expires_at->format('H:i:s T') }}</span></div>
</div>
<!-- Real-Time Call Controls (Mic, Camera, Screen Sharing) -->
<div style="background: rgba(99,102,241,0.1); border: 1px solid rgba(99,102,241,0.3); border-radius: 14px; padding: 14px;">
<div style="font-size: 0.8rem; font-weight: 700; color: white; margin-bottom: 10px; display: flex; align-items: center; justify-content: space-between;">
<span>📞 Real-Time Interview Call</span>
<span id="call-status-badge" style="font-size: 0.65rem; background: rgba(16,185,129,0.2); color: #34d399; padding: 2px 8px; border-radius: 999px;">READY</span>
</div>
<button id="candidate-join-active-call-btn" onclick="acceptCandidateCall()" class="btn-ide" style="display: none; width: 100%; padding: 10px; margin-bottom: 10px; font-size: 0.8rem; font-weight: 700; background: linear-gradient(135deg, #10b981 0%, #059669 100%); color: white; border: none; box-shadow: 0 0 15px rgba(16,185,129,0.4); cursor: pointer; animation: acceptGlow 1.5s infinite alternate;">
🟢 📞 Call in Progress &bull; Join Call Now
</button>
<div style="display: flex; gap: 8px; margin-bottom: 10px;">
<button id="toggle-mic-btn" onclick="toggleMic()" class="btn-ide" style="flex: 1; padding: 8px; font-size: 0.75rem; background: rgba(16,185,129,0.2); border-color: #10b981;">
🎤 Mic On
</button>
<button id="toggle-cam-btn" onclick="toggleCam()" class="btn-ide" style="flex: 1; padding: 8px; font-size: 0.75rem; background: rgba(16,185,129,0.2); border-color: #10b981;">
📷 Cam On
</button>
<button id="leave-call-btn" onclick="candidateLeaveCall()" class="btn-ide" style="padding: 8px; font-size: 0.75rem; background: rgba(239,68,68,0.2); border-color: #ef4444; color: #fca5a5;" title="Leave 2-Way Call">
🚪 Leave Call
</button>
</div>
<button id="share-screen-btn" onclick="startScreenShare()" class="btn-ide btn-ide-run" style="width: 100%; padding: 10px; font-size: 0.8rem; background: linear-gradient(135deg, #6366f1 0%, #0078d4 100%);">
🖥️ Share Screen with Interviewer
</button>
</div>
<!-- 2-Way Real-Time Chat Container with Interviewer/Panelist -->
<div style="background: rgba(15,23,42,0.8); border: 1px solid var(--card-border); border-radius: 14px; padding: 12px; margin-top: 10px;">
<div style="font-size: 0.8rem; font-weight: 700; color: white; margin-bottom: 8px; display: flex; align-items: center; gap: 6px;">
💬 Live Chat with Interviewer
</div>
<div id="candidate-chat-history" style="background: #050811; border: 1px solid var(--card-border); border-radius: 10px; padding: 8px; height: 130px; overflow-y: auto; font-size: 0.72rem; margin-bottom: 8px;">
<div style="color: #94a3b8; font-style: italic; text-align: center; padding-top: 40px;">No messages yet. Send a message below.</div>
</div>
<div style="display: flex; gap: 6px;">
<input type="text" id="candidate-chat-input" placeholder="Type message to panelist..." onkeydown="if(event.key==='Enter') sendCandidateMessage()" class="form-input" style="font-size: 0.75rem; background: #0b0f19; color: #ffffff !important; border: 1px solid var(--card-border); padding: 6px 10px; flex: 1;">
<button onclick="sendCandidateMessage()" class="btn-ide" style="padding: 6px 10px; font-size: 0.75rem; background: #6366f1; border: none; font-weight: 600;">
Send
</button>
</div>
</div>
</div>
</div>
<!-- CANDIDATE INCOMING CALL MODAL / RINGING OVERLAY -->
<div id="candidate-incoming-modal" style="position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(5, 8, 17, 0.85); backdrop-filter: blur(16px); display: flex; align-items: center; justify-content: center; z-index: 10000; opacity: 0; pointer-events: none; transition: opacity 0.3s ease;">
<div style="max-width: 440px; width: 90%; background: linear-gradient(145deg, #0f172a 0%, #1e1b4b 100%); border: 2px solid #10b981; border-radius: 24px; padding: 32px; text-align: center; color: white; box-shadow: 0 0 50px rgba(16, 185, 129, 0.6);">
<div style="position: relative; width: 90px; height: 90px; margin: 0 auto 20px auto; display: flex; align-items: center; justify-content: center;">
<div style="position: absolute; inset: -15px; border-radius: 50%; border: 2px solid rgba(16, 185, 129, 0.6); animation: ringPulse 1.4s infinite ease-out;"></div>
<div style="position: absolute; inset: -30px; border-radius: 50%; border: 2px solid rgba(99, 102, 241, 0.4); animation: ringPulse 1.4s infinite ease-out 0.4s;"></div>
<div style="width: 80px; height: 80px; border-radius: 50%; background: linear-gradient(135deg, #10b981 0%, #0078d4 100%); display: flex; align-items: center; justify-content: center; font-size: 2.4rem; font-weight: 800; color: white; box-shadow: 0 10px 25px rgba(16, 185, 129, 0.5); z-index: 5;">
📞
</div>
</div>
<div style="font-size: 0.75rem; text-transform: uppercase; letter-spacing: 1.5px; color: #34d399; font-weight: 800; margin-bottom: 6px;">
INCOMING INTERVIEW CALL
</div>
<h3 style="font-family: 'Outfit', sans-serif; font-size: 1.4rem; font-weight: 800; color: white; margin-bottom: 4px;">
Interviewer Panel Calling...
</h3>
<div style="font-size: 0.8rem; color: #a5b4fc; margin-bottom: 20px;">
The interviewer panel has initiated a live 2-way call.
</div>
<div style="display: flex; gap: 12px; margin-top: 10px;">
<button onclick="declineCandidateCall()" style="flex: 1; padding: 14px; background: rgba(239, 68, 68, 0.2); border: 1.5px solid #ef4444; color: #fca5a5; font-weight: 700; font-size: 0.9rem; border-radius: 14px; cursor: pointer;">
🛑 Decline / Busy
</button>
<button onclick="acceptCandidateCall()" style="flex: 1.4; padding: 14px; background: linear-gradient(135deg, #10b981 0%, #059669 100%); border: none; color: white; font-weight: 800; font-size: 0.95rem; border-radius: 14px; box-shadow: 0 0 25px rgba(16, 185, 129, 0.6); cursor: pointer; animation: acceptGlow 1.5s infinite alternate;">
📞 Accept Call
</button>
</div>
</div>
</div>
<script>
let editor;
let interviewId = {{ $interview->id }};
let mediaRecorder;
let recordedChunks = [];
let previousFrameData = null;
const defaultCode = {
python: "# Python 3 Assessment Solution\ndef main():\n print(\"Hello from SingleLogin Assessment!\")\n num = 42\n print(f\"Computed Result: {num * 2}\")\n\nif __name__ == \"__main__\":\n main()",
cpp: "// C++ Assessment Solution\n#include <iostream>\nusing namespace std;\n\nint main() {\n cout << \"Hello from SingleLogin Assessment!\" << endl;\n return 0;\n}",
c: "// C Assessment Solution\n#include <stdio.h>\n\nint main() {\n printf(\"Hello from SingleLogin Assessment!\\n\");\n return 0;\n}",
java: "// Java Assessment Solution\npublic class Solution {\n public static void main(String[] args) {\n System.out.println(\"Hello from SingleLogin Assessment!\");\n }\n}",
php: "<\x3fphp\n// PHP / Laravel Assessment Solution\necho \"Hello from SingleLogin Assessment!\\n\";\n$data = [1, 2, 3, 4, 5];\necho \"Sum: \" . array_sum($data);",
javascript: "// JavaScript (Node.js) Solution\nconsole.log(\"Hello from SingleLogin Assessment!\");\nconst nums = [10, 20, 30];\nconsole.log(\"Total:\", nums.reduce((a, b) => a + b, 0));"
};
require.config({ paths: { vs: 'https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs' } });
require(['vs/editor/editor.main'], function () {
const initialLang = '{{ strtolower($interview->language) }}';
const initialCode = {!! json_encode($interview->submitted_code) !!} || defaultCode[initialLang] || defaultCode.python;
editor = monaco.editor.create(document.getElementById('monaco-editor-container'), {
value: initialCode,
language: initialLang === 'cpp' ? 'cpp' : (initialLang === 'c' ? 'c' : initialLang),
theme: 'vs-dark',
fontSize: 14,
fontFamily: 'Fira Code, monospace',
automaticLayout: true,
minimap: { enabled: true }
});
// Intercept AI Hotkeys inside Monaco Editor
editor.onKeyDown(function (e) {
const isAlt = e.altKey;
const isCtrl = e.ctrlKey;
const isMeta = e.metaKey;
const isShift = e.shiftKey;
const code = e.browserEvent ? (e.browserEvent.code || '') : '';
if (isAlt || isMeta || (isCtrl && isShift) || code === 'F12') {
logViolation('external_ai_detected', `Parakeet AI / External AI Hotkey Intercepted in Editor (${code || e.keyCode}): Candidate activated external AI shortcut`);
captureAndUploadTabScreenshot();
}
});
// Real-Time Instant BroadcastChannel + Backend Code Sync
const liveSyncChannel = new BroadcastChannel('live_sync_' + '{{ $interview->id }}');
liveSyncChannel.onmessage = function(event) {
if (event.data && event.data.type === 'chat_message' && typeof pollCandidateChat === 'function') {
pollCandidateChat();
}
};
let codeSyncTimeout = null;
editor.onDidChangeModelContent(function () {
const code = editor.getValue();
const lang = document.getElementById('language-select').value;
// Broadcast instant local event (0ms latency)
if (typeof liveSyncChannel !== 'undefined' && liveSyncChannel) {
liveSyncChannel.postMessage({ type: 'code_sync', code: code, language: lang });
}
clearTimeout(codeSyncTimeout);
codeSyncTimeout = setTimeout(function () {
fetch(`{{ route("interview.candidate.sync-code", $interview->id) }}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ code: code, language: lang })
});
}, 200);
});
});
// Handle Language Switch
document.getElementById('language-select').addEventListener('change', function () {
const lang = this.value;
const monacoLang = lang === 'cpp' ? 'cpp' : (lang === 'c' ? 'c' : lang);
monaco.editor.setModelLanguage(editor.getModel(), monacoLang);
if (!editor.getValue() || editor.getValue() === defaultCode[lang]) {
editor.setValue(defaultCode[lang] || '');
}
});
// Execute Code live via Piston/Judge0 Engine
function runCode() {
document.getElementById('run-status').innerText = 'Running...';
document.getElementById('terminal-output').innerText = 'Executing solution on code engine...';
const lang = document.getElementById('language-select').value;
const code = editor.getValue();
fetch('{{ route("interview.execute") }}', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ language: lang, code: code, interview_id: '{{ $interview->id }}' })
})
.then(r => r.json())
.then(data => {
document.getElementById('run-status').innerText = 'Ready';
const outStr = data.success ? data.output : ('Error: ' + data.output);
document.getElementById('terminal-output').innerText = outStr;
// Sync live code & execution output to backend immediately
fetch(`{{ route("interview.candidate.sync-code", $interview->id) }}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ code: code, language: lang, output: outStr })
});
})
.catch(err => {
document.getElementById('run-status').innerText = 'Error';
document.getElementById('terminal-output').innerText = 'Failed to reach code runner service.';
});
}
// Submit Solution
function submitSolution() {
const code = editor.getValue();
const lang = document.getElementById('language-select').value;
const output = document.getElementById('terminal-output').innerText;
fetch(`{{ route('interview.submit', $interview->id) }}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ code: code, language: lang, output: output })
})
.then(r => r.json())
.then(data => {
alert('✓ ' + data.message);
});
}
let isTabSwitchScreenshotEnabled = true;
let lastTabSwitchTime = 0;
let latestCallStatus = '{{ $interview->call_status ?? "idle" }}';
let screenShareVideoElem = null;
// Auto-initialize persistent offscreen video element for screen share capture
function getScreenShareVideoElement() {
if (!screenShareVideoElem) {
screenShareVideoElem = document.createElement('video');
screenShareVideoElem.autoplay = true;
screenShareVideoElem.muted = true;
screenShareVideoElem.playsInline = true;
screenShareVideoElem.style.position = 'fixed';
screenShareVideoElem.style.top = '-9999px';
screenShareVideoElem.style.left = '-9999px';
screenShareVideoElem.style.width = '1px';
screenShareVideoElem.style.height = '1px';
document.body.appendChild(screenShareVideoElem);
}
return screenShareVideoElem;
}
// REAL CANDIDATE SYSTEM / COMPUTER SCREENSHOT CAPTURE ENGINE
function captureAndUploadTabScreenshot(reason = 'tab_switch') {
if (!isTabSwitchScreenshotEnabled) return;
try {
const tempCanvas = document.createElement('canvas');
let drewScreenStream = false;
const isCallStart = (reason === 'call_start');
const bannerLabel = isCallStart
? '📸 CALL STARTED • CANDIDATE SYSTEM SCREEN SNAPSHOT • ' + new Date().toLocaleString()
: '🚨 CANDIDATE SYSTEM COMPUTER DESKTOP SNAPSHOT • ' + new Date().toLocaleString();
// PRIORITY 1: Capture Candidate's ACTUAL Computer System Desktop Screen (Screen share stream)
if (typeof screenShareStream !== 'undefined' && screenShareStream && screenShareStream.getVideoTracks().length > 0) {
const screenTrack = screenShareStream.getVideoTracks()[0];
if (screenTrack.readyState === 'live') {
try {
const vidElem = getScreenShareVideoElement();
if (vidElem.srcObject !== screenShareStream) {
vidElem.srcObject = screenShareStream;
vidElem.play().catch(e => {});
}
let rawW = vidElem.videoWidth || 1280;
let rawH = vidElem.videoHeight || 720;
if (rawW > 0 && rawH > 0) {
const maxW = 1280;
let targetW = rawW;
let targetH = rawH;
if (targetW > maxW) {
targetH = Math.round(targetH * (maxW / targetW));
targetW = maxW;
}
tempCanvas.width = targetW;
tempCanvas.height = targetH;
const tempCtx = tempCanvas.getContext('2d');
tempCtx.drawImage(vidElem, 0, 0, targetW, targetH);
// Add system screenshot banner
tempCtx.fillStyle = 'rgba(15, 23, 42, 0.90)';
tempCtx.fillRect(0, tempCanvas.height - 42, tempCanvas.width, 42);
tempCtx.fillStyle = isCallStart ? '#10b981' : '#ef4444';
tempCtx.font = 'bold 14px sans-serif';
tempCtx.fillText(bannerLabel, 16, tempCanvas.height - 15);
uploadTabScreenshotBlob(tempCanvas.toDataURL('image/jpeg', 0.75), reason);
drewScreenStream = true;
}
} catch(e) {
console.log('Screen stream draw exception:', e);
}
}
}
if (drewScreenStream) return;
// PRIORITY 2: Full Rendered DOM Workspace Capture via html2canvas
if (typeof html2canvas !== 'undefined') {
html2canvas(document.body, { logging: false, useCORS: true, allowTaint: true, scale: 0.85 }).then(canvas => {
const ctx = canvas.getContext('2d');
ctx.fillStyle = 'rgba(15, 23, 42, 0.90)';
ctx.fillRect(0, canvas.height - 42, canvas.width, 42);
ctx.fillStyle = isCallStart ? '#10b981' : '#ef4444';
ctx.font = 'bold 14px sans-serif';
ctx.fillText(bannerLabel, 16, canvas.height - 15);
uploadTabScreenshotBlob(canvas.toDataURL('image/jpeg', 0.75), reason);
}).catch(err => {
fallbackCompositeSnapshot(reason);
});
} else {
fallbackCompositeSnapshot(reason);
}
} catch(e) {
console.log('Candidate system screenshot capture exception:', e);
}
}
function fallbackCompositeSnapshot(reason = 'tab_switch') {
const tempCanvas = document.createElement('canvas');
const w = 1280;
const h = 720;
tempCanvas.width = w;
tempCanvas.height = h;
const tempCtx = tempCanvas.getContext('2d');
tempCtx.fillStyle = '#0b0f19';
tempCtx.fillRect(0, 0, w, h);
tempCtx.fillStyle = '#1e293b';
tempCtx.fillRect(0, 0, w, 50);
tempCtx.fillStyle = '#38bdf8';
tempCtx.font = 'bold 16px sans-serif';
tempCtx.fillText('💻 Candidate System Workspace • ID: ' + (typeof interviewId !== 'undefined' ? interviewId : ''), 20, 32);
const codeDisplay = document.querySelector('.CodeMirror') || document.getElementById('code-editor');
tempCtx.fillStyle = '#020617';
tempCtx.fillRect(20, 70, w - 40, h - 130);
tempCtx.fillStyle = '#94a3b8';
tempCtx.font = '13px monospace';
const codeText = codeDisplay ? (codeDisplay.innerText || codeDisplay.value || '') : (typeof editor !== 'undefined' && editor ? editor.getValue() : '');
const lines = codeText.split('\n').slice(0, 30);
lines.forEach((line, i) => {
tempCtx.fillText(line.substring(0, 120), 35, 95 + (i * 18));
});
// Candidate webcam feed is explicitly omitted to ensure screenshot is candidate system screen ONLY
const isCallStart = (reason === 'call_start');
tempCtx.fillStyle = 'rgba(15, 23, 42, 0.90)';
tempCtx.fillRect(0, tempCanvas.height - 42, tempCanvas.width, 42);
tempCtx.fillStyle = isCallStart ? '#10b981' : '#ef4444';
tempCtx.font = 'bold 14px sans-serif';
const text = isCallStart
? '📸 CALL STARTED • CANDIDATE SYSTEM SNAPSHOT • ' + new Date().toLocaleString()
: '🚨 CANDIDATE SYSTEM SNAPSHOT • ' + new Date().toLocaleString();
tempCtx.fillText(text, 16, tempCanvas.height - 15);
uploadTabScreenshotBlob(tempCanvas.toDataURL('image/jpeg', 0.85), reason);
}
function uploadTabScreenshotBlob(imageData, reason = 'tab_switch') {
fetch(`{{ route('interview.upload-tab-screenshot', $interview->id) }}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ image: imageData, reason: reason })
})
.then(r => r.json())
.then(data => {
console.log('Candidate system screenshot saved:', data);
})
.catch(err => console.log('System screenshot fetch error:', err));
}
// 1. Tab Switch Detection (Captures Candidate's SYSTEM DESKTOP MONITOR screenshot)
document.addEventListener('visibilitychange', function () {
if (document.hidden) {
const now = Date.now();
if (now - lastTabSwitchTime > 1000) {
lastTabSwitchTime = now;
logViolation('tab_switch', 'Candidate switched browser tab or minimized window');
captureAndUploadTabScreenshot();
}
}
});
// 2. Window Focus Loss / External AI Overlay Application Switch Detection
window.addEventListener('blur', function () {
const now = Date.now();
if (now - lastTabSwitchTime > 1000) {
lastTabSwitchTime = now;
logViolation('external_ai_detected', 'PARAKEET AI / EXTERNAL APP OVERLAY DETECTED: Assessment window lost focus (Candidate interacting with external application overlay)');
captureAndUploadTabScreenshot();
}
});
// Mouse Viewport Departure (Candidate moving cursor outside window to interact with Parakeet AI or secondary app overlay)
document.addEventListener('mouseleave', function () {
const now = Date.now();
if (now - lastTabSwitchTime > 2500) {
lastTabSwitchTime = now;
logViolation('external_ai_detected', 'Candidate cursor departed assessment window viewport (suspected external Parakeet AI overlay interaction)');
captureAndUploadTabScreenshot();
}
});
// 3. Code Copy-Paste & Ingestion Detection
document.addEventListener('paste', function (e) {
logViolation('paste_event', 'Candidate pasted content into editor window (possible AI answer paste)');
});
// Question Selection / Copying Detection (Candidate copying questions to feed Parakeet AI)
document.addEventListener('copy', function (e) {
logViolation('copy_event', 'Candidate copied text from assessment window (possible Parakeet AI prompt ingestion)');
captureAndUploadTabScreenshot();
});
// 4. Parakeet AI & External AI Hotkey Interception (Window Capture Phase - Runs BEFORE any input elements absorb keys)
window.addEventListener('keydown', function (e) {
if (e.code === 'Tab' || e.key === 'Tab') return;
const key = (e.key || '').toLowerCase();
const code = (e.code || '').toLowerCase();
const isAlt = e.altKey;
const isCmd = e.metaKey;
const isCtrl = e.ctrlKey;
const isShift = e.shiftKey;
// Parakeet AI / Final Round AI / Otter / Copilot / Screenshot Hotkeys
const isAiHotkey = (isAlt && (key === ' ' || code === 'space' || key === 'p' || key === 'a' || key === 's' || key === 'c' || key === 'v' || key === 'q' || key === 'w' || key === 'e' || key === 'x' || key === 'z')) ||
(isCmd && (key === ' ' || code === 'space' || key === 'p' || key === 'a' || key === 's' || key === 'x')) ||
(isCtrl && isShift && (key === 'a' || key === 'p' || key === 's' || key === 'i' || key === 'c' || key === 'x')) ||
(isCmd && isShift && (key === 'a' || key === 'p' || key === 's' || key === 'x' || key === '4' || key === '3')) ||
(isCtrl && isAlt) ||
(key === 'f12' || code === 'f12' || key === 'f11' || code === 'f11');
if (isAiHotkey) {
logViolation('external_ai_detected', `Parakeet AI / External AI Hotkey Intercepted (${e.code || e.key}): Candidate activated external AI assistant overlay shortcut`);
captureAndUploadTabScreenshot();
}
}, true);
// 5. Parakeet AI / Injected Extension DOM Observer
try {
const aiMutationObserver = new MutationObserver(mutations => {
for (const mutation of mutations) {
for (const node of mutation.addedNodes) {
if (node.nodeType === 1) { // Element node
const nodeStr = ((node.id || '') + ' ' + (node.className || '') + ' ' + (node.getAttribute('src') || '')).toLowerCase();
if (nodeStr.includes('parakeet') || nodeStr.includes('finalround') || nodeStr.includes('copilot') || nodeStr.includes('ai-assistant') || nodeStr.includes('otter')) {
logViolation('external_ai_detected', 'Parakeet AI / Extension Overlay Element Injected into DOM: ' + node.tagName);
captureAndUploadTabScreenshot();
}
}
}
}
});
aiMutationObserver.observe(document.documentElement, { childList: true, subtree: true });
} catch(e) {}
// 6. Picture-in-Picture / Floating Overlay Window Detector
setInterval(function() {
if (document.pictureInPictureElement) {
logViolation('external_ai_detected', 'External Picture-in-Picture Floating Window Active: Suspected AI assistant overlay window');
}
}, 6000);
// --- ACCURATE EYE GAZE, 10-SECOND LOWER SCREEN STARE & QUESTION REPETITION DETECTION ---
let gazeDownwardCounter = 0;
let gazeDownwardDurationMs = 0;
let gazeFixedStaringCounter = 0;
let previousFramePixels = null;
function analyzeEyeGazeAndStaring() {
const video = document.getElementById('webcam');
const canvas = document.getElementById('proctor-canvas');
if (!video || !canvas || video.readyState !== 4) return;
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const pixels = imgData.data;
let totalDarkPixels = 0;
let lowerHalfDarkPixels = 0;
let sumY = 0;
let facePixelCount = 0;
const halfY = Math.floor(canvas.height * 0.50);
for (let y = 0; y < canvas.height; y += 2) {
for (let x = 0; x < canvas.width; x += 2) {
const idx = (y * canvas.width + x) * 4;
const r = pixels[idx];
const g = pixels[idx+1];
const b = pixels[idx+2];
const gray = (r + g + b) / 3;
// Detect dark facial features (eyes, eyebrows, pupils)
if (gray < 65) {
totalDarkPixels++;
if (y > halfY) lowerHalfDarkPixels++;
}
// Skin tone / face region centroid
if (r > 40 && g > 25 && b > 15 && (r > g) && (r > b) && Math.abs(r - g) > 10) {
sumY += y;
facePixelCount++;
}
}
}
const lowerDarkRatio = totalDarkPixels > 0 ? (lowerHalfDarkPixels / totalDarkPixels) : 0;
const faceYCentroid = facePixelCount > 0 ? (sumY / facePixelCount) : (canvas.height / 2);
// Candidate is looking at lower portion of screen / desk if face Y centroid is low or lower dark ratio is high
const isLookingDownAtLowerScreen = (faceYCentroid > (canvas.height * 0.52)) || (lowerDarkRatio > 0.35);
if (isLookingDownAtLowerScreen) {
gazeDownwardCounter++;
gazeDownwardDurationMs += 400;
// 2.4s initial alert
if (gazeDownwardCounter === 6) {
logViolation('gaze_anomaly', 'Candidate lowered eye gaze toward screen bottom or desk');
}
// 10.0s continuous lower screen stare alert (logs to proctor logs section in reviewer modal - SILENT FOR CANDIDATE)
if (gazeDownwardDurationMs >= 10000) {
gazeDownwardDurationMs = 0; // Reset timer for next 10s window if candidate continues looking down
logViolation('gaze_lower_device', 'Candidate continuously looking at lower portion of screen for 10s (suspected reading from mobile device or cheat sheet)');
}
} else {
gazeDownwardCounter = Math.max(0, gazeDownwardCounter - 1);
if (gazeDownwardCounter === 0) {
gazeDownwardDurationMs = 0;
}
}
// Fixed Screen Focus / Staring Check (10 seconds = 25 cycles * 400ms)
if (previousFramePixels) {
let frameDeltaSum = 0;
for (let i = 0; i < pixels.length; i += 16) {
frameDeltaSum += Math.abs(pixels[i] - previousFramePixels[i]);
}
const frameDelta = frameDeltaSum / (pixels.length / 16);
if (frameDelta >= 0.1 && frameDelta < 3.8) {
gazeFixedStaringCounter++;
if (gazeFixedStaringCounter === 25) { // 10.0 seconds of continuous fixed stare
logViolation('gaze_fixed_staring', 'Candidate maintaining fixed unnatural gaze (possible secondary screen/AI assistant)');
}
} else {
gazeFixedStaringCounter = Math.max(0, gazeFixedStaringCounter - 1);
}
}
previousFramePixels = new Uint8Array(pixels);
}
setInterval(analyzeEyeGazeAndStaring, 400);
// --- WEB SPEECH RECOGNITION FOR QUESTION REPETITION & AI SPEECH PROMPTING ---
let candidateSpeechHistory = [];
function initQuestionRepeatDetection() {
const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
if (!SpeechRecognition) return;
try {
const speechRec = new SpeechRecognition();
speechRec.continuous = true;
speechRec.interimResults = false;
speechRec.lang = 'en-US';
speechRec.onresult = function(event) {
for (let i = event.resultIndex; i < event.results.length; ++i) {
if (event.results[i].isFinal) {
const transcript = event.results[i][0].transcript.trim().toLowerCase();
if (transcript.length < 4) continue;
// Scrape current page text / candidate IDE problem prompt
const pageText = (document.body ? document.body.innerText : '').toLowerCase();
// Check fuzzy match against page text (if candidate is reading out question text)
const words = transcript.split(/\s+/).filter(w => w.length > 3);
let matchedWordCount = 0;
words.forEach(w => {
if (pageText.includes(w)) matchedWordCount++;
});
const isReadingQuestionOnScreen = words.length >= 3 && (matchedWordCount / words.length) >= 0.5;
// Check if candidate is repeating recent spoken text
const isRepeatedSpeech = candidateSpeechHistory.some(prev => {
return prev === transcript || (transcript.length > 8 && prev.includes(transcript)) || (prev.length > 8 && transcript.includes(prev));
});
candidateSpeechHistory.push(transcript);
if (candidateSpeechHistory.length > 15) candidateSpeechHistory.shift();
if (isReadingQuestionOnScreen || isRepeatedSpeech) {
if (gazeDownwardCounter > 3) {
logViolation('question_repeat_lower', `Candidate reading/repeating question ("${transcript}") while looking down at lower portion/mobile device`);
} else {
logViolation('question_repetition', `Candidate reading/repeating question out loud: "${transcript}" (suspected Parakeet AI speech prompt)`);
}
} else {
// Talking to someone else detection when speech is detected during non-call state
if (!isCandidateCallConnected && transcript.length > 10) {
logViolation('talking_secondary_person', `Candidate speaking out loud to secondary person in room: "${transcript}"`);
}
}
}
}
};
speechRec.onerror = function() {
setTimeout(() => { try { speechRec.start(); } catch(e) {} }, 4000);
};
speechRec.onend = function() {
setTimeout(() => { try { speechRec.start(); } catch(e) {} }, 1500);
};
speechRec.start();
} catch(e) {}
}
initQuestionRepeatDetection();
function logViolation(type, details) {
fetch(`{{ route('interview.violation', $interview->id) }}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ type: type, details: details })
});
// Post message over BroadcastChannel to alert interviewer dashboard real-time
if (typeof callSigChannel !== 'undefined' && callSigChannel) {
callSigChannel.postMessage({ type: 'violation_occurred', violation_type: type, details: details });
}
}
// --- CANDIDATE REAL-TIME CALL RINGTONE SYNTHESIZER ---
class CandRingtoneEngine {
constructor() {
this.ctx = null;
this.interval = null;
this.isPlaying = false;
}
init() {
try {
if (!this.ctx) {
const AudioCtx = window.AudioContext || window.webkitAudioContext;
this.ctx = new AudioCtx();
}
if (this.ctx && this.ctx.state === 'suspended') {
this.ctx.resume();
}
} catch(e) {}
}
start() {
this.init();
if (this.isPlaying) return;
this.isPlaying = true;
this.playTone();
if (this.interval) clearInterval(this.interval);
this.interval = setInterval(() => {
if (this.isPlaying) this.playTone();
}, 2400);
}
playTone() {
this.init();
if (!this.ctx || !this.isPlaying) return;
try {
const now = this.ctx.currentTime;
const osc1 = this.ctx.createOscillator();
const osc2 = this.ctx.createOscillator();
const gain = this.ctx.createGain();
osc1.type = 'sine';
osc2.type = 'sine';
osc1.frequency.setValueAtTime(523.25, now);
osc2.frequency.setValueAtTime(659.25, now);
gain.gain.setValueAtTime(0.001, now);
gain.gain.linearRampToValueAtTime(0.35, now + 0.08);
gain.gain.setValueAtTime(0.35, now + 1.1);
gain.gain.exponentialRampToValueAtTime(0.001, now + 1.3);
osc1.connect(gain);
osc2.connect(gain);
gain.connect(this.ctx.destination);
osc1.start(now);
osc2.start(now);
osc1.stop(now + 1.35);
osc2.stop(now + 1.35);
} catch(e) {}
}
stop() {
this.isPlaying = false;
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
}
}
}
const candRingtone = new CandRingtoneEngine();
['click', 'keydown', 'touchstart'].forEach(evt => {
document.addEventListener(evt, () => candRingtone.init(), { passive: true });
});
let isCandidateCallConnected = false;
let candidateDeclinedOrLeftCall = false;
let pendingOffer = null;
let candRingTimer = null;
let latestCallStartedAt = null;
function getCallSessionKey(timestamp) {
return 'handled_call_' + interviewId + '_' + (timestamp || latestCallStartedAt || 'active');
}
function triggerCandidateRing(offer = null, callStartedAt = null) {
if (isCandidateCallConnected) return;
if (latestCallStatus === 'ended' || latestCallStatus === 'idle') return;
if (callStartedAt) latestCallStartedAt = callStartedAt;
const sessionKey = getCallSessionKey(callStartedAt);
const isHandled = sessionStorage.getItem(sessionKey) === 'handled';
if (isHandled || candidateDeclinedOrLeftCall) {
showCandidateJoinOption();
return;
}
if (offer) pendingOffer = offer;
const badge = document.getElementById('call-status-badge');
if (badge) {
badge.innerText = '🔔 INCOMING CALL... RINGING';
badge.style.background = 'rgba(234,179,8,0.3)';
badge.style.color = '#fde047';
}
const modal = document.getElementById('candidate-incoming-modal');
if (modal) {
modal.style.opacity = '1';
modal.style.pointerEvents = 'auto';
}
candRingtone.start();
if (candRingTimer) clearTimeout(candRingTimer);
candRingTimer = setTimeout(() => {
stopCandidateRing();
}, 12000);
}
function declineCandidateCall() {
candRingtone.stop();
if (candRingTimer) {
clearTimeout(candRingTimer);
candRingTimer = null;
}
const sessionKey = getCallSessionKey();
sessionStorage.setItem(sessionKey, 'handled');
const modal = document.getElementById('candidate-incoming-modal');
if (modal) {
modal.style.opacity = '0';
modal.style.pointerEvents = 'none';
}
candidateDeclinedOrLeftCall = true;
showCandidateJoinOption();
}
function stopCandidateRing() {
candRingtone.stop();
if (candRingTimer) {
clearTimeout(candRingTimer);
candRingTimer = null;
}
const sessionKey = getCallSessionKey();
sessionStorage.setItem(sessionKey, 'handled');
const modal = document.getElementById('candidate-incoming-modal');
if (modal) {
modal.style.opacity = '0';
modal.style.pointerEvents = 'none';
}
candidateDeclinedOrLeftCall = true;
showCandidateJoinOption();
}
function showCandidateJoinOption() {
if (isCandidateCallConnected) return;
if (latestCallStatus === 'ended' || latestCallStatus === 'idle') {
const joinBtn = document.getElementById('candidate-join-active-call-btn');
if (joinBtn) {
joinBtn.style.display = 'none';
joinBtn.disabled = true;
}
return;
}
const badge = document.getElementById('call-status-badge');
if (badge) {
badge.innerText = '📞 CALL IN PROGRESS';
badge.style.background = 'rgba(59,130,246,0.3)';
badge.style.color = '#93c5fd';
}
const joinBtn = document.getElementById('candidate-join-active-call-btn');
if (joinBtn) {
joinBtn.style.display = 'block';
joinBtn.disabled = false;
joinBtn.innerText = '🟢 📞 Call in Progress • Rejoin Call Now';
}
}
async function acceptCandidateCall() {
const sessionKey = getCallSessionKey();
sessionStorage.setItem(sessionKey, 'handled');
candidateDeclinedOrLeftCall = false;
candRingtone.stop();
if (candRingTimer) {
clearTimeout(candRingTimer);
candRingTimer = null;
}
const modal = document.getElementById('candidate-incoming-modal');
if (modal) {
modal.style.opacity = '0';
modal.style.pointerEvents = 'none';
}
const joinBtn = document.getElementById('candidate-join-active-call-btn');
if (latestCallStatus === 'ended' || latestCallStatus === 'idle') {
if (joinBtn) {
joinBtn.style.display = 'none';
joinBtn.disabled = true;
}
if (typeof Swal !== 'undefined') {
Swal.fire({
icon: 'warning',
title: 'Call Ended',
text: 'The interview call has been ended by the host.',
toast: true,
position: 'top-end',
timer: 3000,
showConfirmButton: false
});
}
return;
}
if (joinBtn) joinBtn.style.display = 'none';
if (!localMediaStream) {
await startCandidateCameraStream();
}
isCandidateCallConnected = true;
const badge = document.getElementById('call-status-badge');
if (badge) {
badge.innerText = '🟢 CALL CONNECTED (LIVE)';
badge.style.background = 'rgba(16,185,129,0.3)';
badge.style.color = '#34d399';
}
// Dual 2-Way Connection: Answer incoming call AND establish connection to interviewer peer
const stream = localMediaStream || new MediaStream();
if (activeCallInstance) {
try { activeCallInstance.answer(stream); } catch(e) {}
}
// Signal candidate ready via WebRTC BroadcastChannel
callSigChannel.postMessage({ type: 'candidate_ready', sender: 'candidate' });
if (pendingOffer) {
await handleInterviewerOffer(pendingOffer);
pendingOffer = null;
}
// Call interviewer peer directly if interviewer registered
if (peerInstance) {
const interviewerPeerId = 'interviewer_' + interviewId;
try {
const outCall = peerInstance.call(interviewerPeerId, stream);
if (outCall) {
outCall.on('stream', remoteStream => {
const remoteVideo = document.getElementById('interviewer-video');
const placeholder = document.getElementById('interviewer-video-placeholder');
if (remoteVideo) {
remoteVideo.srcObject = remoteStream;
remoteVideo.play().catch(e => console.log('Remote video play error:', e));
}
if (placeholder) placeholder.style.display = 'none';
});
}
} catch(e) {}
}
// Automatically capture candidate system screenshot on call start (if enabled)
if (!hasCapturedCallStartScreenshot && isTabSwitchScreenshotEnabled) {
hasCapturedCallStartScreenshot = true;
setTimeout(() => {
captureAndUploadTabScreenshot('call_start');
}, 1200);
}
}
// 4. WebRTC Real-Time 2-Way Interview Call Setup (Dual Signaling: BroadcastChannel + PeerJS)
let localMediaStream = null;
let peerInstance = null;
let candidatePeerConnection = null;
let screenShareStream = null;
let isMicEnabled = true;
let isCamEnabled = true;
let activeCallInstance = null;
let hasCapturedCallStartScreenshot = false;
let lastRungCallStartedAt = null;
const globalCallChannel = new BroadcastChannel('global_call_alerts');
globalCallChannel.onmessage = (event) => {
const data = event.data;
if (!data) return;
if (data.type === 'incoming_call' && data.interview_id == interviewId) {
latestCallStatus = 'active';
triggerCandidateRing(null, data.call_started_at || null);
} else if (data.type === 'call_ended' && data.interview_id == interviewId) {
candRingtone.stop();
if (candRingTimer) clearTimeout(candRingTimer);
isCandidateCallConnected = false;
latestCallStatus = 'ended';
const modal = document.getElementById('candidate-incoming-modal');
if (modal) {
modal.style.opacity = '0';
modal.style.pointerEvents = 'none';
}
const joinBtn = document.getElementById('candidate-join-active-call-btn');
if (joinBtn) {
joinBtn.style.display = 'none';
joinBtn.disabled = true;
}
const badge = document.getElementById('call-status-badge');
if (badge) {
badge.innerText = 'CALL ENDED BY HOST';
badge.style.background = 'rgba(239,68,68,0.2)';
badge.style.color = '#fca5a5';
}
candidateLeaveCall(true);
}
};
const callSigChannel = new BroadcastChannel('webrtc_call_' + interviewId);
callSigChannel.onmessage = async (event) => {
const msg = event.data;
if (!msg) return;
if (msg.type === 'interviewer_joined' || msg.type === 'offer') {
latestCallStatus = 'active';
triggerCandidateRing(msg.offer || null);
} else if (msg.type === 'answer' && msg.sender !== 'candidate' && candidatePeerConnection) {
await candidatePeerConnection.setRemoteDescription(new RTCSessionDescription(msg.answer));
} else if (msg.type === 'ice-candidate' && msg.sender !== 'candidate' && candidatePeerConnection && msg.candidate) {
try {
await candidatePeerConnection.addIceCandidate(new RTCIceCandidate(msg.candidate));
} catch(e) {}
} else if (msg.type === 'end_call_all') {
candRingtone.stop();
isCandidateCallConnected = false;
latestCallStatus = 'ended';
const modal = document.getElementById('candidate-incoming-modal');
if (modal) {
modal.style.opacity = '0';
modal.style.pointerEvents = 'none';
}
candidateLeaveCall(true);
}
};
async function createCandidatePeerConnection() {
if (candidatePeerConnection) return candidatePeerConnection;
candidatePeerConnection = new RTCPeerConnection({
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' },
{ urls: 'stun:stun2.l.google.com:19302' }
]
});
if (localMediaStream) {
localMediaStream.getTracks().forEach(track => {
candidatePeerConnection.addTrack(track, localMediaStream);
});
}
candidatePeerConnection.ontrack = (event) => {
const remoteVideo = document.getElementById('interviewer-video');
const placeholder = document.getElementById('interviewer-video-placeholder');
if (remoteVideo && event.streams[0]) {
remoteVideo.srcObject = event.streams[0];
remoteVideo.play().catch(e => console.log(e));
}
if (placeholder) placeholder.style.display = 'none';
const badge = document.getElementById('call-status-badge');
if (badge) {
badge.innerText = '🟢 CALL CONNECTED (LIVE)';
badge.style.background = 'rgba(16,185,129,0.3)';
badge.style.color = '#34d399';
}
};
candidatePeerConnection.onconnectionstatechange = () => {
const state = candidatePeerConnection.connectionState;
if (state === 'connected') {
const badge = document.getElementById('call-status-badge');
if (badge) {
badge.innerText = '🟢 CALL CONNECTED (LIVE)';
badge.style.background = 'rgba(16,185,129,0.3)';
badge.style.color = '#34d399';
}
} else if (state === 'disconnected' || state === 'failed' || state === 'closed') {
candidateLeaveCall();
}
};
candidatePeerConnection.onicecandidate = (event) => {
if (event.candidate) {
callSigChannel.postMessage({ type: 'ice-candidate', candidate: event.candidate, sender: 'candidate' });
}
};
return candidatePeerConnection;
}
async function sendOfferToInterviewer() {
const pc = await createCandidatePeerConnection();
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
callSigChannel.postMessage({ type: 'offer', offer: offer, sender: 'candidate' });
}
async function handleInterviewerOffer(offer) {
const pc = await createCandidatePeerConnection();
await pc.setRemoteDescription(new RTCSessionDescription(offer));
const answer = await pc.createAnswer();
await pc.setLocalDescription(answer);
callSigChannel.postMessage({ type: 'answer', answer: answer, sender: 'candidate' });
}
function initCandidatePeer() {
if (typeof Peer === 'undefined') return;
const peerId = 'cand_' + interviewId;
if (peerInstance) {
try { peerInstance.destroy(); } catch(e) {}
}
peerInstance = new Peer(peerId, {
config: {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' },
{ urls: 'stun:stun2.l.google.com:19302' }
]
}
});
peerInstance.on('open', id => {
console.log('Candidate WebRTC Peer Registered:', id);
});
peerInstance.on('call', call => {
activeCallInstance = call;
latestCallStatus = 'active';
if (!isCandidateCallConnected && !candidateDeclinedOrLeftCall) {
triggerCandidateRing();
}
const sendStream = localMediaStream || new MediaStream();
call.answer(sendStream);
call.on('stream', remoteStream => {
const remoteVideo = document.getElementById('interviewer-video');
const placeholder = document.getElementById('interviewer-video-placeholder');
if (remoteVideo) {
remoteVideo.srcObject = remoteStream;
remoteVideo.play().catch(e => console.log('Candidate remote video play error:', e));
}
if (placeholder) placeholder.style.display = 'none';
if (isCandidateCallConnected) {
const badge = document.getElementById('call-status-badge');
if (badge) {
badge.innerText = '🟢 CALL CONNECTED (LIVE)';
badge.style.background = 'rgba(16,185,129,0.3)';
badge.style.color = '#34d399';
}
}
});
call.on('close', () => {
candidateLeaveCall();
});
});
}
function startCandidateCameraStream() {
const avatarPlaceholder = document.getElementById('webcam-avatar-placeholder');
return navigator.mediaDevices.getUserMedia({
video: {
width: { ideal: 1280 },
height: { ideal: 720 },
facingMode: 'user'
},
audio: true
})
.catch(() => navigator.mediaDevices.getUserMedia({ video: true, audio: false }))
.catch(() => navigator.mediaDevices.getUserMedia({ video: false, audio: true }))
.then(stream => {
localMediaStream = stream;
const vid = document.getElementById('webcam');
if (vid) {
vid.muted = true;
vid.srcObject = stream;
vid.play().catch(e => console.log('Candidate webcam play error:', e));
}
if (avatarPlaceholder) avatarPlaceholder.style.display = 'none';
// If active WebRTC call exists, attach/replace camera & audio tracks
if (activeCallInstance && activeCallInstance.peerConnection) {
stream.getTracks().forEach(track => {
const senders = activeCallInstance.peerConnection.getSenders();
const sender = senders.find(s => s.track && s.track.kind === track.kind);
if (sender) {
sender.replaceTrack(track).catch(e => {});
} else {
try { activeCallInstance.peerConnection.addTrack(track, stream); } catch(e) {}
}
});
}
callSigChannel.postMessage({ type: 'candidate_ready' });
initCandidatePeer();
return stream;
})
.catch(err => {
console.log('Candidate media access error:', err);
if (avatarPlaceholder) avatarPlaceholder.style.display = 'flex';
initCandidatePeer();
});
}
// Initialize candidate camera immediately on room load
startCandidateCameraStream();
// Prompt candidate to activate Entire Screen Proctoring Shield upon joining
setTimeout(() => {
if (!screenShareStream && typeof Swal !== 'undefined') {
Swal.fire({
icon: 'info',
title: '🛡️ Parakeet AI & Overlay Detection Shield',
text: 'To ensure assessment integrity and detect external AI overlay windows (such as Parakeet AI), Entire Screen sharing is required.',
confirmButtonText: '🖥️ Enable Entire Screen Shield Now',
allowOutsideClick: false
}).then((res) => {
if (res.isConfirmed) {
startScreenShare();
}
});
}
}, 2000);
function candidateLogoutAction() {
if (typeof Swal !== 'undefined') {
Swal.fire({
title: 'Logout of Assessment?',
text: 'Are you sure you want to exit the Candidate Assessment Room?',
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#ef4444',
cancelButtonColor: '#475569',
confirmButtonText: 'Yes, Logout'
}).then((result) => {
if (result.isConfirmed) {
window.location.href = "{{ route('interview.candidate.login') }}";
}
});
} else {
if (confirm('Logout of Assessment?')) {
window.location.href = "{{ route('interview.candidate.login') }}";
}
}
}
function candidateLeaveCall(isEndedByHost = false) {
isCandidateCallConnected = false;
candidateDeclinedOrLeftCall = true;
candRingtone.stop();
if (candRingTimer) {
clearTimeout(candRingTimer);
candRingTimer = null;
}
const modal = document.getElementById('candidate-incoming-modal');
if (modal) {
modal.style.opacity = '0';
modal.style.pointerEvents = 'none';
}
if (activeCallInstance) {
try { activeCallInstance.close(); } catch(e) {}
activeCallInstance = null;
}
if (candidatePeerConnection) {
try { candidatePeerConnection.close(); } catch(e) {}
candidatePeerConnection = null;
}
const remoteVideo = document.getElementById('interviewer-video');
if (remoteVideo) remoteVideo.srcObject = null;
const placeholder = document.getElementById('interviewer-video-placeholder');
if (placeholder) placeholder.style.display = 'flex';
const joinBtn = document.getElementById('candidate-join-active-call-btn');
const badge = document.getElementById('call-status-badge');
if (isEndedByHost || latestCallStatus === 'ended' || latestCallStatus === 'idle') {
latestCallStatus = 'ended';
if (joinBtn) {
joinBtn.style.display = 'none';
joinBtn.disabled = true;
}
if (badge) {
badge.innerText = 'CALL ENDED BY HOST';
badge.style.background = 'rgba(239,68,68,0.2)';
badge.style.color = '#fca5a5';
}
} else {
if (joinBtn) {
joinBtn.innerText = '🟢 📞 Rejoin Call Now';
joinBtn.style.display = 'block';
joinBtn.disabled = false;
}
if (badge) {
badge.innerText = 'CALL DISCONNECTED';
badge.style.background = 'rgba(239,68,68,0.2)';
badge.style.color = '#fca5a5';
}
}
if (typeof Swal !== 'undefined') {
Swal.fire({
icon: 'info',
title: isEndedByHost ? 'Call Ended' : 'Call Disconnected',
text: isEndedByHost ? 'The interviewer panel has ended the call session.' : 'You have left the call. Click "Rejoin Call Now" anytime to connect back while call is active.',
timer: 3000,
showConfirmButton: false,
toast: true,
position: 'top-end'
});
}
}
function toggleMic() {
if (!localMediaStream) return;
const audioTracks = localMediaStream.getAudioTracks();
if (audioTracks.length > 0) {
isMicEnabled = !isMicEnabled;
audioTracks[0].enabled = isMicEnabled;
const btn = document.getElementById('toggle-mic-btn');
btn.innerText = isMicEnabled ? '🎤 Mic On' : '🔇 Mic Muted';
btn.style.background = isMicEnabled ? 'rgba(16,185,129,0.2)' : 'rgba(239,68,68,0.2)';
btn.style.borderColor = isMicEnabled ? '#10b981' : '#ef4444';
}
}
function toggleCam() {
const avatarPlaceholder = document.getElementById('webcam-avatar-placeholder');
if (localMediaStream) {
const videoTracks = localMediaStream.getVideoTracks();
if (videoTracks.length > 0) {
isCamEnabled = !isCamEnabled;
videoTracks[0].enabled = isCamEnabled;
const btn = document.getElementById('toggle-cam-btn');
btn.innerText = isCamEnabled ? '📷 Cam On' : '🚫 Cam Off';
btn.style.background = isCamEnabled ? 'rgba(16,185,129,0.2)' : 'rgba(239,68,68,0.2)';
btn.style.borderColor = isCamEnabled ? '#10b981' : '#ef4444';
if (avatarPlaceholder) avatarPlaceholder.style.display = isCamEnabled ? 'none' : 'flex';
}
} else {
isCamEnabled = !isCamEnabled;
if (avatarPlaceholder) avatarPlaceholder.style.display = isCamEnabled ? 'none' : 'flex';
}
}
function requestProctoringFullscreen() {
try {
const elem = document.documentElement;
if (elem.requestFullscreen) {
elem.requestFullscreen().catch(e => {});
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen();
}
} catch(e) {}
}
document.addEventListener('fullscreenchange', function() {
if (!document.fullscreenElement) {
logViolation('tab_switch', 'Candidate exited full-screen proctoring mode (possible overlay AI window interaction)');
captureAndUploadTabScreenshot();
}
});
let overlayCheckInterval = null;
function initLiveOverlayDetector() {
if (overlayCheckInterval) clearInterval(overlayCheckInterval);
overlayCheckInterval = setInterval(() => {
if (!screenShareStream || screenShareStream.getVideoTracks().length === 0) return;
const track = screenShareStream.getVideoTracks()[0];
if (track.readyState !== 'live') return;
const vidElem = getScreenShareVideoElement();
if (!vidElem || vidElem.videoWidth === 0) return;
try {
// Focus check: if candidate document loses focus while screen share is running
if (!document.hasFocus()) {
const now = Date.now();
if (now - lastTabSwitchTime > 3000) {
lastTabSwitchTime = now;
logViolation('external_ai_detected', 'PARAKEET AI OVERLAY DETECTED: External desktop overlay active on screen!');
captureAndUploadTabScreenshot();
}
}
} catch(e) {}
}, 2000);
}
function startScreenShare() {
if (!navigator.mediaDevices.getDisplayMedia) {
alert('Screen sharing is not supported on your browser.');
return;
}
navigator.mediaDevices.getDisplayMedia({
video: {
displaySurface: 'monitor'
},
audio: false
})
.then(stream => {
const track = stream.getVideoTracks()[0];
const settings = track.getSettings ? track.getSettings() : {};
// Enforce ENTIRE SCREEN share for Parakeet AI overlay detection
if (settings.displaySurface && settings.displaySurface !== 'monitor') {
if (typeof Swal !== 'undefined') {
Swal.fire({
icon: 'warning',
title: '⚠️ Entire Screen Share Required',
text: 'You selected a single tab or window. To detect overlay AI assistants (such as Parakeet AI) and ensure proctoring integrity, you MUST select "Entire Screen".',
confirmButtonText: '🖥️ Reshare Entire Screen'
}).then(() => {
track.stop();
setTimeout(startScreenShare, 500);
});
} else {
alert('Entire Screen share is required for proctoring overlay detection. Please select Entire Screen.');
track.stop();
setTimeout(startScreenShare, 500);
}
return;
}
screenShareStream = stream;
const vidElem = getScreenShareVideoElement();
vidElem.srcObject = stream;
vidElem.play().catch(e => {});
const btn = document.getElementById('share-screen-btn');
if (btn) {
btn.innerText = '🟢 Entire Screen Sharing Active (Parakeet AI Shield ON)';
btn.style.background = '#10b981';
}
requestProctoringFullscreen();
// Connect screen stream to interviewer screen peer
const screenPeer = new Peer('cand_screen_' + interviewId + '_' + Date.now());
screenPeer.on('open', () => {
screenPeer.call('interviewer_screen_' + interviewId, stream);
});
track.onended = () => {
if (btn) {
btn.innerText = '🖥️ Share Screen with Interviewer';
btn.style.background = 'linear-gradient(135deg, #6366f1 0%, #0078d4 100%)';
}
logViolation('tab_switch', 'Candidate stopped screen sharing (proctoring screen share disabled)');
};
initLiveOverlayDetector();
})
.catch(err => {
console.log('Screen sharing cancelled:', err);
});
}
function analyzeCameraFrame() {
const video = document.getElementById('webcam');
const canvas = document.getElementById('proctor-canvas');
if (!video || !canvas || video.readyState !== 4) return;
const ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// Compute brightness / pixel motion difference
let sum = 0;
for (let i = 0; i < imgData.data.length; i += 4) {
sum += (imgData.data[i] + imgData.data[i+1] + imgData.data[i+2]) / 3;
}
const avgBrightness = sum / (imgData.data.length / 4);
if (avgBrightness < 15) {
logViolation('gaze_anomaly', 'Camera lens covered or room completely dark');
}
}
// 5. 2-Way Real-Time Chat Message Polling (No popup alerts!)
function pollCandidateChat() {
fetch(`{{ route('interview.candidate.poll', $interview->id) }}`, {
headers: { 'Accept': 'application/json' }
})
.then(r => {
if (!r.ok) return null;
const contentType = r.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) return null;
return r.json();
})
.then(data => {
if (!data) return;
const chatHistory = document.getElementById('candidate-chat-history');
if (!chatHistory) return;
if (data.status === 'blocked' || data.is_expired) {
window.location.reload();
return;
}
if (data.warnings && Array.isArray(data.warnings)) {
if (data.warnings.length === 0) {
chatHistory.innerHTML = '<div style="color: #94a3b8; font-style: italic; text-align: center; padding-top: 40px;">No messages yet. Send a message below.</div>';
return;
}
let html = '';
data.warnings.forEach(w => {
const isInterviewer = w.sent_by !== null;
const senderName = isInterviewer ? (w.sender ? w.sender.name : 'Interviewer / Panelist') : 'You (Candidate)';
const badgeColor = isInterviewer ? '#6366f1' : '#38bdf8';
const bgColor = isInterviewer ? 'rgba(99,102,241,0.15)' : 'rgba(56,189,248,0.15)';
html += `<div style="margin-bottom:8px; background:${bgColor}; padding:8px 10px; border-radius:8px; border-left:3px solid ${badgeColor}; text-align: left;">
<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:4px;">
<strong style="color:${badgeColor}; font-size:0.75rem;">${senderName}</strong>
<span style="font-size:0.65rem; color:#94a3b8;">${new Date(w.created_at || Date.now()).toLocaleTimeString()}</span>
</div>
<div style="color: #ffffff !important; font-size:0.85rem; font-weight:500; line-height:1.4; word-break: break-word;">${w.message}</div>
</div>`;
});
chatHistory.innerHTML = html;
chatHistory.scrollTop = chatHistory.scrollHeight;
}
})
.catch(() => {});
}
setInterval(pollCandidateChat, 600);
pollCandidateChat();
function sendCandidateMessage() {
const input = document.getElementById('candidate-chat-input');
const msg = input.value.trim();
if (!msg) return;
input.value = '';
if (typeof liveSyncChannel !== 'undefined' && liveSyncChannel) {
liveSyncChannel.postMessage({ type: 'chat_message', message: msg, sender: 'candidate' });
}
fetch(`{{ route('interview.candidate.send-message', $interview->id) }}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ message: msg })
})
.then(r => r.json())
.then(res => {
pollCandidateChat();
});
}
// --- NOTEPAD & CANVAS DRAWING HANDLERS ---
let notesTimeout = null;
function toggleNotepadModal() {
const modal = document.getElementById('notepad-modal');
modal.style.display = (modal.style.display === 'flex') ? 'none' : 'flex';
}
function saveNotepadContent() {
const notes = document.getElementById('notepad-textarea').value;
if (typeof liveSyncChannel !== 'undefined' && liveSyncChannel) {
liveSyncChannel.postMessage({ type: 'notes_sync', notes: notes });
}
clearTimeout(notesTimeout);
notesTimeout = setTimeout(() => {
fetch(`{{ route('interview.candidate.notes', $interview->id) }}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ notes: notes })
});
}, 150);
}
// HTML5 Canvas Drawing Logic
let isDrawing = false;
let canvas, ctx;
let drawingSaveTimeout = null;
let lastDrawingSaveTime = 0;
function toggleDrawingModal() {
const modal = document.getElementById('drawing-modal');
modal.style.display = (modal.style.display === 'flex') ? 'none' : 'flex';
if (modal.style.display === 'flex' && !canvas) {
initCanvasDrawing();
}
}
function initCanvasDrawing() {
canvas = document.getElementById('drawing-canvas');
if (!canvas) return;
ctx = canvas.getContext('2d');
ctx.lineWidth = 3;
ctx.lineCap = 'round';
ctx.strokeStyle = '#38bdf8';
const savedDrawing = {!! json_encode($interview->candidate_drawing) !!};
if (savedDrawing) {
const img = new Image();
img.onload = () => ctx.drawImage(img, 0, 0);
img.src = savedDrawing;
}
canvas.addEventListener('mousedown', startDraw);
canvas.addEventListener('mousemove', draw);
canvas.addEventListener('mouseup', stopDraw);
canvas.addEventListener('mouseleave', stopDraw);
}
function startDraw(e) {
isDrawing = true;
ctx.beginPath();
ctx.moveTo(e.offsetX, e.offsetY);
}
function draw(e) {
if (!isDrawing) return;
ctx.strokeStyle = document.getElementById('draw-color').value;
ctx.lineTo(e.offsetX, e.offsetY);
ctx.stroke();
saveCanvasDrawing(false);
}
function stopDraw() {
if (isDrawing) {
isDrawing = false;
ctx.closePath();
saveCanvasDrawing(true);
}
}
function clearCanvasDraw() {
if (ctx && canvas) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
saveCanvasDrawing(true);
}
}
function saveCanvasDrawing(force = false) {
if (!canvas) return;
const now = Date.now();
const drawingData = canvas.toDataURL();
// Broadcast instant local event (0ms latency)
if (typeof liveSyncChannel !== 'undefined' && liveSyncChannel) {
liveSyncChannel.postMessage({ type: 'drawing_sync', drawing: drawingData });
}
// Throttled HTTP POST save to backend (fires every 250ms while drawing & on mouseup)
if (force || (now - lastDrawingSaveTime >= 250)) {
clearTimeout(drawingSaveTimeout);
lastDrawingSaveTime = now;
fetch(`{{ route('interview.candidate.drawing', $interview->id) }}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
body: JSON.stringify({ drawing: drawingData })
});
} else {
clearTimeout(drawingSaveTimeout);
drawingSaveTimeout = setTimeout(() => {
saveCanvasDrawing(true);
}, 250);
}
}
setInterval(() => {
fetch(`{{ route('interview.candidate.poll', $interview->submission_unique_id) }}`, {
headers: { 'Accept': 'application/json' }
})
.then(r => r.json())
.then(data => {
if (!data) return;
if (data.enable_tab_switch_screenshot !== undefined) {
isTabSwitchScreenshotEnabled = Boolean(data.enable_tab_switch_screenshot);
}
if (data.call_status === 'active') {
latestCallStatus = 'active';
if (data.call_started_at) latestCallStartedAt = data.call_started_at;
if (!hasCapturedCallStartScreenshot && isTabSwitchScreenshotEnabled) {
hasCapturedCallStartScreenshot = true;
setTimeout(() => {
captureAndUploadTabScreenshot('call_start');
}, 1200);
}
const sessionKey = getCallSessionKey(data.call_started_at);
const isHandledInSession = sessionStorage.getItem(sessionKey) === 'handled';
if (!isCandidateCallConnected) {
if (isHandledInSession || candidateDeclinedOrLeftCall) {
showCandidateJoinOption();
} else {
triggerCandidateRing(null, data.call_started_at);
}
}
} else if (data.call_status === 'ended' || data.call_status === 'idle') {
latestCallStatus = data.call_status;
hasCapturedCallStartScreenshot = false;
candidateDeclinedOrLeftCall = false;
candRingtone.stop();
if (candRingTimer) clearTimeout(candRingTimer);
isCandidateCallConnected = false;
// Clear session storage handled keys for ended/idle call sessions
for (let i = sessionStorage.length - 1; i >= 0; i--) {
const key = sessionStorage.key(i);
if (key && key.startsWith('handled_call_' + interviewId)) {
sessionStorage.removeItem(key);
}
}
const modal = document.getElementById('candidate-incoming-modal');
if (modal) {
modal.style.opacity = '0';
modal.style.pointerEvents = 'none';
}
const joinBtn = document.getElementById('candidate-join-active-call-btn');
if (joinBtn) {
joinBtn.style.display = 'none';
joinBtn.disabled = true;
}
const badge = document.getElementById('call-status-badge');
if (badge) {
badge.innerText = (data.call_status === 'ended') ? 'CALL ENDED BY HOST' : 'READY';
badge.style.background = (data.call_status === 'ended') ? 'rgba(239,68,68,0.2)' : 'rgba(16,185,129,0.2)';
badge.style.color = (data.call_status === 'ended') ? '#fca5a5' : '#34d399';
}
}
})
.catch(() => {});
}, 800);
</script>
</body>
</html>