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34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
let mediaRecorder;
let audioChunks = [];
let isRecording = false;
let statusInterval;
// VAD Settings
let silenceStart = Date.now();
const SILENCE_THRESHOLD = 10; // Adjust sensitivity
const SILENCE_DURATION = 1000; // 1 second
let vadInterval;

const recordBtn = document.getElementById('recordBtn');
const statusText = document.getElementById('statusText');
const messagesDiv = document.getElementById('messages');
const visualizerCanvas = document.getElementById('visualizer');
const canvasCtx = visualizerCanvas.getContext('2d');

// Status Dots
const statusDots = {
    asr: document.getElementById('asrStatus'),
    mt: document.getElementById('mtStatus'),
    tts: document.getElementById('ttsStatus')
};

// Check Backend Status
async function checkStatus() {
    try {
        const res = await fetch('/api/status');
        const data = await res.json();

        statusDots.asr.classList.toggle('active', data.asr);
        statusDots.mt.classList.toggle('active', data.mt);
        statusDots.tts.classList.toggle('active', data.tts);

        if (!data.asr) {
            let msg = "ASR Offline";
            if (data.errors && data.errors.asr) msg += `: ${data.errors.asr}`;
            addSystemMessage(msg);
            statusDots.asr.title = msg;
        }

        if (data.errors && data.errors.mt) statusDots.mt.title = data.errors.mt;
        if (data.errors && data.errors.tts) statusDots.tts.title = data.errors.tts;

    } catch (e) {
        console.error("Backend offline", e);
        addSystemMessage("Server Offline or Unreachable");
    }
}
checkStatus();

// Load Chat History
async function loadHistory() {
    try {
        const res = await fetch('/api/history');
        const history = await res.json();

        // Clear default welcome message if history exists
        if (history && history.length > 0) {
            const defaultMsg = document.querySelector('.message.system');
            if (defaultMsg && defaultMsg.innerText.includes("Welcome")) {
                defaultMsg.remove();
            }
        }

        if (history) {
            history.forEach(item => {
                // User Message
                addMessage('user', item.query_santali);

                // Bot Message (with debug info)
                const debugObj = {
                    asr_text: item.query_santali,
                    english_in: item.query_english,
                    english_out: item.response_english,
                    santali_out: item.response_santali
                };
                addMessage('bot', item.response_santali, debugObj);
            });

            // Scroll to bottom after loading
            messagesDiv.scrollTop = messagesDiv.scrollHeight;
        }

    } catch (e) {
        console.error("Failed to load history", e);
    }
}

loadHistory();

// Clear History
const clearBtn = document.getElementById('clearHistoryBtn');
if (clearBtn) {
    clearBtn.addEventListener('click', async () => {
        if (confirm("Are you sure you want to clear all chat history?")) {
            try {
                await fetch('/api/history', { method: 'DELETE' });
                // Clear UI
                const msgs = document.querySelectorAll('.message:not(.system)');
                msgs.forEach(m => m.remove());
                addSystemMessage("History Cleared.");
            } catch (e) {
                console.error("Clear failed", e);
                addSystemMessage("Failed to clear history.");
            }
        }
    });
}

// Audio Context for Visualization
let audioCtx;
let analyser;
let dataArray;
let source;

function initAudioContext() {
    if (!audioCtx) {
        audioCtx = new (window.AudioContext || window.webkitAudioContext)();
        analyser = audioCtx.createAnalyser();
        analyser.fftSize = 256;
        const bufferLength = analyser.frequencyBinCount;
        dataArray = new Uint8Array(bufferLength);
    }
}

