import { initSpeech, setSpeechMode, setSpeechLanguage, speakText, speakNow, stopSpeech } from './speech.js?v=0003-20260801T072507Z';
import { translations, colorNames, shapeNames } from './i18n.js?v=0003-20260801T072507Z';
import { getState, saveState } from './storage.js?v=0003-20260801T072507Z';
import { playSuccess, playTryAgain, playClick } from './audio.js?v=0003-20260801T072507Z';

const BUILD='0003';
const state=getState();
let language=state.language||'da';
let age=state.age||null;
let mode='mix';
let round=0;
let stars=0;
let locked=false;
let currentChallenge=null;
let speechMode=state.speechMode||'auto';
const roundsTotal=5;

const colors=[
  {key:'red',value:'#ff515d'},{key:'blue',value:'#3997f0'},{key:'yellow',value:'#ffd43b'},
  {key:'green',value:'#5dcc70'},{key:'orange',value:'#ff963f'},{key:'purple',value:'#a86be8'},
  {key:'pink',value:'#ff79b7'},{key:'black',value:'#384456'}
];
const shapes=[
  {key:'circle',symbol:'●'},{key:'square',symbol:'■'},{key:'triangle',symbol:'▲'},
  {key:'star',symbol:'★'},{key:'heart',symbol:'♥'},{key:'diamond',symbol:'◆'}
];
const modes=[
  {key:'colors',icon:'🎨'},{key:'numbers',icon:'🔢'},{key:'shapes',icon:'🔷'},{key:'mix',icon:'✨'}
];

const $=id=>document.getElementById(id);
const screens=['screenStart','screenAge','screenModes','screenGame','screenComplete'];
const t=key=>translations[language][key]??key;
const shuffle=array=>{const a=[...array];for(let i=a.length-1;i>0;i--){const j=Math.floor(Math.random()*(i+1));[a[i],a[j]]=[a[j],a[i]];}return a;};

function showScreen(id){
  if(id!=='screenGame')stopSpeech();
  screens.forEach(name=>$(name).classList.toggle('active',name===id));
  $('homeBtn').classList.toggle('hidden',id==='screenStart');
}
function applyLanguage(){
  document.documentElement.lang=language;
  $('langFlag').textContent=language==='da'?'🇩🇰':'🇬🇧';
  $('langCode').textContent=language.toUpperCase();
  $('tagline').textContent=t('tagline');
  $('playLabel').textContent=t('play');
  $('ageTitle').textContent=t('ageTitle');
  $('ageHelp').textContent=t('ageHelp');
  $('modeTitle').textContent=t('modeTitle');
  $('modeHelp').textContent=t('modeHelp');
  $('againLabel').textContent=t('again');
  $('homeBtn').setAttribute('aria-label',t('home'));
  $('langBtn').setAttribute('aria-label',t('language'));
  $('speechBtn').setAttribute('aria-label',t('speechButton'));setSpeechLanguage(language);updateSpeechButton();
  renderAges();renderModes();
  if($('screenGame').classList.contains('active')&&currentChallenge) renderChallenge(currentChallenge,false);
}
function updateSpeechButton(){
  const map={
    off:{icon:'🔇',label:t('speechOff')},
    click:{icon:'🔈',label:t('speechClick')},
    auto:{icon:'🔊',label:t('speechAuto')}
  };
  const current=map[speechMode]||map.auto;
  $('speechIcon').textContent=current.icon;
  $('speechLabel').textContent=speechMode==='auto'?'AUTO':speechMode==='click'?'TRYK':'FRA';
  $('speechBtn').title=current.label;
}

function getChallengeSpeech(challenge){
  if(challenge.type==='colors') return `${t('findColor')} ${colorNames[challenge.target.key][language]}`;
  if(challenge.type==='numbers') return t('count');
  return `${t('findShape')} ${shapeNames[challenge.target.key][language]}`;
}

function speakCurrentChallenge(force=false){
  if(!currentChallenge) return;
  const text=getChallengeSpeech(currentChallenge);
  if(force) speakNow(text); else speakText(text);
}

