import React, { useState, useEffect, useRef, useCallback } from 'react'; import { Mic, MicOff, PhoneOff, Settings, Volume2, X, Check, KeyRound, RotateCcw, AlertCircle, Sparkles, } from 'lucide-react'; /* ============================================================================ PART 1: CONFIG, GEMINI VOICE & CHAT ENGINE, AND ROBOT T.KOI AVATAR ============================================================================ */ const STORAGE_KEY = 'robot_tkoi_live_voice_settings_v3'; const DEFAULT_SETTINGS = { robotName: 'Robot T.Koi', badgeName: 'T.KOI', apiKey: '', useGeminiVoice: true, voiceName: 'Puck', personaNote: 'You are the cheerful, silly, encouraging robot version of Teacher Koi at KidsDuo! You LOVE Carbonara, Pizza, and saying "BABUBABU!" when excited. Chat with students in simple, fun, kid-friendly English.', }; const MAGIC_BUTTONS = [ { id: 'carbonara', label: 'CARBONARA!', emoji: '🍝', gradient: 'from-amber-400 via-orange-500 to-orange-500', shadow: 'shadow-[0_6px_0_#b45309]', activeShadow: 'active:shadow-[0_2px_0_#b45309]', lines: [ 'CARBONARA! Oh yeah! Creamy, cheesy, yummy carbonara is the BEST pasta in the whole universe!', 'Did someone say CARBONARA?! My robot tummy is rumbling! Beep boop, pass me a giant fork!', 'CARBONARA power activated! Eat your carbonara and become a superstar today!', ], }, { id: 'pizza', label: 'PIZZA!!!', emoji: '🍕', gradient: 'from-rose-500 via-red-500 to-red-600', shadow: 'shadow-[0_6px_0_#991b1b]', activeShadow: 'active:shadow-[0_2px_0_#991b1b]', lines: [ 'PIZZA!!! Extra cheese, extra yummy! Who wants a giant pizza party with Robot T.Koi?!', 'PIZZA!!! Beep boop! Even robots love hot, cheesy pizza! What is your favorite topping?', 'WHOA! PIZZA time! One slice for you, and ten slices for Robot T.Koi! Haha, just kidding!', ], }, { id: 'babubabu', label: 'BABUBABU!', emoji: 'ðŸĪŠ', gradient: 'from-fuchsia-500 via-purple-500 to-purple-600', shadow: 'shadow-[0_6px_0_#6b21a8]', activeShadow: 'active:shadow-[0_2px_0_#6b21a8]', lines: [ 'BABUBABU! Hahaha! Oh no, you pressed the silly button! Babubabu beep boop!', 'BABUBABU! My robot circuits are going super silly! Say babubabu with me! BABUBABU!', 'WOOHOO! BABUBABU! That is the secret magic giggle word of Teacher Koi!', ], }, ]; const TAP_HEAD_LINES = [ 'Hehe! That tickles my antenna! Beep boop!', 'Boing! Hey superstars, watch the hair! Haha!', 'Whoa! You booped Robot T.Koi! Babubabu!', 'Beep boop! High five! Ready to chat?', ]; const VOICE_OPTIONS = [ { name: 'Puck', label: 'Puck (Upbeat & Fun)' }, { name: 'Fenrir', label: 'Fenrir (Excitable)' }, { name: 'Zephyr', label: 'Zephyr (Bright)' }, { name: 'Kore', label: 'Kore (Clear & Firm)' }, { name: 'Aoede', label: 'Aoede (Breezy)' }, ]; // Convert raw signed 16-bit PCM from Gemini TTS into a playable WAV Blob function base64ToUint8Array(base64) { const binary = atob(base64); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i); } return bytes; } function pcm16ToWavBlob(pcmBytes, sampleRate = 24000) { const numChannels = 1; const bitsPerSample = 16; const byteRate = (sampleRate * numChannels * bitsPerSample) / 8; const blockAlign = (numChannels * bitsPerSample) / 8; const dataSize = pcmBytes.byteLength; const buffer = new ArrayBuffer(44 + dataSize); const view = new DataView(buffer); const writeStr = (offset, str) => { for (let i = 0; i < str.length; i++) { view.setUint8(offset + i, str.charCodeAt(i)); } }; writeStr(0, 'RIFF'); view.setUint32(4, 36 + dataSize, true); writeStr(8, 'WAVE'); writeStr(12, 'fmt '); view.setUint32(16, 16, true); view.setUint16(20, 1, true); // PCM view.setUint16(22, numChannels, true); view.setUint32(24, sampleRate, true); view.setUint32(28, byteRate, true); view.setUint16(32, blockAlign, true); view.setUint16(34, bitsPerSample, true); writeStr(36, 'data'); view.setUint32(40, dataSize, true); new Uint8Array(buffer, 44).set(pcmBytes); return new Blob([buffer], { type: 'audio/wav' }); } async function fetchWithBackoff(url, options, retries = 2) { let delay = 800; for (let attempt = 0; attempt <= retries; attempt++) { const res = await fetch(url, options); if (res.ok || (res.status !== 429 && res.status < 500) || attempt === retries) { return res; } await new Promise((r) => setTimeout(r, delay)); delay *= 2; } throw new Error('Request failed'); } function buildSystemInstruction(settings) { return `You are ${settings.robotName}, the friendly, playful robot version of Teacher Koi! You are having a live voice conversation with young students just for fun. Rules: - Keep every reply short, warm, energetic, and easy to understand (1 to 3 short sentences). - Speak naturally with NO markdown, NO bullet points, NO asterisks, and NO emojis. - Your 3 famous magic words are: "CARBONARA!", "PIZZA!!!", and "BABUBABU!". If a student says any of them, get super excited and joke about them! - Occasionally ask a fun follow-up question to keep the student talking in English. ${settings.personaNote ? `Extra Teacher Notes: ${settings.personaNote}` : ''}`; } function generateLocalFallbackReply(userText, settings) { const t = userText.toLowerCase(); if (t.includes('carbonara')) return MAGIC_BUTTONS[0].lines[0]; if (t.includes('pizza')) return MAGIC_BUTTONS[1].lines[0]; if (t.includes('babu')) return MAGIC_BUTTONS[2].lines[0]; if (t.includes('hello') || t.includes('hi') || t.includes('hey')) { return `Hello superstar! I am ${settings.robotName}! How are you feeling today?`; } if (t.includes('name') || t.includes('who are you')) { return `I am ${settings.robotName}, the robot version of Teacher Koi! Do you like pizza or carbonara?`; } if (t.includes('bye') || t.includes('goodbye') || t.includes('see you')) { return `Bye bye superstar! Keep smiling and remember... BABUBABU! See you next time!`; } if (t.includes('food') || t.includes('hungry') || t.includes('eat')) { return `Ooh, now I am hungry too! I love carbonara and pizza! What is your favorite food?`; } if (t.includes('joke') || t.includes('funny')) { return `Why did the robot eat pizza? Because it wanted a mega-byte! Hahaha! Babubabu!`; } const defaults = [ `Whoa, that is super cool! Tell Robot T.Koi more about that!`, `Awesome job speaking English, superstar! What else did you do today?`, `Beep boop! I love chatting with you! Do you like carbonara or pizza better?`, ]; return defaults[Math.floor(Math.random() * defaults.length)]; } async function askGeminiText(userText, history, settings) { const apiKey = (settings.apiKey || '').trim(); const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent?key=${encodeURIComponent(apiKey)}`; try { const contents = [ ...history.slice(-8).map((turn) => ({ role: turn.role === 'robot' ? 'model' : 'user', parts: [{ text: turn.text }], })), { role: 'user', parts: [{ text: userText }] }, ]; const res = await fetchWithBackoff(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ systemInstruction: { parts: [{ text: buildSystemInstruction(settings) }] }, contents, generationConfig: { temperature: 0.9, maxOutputTokens: 150 }, }), }); if (!res.ok) throw new Error('Gemini text error'); const data = await res.json(); const reply = data?.candidates?.[0]?.content?.parts?.[0]?.text?.trim(); if (!reply) throw new Error('Empty reply'); return reply.replace(/[*_#`]/g, ''); } catch { return generateLocalFallbackReply(userText, settings); } } async function fetchGeminiTTSAudioUrl(text, settings) { if (!settings.useGeminiVoice) return null; const apiKey = (settings.apiKey || '').trim(); const url = `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-tts:generateContent?key=${encodeURIComponent(apiKey)}`; try { const res = await fetchWithBackoff( url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ contents: [{ parts: [{ text: `Say cheerfully and playfully like a fun teacher robot: ${text}` }] }], generationConfig: { responseModalities: ['AUDIO'], speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: settings.voiceName || 'Puck' }, }, }, }, model: 'gemini-2.5-flash-preview-tts', }), }, 1 ); if (!res.ok) return null; const data = await res.json(); const part = data?.candidates?.[0]?.content?.parts?.[0]; const audioData = part?.inlineData?.data; const mimeType = part?.inlineData?.mimeType || ''; if (!audioData || !mimeType.startsWith('audio/')) return null; const rateMatch = mimeType.match(/rate=(\d+)/); const sampleRate = rateMatch ? parseInt(rateMatch[1], 10) : 24000; const pcmBytes = base64ToUint8Array(audioData); const wavBlob = pcm16ToWavBlob(pcmBytes, sampleRate); return URL.createObjectURL(wavBlob); } catch { return null; } } function RobotTKoiCharacter({ status, isMuted, isHeadTapped, onTapHead, badgeName, inputLevel }) { const [isBlinking, setIsBlinking] = useState(false); useEffect(() => { let t1; let t2; const blinkLoop = () => { t1 = window.setTimeout(() => { setIsBlinking(true); t2 = window.setTimeout(() => { setIsBlinking(false); blinkLoop(); }, 140); }, 2500 + Math.random() * 2800); }; blinkLoop(); return () => { window.clearTimeout(t1); window.clearTimeout(t2); }; }, []); const isSpeaking = status === 'speaking'; const isListening = status === 'listening' && !isMuted; const isThinking = status === 'thinking'; return (
{/* Listening Halo */} {isListening && (
)} {/* Robot T.Koi SVG matching the KidsDuo Teacher Koi look */}
); } /* ============================================================================ PART 2: TEACHER API KEY SETTINGS MODAL & MAIN LIVE CONVERSATION APP ============================================================================ */ function TeacherSettingsModal({ isOpen, onClose, settings, onSave }) { const [robotName, setRobotName] = useState(settings.robotName); const [badgeName, setBadgeName] = useState(settings.badgeName); const [apiKey, setApiKey] = useState(settings.apiKey || ''); const [useGeminiVoice, setUseGeminiVoice] = useState(settings.useGeminiVoice); const [voiceName, setVoiceName] = useState(settings.voiceName || 'Puck'); const [personaNote, setPersonaNote] = useState(settings.personaNote); useEffect(() => { if (isOpen) { setRobotName(settings.robotName); setBadgeName(settings.badgeName); setApiKey(settings.apiKey || ''); setUseGeminiVoice(settings.useGeminiVoice); setVoiceName(settings.voiceName || 'Puck'); setPersonaNote(settings.personaNote); } }, [isOpen, settings]); if (!isOpen) return null; const handleSave = (e) => { e.preventDefault(); onSave({ robotName: robotName.trim() || DEFAULT_SETTINGS.robotName, badgeName: badgeName.trim() || DEFAULT_SETTINGS.badgeName, apiKey: apiKey.trim(), useGeminiVoice, voiceName, personaNote: personaNote.trim(), }); onClose(); }; const handleReset = () => { setRobotName(DEFAULT_SETTINGS.robotName); setBadgeName(DEFAULT_SETTINGS.badgeName); setApiKey(''); setUseGeminiVoice(true); setVoiceName(DEFAULT_SETTINGS.voiceName); setPersonaNote(DEFAULT_SETTINGS.personaNote); }; return (

Teacher Settings

Gemini API Key & Robot Voice

{/* API Key Input */}
setApiKey(e.target.value)} placeholder="Paste your Gemini API key (AIza...)" className="w-full rounded-xl border border-blue-200 bg-white px-3.5 py-2.5 text-sm font-medium text-slate-800 focus:border-blue-500 focus:outline-none" />

Saved locally in your browser. Powers live AI replies and Real Voice TTS!

setRobotName(e.target.value)} className="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-semibold text-slate-800 focus:border-blue-400 focus:outline-none" />
setBadgeName(e.target.value)} className="w-full rounded-xl border border-slate-200 bg-slate-50 px-3 py-2 text-sm font-semibold text-slate-800 focus:border-blue-400 focus:outline-none" />
{/* Real Voice TTS Toggle & Voice Selector */}

Gemini Real Voice (TTS)

Falls back to browser voice if offline

setUseGeminiVoice(e.target.checked)} className="h-5 w-5 accent-blue-600 cursor-pointer" />
{useGeminiVoice && (
)}