// Draw Visualizer
function drawVisualizer() {
    requestAnimationFrame(drawVisualizer);

    if (!analyser) return;
    analyser.getByteFrequencyData(dataArray);

    canvasCtx.fillStyle = '#0f172a'; // Clear with bg color
    canvasCtx.fillRect(0, 0, visualizerCanvas.width, visualizerCanvas.height);

    const barWidth = (visualizerCanvas.width / dataArray.length) * 2.5;
    let barHeight;
    let x = 0;

    // VAD Logic within Visualizer Loop for efficiency
    let sum = 0;
    for (let i = 0; i < dataArray.length; i++) {
        sum += dataArray[i];
    }
    const average = sum / dataArray.length;

    // Drawing
    for (let i = 0; i < dataArray.length; i++) {
        barHeight = dataArray[i] / 2;
        // Visual feedback for voice activity
        if (average > SILENCE_THRESHOLD) {
            canvasCtx.fillStyle = `rgb(${barHeight + 100}, 50, 50)`; // Red tint when speaking
        } else {
            canvasCtx.fillStyle = `rgb(${barHeight + 100}, 189, 248)`;
        }
        canvasCtx.fillRect(x, visualizerCanvas.height - barHeight, barWidth, barHeight);
        x += barWidth + 1;
    }

    // Check Silence
    if (isRecording) {
        if (average > SILENCE_THRESHOLD) {
            silenceStart = Date.now(); // Reset timer
            statusText.innerText = "Listening...";
        } else if (Date.now() - silenceStart > SILENCE_DURATION) {
            console.log("Silence detected, stopping...");
            stopRecording();
        }
    }
}


// Input Mode Logic
const inputMicRadio = document.getElementById('inputMic');
const inputFileRadio = document.getElementById('inputFile');
const fileInput = document.getElementById('fileInput');
const inputIcon = document.getElementById('inputIcon');
let inputMode = 'mic';


function updateInputMode() {
    // Safety: Stop recording if active when switching
    if (isRecording) {
        stopRecording();
    }

    if (inputFileRadio.checked) {
        inputMode = 'file';
        inputIcon.className = 'fas fa-file-upload';
        recordBtn.title = "Click to Upload Audio";
        statusText.innerText = "Upload Mode";
    } else {
        inputMode = 'mic';
        inputIcon.className = 'fas fa-microphone';
        recordBtn.title = "Hold/Click to Record";
        statusText.innerText = "Tap to Speak";
    }
}

inputMicRadio.addEventListener('change', updateInputMode);
inputFileRadio.addEventListener('change', updateInputMode);

// Initialize state
updateInputMode();

// File Upload Handling
fileInput.addEventListener('change', async (e) => {
    if (e.target.files.length > 0) {
        const file = e.target.files[0];
        statusText.innerText = "Uploading...";
        await sendAudioToBackend(file);
        // Reset input so same file can be selected again if needed
        fileInput.value = '';
    }
});

// Recording Logic
recordBtn.addEventListener('click', async () => {
    if (inputMode === 'file') {
        fileInput.click();
        return;
    }

    if (!isRecording) {
        startRecording();
    } else {
        stopRecording();
    }
});

async function startRecording() {
    try {
        const stream = await navigator.mediaDevices.getUserMedia({ audio: true });

        initAudioContext();
        source = audioCtx.createMediaStreamSource(stream);
        source.connect(analyser);
        drawVisualizer();

        mediaRecorder = new MediaRecorder(stream);
        audioChunks = [];

        mediaRecorder.ondataavailable = event => {
            audioChunks.push(event.data);
        };

        mediaRecorder.onstop = async () => {
            const audioBlob = new Blob(audioChunks, { type: 'audio/wav' });
            sendAudioToBackend(audioBlob);

            // Stop tracks
            stream.getTracks().forEach(track => track.stop());
        };

        mediaRecorder.start();
        isRecording = true;
        silenceStart = Date.now(); // Initialize silence timer
        recordBtn.classList.add('recording');
        recordBtn.innerHTML = '<i class="fas fa-stop"></i>';
        statusText.innerText = "Listening...";

    } catch (err) {
        console.error("Mic Error:", err);
        addSystemMessage("Microphone access denied.");
    }
}

// Simulated Progress Steps
function startProcessingSim() {
    let steps = ["Uploading...", "Transcribing (Santali)...", "Translating to English...", "AI Thinking...", "Translating to Santali...", "Generating Voice..."];
    let i = 0;
    statusText.innerText = steps[0];
    statusInterval = setInterval(() => {
        i = (i + 1) % steps.length;
        statusText.innerText = steps[i];
    }, 800); // Faster updates (0.8s) to make UI feel more responsive
}

function stopProcessingSim() {
    clearInterval(statusInterval);
}

function stopRecording() {
    if (mediaRecorder && isRecording) {
        mediaRecorder.stop();
        isRecording = false;
        recordBtn.classList.remove('recording');
        statusText.innerText = "Processing...";
        startProcessingSim(); // Start visual feedback
    }
}