function renderAges(){
  $('ageGrid').innerHTML='';
  for(let i=3;i<=8;i++){
    const b=document.createElement('button');b.className='age-button';b.type='button';b.textContent=i;
    b.setAttribute('aria-label',`${i} ${t('years')}`);b.addEventListener('click',()=>selectAge(i));$('ageGrid').appendChild(b);
  }
}
function renderModes(){
  $('modeGrid').innerHTML='';
  modes.forEach(item=>{
    const best=(state.bestScores&&state.bestScores[item.key])||0;
    const b=document.createElement('button');b.className='mode-button';b.type='button';
    b.innerHTML=`<span class="mode-icon">${item.icon}</span><strong>${t(item.key)}</strong><small>${t('best')}: ${best}/5</small>`;
    b.addEventListener('click',()=>{playClick();mode=item.key;startGame();});$('modeGrid').appendChild(b);
  });
}
function selectAge(value){playClick();age=value;state.age=age;saveState(state);showScreen('screenModes');}
function startGame(){round=0;stars=0;showScreen('screenGame');nextRound();}
function optionCount(){return age<=4?3:4;}
function nextRound(){locked=false;$('feedback').textContent='';currentChallenge=createChallenge();renderChallenge(currentChallenge,true);}
function createChallenge(){
  let type=mode;
  if(type==='mix') type=shuffle(['colors','numbers','shapes'])[0];
  if(type==='colors') return createColorChallenge();
  if(type==='numbers') return createNumberChallenge();
  return createShapeChallenge();
}
function createColorChallenge(){
  const options=shuffle(colors).slice(0,optionCount());
  const target=options[Math.floor(Math.random()*options.length)];
  return {type:'colors',target,options};
}
function createNumberChallenge(){
  const max=age<=4?5:age<=6?8:10;
  const target=1+Math.floor(Math.random()*max);
  const pool=[];for(let i=1;i<=max;i++)if(i!==target)pool.push(i);
  const options=shuffle([target,...shuffle(pool).slice(0,optionCount()-1)]);
  return {type:'numbers',target,options};
}
function createShapeChallenge(){
  const options=shuffle(shapes).slice(0,optionCount());
  const target=options[Math.floor(Math.random()*options.length)];
  return {type:'shapes',target,options};
}
function renderChallenge(challenge,updateProgress=true){
  if(updateProgress){
    $('roundLabel').textContent=t('round').replace('{current}',round+1).replace('{total}',roundsTotal);
    $('stars').textContent='★ '.repeat(stars)+'☆ '.repeat(roundsTotal-stars);
  }
  $('helperText').textContent=t('helpPuffy');
  $('answerGrid').innerHTML='';
  $('answerGrid').style.setProperty('--answer-columns',String(challenge.options.length));
  if(challenge.type==='colors'){
    $('questionText').textContent=`${t('findColor')} ${colorNames[challenge.target.key][language]}`;
    challenge.options.forEach(item=>addAnswer('',item.value,item.key===challenge.target.key,colorNames[item.key][language]));
  }else if(challenge.type==='numbers'){
    $('questionText').textContent=t('count');
    const countBox=document.createElement('div');countBox.className='count-box';
    countBox.textContent='⭐'.repeat(challenge.target);$('answerGrid').appendChild(countBox);
    challenge.options.forEach(number=>addAnswer(String(number),'',number===challenge.target,String(number)));
  }else{
    $('questionText').textContent=`${t('findShape')} ${shapeNames[challenge.target.key][language]}`;
    challenge.options.forEach((item,index)=>addAnswer(item.symbol,colors[index%colors.length].value,item.key===challenge.target.key,shapeNames[item.key][language],'shape'));
  }
  if(updateProgress&&speechMode==='auto')setTimeout(()=>speakCurrentChallenge(false),180);
}
function addAnswer(text,background,isCorrect,label,extra=''){
  const b=document.createElement('button');b.className=`answer-button ${extra}`;b.type='button';
  if(background)b.style.background=background;b.textContent=text;b.setAttribute('aria-label',label);
  b.addEventListener('click',()=>checkAnswer(b,isCorrect));$('answerGrid').appendChild(b);
}
function checkAnswer(button,isCorrect){
  if(locked)return;
  if(isCorrect){
    locked=true;stars++;button.classList.add('correct');$('feedback').textContent=t('great');playSuccess();
    setTimeout(()=>{round++;if(round>=roundsTotal)finishGame();else nextRound();},800);
  }else{
    button.classList.remove('wrong');void button.offsetWidth;button.classList.add('wrong');$('feedback').textContent=t('tryAgain');playTryAgain();
  }
}
function finishGame(){
  state.totalStars=(state.totalStars||0)+stars;state.bestScores=state.bestScores||{};
  state.bestScores[mode]=Math.max(state.bestScores[mode]||0,stars);saveState(state);
  $('completeTitle').textContent=t('completeTitle');$('completeText').textContent=t('completeText');
  $('completeStars').textContent='★'.repeat(stars)+'☆'.repeat(roundsTotal-stars);showScreen('screenComplete');playSuccess();
}

$('playBtn').addEventListener('click',()=>{playClick();showScreen('screenAge');});
$('againBtn').addEventListener('click',()=>{playClick();startGame();});
$('homeBtn').addEventListener('click',()=>{playClick();showScreen('screenStart');});
$('langBtn').addEventListener('click',()=>{playClick();language=language==='da'?'en':'da';state.language=language;saveState(state);applyLanguage();});
$('speechBtn').addEventListener('click',()=>{
  playClick();
  speechMode=speechMode==='auto'?'click':speechMode==='click'?'off':'auto';
  state.speechMode=speechMode;
  saveState(state);
  setSpeechMode(speechMode);
  updateSpeechButton();
  if(speechMode==='click'&&$('screenGame').classList.contains('active'))speakCurrentChallenge(true);
  if(speechMode==='auto'&&$('screenGame').classList.contains('active'))speakCurrentChallenge(false);
});
$('questionText').addEventListener('click',()=>{if(speechMode==='click')speakCurrentChallenge(true);});
$('helperText').addEventListener('click',()=>{if(speechMode==='click')speakCurrentChallenge(true);});
$('screenGame').querySelector('.question-card').addEventListener('click',()=>{if(speechMode==='click')speakCurrentChallenge(true);});


initSpeech({
  mode:speechMode,
  language,
  onStart:()=>document.querySelector('.question-character')?.classList.add('is-speaking'),
  onEnd:()=>document.querySelector('.question-character')?.classList.remove('is-speaking')
});
setSpeechMode(speechMode);
setSpeechLanguage(language);
applyLanguage();showScreen('screenStart');
console.log(`%c FORGE ACADEMY BUILD ${BUILD} `,'background:#ff9f36;color:#19324d;font-weight:bold;padding:6px 12px;border-radius:6px');
if('serviceWorker'in navigator){window.addEventListener('load',async()=>{try{const reg=await navigator.serviceWorker.register('./sw.js?v=0003-20260801T072507Z',{updateViaCache:'none'});await reg.update();}catch(error){console.warn(error);}});}
