const $=s=>document.querySelector(s),$$=s=>[...document.querySelectorAll(s)];
const wait=ms=>new Promise(r=>setTimeout(r,ms));
const shuffle=a=>{for(let i=a.length-1;i>0;i--){const j=Math.random()*(i+1)|0;[a[i],a[j]]=[a[j],a[i]]}return a};
const pick=a=>a[Math.random()*a.length|0];
const store={get(k,d){try{const v=localStorage.getItem('squad1_'+k);return v==null?d:JSON.parse(v)}catch(e){return d}},set(k,v){try{localStorage.setItem('squad1_'+k,JSON.stringify(v))}catch(e){}}};
const state={stars:store.get('stars',0),stickers:store.get('stickers',[]),name:store.get('name',''),voiceName:store.get('voice',null),music:store.get('music',true),
sounds:store.get('sounds',['th','f','v','s']),micWanted:store.get('mic',true)};
const J=Object.assign({round:0,station:0,joke:0,costume:0,lastCostume:{}},store.get('journey',{}));
const saveJ=()=>store.set('journey',J);
/* ---------- THE SILLY SOUND SQUAD ---------- */
// Each friend shows the mouth for its sound: Thunder's tongue peeks out (TH), Fifi's teeth sit on her lip (F),
// Vinny the race car has buck teeth on his bumper-lip and a buzzy motor (V), Sunny smiles with her teeth together (S).
function puppySVG(){return ``}
function bunnySVG(){return ``}
function carSVG(){return ``}
function snakeSVG(){return ``}
const SQUAD={
th:{key:'th',name:'Thunder',animal:'puppy',icon:'🐶',svg:puppySVG,color:'#f2a64a',pose:'thAir',rest:'th',want:'soft',her:'him',
steps:[['open','Open wide, just a tiny bit.'],['th','Let your tongue peek out, like a puppy tongue!'],['thAir','Now blow softly, like a little breeze.']],
words:[['thumb','👍','I'],['three','3️⃣','I'],['think','🤔','I'],['thunder','⛈️','I'],['bath','🛁','F'],['teeth','🦷','F'],['mouth','👄','F']],
game:'bubbles'},
f:{key:'f',name:'Fifi',animal:'bunny',icon:'🐰',svg:bunnySVG,color:'#a98bff',pose:'f',rest:'fRest',want:'soft',her:'her',
steps:[['fRest','Make bunny teeth! Put them on your bottom lip.'],['f','Now blow softly, like a little breeze.']],
words:[['fish','🐟','I'],['fan','🪭','I'],['feet','🦶','I'],['fox','🦊','I'],['fork','🍴','I'],['five','5️⃣','I']],
game:'candles'},
v:{key:'v',name:'Vinny',animal:'race car',icon:'🏎️',svg:carSVG,color:'#ff4d4d',pose:'v',rest:'fRest',want:'voice',her:'him',
steps:[['fRest','Make bunny teeth! Put them on your bottom lip.'],['v','Now turn on your motor, and make it buzz. Your lip will tickle!']],
words:[['van','🚐','V'],['vase','🏺','V'],['violin','🎻','V'],['volcano','🌋','V']],
game:'race'},
s:{key:'s',name:'Sunny',animal:'snake',icon:'🐍',svg:snakeSVG,color:'#3fbf74',pose:'s',rest:'sRest',want:'sharp',her:'her',
steps:[['smile','Smile big, and put your teeth together.'],['sRest','Keep your tongue hiding inside.'],['s','Now let the air hiss out, like a happy snake.']],
words:[['sun','☀️','I'],['sock','🧦','I'],['soap','🧼','I'],['soup','🍲','I'],['six','6️⃣','I'],['sandwich','🥪','I']],
game:'balloon'}};
const COSTUMES=[['Super','🦸','⚡'],['Pirate','🏴☠️','🦜'],['Space','👩🚀','🚀'],['Wizard','🧙','🪄'],['Chef','👨🍳','🍕'],['Firefighter','🚒','🧯'],['Rock Star','🎸','🎤']];
const HATS={Super:'🦸',Pirate:'🏴☠️',Space:'🪐',Wizard:'🎩',Chef:'🍳',Firefighter:'⛑️','Rock Star':'👑'};
function charHTML(k,extra=''){return `
${SQUAD[k].svg()}
`}
function dress(el,costume){const h=el.querySelector('.hat'),o=el.querySelector('.hold');if(!h)return;if(!costume){h.textContent='';o.textContent='';return}
const c=COSTUMES.find(x=>x[0]===costume);h.textContent=HATS[costume]||'';o.textContent=c?c[2]:''}
function act(el,on){if(el)el.classList.toggle('act',!!on)}
function hop(el){if(!el)return;el.classList.remove('hop');void el.offsetWidth;el.classList.add('hop')}
/* ---------- AUDIO ---------- */
let AC=null,master=null,musicGain=null,voiceGain=null,whooshNode=null,noiseBuf=null,speaking=false;
/* iPhone: Web Audio is muted by the silent switch unless the page asks for "playback" audio. */
let silentEl=null;
function iosUnlock(){try{const want=(typeof mic!=='undefined'&&mic.state==='on')?'play-and-record':'playback';if(navigator.audioSession&&navigator.audioSession.type!==want)navigator.audioSession.type=want}catch(e){}
if(!('audioSession' in navigator)){try{if(!silentEl){silentEl=new Audio('audio/silence.mp3');silentEl.loop=true;silentEl.setAttribute('playsinline','')}const p=silentEl.play();if(p&&p.catch)p.catch(()=>{})}catch(e){}}}
function wake(){iosUnlock();if(AC&&AC.state!=='running'){try{const p=AC.resume();if(p&&p.catch)p.catch(()=>{})}catch(e){}}}
['pointerdown','touchend','click','keydown'].forEach(ev=>document.addEventListener(ev,wake,{passive:true,capture:true}));
document.addEventListener('visibilitychange',()=>{if(!document.hidden)wake()});
function initAudio(){iosUnlock();if(AC){wake();return}try{AC=new(window.AudioContext||window.webkitAudioContext)();try{AC.resume()}catch(e){}master=AC.createGain();master.gain.value=.5;master.connect(AC.destination);musicGain=AC.createGain();musicGain.gain.value=.6;musicGain.connect(master);voiceGain=AC.createGain();voiceGain.gain.value=1.7;voiceGain.connect(AC.destination)}catch(e){AC=null}}
function tone(f,d,type='sine',v=.2,when=0,slide,dest){if(!AC)return;const t=AC.currentTime+when,o=AC.createOscillator(),g=AC.createGain();o.type=type;o.frequency.setValueAtTime(f,t);if(slide)o.frequency.exponentialRampToValueAtTime(slide,t+d);g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(v,t+.015);g.gain.exponentialRampToValueAtTime(.0001,t+d);o.connect(g);g.connect(dest||master);o.start(t);o.stop(t+d+.05)}
const sfx={chime(){[523,659,784,1047].forEach((f,i)=>tone(f,.4,'triangle',.17,i*.09))},pop(){tone(760,.16,'sine',.22,0,260)},boing(){tone(330,.45,'sine',.2,0,130)},hop(){tone(380,.16,'square',.05,0,820)},tap(){tone(900,.07,'sine',.1)},
fanfare(){[392,523,659,784,659,784,1047].forEach((f,i)=>tone(f,.32,'triangle',.17,i*.13))},
drum(){for(let i=0;i<14;i++)tone(140+i*6,.06,'triangle',.12+i*.008,i*.07)},
rimshot(){tone(200,.12,'square',.12);tone(900,.25,'triangle',.12,.12);tone(1300,.35,'triangle',.08,.16)},
silly(){tone(500,.18,'sine',.18,0,900);tone(900,.18,'sine',.18,.18,400);tone(400,.3,'sine',.18,.36,700)},
slide(){tone(300,.5,'sine',.15,0,1200)},
sparkle(){[1319,1568,2093,2637].forEach((f,i)=>tone(f,.25,'sine',.08,i*.06))},
bloop(){tone(180,.35,'sine',.3,0,520);tone(520,.25,'sine',.15,.3,260)},
scratch(){tone(900,.35,'sawtooth',.08,0,90)},
slideUp(){const t=AC&&AC.currentTime;if(!AC)return;const o=AC.createOscillator(),g=AC.createGain(),l=AC.createOscillator(),lg=AC.createGain();o.type='sine';o.frequency.setValueAtTime(400,t);o.frequency.exponentialRampToValueAtTime(1600,t+.5);l.frequency.value=12;lg.gain.value=25;l.connect(lg);lg.connect(o.frequency);g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(.16,t+.03);g.gain.exponentialRampToValueAtTime(.001,t+.55);o.connect(g);g.connect(master);o.start(t);l.start(t);o.stop(t+.6);l.stop(t+.6)},
slideDown(){const t=AC&&AC.currentTime;if(!AC)return;const o=AC.createOscillator(),g=AC.createGain();o.type='sine';o.frequency.setValueAtTime(1400,t);o.frequency.exponentialRampToValueAtTime(300,t+.6);g.gain.setValueAtTime(.15,t);g.gain.exponentialRampToValueAtTime(.001,t+.65);o.connect(g);g.connect(master);o.start(t);o.stop(t+.7)},
boing2(){const t=AC&&AC.currentTime;if(!AC)return;const o=AC.createOscillator(),g=AC.createGain(),l=AC.createOscillator(),lg=AC.createGain();o.type='triangle';o.frequency.value=220;l.frequency.setValueAtTime(18,t);l.frequency.exponentialRampToValueAtTime(4,t+.6);lg.gain.setValueAtTime(120,t);lg.gain.exponentialRampToValueAtTime(5,t+.6);l.connect(lg);lg.connect(o.frequency);g.gain.setValueAtTime(.22,t);g.gain.exponentialRampToValueAtTime(.001,t+.65);o.connect(g);g.connect(master);o.start(t);l.start(t);o.stop(t+.7);l.stop(t+.7)},
kazoo(){if(!AC)return;[523,659,784,1047,784,1047].forEach((f,i)=>{const t=AC.currentTime+i*.12,o=AC.createOscillator(),bp=AC.createBiquadFilter(),g=AC.createGain(),l=AC.createOscillator(),lg=AC.createGain();o.type='sawtooth';o.frequency.value=f;l.frequency.value=7;lg.gain.value=f*.02;l.connect(lg);lg.connect(o.frequency);bp.type='bandpass';bp.frequency.value=1400;bp.Q.value=2;g.gain.setValueAtTime(0,t);g.gain.linearRampToValueAtTime(.12,t+.02);g.gain.exponentialRampToValueAtTime(.001,t+(i===5?.5:.16));o.connect(bp);bp.connect(g);g.connect(master);o.start(t);l.start(t);o.stop(t+.55);l.stop(t+.55)})},
honk2(){tone(330,.16,'square',.1);tone(262,.25,'square',.1,.18)},
chomp(){noiseHit(.07,900,'bandpass',.5);noiseHit(.07,900,'bandpass',.5,.16);tone(220,.1,'square',.06,0,120)},
toot(){tone(110,.55,'sawtooth',.16,0,70);tone(95,.5,'square',.06,.05,60)},
honk(){tone(392,.22,'square',.12);tone(330,.3,'square',.12,.26)}};
function noiseHit(dur,freq,type,v,when=0){if(!AC)return;if(!noiseBuf){noiseBuf=AC.createBuffer(1,AC.sampleRate*2,AC.sampleRate);const d=noiseBuf.getChannelData(0);for(let i=0;i{const s=beatStep%16;if(s%4===0)kick();if(s===4||s===12)noiseHit(.13,1800,'highpass',.3);if(s%2===0)noiseHit(.03,7000,'highpass',.09);if(BASS[s])tone(BASS[s],.2,'square',.06);if(s%2===1)tone(ARP[(beatStep>>1)%8],.13,'triangle',.06);beatStep++},125)}
function beatStop(){clearInterval(beatTimer);beatTimer=null}
function whoosh(on){if(!AC)return;const now=AC.currentTime;if(on){if(whooshNode)return;if(!noiseBuf){noiseBuf=AC.createBuffer(1,AC.sampleRate*2,AC.sampleRate);const d=noiseBuf.getChannelData(0);for(let i=0;iwhoosh(false),ms)}
let musicTimer=null,mStep=0;const GROOVE=[523,0,659,0,784,0,659,784,880,0,784,0,659,0,587,0,523,0,659,0,784,0,1047,0,988,0,880,0,784,659,587,0],BASS2=[131,131,175,175,196,196,131,196];const MEL=[523,659,784,659,587,698,880,698,523,659,784,1047,880,784,659,587];
function setMusic(on){state.music=on;$('#musicBtn').classList.toggle('off',!on);clearInterval(musicTimer);musicTimer=null;if(on){initAudio();if(!AC)return;duck(speaking);musicTimer=setInterval(()=>{const s=mStep++%32,f=GROOVE[s];if(f)tone(f,.16,'triangle',.07,0,null,musicGain);if(s%4===0)tone(BASS2[(s>>2)%8],.22,'triangle',.09,0,null,musicGain);if(s%8===4)tone(1800,.03,'square',.012,0,null,musicGain)},190)}}
function duck(on){if(!musicGain||!AC)return;const e=document.getElementById('ear');const lis=(e&&e.classList.contains('on'))||(typeof mic!=='undefined'&&mic.rec);musicGain.gain.setTargetAtTime(lis?0:(on?.12:.5),AC.currentTime,.08)}
/* ---------- VOICE: Kokoro Heart clips, never overlapping ---------- */
let voice=null;
function enVoices(){if(!('speechSynthesis' in window))return[];return speechSynthesis.getVoices().filter(v=>/^en([-_]|$)/i.test(v.lang))}
function pickVoice(){const en=enVoices();if(!en.length)return;if(state.voiceName){const v=en.find(v=>v.name===state.voiceName);if(v){voice=v;return}}
const sc=v=>{let s=0;if(/en[-_]US/i.test(v.lang))s+=3;if(/premium/i.test(v.name))s+=7;if(/enhanced|neural|natural/i.test(v.name))s+=5;if(/Ava|Samantha|Allison|Aria|Jenny|Google US English/i.test(v.name))s+=3;if(/Albert|Bad News|Bahh|Bells|Boing|Bubbles|Cellos|Wobble|Zarvox|Trinoids|Whisper|Jester|Organ|Superstar|Fred|Ralph|Junior|Grandma|Grandpa|Rocko|Good News/i.test(v.name))s-=20;return s};
voice=en.slice().sort((a,b)=>sc(b)-sc(a))[0]}
function fillVoiceSel(){const sel=$('#voiceSel');const en=enVoices();sel.innerHTML=en.map(v=>``).join('')||'';if(voice)sel.value=voice.name}
if('speechSynthesis' in window){speechSynthesis.onvoiceschanged=()=>{pickVoice();fillVoiceSel()};pickVoice()}
function setCaption(t){$('#cap').textContent=t}
const CLIPS={"open wide just a tiny bit": "366e7e8a92.mp3", "let your tongue peek out like a puppy tongue": "bc497ca990.mp3", "now blow softly like a little breeze": "6e02f3efdc.mp3", "w:thumb": "be868afff3.mp3", "slow:thumb": "0770c1fe60.mp3", "your turn say thumb": "4eda773f21.mp3", "w:three": "54f7f97599.mp3", "slow:three": "659ab9f0e7.mp3", "your turn say three": "fc3ed7cf89.mp3", "w:think": "d588c62718.mp3", "slow:think": "659b75e53c.mp3", "your turn say think": "04a37d6fe7.mp3", "w:thunder": "d14cad4b10.mp3", "slow:thunder": "b103dc271b.mp3", "your turn say thunder": "b230c1027e.mp3", "w:bath": "b1bfb698e1.mp3", "slow:bath": "ee65d6f86b.mp3", "your turn say bath": "a3549cc069.mp3", "w:teeth": "1d711a2f5f.mp3", "slow:teeth": "f97e6f1ec1.mp3", "your turn say teeth": "c7e35ce3f5.mp3", "w:mouth": "ac736979b3.mp3", "slow:mouth": "573fbab9ac.mp3", "your turn say mouth": "952c954836.mp3", "it's thunder the puppy thunder's sound has a peeking tongue like in thumb": "d19a11610e.mp3", "your turn make thunder's sound": "4f55a6ae7d.mp3", "woohoo that's thunder's sound": "28cf63ca23.mp3", "thunder loves bubbles make thunder's sound to blow bubbles keep going": "b175749f70.mp3", "look at all those bubbles thunder is so happy": "d303b1d123.mp3", "thunder is hungry say each word to feed him": "d1b402d329.mp3", "you found thunder": "e7e8942ecc.mp3", "ta da it's super thunder": "0ad02d0602.mp3", "ta da it's pirate thunder": "385e8b9d94.mp3", "ta da it's space thunder": "8e3cfc0bd5.mp3", "ta da it's wizard thunder": "ca567fd41c.mp3", "ta da it's chef thunder": "5822552e06.mp3", "ta da it's firefighter thunder": "fb090d6335.mp3", "ta da it's rock star thunder": "35d16341e3.mp3", "bye bye thunder who's next": "71d983132c.mp3", "make bunny teeth put them on your bottom lip": "6a507440fb.mp3", "w:fish": "e606954544.mp3", "slow:fish": "4721ff2d46.mp3", "your turn say fish": "f879f58145.mp3", "w:fan": "01475a9ede.mp3", "slow:fan": "6da44e3ebb.mp3", "your turn say fan": "229020cae8.mp3", "w:feet": "c8b88c2d9e.mp3", "slow:feet": "f4bc85da4c.mp3", "your turn say feet": "68232706a8.mp3", "w:fox": "0d3c39d6bc.mp3", "slow:fox": "dbd73fe4a5.mp3", "your turn say fox": "a61bd4e6a7.mp3", "w:fork": "1d6e9dde95.mp3", "slow:fork": "de13eb1454.mp3", "your turn say fork": "d798fc5c51.mp3", "w:five": "04ebd423c4.mp3", "slow:five": "449dcbe297.mp3", "your turn say five": "2117c0e42a.mp3", "it's fifi the bunny fifi's sound has bunny teeth like in fish": "3379b10785.mp3", "your turn make fifi's sound": "af878b4d7e.mp3", "hooray that's fifi's sound": "bdc31816bd.mp3", "fifi has a party cake make fifi's sound to blow out the candles": "5ba57420dc.mp3", "you blew out all the candles hooray for fifi": "8b8bfa5849.mp3", "fifi is hungry say each word to feed her": "d2cf3a3cdf.mp3", "you found fifi": "663e9dfadd.mp3", "ta da it's super fifi": "cc5df5f983.mp3", "ta da it's pirate fifi": "258c249c99.mp3", "ta da it's space fifi": "4fe6feff41.mp3", "ta da it's wizard fifi": "05bac0f8d2.mp3", "ta da it's chef fifi": "0ea9a3e14b.mp3", "ta da it's firefighter fifi": "934068d3ca.mp3", "ta da it's rock star fifi": "ce7a5e8eaa.mp3", "bye bye fifi who's next": "28c9c55a0c.mp3", "now turn on your motor and make it buzz your lip will tickle": "3cf00bac19.mp3", "w:van": "c42e8fb1be.mp3", "slow:van": "b08cfdd8d4.mp3", "your turn say van": "00cad95a48.mp3", "w:vase": "de519e077d.mp3", "slow:vase": "137d1b614c.mp3", "your turn say vase": "df6f5ffba1.mp3", "w:violin": "0b54fa5687.mp3", "slow:violin": "9bf0a189a7.mp3", "your turn say violin": "1426c72ad9.mp3", "w:volcano": "9a9a001af1.mp3", "slow:volcano": "e048f4ef6e.mp3", "your turn say volcano": "849756ae45.mp3", "it's vinny the race car vinny's sound is a buzzy motor like in van": "be87fa3010.mp3", "your turn make vinny's motor sound": "81a1f82476.mp3", "yippee that's vinny's sound": "eb4ed3a895.mp3", "help vinny win the race make vinny's motor sound to drive keep going": "99eb7e65b9.mp3", "vinny wins the race hooray": "4c9860eb70.mp3", "vinny needs fuel say each word to fill him up": "19008f0500.mp3", "you found vinny": "8c1e3ff92d.mp3", "ta da it's super vinny": "eff4ea5c7a.mp3", "ta da it's pirate vinny": "bc938393af.mp3", "ta da it's space vinny": "10ba8b4059.mp3", "ta da it's wizard vinny": "712ecc74fb.mp3", "ta da it's chef vinny": "513d1dde64.mp3", "ta da it's firefighter vinny": "c52d4a26e5.mp3", "ta da it's rock star vinny": "d79055be34.mp3", "bye bye vinny who's next": "4f73317bba.mp3", "smile big and put your teeth together": "ba8ddb359f.mp3", "keep your tongue hiding inside": "393d2b6de5.mp3", "now let the air hiss out like a happy snake": "024f0db743.mp3", "w:sun": "31234f0b9d.mp3", "slow:sun": "fa3b4a0692.mp3", "your turn say sun": "93ccf1ebf5.mp3", "w:sock": "6ca5215f78.mp3", "slow:sock": "7e30f3666e.mp3", "your turn say sock": "1ac3d10398.mp3", "w:soap": "c7f57800fb.mp3", "slow:soap": "490698060e.mp3", "your turn say soap": "87828d2eb8.mp3", "w:soup": "070fd95c24.mp3", "slow:soup": "0a9f7d7d7a.mp3", "your turn say soup": "cfc7aad5ec.mp3", "w:six": "c14739374c.mp3", "slow:six": "641571012c.mp3", "your turn say six": "57d747d0be.mp3", "w:sandwich": "6ace1d926c.mp3", "slow:sandwich": "8f05c2f49c.mp3", "your turn say sandwich": "816c62a2a7.mp3", "it's sunny the snake sunny's sound is a happy hiss like in sun": "b6e8638118.mp3", "your turn make sunny's hissy sound": "1eb317ae26.mp3", "yes that's sunny's sound": "d83f294c3d.mp3", "sunny wants to fly a balloon make sunny's sound to fill it up": "1d30b46d31.mp3", "up up and away sunny's balloon is flying": "44e096da5d.mp3", "sunny is hungry say each word to feed her": "e90a82727d.mp3", "you found sunny": "91821c4f89.mp3", "ta da it's super sunny": "84e486c171.mp3", "ta da it's pirate sunny": "af6aa308cc.mp3", "ta da it's space sunny": "904c30839c.mp3", "ta da it's wizard sunny": "1b31e5097c.mp3", "ta da it's chef sunny": "846435c7c9.mp3", "ta da it's firefighter sunny": "91a4f59be9.mp3", "ta da it's rock star sunny": "6bef30dabd.mp3", "bye bye sunny who's next": "4bc7c7d36b.mp3", "hee hee that was a snake hiss like sunny's for thunder let your tongue peek out and blow softly": "b6c16b425e.mp3", "pop that was quick for thunder let your tongue peek out and make it long like a breeze": "0e1974c024.mp3", "hee hee that was sunny's snake hiss for fifi put your top teeth on your lip and blow softly": "f48bb3ff6b.mp3", "pop that was quick for fifi put your teeth on your lip and make it long like a breeze": "5298be6843.mp3", "ooh a soft breezy sound like thunder's for sunny put your teeth together smile and hiss": "b4526d9e85.mp3", "pop that was quick for sunny make it long like a snake teeth together and hiss": "b5e4a508e4.mp3", "ooh a hissy sound for vinny put your teeth on your lip and turn on your buzzy motor": "616a31a852.mp3", "i can't hear you can you say it with a big lion voice": "3bcd852714.mp3", "here comes a yummy word": "4114898785.mp3", "ooh what's this": "0e1eba694a.mp3", "next one": "47660cec0d.mp3", "what do you call a sleeping dinosaur": "12c2d19ca8.mp3", "a dino snore": "a08a73cd60.mp3", "what do you call a snake that builds houses": "bfe5ef69ce.mp3", "a boa constructor": "409f7787fd.mp3", "what does a race car eat": "617cdd6c65.mp3", "fast food": "2b50b29ca6.mp3", "what is a puppy's favorite snack": "a4bbd56bec.mp3", "pup corn": "3fb22243ec.mp3", "knock knock who's there lettuce": "31c4c9e693.mp3", "lettuce who lettuce play some more": "d9a54517df.mp3", "where do dogs park their cars": "eacde12a0d.mp3", "in the barking lot": "6877c458eb.mp3", "v_th:woof woof hi hi hi wanna play with me": "0d8ed8f141.mp3", "v_th:hee hee hee that tickles": "461bdf23af.mp3", "v_th:woof do it again": "4309f62b16.mp3", "v_th:woof you did it yippee": "ad29266c38.mp3", "v_th:woof woof hooray": "7344e7f879.mp3", "v_th:yum yum yum woof": "444a050b65.mp3", "v_th:burp oops woof": "65ee6b6194.mp3", "v_th:bye bye woof woof": "da523fd800.mp3", "v_th:woof woof dance with me": "c8e68f8104.mp3", "v_f:hop hop hop hello let's play": "e4a5930422.mp3", "v_f:hee hee bunny giggles": "5bbdc28fc0.mp3", "v_f:yippee you did it": "266394760d.mp3", "v_f:crunchy munchy yum": "162de2fa42.mp3", "v_f:nom nom nom yummy": "c5eb0f3a68.mp3", "v_f:bye bye hop hop": "ec6dd3ec8e.mp3", "v_f:hop hop dance with me": "dae13eaa76.mp3", "v_v:beep beep ready set go": "2645adb918.mp3", "v_v:beep hee hee that tickles": "7431716012.mp3", "v_v:beep beep beep hee hee": "27464536e8.mp3", "v_v:beep beep you're a superstar": "19854a6648.mp3", "v_v:glug glug glug yummy": "43f795bb40.mp3", "v_v:beep beep bye bye": "6ffccbed98.mp3", "v_v:beep beep dance with me": "5c0e18d0a4.mp3", "v_s:hiss hiss hello hello i'm so happy": "acc2dffdc2.mp3", "v_s:hee hee wiggle wiggle": "4a62c88a2b.mp3", "v_s:hee hee hee that tickles": "66cd27e406.mp3", "v_s:yes yes yes you did it": "461b0a5962.mp3", "v_s:slurp yummy yummy": "0df19aa80e.mp3", "v_s:slurp slurp yum": "f5f3dfebfc.mp3", "v_s:bye bye hiss hiss": "1e56f98d82.mp3", "v_s:wiggle wiggle dance with me": "f10e8b4b4e.mp3", "wiggle wiggle": "a2bdcab01d.mp3", "spin around": "279e2d8240.mp3", "wiggle your tongue peek peek peek": "0c8f95baf0.mp3", "knock knock who is coming to play today tap the door": "1b4fdb2a7c.mp3", "who said it listen and tap the friend whose sound you hear": "631614473e.mp3", "listen again": "5c6d8951db.mp3", "let's do it together slowly": "f016159d20.mp3", "ooh nice try": "ed2c58fe1c.mp3", "prize time tap the present": "9922373dc2.mp3", "ready for a joke": "697c82a59c.mp3", "hee hee hee": "316a3fadca.mp3", "oops was that a toot hee hee": "01ff1b5015.mp3", "beep beep coming through": "f6160d68d3.mp3", "peekaboo i see you": "0b4669bd8d.mp3", "squad dance party dance with your friends": "40db5a56ad.mp3", "freeze": "eb47960527.mp3", "dance": "3355d92c04.mp3", "v_f:hop hop hee hee": "14d75e8d31.mp3", "v_f:yay you did it hop hop": "f35e1f7ef3.mp3", "v_v:yay beep beep you did it": "c60e7abe2b.mp3", "v_v:yummy burp beep beep": "7d8d4aea48.mp3", "v_s:yay wiggle wiggle": "7e47bdfe86.mp3"};
const bufCache={};let curSrc=null,sayId=0;
function ckey(t){return t.toLowerCase().replace(/’/g,"'").replace(/[^a-z0-9' ]+/g,' ').replace(/\s+/g,' ').trim()}
function loadClip(fn){if(!bufCache[fn])bufCache[fn]=fetch('audio/'+fn).then(r=>{if(!r.ok)throw 0;return r.arrayBuffer()}).then(b=>new Promise((res,rej)=>AC.decodeAudioData(b,res,rej))).catch(e=>{delete bufCache[fn];throw e});return bufCache[fn]}
function preloadClips(){if(!AC)return;let i=0;const fns=Object.values(CLIPS);const next=()=>{if(i>=fns.length)return;loadClip(fns[i++]).catch(()=>{}).finally(next)};for(let k=0;k<4;k++)next()}
function stopVoice(){sayId++;if(curSrc){const c=curSrc;curSrc=null;try{c.stop()}catch(e){}}if('speechSynthesis' in window)speechSynthesis.cancel()}
const nm=()=>state.name?', '+state.name:'';
function say(text,o={}){setCaption(o.caption!=null?o.caption:text);stopVoice();const id=sayId;const fn=CLIPS[(o.pre||'')+ckey(text)];
return new Promise(res=>{let done=false,tm=null;const fin=()=>{if(done)return;done=true;clearTimeout(tm);if(id===sayId){speaking=false;duck(false)}res()};
speaking=true;duck(true);
const tts=()=>{if(id!==sayId)return fin();if(!('speechSynthesis' in window)){tm=setTimeout(fin,900+text.length*70);return}
const u=new SpeechSynthesisUtterance(text);if(voice)u.voice=voice;u.lang=voice?voice.lang:'en-US';u.rate=(o.rate||.9)*.85;u.pitch=1.1;u.onend=fin;u.onerror=fin;tm=setTimeout(fin,2000+text.length*140/u.rate);setTimeout(()=>{if(!done)speechSynthesis.speak(u)},70)};
if(fn&&AC){loadClip(fn).then(buf=>{if(id!==sayId)return fin();const src=AC.createBufferSource();src.buffer=buf;src.connect(voiceGain);src.onended=fin;curSrc=src;src.start();tm=setTimeout(fin,buf.duration*1000+1500)}).catch(tts)}else tts()})}
/* ---------- MOUTH ---------- */
const BASE={open:.06,spread:.3,tOut:0,tUp:0,bite:0,air:0,buzz:0};
const POSES={rest:{},open:{open:.34,spread:.38},th:{open:.6,spread:.45,tOut:1,tUp:.5},thAir:{open:.6,spread:.45,tOut:1,tUp:.5,air:1},thBuzz:{open:.6,spread:.45,tOut:1,tUp:.5,buzz:1},
f:{open:.5,spread:.5,bite:1,air:1},d:{open:.75,spread:.4,tUp:1},s:{open:.36,spread:.95,air:1},smile:{open:.38,spread:.95},fRest:{open:.5,spread:.5,bite:1},v:{open:.5,spread:.5,bite:1,buzz:1},sRest:{open:.36,spread:.95}};
const mouths=[];let mid=0;
function mouthMarkup(id){let up='',lo='';for(let i=0;i<6;i++){up+=``;lo+=``}
return ``}
function makeMouth(el){const id=++mid;el.innerHTML=mouthMarkup(id);const q=s=>el.querySelector(s);
const m={el,p:{...BASE},t:{...BASE},pt:[],spawn:0,
P:{out:q('.mOut'),int:q('.mInt'),intF:q('.mIntF'),up:q('.tUp'),lo:q('.tLo'),back:q('.tBack'),fG:q('.tFront'),fE:q('.tFrontE'),eyes:q('.tEyes'),air:q('.air'),buzz:q('.buzz'),bzL:q('.bzL'),bzR:q('.bzR'),jit:q('.jit')},
set(n){this.t={...BASE,...(POSES[n]||{})}}};
for(let i=0;i<14;i++){const c=document.createElementNS('http://www.w3.org/2000/svg','circle');c.setAttribute('fill','#ffffff55');c.setAttribute('stroke','#fff');c.setAttribute('stroke-width','3');c.setAttribute('r','0');m.P.air.appendChild(c);m.pt.push({c,life:0})}
mouths.push(m);updateMouth(m,1);return m}
function updateMouth(m,dt){const p=m.p,t=m.t,k=Math.min(1,dt*5);for(const key in p)p[key]+=(t[key]-p[key])*k;
const cx=200,cy=150,hw=105+p.spread*28,gap=6+p.open*70,uy=cy-gap/2,ly0=cy+gap/2,ly=ly0+(uy+14-ly0)*p.bite;
m.P.out.setAttribute('d',`M${cx-hw},${cy} C${cx-hw*.55},${uy-30} ${cx-34},${uy-36} ${cx},${uy-21} C${cx+34},${uy-36} ${cx+hw*.55},${uy-30} ${cx+hw},${cy} C${cx+hw*.7},${ly+42} ${cx-hw*.7},${ly+42} ${cx-hw},${cy}Z`);
const xi=hw-12,Yu=(8*uy-2*cy)/6,Yl=(8*ly-2*cy)/6,d=`M${cx-xi},${cy} C${cx-xi*.5},${Yu} ${cx+xi*.5},${Yu} ${cx+xi},${cy} C${cx+xi*.5},${Yl} ${cx-xi*.5},${Yl} ${cx-xi},${cy}Z`;
m.P.int.setAttribute('d',d);m.P.intF.setAttribute('d',d);
m.P.up.setAttribute('transform',`translate(0,${uy.toFixed(1)})`);m.P.lo.setAttribute('transform',`translate(0,${ly0.toFixed(1)})`);
m.P.back.setAttribute('cy',((ly0+26)+((uy+14)-(ly0+26))*p.tUp).toFixed(1));
const top=uy+15,full=Math.max(0,(ly0+24-top)/2),ry=Math.max(.01,full*p.tOut);
m.P.fE.setAttribute('ry',ry.toFixed(2));m.P.fE.setAttribute('cy',(top+ry).toFixed(1));m.P.fG.style.opacity=Math.min(1,p.tOut*3);
m.P.eyes.setAttribute('transform',`translate(0,${(top+ry*1.05).toFixed(1)})`);m.P.eyes.style.opacity=Math.max(0,Math.min(1,(p.tOut-.75)/.25));
m.spawn-=dt;if(p.air>.5&&m.spawn<=0){m.spawn=.11;const s=m.pt.find(o=>o.life<=0);if(s){s.life=1;s.x=cx+(Math.random()-.5)*40;s.y=(uy+ly)/2+6;s.vx=(Math.random()-.5)*50;s.r=6}}
for(const s of m.pt){if(s.life>0){s.life-=dt*.9;s.r+=dt*40;s.y+=dt*32;s.x+=s.vx*dt;s.c.setAttribute('cx',s.x.toFixed(1));s.c.setAttribute('cy',s.y.toFixed(1));s.c.setAttribute('r',s.r.toFixed(1));s.c.style.opacity=Math.max(0,s.life*.8)}else s.c.style.opacity=0}
m.P.buzz.style.opacity=p.buzz;
if(p.buzz>.05){const z=x0=>{let s=`M${x0},96`;for(let i=1;i<=8;i++)s+=` L${x0+(i%2?1:-1)*(9+Math.random()*7)},${96+i*14}`;return s};m.P.bzL.setAttribute('d',z(44));m.P.bzR.setAttribute('d',z(356));
m.P.jit.setAttribute('transform',`translate(${((Math.random()-.5)*2*p.buzz).toFixed(1)},${((Math.random()-.5)*2*p.buzz).toFixed(1)})`)}else m.P.jit.removeAttribute('transform')}
/* ---------- FX ---------- */
const fx=$('#fx'),fctx=fx.getContext('2d');let conf=[];
function sizeFx(){fx.width=innerWidth*devicePixelRatio;fx.height=innerHeight*devicePixelRatio}addEventListener('resize',sizeFx);sizeFx();
function confetti(n=110){const cols=['#ff5d8f','#ffc93c','#3fbf74','#36a9e1','#8a6cff','#ff9f43'];for(let i=0;ic.life>0&&c.ys.remove(),9500)}
let btBusy=false;
function bigRise(talk=true){if(btBusy)return;btBusy=true;const b=$('#bigTurtle');const side=pick([18,82,22,78,50]);b.style.left=side+'vw';b.classList.remove('up');void b.offsetWidth;b.classList.add('up');sfx.bloop();
for(let i=0;i<6;i++)setTimeout(()=>{const d=document.createElement('div');d.className='flo leap';d.textContent=pick(['✨','⭐','💛']);d.style.left=(parseFloat(b.style.left)-10+Math.random()*20)+'vw';d.style.top='78vh';d.style.fontSize='34px';$('#fxLayer').appendChild(d);setTimeout(()=>d.remove(),2100)},300+i*90);
setTimeout(()=>{if(talk&&!speaking){sfx.silly();say('Peekaboo! I see you!')}},3300);setTimeout(()=>{b.classList.remove('up');btBusy=false},5600)}
function surprise(){const r=Math.random();sfx.pop();
if(r<.28)return bigRise();
if(r<.40)return floater('🐶','swim');
const[e,a]=pick([['🐟','leap'],['🐬','leap'],['🦋','fly'],['🚀','rise'],['🎈','rise'],['🦀','fly'],['🦄','fly'],['🐙','leap'],['🦖','fly'],['🐸','leap'],['🌈','rise'],['🐳','leap']]);floater(e,a);if(Math.random()<.4)setTimeout(()=>floater(pick(['🎈','🫧','⭐']),'rise'),400)}
let last=performance.now();
function loop(now){const dt=Math.min(.05,(now-last)/1000);last=now;for(const m of mouths)if(m.el.offsetParent!==null)updateMouth(m,dt);powerTick(dt);earTick();drawConf(dt);requestAnimationFrame(loop)}
requestAnimationFrame(loop);
/* Silly Sound Squad listener: finds the word in a short recording and measures the hiss next to the vowel.
Verdicts: soft (a soft, spread hiss: TH or F), sharp (a loud, narrow S/Z hiss), pop (no long hiss: T, P, D),
voice (voicing, used for V), quiet (nothing heard). TH and F sound almost the same, so the listener
cannot tell them apart: the mouth picture and a grown-up cover that one. Nothing is saved or sent. */
(function (G) {
function fft(re, im) {
const n = re.length;
for (let i = 1, j = 0; i < n; i++) {
let bit = n >> 1;
for (; j & bit; bit >>= 1) j ^= bit;
j ^= bit;
if (i < j) { let t = re[i]; re[i] = re[j]; re[j] = t; t = im[i]; im[i] = im[j]; im[j] = t; }
}
for (let len = 2; len <= n; len <<= 1) {
const a = -2 * Math.PI / len, wr = Math.cos(a), wi = Math.sin(a);
for (let i = 0; i < n; i += len) {
let cr = 1, ci = 0;
for (let k = 0; k < len / 2; k++) {
const ur = re[i + k], ui = im[i + k];
const vr = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci;
const vi = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr;
re[i + k] = ur + vr; im[i + k] = ui + vi;
re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi;
const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t;
}
}
}
}
const winCache = {};
function hann(N) { if (!winCache[N]) { const w = new Float32Array(N); for (let i = 0; i < N; i++) w[i] = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (N - 1)); winCache[N] = w; } return winCache[N]; }
function frameSize(sr) { return sr > 32000 ? 1024 : 512; }
// One frame of features from N samples starting at s.
function frame(x, s, N, sr) {
const w = hann(N), re = new Float64Array(N), im = new Float64Array(N);
let sq = 0, zc = 0, prev = x[s];
for (let i = 0; i < N; i++) { const v = x[s + i]; sq += v * v; re[i] = v * w[i]; if ((v >= 0) !== (prev >= 0)) zc++; prev = v; }
fft(re, im);
const bin = sr / N, half = N / 2, top = Math.min(11000, sr / 2 - bin);
let low = 0, mid = 0, high = 0, cn = 0, cd = 0, fl = 0, fa = 0, fc = 0, mx = 0, ca = 0, cc = 0;
for (let k = 1; k < half; k++) {
const f = k * bin, p = re[k] * re[k] + im[k] * im[k] + 1e-12;
if (f >= 80 && f < 900) low += p; else if (f >= 900 && f < 3000) mid += p; else if (f >= 3000 && f <= top) high += p;
if (f >= 1000 && f <= top) { cn += f * p; cd += p; }
if (f >= 1500 && f <= Math.min(10000, top)) { fl += Math.log(p); fa += p; fc++; }
if (f >= 3000 && f <= Math.min(10000, top)) { if (p > mx) mx = p; ca += p; cc++; }
}
const rms = Math.sqrt(sq / N);
return { db: 20 * Math.log10(rms + 1e-9), low, mid, high, zcr: zc / N,
cen: cd ? cn / cd : 0, flat: fc ? Math.exp(fl / fc) / (fa / fc) : 0, crest: cc ? mx / (ca / cc) : 0 };
}
function features(x, sr) {
const N = frameSize(sr), H = N / 2, out = [];
for (let s = 0; s + N <= x.length; s += H) { const f = frame(x, s, N, sr); f.t = s / sr; out.push(f); }
out.hopMs = 1000 * H / sr;
return out;
}
// The hiss right before (dir -1) or after (dir +1) the vowel.
function hissNear(F, from, dir, floor) {
const got = []; let miss = 0;
for (let i = from, n = 0; i >= 0 && i < F.length && n < 45; i += dir, n++) {
const f = F[i];
const fric = f.db > floor + 6 && f.high > f.low * 1.2 && f.zcr > 0.15;
if (fric) { got.push(f); miss = 0; }
else if (f.db < floor + 6) { if (++miss > 2 && got.length) break; if (miss > 4) break; }
else { if (++miss > 3) break; }
}
return got;
}
function analyze(x, sr, kind) {
const F = features(x, sr), hop = F.hopMs;
if (F.length < 8) return { verdict: 'quiet' };
const sorted = F.map(f => f.db).sort((a, b) => a - b);
const floor = Math.max(-75, sorted[Math.floor(sorted.length * 0.1)]), peak = sorted[sorted.length - 1];
if (peak - floor < 15) return { verdict: 'quiet', floor, peak };
// The vowel: the longest run of loud, low-pitched frames.
const voiced = F.map(f => f.db > peak - 24 && f.low > f.high && f.zcr < 0.2);
let best = null, s = -1, gap = 0; const runs = [];
for (let i = 0; i <= F.length; i++) {
if (i < F.length && voiced[i]) { if (s < 0) s = i; gap = 0; }
else if (s >= 0) {
if (i < F.length && ++gap <= 2) continue;
const e = i - gap; runs.push({ s, e }); if (!best || e - s > best.e - best.s) best = { s, e }; s = -1; gap = 0;
}
}
if (!best || (best.e - best.s + 1) * hop < 50) return { verdict: 'quiet', floor, peak };
const big = runs.filter(r => (r.e - r.s + 1) * hop >= 50);
if (kind === 'I' || kind === 'dhI' || kind === 'V') best = big[0]; else if (kind === 'F') best = big[big.length - 1];
let vpk = -200; for (let i = best.s; i <= best.e; i++) vpk = Math.max(vpk, F[i].db);
const info = { floor, peak, vowelMs: Math.round((best.e - best.s + 1) * hop) };
if (kind === 'thM' || kind === 'V') {
// Buzzy sounds (V, buzzy TH) and sounds in the middle of a word: heard is enough, unless a loud sharp hiss starts it (Z).
const pre = hissNear(F, best.s - 1, -1, floor);
if (pre.length >= 3) {
const top = pre.map(f => f.db).sort((a, b) => b - a).slice(0, 3), rel = top.reduce((a, b) => a + b, 0) / top.length - vpk;
const fl = pre.reduce((a, f) => a + f.flat, 0) / pre.length;
if (rel > -16 && fl < 0.25) return Object.assign({ verdict: 'sharp', rel, flat: fl }, info);
}
return Object.assign({ verdict: 'voice' }, info);
}
if (kind === 'dhI') {
// Buzzy TH: a soft start. D starts with a sudden burst; Z starts with a loud hiss.
const pre = hissNear(F, best.s - 1, -1, floor);
if (pre.length >= 3) {
const top = pre.map(f => f.db).sort((a, b) => b - a).slice(0, 3);
const rel = top.reduce((a, b) => a + b, 0) / top.length - vpk;
const cen = pre.reduce((a, f) => a + f.cen, 0) / pre.length;
info.rel = rel; info.cen = cen;
if (rel > -16 && cen > 4000) return Object.assign({ verdict: 'sharp' }, info);
}
// Rise time from first sound to near the vowel's peak.
let on = best.s; while (on > 0 && F[on - 1].db > floor + 8) on--;
let r = on; while (r < F.length && F[r].db < vpk - 8) r++;
info.rise = (r - on) * hop;
let jump = 0; for (let i = Math.max(1, on - 1); i <= Math.min(r, F.length - 1); i++) jump = Math.max(jump, F[i].db - F[i - 1].db);
info.jump = jump; info.onHigh = F[on].high / (F[on].low + 1e-12); info.onDb = F[on].db - vpk;
const quietBefore = on > 0 && F[on - 1].db < floor + 6;
return Object.assign({ verdict: 'voice' }, info);
}
const fr = kind === 'F' ? hissNear(F, best.e + 1, 1, floor) : hissNear(F, best.s - 1, -1, floor);
info.hissMs = Math.round(fr.length * hop);
if (fr.length) { const chron = kind === 'F' ? fr : fr.slice().reverse(), mx = Math.max(...fr.map(f => f.db));
info.attack = Math.max(chron[0].db, (chron[1] || chron[0]).db) - mx; info.mean = fr.reduce((a, f) => a + f.db, 0) / fr.length - vpk;
info.flat = fr.reduce((a, f) => a + f.flat, 0) / fr.length; }
if (fr.length * hop < 40) return Object.assign({ verdict: 'pop' }, info);
const top = fr.map(f => f.db).sort((a, b) => b - a).slice(0, 3);
const rel = top.reduce((a, b) => a + b, 0) / top.length - vpk;
const cen = fr.reduce((a, f) => a + f.cen, 0) / fr.length;
const crest = fr.reduce((a, f) => a + f.crest, 0) / fr.length;
Object.assign(info, { rel, cen, crest });
// A T or D: a loud puff that starts all at once and is over quickly.
if (kind === 'I' && info.mean > -13.5 && info.attack > -5 && info.hissMs <= 120) return Object.assign({ verdict: 'pop' }, info);
if (kind === 'I' && info.hissMs <= 65 && info.attack > -3.5) return Object.assign({ verdict: 'pop' }, info);
// An S: a narrow, sharp hiss (low flatness) that is fairly loud next to the vowel.
if (info.flat < 0.25 && info.mean > -18.5) return Object.assign({ verdict: 'sharp' }, info);
if (info.mean > -11) return Object.assign({ verdict: 'sharp' }, info);
if (info.mean > -20.5 && cen > 8000 && crest >= 10) return Object.assign({ verdict: 'sharp' }, info);
return Object.assign({ verdict: 'soft' }, info);
}
// Live sound for the blowing game: is this frame a soft TH breeze, a snake hiss or a voice?
function liveKind(f, floor) {
if (f.db < floor + 9) return 'none';
const hissy = f.high > f.low && f.zcr > 0.15;
if (hissy) return (f.flat < 0.25 && f.db > floor + 22) ? 'sharp' : 'soft';
if (f.low > f.high && f.zcr < 0.18) return (f.high > f.low * 0.05 || f.mid > f.low * 0.3) ? 'buzz' : 'voice';
return 'none';
}
G.SoundEar = { features, analyze, frame, frameSize, liveKind };
})(typeof window !== 'undefined' ? window : globalThis);
/* ---------- DANCE PARTY (freeze dance) ---------- */
const MOVES=[['mv-bounce',null],['mv-wiggle','Wiggle, wiggle!'],['mv-spin','Spin around!'],['mv-peek','Wiggle your tongue! Peek, peek, peek!'],['mv-jump',null]];
function setMove(m){const p=$('#partyTheo');MOVES.forEach(x=>p.classList.remove(x[0]));p.classList.add(m)}
let partyResume='home';
async function partyRun(T,dur,auto){const P=$('#party');P.classList.toggle('auto',!!auto);P.classList.remove('frozen');P.classList.add('on');$('#partyTheo').innerHTML=active().map(k=>charHTML(k,'act')).join('');setMove('mv-bounce');
await say('Squad dance party! Dance with your friends!');if(T!==tok)return;{const k=active()[J.round%active().length];await fsay(k,'dance',$(`#partyTheo .chwrap[data-ch="${k}"]`));if(T!==tok)return}
beatStart();const t0=Date.now();let nextFreeze=Date.now()+5000+Math.random()*3000,nextMove=Date.now()+3500,mi=0;
while(T===tok&&(dur==null||Date.now()-t0nextMove){mi=(mi+1+Math.floor(Math.random()*(MOVES.length-1)))%MOVES.length;const[m,line]=MOVES[mi];setMove(m);if(line)say(line);nextMove=Date.now()+4500}
if(Date.now()>nextFreeze){beatStop();sfx.scratch();P.classList.add('frozen');await say('Freeze!');if(T!==tok)break;await wait(2300);if(T!==tok)break;P.classList.remove('frozen');await say('Dance!');if(T!==tok)break;beatStart();nextFreeze=Date.now()+6500+Math.random()*4000}}
beatStop();if(T!==tok)return;P.classList.remove('frozen');await say(`Great dancing${nm()}!`);P.classList.remove('on','auto')}
$('#danceBtn').onclick=()=>{sfx.tap();partyResume=$('#s-home').classList.contains('on')?'home':'journey';const T=newTok();partyRun(T,null,false)};
$('#partyX').onclick=()=>{sfx.tap();newTok();if(partyResume==='home')homeScene();else journeyGo()};
$('#partyTheo').onclick=()=>{sfx.silly();const p=$('#partyTheo');p.animate([{transform:'scale(1)'},{transform:'scale(1.15) rotate(-8deg)'},{transform:'scale(1)'}],{duration:400})};
/* ---------- MICROPHONE (the game listens) ---------- */
const mic={state:'off',stream:null,proc:null,floorArr:[],floor:-60,rec:null,onLive:null,level:-90,kind:'none'};
async function micStart(){
if(!state.micWanted){mic.state='off';return false}
if(mic.state==='on')return true;
if(!(navigator.mediaDevices&&navigator.mediaDevices.getUserMedia)){mic.state='unsupported';return false}
try{if(navigator.audioSession)navigator.audioSession.type='play-and-record'}catch(e){}
try{
const st=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:false,noiseSuppression:false,autoGainControl:false,channelCount:1}});
initAudio();mic.stream=st;const src=AC.createMediaStreamSource(st);const proc=AC.createScriptProcessor(1024,1,1);const mute=AC.createGain();mute.gain.value=0;
src.connect(proc);proc.connect(mute);mute.connect(AC.destination);mic.proc=proc;mic.src=src;
proc.onaudioprocess=e=>{const d=e.inputBuffer.getChannelData(0),sr=AC.sampleRate,N=Math.min(SoundEar.frameSize(sr),d.length);const f=SoundEar.frame(d,0,N,sr);
if(mic.rec)mic.rec.push(new Float32Array(d));else if(!speaking){mic.floorArr.push(f.db);if(mic.floorArr.length>240)mic.floorArr.shift();const s=mic.floorArr.slice().sort((a,b)=>a-b);mic.floor=Math.max(-85,s[Math.floor(s.length*.2)])}
mic.level=f.db;mic.kind=SoundEar.liveKind(f,mic.floor);if(mic.onLive)mic.onLive(f,mic.kind)};
mic.state='on';return true
}catch(e){mic.state='denied';try{if(navigator.audioSession)navigator.audioSession.type='playback'}catch(_){}return false}}
function micStop(){try{if(mic.stream)mic.stream.getTracks().forEach(t=>t.stop());if(mic.proc){mic.proc.onaudioprocess=null;mic.proc.disconnect()}if(mic.src)mic.src.disconnect()}catch(e){}mic.stream=mic.proc=mic.src=null;mic.state='off';try{if(navigator.audioSession)navigator.audioSession.type='playback'}catch(e){}}
const hearing=()=>mic.state==='on';
// The listening badge: a big pulsing ear that glows with the sound it hears.
const KCOL={soft:'#7fd3ff',sharp:'#7ee08a',voice:'#ffc93c',buzz:'#ffb347',none:'#ffffff'};
function earShow(on,label){const e=$('#ear');e.classList.toggle('on',on);if(label)$('#earLbl').textContent=label;duck(speaking)}// music goes quiet while listening
function earTick(){const e=$('#ear');if(!e.classList.contains('on'))return;const lv=Math.max(0,Math.min(1,(mic.level-mic.floor)/40));
e.style.setProperty('--lv',lv.toFixed(3));e.style.setProperty('--kc',KCOL[mic.kind]||'#fff')}
// Record one try. Stops early once the child has spoken and gone quiet.
async function listenTake(T,maxMs=4200){earShow(true,'Listening…');await wait(250);if(T!==tok){earShow(false);return new Float32Array(0)}// skip the speaker's echo
mic.rec=[];const early=mic.level>mic.floor+16;const t0=Date.now();let spoke=0,quietSince=0;
while(T===tok&&Date.now()-t0mic.floor+16){spoke=Date.now();quietSince=0}else if(spoke&&!quietSince)quietSince=Date.now();
if(spoke&&quietSince&&Date.now()-quietSince>650&&Date.now()-t0>1100)break}
const parts=mic.rec||[];mic.rec=null;earShow(false);let n=0;parts.forEach(p=>n+=p.length);const x=new Float32Array(n);let o=0;parts.forEach(p=>{x.set(p,o);o+=p.length});x.early=early;return x}
function judge(F,verdict){if(verdict==='quiet')return'quiet';
if(F.want==='voice')return(verdict==='voice'||verdict==='buzz')?'yes':(verdict==='sharp'?'sharp':'yes');
return verdict===F.want?'yes':verdict}
/* ---------- JOURNEY (one loop, never back to a menu) ---------- */
let tok=0;
function newTok(){tok++;stopVoice();beatStop();whoosh(false);$('#turn').classList.remove('on');earShow(false);mic.onLive=null;mic.rec=null;PW.active=false;PW.holding=false;whoPick=null;
const P=$('#party');if(P)P.classList.remove('on','frozen','auto');$$('.override').forEach(b=>b.remove());return tok}
function show(id){$$('.screen').forEach(s=>s.classList.toggle('on',s.id==='s-'+id));$('#trail').style.visibility=id==='home'?'hidden':'visible'}
const STATIONS=['reveal','mirror','power','who','feed','prize'];
const STATION_INFO=[['🚪','Who is here?'],['👄','Mouth mirror'],['⚡','Power play'],['👂','Who said it?'],['🍎','Feed the friend'],['🎁','Prize time']];
function active(){const a=state.sounds.filter(k=>SQUAD[k]);return a.length?a:['th','f','v','s']}
function cur(){const a=active();return SQUAD[a[J.round%a.length]]}
function setTrail(i){$$('#trail i').forEach((e,j)=>{e.classList.toggle('done',j=6){J.station=0;J.round++}saveJ();journeyGo()}
function addStar(){state.stars++;store.set('stars',state.stars);$('#starN').textContent=state.stars;const s=$('#stars');s.classList.remove('bump');void s.offsetWidth;s.classList.add('bump')}
async function cheer(T,el,line,k){confetti(160);burst();pick([sfx.kazoo,sfx.chime])();addStar();hop(el);trick(el);if(Math.random()<.15)bigRise(false);await say(line||`Yes! Good job${nm()}!`);if(T!==tok)return;if(k){await fsay(k,'yay',el);if(T!==tok)return}await wait(400)}
function choose(el,items){el.innerHTML='';return new Promise(res=>{items.forEach(([label,val,cls])=>{const b=document.createElement('button');b.className='btn popIn '+(cls||'');b.innerHTML=label;b.onclick=()=>{sfx.tap();el.innerHTML='';res(val)};el.appendChild(b)})})}
// A grown-up can always say "he got it" when the listener is unsure.
function override(){return new Promise(res=>{const b=document.createElement('button');b.className='override';b.textContent='👍 Said it right';b.onclick=()=>{sfx.tap();b.remove();res(true)};document.body.appendChild(b);setTimeout(()=>{if(b.isConnected){b.remove();res(false)}},4200)})}
async function yourTurnNoMic(T,line){await say(line);if(T!==tok)return false;const r=$('#turn');r.classList.remove('on');void r.offsetWidth;r.classList.add('on');await wait(4200);r.classList.remove('on');return T===tok}
/* Friendly tips when a different sound comes out: never "wrong", always another friend's sound. */
const TIP={
th_sharp:'Hee hee! That was a snake hiss, like Sunny’s. For Thunder, let your tongue peek out, and blow softly.',
th_pop:'Pop! That was quick. For Thunder, let your tongue peek out, and make it long, like a breeze.',
f_sharp:'Hee hee! That was Sunny’s snake hiss. For Fifi, put your top teeth on your lip, and blow softly.',
f_pop:'Pop! That was quick. For Fifi, put your teeth on your lip, and make it long, like a breeze.',
s_soft:'Ooh, a soft breezy sound, like Thunder’s! For Sunny, put your teeth together, smile, and hiss.',
s_pop:'Pop! That was quick. For Sunny, make it long, like a snake. Teeth together, and hiss.',
v_sharp:'Ooh, a hissy sound! For Vinny, put your teeth on your lip, and turn on your buzzy motor.',
quiet:'I can’t hear you! Can you say it with a big lion voice?'};
const YAY={th:'Woohoo! That’s Thunder’s sound!',f:'Hooray! That’s Fifi’s sound!',v:'Yippee! That’s Vinny’s sound!',s:'Yes! That’s Sunny’s sound!'};
const INTRO={th:'It’s Thunder the puppy! Thunder’s sound has a peeking tongue. Like in thumb.',f:'It’s Fifi the bunny! Fifi’s sound has bunny teeth. Like in fish.',
v:'It’s Vinny the race car! Vinny’s sound is a buzzy motor. Like in van.',s:'It’s Sunny the snake! Sunny’s sound is a happy hiss. Like in sun.'};
const TURN={th:'Your turn! Make Thunder’s sound.',f:'Your turn! Make Fifi’s sound.',v:'Your turn! Make Vinny’s motor sound.',s:'Your turn! Make Sunny’s hissy sound.'};
const POWER={th:['Thunder loves bubbles! Make Thunder’s sound to blow bubbles. Keep going!','Look at all those bubbles! Thunder is so happy!'],
f:['Fifi has a party cake! Make Fifi’s sound to blow out the candles.','You blew out all the candles! Hooray for Fifi!'],
v:['Help Vinny win the race! Make Vinny’s motor sound to drive. Keep going!','Vinny wins the race! Hooray!'],
s:['Sunny wants to fly a balloon! Make Sunny’s sound to fill it up.','Up, up, and away! Sunny’s balloon is flying!']};
const FEED={th:'Thunder is hungry! Say each word to feed him.',f:'Fifi is hungry! Say each word to feed her.',v:'Vinny needs fuel! Say each word to fill him up.',s:'Sunny is hungry! Say each word to feed her.'};
const FOUND={th:'You found Thunder!',f:'You found Fifi!',v:'You found Vinny!',s:'You found Sunny!'};
const EAT=['Chomp, chomp! Yummy!','Yum! Delicious!','Nom, nom, nom!','Burp! Oh, excuse me! Hee hee!'];
const NEXTWORD=['Here comes a yummy word!','Ooh, what’s this?','Next one!'];
/* ---------- 1. WHO IS HERE? (surprise reveal) ---------- */
function prepReveal(){$('#door').className='door';$('#revealCh').innerHTML='';$('#revealName').textContent=''}
async function revealScene(T){const F=cur();const d=$('#door');d.classList.add('wiggle');const tapped=new Promise(r=>{d.onclick=()=>{d.onclick=null;stopVoice();r()}});
say('Knock, knock! Who is coming to play today? Tap the door!');await tapped;if(T!==tok)return;
d.classList.remove('wiggle');d.classList.add('open');sfx.fanfare();await wait(400);
$('#revealCh').innerHTML=charHTML(F.key,'big popOut');const ch=$('#revealCh .chwrap');dress(ch,J.lastCostume&&J.lastCostume[F.key]);$('#revealName').textContent=F.icon+' '+F.name;confetti(80);
sfx.boing2();await fsay(F.key,'hi',ch);if(T!==tok)return;await wait(300);act(ch,true);await say(INTRO[F.key]);act(ch,false);if(T!==tok)return;await wait(700);sceneDone(T)}
/* ---------- 2. MOUTH MIRROR ---------- */
let mirrorMouth;
function prepMirror(){const F=cur();$('#mirrorCh').innerHTML=charHTML(F.key);$('#stepBig').innerHTML='';$('#mirrorCtl').innerHTML='';mirrorMouth.set('rest')}
function stepBig(icon,label){const e=$('#stepBig');e.innerHTML=`${icon}${label}`;e.classList.remove('popIn');void e.offsetWidth;e.classList.add('popIn')}
async function sustainedTry(T,F,ms=3200){// counts what kind of sound comes out for a few seconds
const c={soft:0,sharp:0,voice:0,buzz:0,none:0};mic.onLive=(f,k)=>{if(!speaking)c[k]=(c[k]||0)+1};earShow(true,'Listening…');const t0=Date.now();
while(T===tok&&Date.now()-t0k!=='none'&&k!==F.want&&!(F.want==='voice'&&(k==='voice'||k==='buzz'))).sort((a,b)=>b[1]-a[1])[0];
if(want>=18)return'yes';if(other&&other[1]>=18)return other[0];if(want+(other?other[1]:0)<10)return'quiet';return'yes'}
async function mirrorScene(T){const F=cur(),ch=$('#mirrorCh .chwrap');
for(const[pose,line]of F.steps){mirrorMouth.set(pose);stepBig(F.icon,line.split(/[,.!]/)[0]);act(ch,/Air|^f$|^v$|^s$/.test(pose));await say(line);if(T!==tok)return;await wait(900);if(T!==tok)return}
mirrorMouth.set(F.pose);act(ch,true);stepBig('🗣️','Your turn!');
for(let tries=0;tries<3;tries++){
let r;
if(hearing()){await say(TURN[F.key]);if(T!==tok)return;r=await sustainedTry(T,F);if(T!==tok)return}
else{if(!await yourTurnNoMic(T,TURN[F.key]))return;await choose($('#mirrorCtl'),[['⭐ I did it!','ok','gold big']]);if(T!==tok)return;r='yes'}
if(r==='yes'){await cheer(T,ch,YAY[F.key],F.key);if(T!==tok)return;break}
if(r==='quiet'&&tries<2){await say(TIP.quiet);if(T!==tok)return;continue}
if(tries>=1){await cheer(T,ch,`Great trying${nm()}!`);if(T!==tok)return;break}
const tip=TIP[F.key+'_'+r];if(tip){popFriendFor(r);await say(tip);if(T!==tok)return}await wait(400)}
act(ch,false);mirrorMouth.set('rest');sceneDone(T)}
// The friend whose sound came out pops in to wave (never as a "wrong" signal).
function popFriendFor(kind){const k=kind==='sharp'?'s':(kind==='soft'?'th':null);if(!k)return;const p=document.createElement('div');p.className='cameo';p.innerHTML=charHTML(k);document.body.appendChild(p);sfx.pop();setTimeout(()=>p.remove(),3600)}
/* ---------- 3. POWER PLAY (the child's sound drives it) ---------- */
const PW={active:false,holding:false,prog:0,t:0,idle:0,done:null,game:'bubbles',lastK:'none',bub:0};
function prepPower(){const F=cur();PW.game=F.game;PW.prog=0;PW.active=false;$('#pbar').style.width='0';const fld=$('#field');fld.className='field g-'+F.game;
let h='';
if(F.game==='bubbles')h=`
w.remove(),820)}
const prev=PW.lastStage||0,stage=Math.floor(PW.prog*5);if(stage>prev){sfx.sparkle();PW.lastStage=stage}
powerDraw();if(PW.prog>=1){PW.active=false;PW.holding=false;$('#holdBtn').classList.remove('pressed');const d=PW.done;PW.done=null;d&&d()}}
const hb=$('#holdBtn');
hb.addEventListener('pointerdown',e=>{e.preventDefault();if(!PW.active)return;initAudio();PW.holding=true;hb.classList.add('pressed')});
['pointerup','pointercancel','pointerleave'].forEach(ev=>hb.addEventListener(ev,()=>{PW.holding=false;hb.classList.remove('pressed')}));
hb.addEventListener('contextmenu',e=>e.preventDefault());
async function powerScene(T){const F=cur();PW.lastStage=0;await say(POWER[F.key][0]);if(T!==tok)return;
if(hearing())earShow(true,'Your turn!');hb.classList.remove('disabled');PW.active=true;PW.idle=0;
const t0=Date.now();let nudged=0;
const done=new Promise(r=>PW.done=r);
while(T===tok&&PW.active){await wait(250);if(PW.idle>7&&nudged<2&&!speaking){nudged++;PW.idle=0;say(TURN[F.key])}
if(Date.now()-t0>30000){PW.prog=1}}
await done;if(T!==tok)return;earShow(false);hb.classList.add('disabled');
if(F.game==='balloon'){const b=$('#field .balloon');if(b)b.animate([{transform:b.style.transform},{transform:'translate(-50%,-260%) scale(1.2)'}],{duration:1600,fill:'forwards'})}
surprise();await cheer(T,$('#field .chwrap'),POWER[F.key][1],F.key);if(T!==tok)return;await wait(400);sceneDone(T)}
/* ---------- 4. WHO SAID IT? (tap the friend whose sound you hear) ---------- */
let whoPick=null;
function prepWho(){$('#whoRow').innerHTML='';$('#whoProg').textContent=''}
async function whoScene(T){const act_=active(),pool=act_.length>=3?act_:[...new Set([...act_,...shuffle(['th','f','v','s'])])].slice(0,3);
const friends=shuffle(pool.slice());$('#whoRow').innerHTML=friends.map(k=>``).join('');
$$('.whoBtn').forEach(b=>b.onclick=()=>{if(whoPick){const f=whoPick;whoPick=null;f(b.dataset.k)}});
await say('Who said it? Listen, and tap the friend whose sound you hear.');if(T!==tok)return;
const order=shuffle(act_.slice());
for(let r=0;r<3;r++){$('#whoProg').textContent='⭐'.repeat(r)+'🔊'.repeat(3-r);const k=order[r%order.length];const[w]=pick(SQUAD[k].words);
const play=()=>say(w,{pre:'w:',caption:'👂 Listen…'});$('#whoSpk').onclick=()=>{sfx.tap();play()};
await wait(400);await play();if(T!==tok)return;let tries=0;
while(true){const got=await new Promise(res=>whoPick=res);if(T!==tok)return;
if(got===k)break;tries++;const b=$(`.whoBtn[data-k="${got}"]`);b.classList.add('nope');setTimeout(()=>b.classList.remove('nope'),700);
if(tries>=2){$(`.whoBtn[data-k="${k}"]`).classList.add('hint')}await say('Listen again.');if(T!==tok)return;await play();if(T!==tok)return}
const wb=$(`.whoBtn[data-k="${k}"]`);wb.classList.remove('hint');act(wb.querySelector('.chwrap'),true);await cheer(T,wb.querySelector('.chwrap'),FOUND[k],k);act(wb.querySelector('.chwrap'),false);if(T!==tok)return}
$('#whoProg').textContent='⭐⭐⭐';await wait(300);sceneDone(T)}
/* ---------- 5. FEED THE FRIEND (say the words) ---------- */
let feedMouth;
function hl(w,k){const re={th:/th/i,f:/f/i,v:/v/i,s:/s/i}[k];return w.replace(re,m=>`${m}`)}
function prepFeed(){const F=cur();$('#feedCh').innerHTML=charHTML(F.key,'big');$('#food').textContent='';$('#foodWord').innerHTML='';$('#feedCtl').innerHTML='';feedMouth.set('rest')}
async function feedScene(T){const F=cur(),ch=$('#feedCh .chwrap');const words=shuffle(F.words.slice()).slice(0,3);
await say(FEED[F.key]);if(T!==tok)return;
for(const[w,e,kind]of words){const fd=$('#food');fd.textContent=e;fd.className='popIn';$('#foodWord').innerHTML=hl(w,F.key);feedMouth.set('rest');
await say(pick(NEXTWORD));if(T!==tok)return;await wait(400);feedMouth.set(F.pose);await say(w,{pre:'w:'});if(T!==tok)return;await wait(500);
let ok=false;
for(let tries=0,quiet=0,redo=0;tries<2;){
let res;
if(hearing()){await say(`Your turn! Say: ${w}.`);if(T!==tok)return;const x=await listenTake(T);if(T!==tok)return;res=judge(F,SoundEar.analyze(x,AC.sampleRate,kind).verdict);
if(x.early&&res!=='yes'&&!redo){redo=1;continue}// he started before the listening did: just ask again
if(res!=='yes'){let ovPressed=false;override().then(v=>{ovPressed=v});
if(res==='quiet'&&quiet<1){quiet++;await say(TIP.quiet);if(T!==tok)return;if(ovPressed)res='yes';else continue}
else if(tries===0){const tip=TIP[F.key+'_'+res];if(tip){popFriendFor(res);await say(tip)}else await say('Ooh, nice try!');if(T!==tok)return;if(ovPressed)res='yes'}
else{await wait(1800);if(T!==tok)return;if(ovPressed)res='yes'}}}
else{if(!await yourTurnNoMic(T,`Your turn! Say: ${w}.`))return;res=await choose($('#feedCtl'),[['👍 Said it!','yes','green big'],['🔁 Again','again']]);if(T!==tok)return}
if(res==='yes'){ok=true;break}
tries++;if(tries<2){feedMouth.set(F.rest);await say('Let’s do it together, slowly.');if(T!==tok)return;feedMouth.set(F.pose);await say(w,{pre:'slow:'});if(T!==tok)return;await wait(400)}}
// eat it either way: effort always wins
const r=fd.getBoundingClientRect(),c=ch.getBoundingClientRect();const fly=fd.cloneNode(true);fly.className='flyFood';fly.style.left=(r.left+r.width/2)+'px';fly.style.top=(r.top+r.height/2)+'px';document.body.appendChild(fly);fd.textContent='';
const a=fly.animate([{left:fly.style.left,top:fly.style.top,transform:'translate(-50%,-50%) scale(1)'},{left:(c.left+c.width/2)+'px',top:(c.top+c.height*.62)+'px',transform:'translate(-50%,-50%) scale(.2)'}],{duration:700,easing:'ease-in',fill:'forwards'});
await a.finished.catch(()=>{});fly.remove();sfx.chomp();act(ch,true);
if(ok){confetti(140);burst();sfx.kazoo();addStar();hop(ch);await fsay(F.key,'yum',ch)}else{hop(ch);addStar();await say(`Great trying${nm()}!`);if(T!==tok)return;await fsay(F.key,'yum',ch)}
act(ch,false);if(T!==tok)return;await wait(500)}
sceneDone(T)}
/* ---------- 6. PRIZE: a costume, a dance party and a joke ---------- */
const JOKES=[['What do you call a sleeping dinosaur?','A dino-snore!','🦕'],['What do you call a snake that builds houses?','A boa constructor!','🐍'],['What does a race car eat?','Fast food!','🍔'],
['What is a puppy’s favorite snack?','Pup-corn!','🍿'],['Knock knock! Who’s there? Lettuce.','Lettuce who? Lettuce play some more!','🥬'],['Where do dogs park their cars?','In the barking lot!','🚗']];
function prepPrize(){const b=$('#box');b.textContent='🎁';b.className='';b.style.display='';$('#prizeCh').innerHTML='';$('#prizeName').textContent='';$('#jokeBox').textContent=''}
async function prizeScene(T){const F=cur(),b=$('#box');b.className='shake';const tapped=new Promise(r=>{b.onclick=()=>{b.onclick=null;stopVoice();r()}});
say('Prize time! Tap the present!');await tapped;if(T!==tok)return;
const[cname,cicon]=COSTUMES[J.costume%COSTUMES.length];J.costume++;J.lastCostume=Object.assign({},J.lastCostume||{},{[F.key]:cname});saveJ();
sfx.fanfare();b.style.display='none';$('#prizeCh').innerHTML=charHTML(F.key,'big popOut');const ch=$('#prizeCh .chwrap');dress(ch,cname);confetti(180);
$('#prizeName').textContent=cicon+' '+cname+' '+F.name+' '+cicon;state.stickers.push([F.key,cname]);store.set('stickers',state.stickers);addStar();
await say(`Ta-da! It’s ${cname} ${F.name}!`);if(T!==tok)return;await fsay(F.key,'yay',ch);if(T!==tok)return;await wait(700);
await partyRun(T,16,true);if(T!==tok)return;await wait(400);
const[q,ans,em]=JOKES[J.joke%JOKES.length];J.joke++;saveJ();
await say('Ready for a joke?');if(T!==tok)return;await wait(600);$('#jokeBox').textContent='🤔';await say(q);if(T!==tok)return;sfx.drum();await wait(1500);if(T!==tok)return;
$('#jokeBox').textContent=em;$('#jokeBox').classList.remove('popIn');void $('#jokeBox').offsetWidth;$('#jokeBox').classList.add('popIn');
await say(ans);if(T!==tok)return;sfx.rimshot();hop(ch);await wait(400);await say('Hee hee hee!');if(T!==tok)return;await wait(700);
await fsay(F.key,'bye',ch);if(T!==tok)return;await say(`Bye bye, ${F.name}! Who’s next?`);if(T!==tok)return;sceneDone(T)}
/* ---------- SILLY BUTTON and the giant puppy ---------- */
async function silly(){sfx.tap();const r=Math.random(),chs=$$('.screen.on .chwrap');if(r<.3){bigRise(true);return}
if(r<.55){sfx.toot();chs.forEach(c=>{hop(c);trick(c)});if(!speaking)say('Oops! Was that a toot? Hee hee!');return}
if(r<.8){visitor();chs.forEach(trick);return}
sfx.kazoo();burst();confetti(80);chs.forEach(trick);if(!speaking)say('Beep, beep! Coming through!')}
/* ---------- HOME ---------- */
let greeted=false;
function homeScene(){newTok();show('home');$('#homeRow').innerHTML=['th','f','v','s'].map(k=>charHTML(k,'homeCh')).join('');
$('#shelf').innerHTML=state.stickers.length?'Sticker book:'+state.stickers.slice(-14).map(([k,c])=>`${SQUAD[k].icon}${HATS[c]||''}`).join(''):'';
say(greeted?`Tap play${nm()}!`:`Hi${state.name?' '+state.name:''}! Meet the Silly Sound Squad! Tap the big play button!`);greeted=true}
const SCENES={reveal:revealScene,mirror:mirrorScene,power:powerScene,who:whoScene,feed:feedScene,prize:prizeScene};
const PREP={reveal:prepReveal,mirror:prepMirror,power:prepPower,who:prepWho,feed:prepFeed,prize:prepPrize};
/* Every line the game can say (the recording script reads this). */
function allLines(n){const L=[];const add=(t,pre='')=>L.push([t,pre]);
Object.values(SQUAD).forEach(F=>{F.steps.forEach(s=>add(s[1]));F.words.forEach(([w])=>{add(w,'w:');add(w,'slow:');add(`Your turn! Say: ${w}.`)});add(INTRO[F.key]);add(TURN[F.key]);add(YAY[F.key]);POWER[F.key].forEach(x=>add(x));add(FEED[F.key]);add(FOUND[F.key]);
COSTUMES.forEach(c=>add(`Ta-da! It’s ${c[0]} ${F.name}!`));add(`Bye bye, ${F.name}! Who’s next?`)});
Object.values(TIP).forEach(x=>add(x));NEXTWORD.forEach(x=>add(x));
JOKES.forEach(j=>{add(j[0]);add(j[1])});Object.entries(FRIEND).forEach(([k,o])=>Object.values(o).flat().forEach(t=>add(t,'v_'+k+':')));MOVES.forEach(m=>{if(m[1])add(m[1])});
['Knock, knock! Who is coming to play today? Tap the door!','Who said it? Listen, and tap the friend whose sound you hear.','Listen again.','Let’s do it together, slowly.','Ooh, nice try!',
'Prize time! Tap the present!','Ready for a joke?','Hee hee hee!','Oops! Was that a toot? Hee hee!','Beep, beep! Coming through!','Peekaboo! I see you!','Squad dance party! Dance with your friends!','Freeze!','Dance!',
`Great dancing, ${n}!`,`Yes! Good job, ${n}!`,`Great trying, ${n}!`,`Tap play, ${n}!`,`Hi ${n}! Meet the Silly Sound Squad! Tap the big play button!`].forEach(x=>add(x));
return L}
/* ---------- SILLY EXTRAS: friend voices, googly eyes, tap tricks, visitors, comic bursts ---------- */
// Each friend talks in its own cartoon voice (clips keyed "v_:"). No friend line uses a practice sound
// except where a checked word is spliced in, so the voices are silly without modelling a sound wrong.
const FRIEND={
th:{hi:'Woof woof! Hi hi hi! Wanna play with me?',tickle:['Hee hee hee! That tickles!','Woof! Do it again!'],yay:['Woof! You did it! Yippee!','Woof woof! Hooray!'],yum:['Yum yum yum! Woof!','Burp! Oops! Woof!'],bye:'Bye bye! Woof woof!',dance:'Woof woof! Dance with me!'},
f:{hi:'Hop hop hop! Hello! Let’s play!',tickle:['Hee hee! Bunny giggles!','Hop hop! Hee hee!'],yay:['Yay! You did it! Hop hop!','Yippee! You did it!'],yum:['Crunchy munchy! Yum!','Nom nom nom! Yummy!'],bye:'Bye bye! Hop hop!',dance:'Hop hop! Dance with me!'},
v:{hi:'Beep beep! Ready, set, go!',tickle:['Beep! Hee hee! That tickles!','Beep beep beep! Hee hee!'],yay:['Beep beep! You’re a superstar!','Yay! Beep beep! You did it!'],yum:['Glug glug glug! Yummy!','Yummy! Burp! Beep beep!'],bye:'Beep beep! Bye bye!',dance:'Beep beep! Dance with me!'},
s:{hi:'Hiss hiss! Hello, hello! I’m so happy!',tickle:['Hee hee! Wiggle wiggle!','Hee hee hee! That tickles!'],yay:['Yes yes yes! You did it!','Yay! Wiggle wiggle!'],yum:['Slurp! Yummy yummy!','Slurp slurp! Yum!'],bye:'Bye bye! Hiss hiss!',dance:'Wiggle wiggle! Dance with me!'}};
const fline=(k,kind)=>{const v=FRIEND[k][kind];return Array.isArray(v)?pick(v):v};
function fsay(k,kind,el){const t=fline(k,kind);if(el){act(el,true);trick(el)}const p=say(t,{pre:'v_'+k+':'});if(el)p.then(()=>act(el,false));return p}
// Tap any friend: a giggle and a random trick (never while the game is listening).
const TRICKS=['r-spin','r-jelly','r-flip','r-boing','r-eyes','r-squish'];
function trick(el){if(!el)return;TRICKS.forEach(c=>el.classList.remove(c));void el.offsetWidth;const c=pick(TRICKS);el.classList.add(c);setTimeout(()=>el.classList.remove(c),900)}
document.addEventListener('click',e=>{const el=e.target.closest('.chwrap');if(!el||e.target.closest('.whoBtn'))return;const k=el.dataset.ch;
if(!k)return;pick([sfx.boing2,sfx.slideUp,sfx.pop])();trick(el);if(!speaking&&!mic.rec&&!PW.active&&!$('#ear').classList.contains('on'))fsay(k,'tickle',el)});
// Googly eyes follow the finger or mouse.
function lookAt(x,y){const r=document.documentElement;r.style.setProperty('--ex',(((x/innerWidth)-.5)*7).toFixed(2)+'px');r.style.setProperty('--ey',(((y/innerHeight)-.5)*6).toFixed(2)+'px')}
['pointermove','pointerdown'].forEach(ev=>addEventListener(ev,e=>lookAt(e.clientX,e.clientY),{passive:true}));
setInterval(()=>{if(Math.random()<.5)lookAt(Math.random()*innerWidth,Math.random()*innerHeight)},2600);
// Comic burst words on every win.
const BURSTS=['WOW!','YAY!','SUPER!','BOOM!','WOO-HOO!','YES!','KA-POW!'];
function burst(){const b=document.createElement('div');b.className='burst';b.textContent=pick(BURSTS);b.style.left=(25+Math.random()*50)+'vw';b.style.top=(28+Math.random()*25)+'vh';b.style.setProperty('--r',(Math.random()*24-12).toFixed(0)+'deg');document.body.appendChild(b);setTimeout(()=>b.remove(),1300)}
// Silly visitors wander across now and then.
const VISITORS=[['🐄🎈','rise'],['🐔','run'],['🦆','run'],['🛸','fly'],['🐸','leap'],['🦕','run'],['🐷🎈','rise'],['🐒','leap'],['🦒','run'],['🍕','fly'],['🐳','swim'],['🦄','fly']];
function visitor(){if($('#party').classList.contains('on')||mic.rec||$('#ear').classList.contains('on')||$('#start'))return;const[e,a]=pick(VISITORS);floater(e,a);pick([sfx.slideUp,sfx.boing2,sfx.honk2])()}
setInterval(()=>{if(Math.random()<.55)visitor()},14000);
/* ---------- WIRING ---------- */
mirrorMouth=makeMouth($('#mirrorMouth'));feedMouth=makeMouth($('#feedMouth'));
$('#starN').textContent=state.stars;
$('#startRow').innerHTML=['th','f','v','s'].map(k=>charHTML(k)).join('');
setInterval(()=>{if($('#s-home').classList.contains('on')&&!speaking&&!$('#party').classList.contains('on'))bigRise(false)},16000);
$('#playBtn').onclick=()=>{sfx.tap();journeyGo()};
$('#homeBtn').onclick=()=>{sfx.tap();homeScene()};
$('#sillyBtn').onclick=silly;
$('#musicBtn').onclick=()=>{setMusic(!state.music);store.set('music',state.music)};
$('#fsBtn').onclick=()=>{const el=document.documentElement;try{if(document.fullscreenElement||document.webkitFullscreenElement){(document.exitFullscreen||document.webkitExitFullscreen).call(document)}else{const f=el.requestFullscreen||el.webkitRequestFullscreen;const p=f&&f.call(el);if(p&&p.catch)p.catch(()=>{})}}catch(e){}};
function micText(){const m={on:'🎤 The friends can hear him.',off:'Microphone is off. You tap “He did it” instead.',denied:'The microphone was blocked. Allow it in the browser settings, then reload. Until then you tap instead.',unsupported:'This browser cannot share the microphone here. You tap instead.'};$('#micState').textContent=m[mic.state]||''}
$('#grownBtn').onclick=()=>{$('#nameIn').value=state.name;fillVoiceSel();$$('#soundPick input').forEach(c=>c.checked=state.sounds.includes(c.value));$('#micIn').checked=state.micWanted;micText();$('#grown').classList.add('on')};
$('#micIn').onchange=async()=>{state.micWanted=$('#micIn').checked;store.set('mic',state.micWanted);if(state.micWanted){initAudio();await micStart()}else micStop();micText()};
$('#closeGrown').onclick=()=>{const n=$('#nameIn').value.trim();if(n){state.name=n;store.set('name',n)}const v=$('#voiceSel').value;const vv=enVoices().find(x=>x.name===v);if(vv){voice=vv;state.voiceName=v;store.set('voice',v)}
const s=$$('#soundPick input').filter(c=>c.checked).map(c=>c.value);const changed=s.join()!==state.sounds.join();state.sounds=s.length?s:['th','f','v','s'];store.set('sounds',state.sounds);
$('#grown').classList.remove('on');if(changed){J.station=0;saveJ();homeScene()}};
$('#resetBtn').onclick=()=>{state.stars=0;state.stickers=[];Object.assign(J,{round:0,station:0,joke:0,costume:0,lastCostume:{}});saveJ();store.set('stars',0);store.set('stickers',[]);$('#starN').textContent=0;$('#grown').classList.remove('on');homeScene()};
$('#startBtn').onclick=async()=>{const b=$('#startBtn');if(b.disabled)return;b.disabled=true;initAudio();preloadClips();pickVoice();if(state.micWanted)await micStart();$('#start').remove();setMusic(state.music);homeScene()};