async function sendAudioToBackend(blob) {
    const formData = new FormData();
    formData.append('audio', blob, 'input.wav');


    const modeSelect = document.getElementById('modeSelect');
    if (modeSelect) {
        formData.append('mode', modeSelect.value);
    }

    // Send selected MT Mode
    const mtModeSelect = document.getElementById('mtModeSelect');
    if (mtModeSelect) {
        formData.append('mt_mode', mtModeSelect.value);
    }

    try {
        // Show temp message with spinner
        addMessage('user', '<i class="fas fa-spinner fa-spin"></i> Processing...', null);

        const response = await fetch('/api/process', {
            method: 'POST',
            body: formData
        });

        const data = await response.json();

        if (data.error) {
            addSystemMessage(`Error: ${data.error}`);
            statusText.innerText = "Error occurred";
        } else {
            // Update last user message
            const lastMsg = document.querySelector('.message.user:last-child');
            if (lastMsg) lastMsg.remove();

            addMessage('user', data.query_santali);

            const debugObj = {
                asr_text: data.query_santali,
                english_in: data.query_english,
                english_out: data.response_english,
                santali_out: data.response_santali
            };
            addMessage('bot', data.response_santali, debugObj);

            if (data.audio_url) {
                const audioControls = document.getElementById('audio-controls');
                const audioPlayer = document.getElementById('responseAudio');
                const playBtn = document.getElementById('playResponseBtn');

                // Update button state
                playBtn.disabled = false;
                // Add a glow effect or change icon color to indicate readiness if needed via CSS classes, 
                // but default enabled state is enough.

                // Set audio source with timestamp
                audioPlayer.src = data.audio_url + "?t=" + new Date().getTime();

                // Set up button click
                playBtn.onclick = () => {
                    audioPlayer.play();
                };

                // Check Auto-Play
                const autoPlayCheckbox = document.getElementById('autoPlayToggle');
                if (autoPlayCheckbox && autoPlayCheckbox.checked) {
                    console.log("Auto-playing response...");
                    setTimeout(() => {
                        audioPlayer.play().catch(e => {
                            console.log("Auto-play blocked:", e);
                            addSystemMessage("Click Play to listen.");
                        });
                    }, 500);
                }
            } // End audio logic
        } // End else (success)
        stopProcessingSim();
        statusText.innerText = "Reply Sent";
    } catch (err) {
        console.error(err);
        stopProcessingSim();
        addSystemMessage("Network Error");
        statusText.innerText = "Offline?";
    }
}

// Enhanced addMessage to support multi-stage display
function addMessage(type, primaryText, debugInfo = null) {
    const div = document.createElement('div');
    div.className = `message ${type}`;

    let content = `<div class="primary">${primaryText}</div>`;

    // If we have debug info (only for bot usually), render the grid
    if (debugInfo) {
        content += `
            <div class="debug-grid">
                <div class="debug-item">
                    <span class="debug-label">1. Input (Sat)</span>
                    ${debugInfo.asr_text || '-'}
                </div>
                <div class="debug-item">
                    <span class="debug-label">2. MT (Eng)</span>
                    ${debugInfo.english_in || '-'}
                </div>
                <div class="debug-item">
                    <span class="debug-label">3. AI Reason (Eng)</span>
                    ${debugInfo.english_out || '-'}
                </div>
                <div class="debug-item">
                    <span class="debug-label">4. MT Reply (Sat)</span>
                    ${debugInfo.santali_out || '-'}
                </div>
            </div>
        `;
    }

    div.innerHTML = content;
    messagesDiv.appendChild(div);

    // Smooth scroll to the new message
    div.scrollIntoView({ behavior: 'smooth', block: 'end' });
}


function addSystemMessage(text) {
    const div = document.createElement('div');
    div.className = `message system`;
    div.innerText = text;
    messagesDiv.appendChild(div);
}

// Scroll Button Logic
const scrollBtn = document.getElementById('scrollBtn');

messagesDiv.addEventListener('scroll', () => {
    // Show button if we are not at the bottom
    const isAtBottom = messagesDiv.scrollHeight - messagesDiv.scrollTop <= messagesDiv.clientHeight + 50;

    if (isAtBottom) {
        scrollBtn.classList.add('hidden');
    } else {
        scrollBtn.classList.remove('hidden');
    }
});

scrollBtn.addEventListener('click', () => {
    messagesDiv.scrollTo({
        top: messagesDiv.scrollHeight,
        behavior: 'smooth'
    });
});