let LESSONS=[], state=null, currentView="home", currentLesson=null; const KEY="familieDeutschA1_v1"; const avatars=["πŸ‘¨","πŸ‘©","πŸ‘§","πŸ‘¦","πŸ§‘","πŸ‘±","πŸ§•","πŸ§”","πŸ‘©β€πŸŽ“","πŸ‘¨β€πŸ’»","🦸","πŸ§™","🐻","🦊","🐼","🐯","🐸","🐧"]; function defaultState(){ return {activeProfile:null, profiles:[], settings:{dailyGoal:20, sound:true}}; } function loadState(){ try{return JSON.parse(localStorage.getItem(KEY))||defaultState()}catch{return defaultState()}} function saveState(){localStorage.setItem(KEY,JSON.stringify(state))} function profile(){ return state.profiles.find(p=>p.id===state.activeProfile)||null; } function newProfile(name, avatar){ return {id:crypto.randomUUID?crypto.randomUUID():Date.now().toString(),name,avatar,created:new Date().toISOString(),completed:[],scores:{},difficult:{},lastStudy:null,streak:0,xp:0}; } function escapeHTML(s){return String(s).replace(/[&<>"']/g,c=>({"&":"&","<":"<",">":">","\"":""","'":"'"}[c]))} function toast(msg){let t=document.getElementById("toast");t.textContent=msg;t.classList.add("show");setTimeout(()=>t.classList.remove("show"),2200)} function speak(text){ if(!state.settings.sound||!("speechSynthesis" in window))return toast("Audio is disabled or unavailable."); speechSynthesis.cancel(); let u=new SpeechSynthesisUtterance(text);u.lang="de-DE";u.rate=.78;speechSynthesis.speak(u); } function setView(v){currentView=v;currentLesson=null;closeDrawer();render();window.scrollTo({top:0,behavior:"smooth"})} function openDrawer(){drawer.classList.add("open");overlay.classList.add("open")} function closeDrawer(){drawer.classList.remove("open");overlay.classList.remove("open")} function ensureProfile(){ if(!profile()){renderProfiles(true);return false} return true; } function completedPct(p){return Math.round((p.completed.length/30)*100)} function updateStreak(p){ const today=new Date().toISOString().slice(0,10); if(p.lastStudy===today)return; const y=new Date();y.setDate(y.getDate()-1); p.streak=p.lastStudy===y.toISOString().slice(0,10)?p.streak+1:1; p.lastStudy=today; } function nextDay(p){for(let d=1;d<=30;d++)if(!p.completed.includes(d))return d;return 30} function render(){ if(currentView==="profiles")return renderProfiles(false); if(!state.profiles.length)return renderWelcome(); if(!profile())state.activeProfile=state.profiles[0].id; document.getElementById("profileBtn").textContent=profile().avatar; const routes={home:renderHome,journey:renderJourney,vocabulary:renderVocabulary,review:renderReview,progress:renderProgress,family:renderFamily,settings:renderSettings}; (routes[currentView]||renderHome)(); } function renderWelcome(){ app.innerHTML=`
🌳

Willkommen!

A friendly 30-day German A1 journey for your whole family.

Create the first learner

Each person receives an avatar, private progress, quiz scores, difficult-word review and a learning streak.

`; } function renderHome(){ const p=profile(), nd=nextDay(p), l=LESSONS[nd-1], pct=completedPct(p); app.innerHTML=`
${p.avatar}

Hallo, ${escapeHTML(p.name)}!

${p.completed.length===30?"Du hast alle 30 Tage geschafft!":"Bereit fΓΌr deine heutige Deutsch-Mission?"}

${p.completed.length} of 30 days Β· ${pct}% complete
Streak
πŸ”₯ ${p.streak}
days
XP
⭐ ${p.xp}
points
Words to review
🧠 ${Object.keys(p.difficult).length}
difficult
Quiz average
${averageScore(p)}%
accuracy

Today’s lesson

15–25 min
${l.icon}
Day ${l.day}: ${l.title}
${l.subtitle}

Quick actions

`; } function averageScore(p){let vals=Object.values(p.scores);return vals.length?Math.round(vals.reduce((a,b)=>a+b,0)/vals.length):0} function openLesson(day){currentLesson=LESSONS[day-1];renderLesson(0)} function renderLesson(step=0){ const l=currentLesson,p=profile(); const stepNames=["Goal","Words","Build","Maple","Play","Quiz","Finish"]; if(step===0){ app.innerHTML=`
${l.icon}
Day ${l.day}

${l.title}

${l.subtitle}

🎯 Today’s goal

Learn ${l.words.length} useful words, practise ${l.patterns.length} sentence patterns and complete Maple’s family mission.

Family mission

${l.mission}

`; } else if(step===1){ app.innerHTML=lessonHeader(l,stepNames,step)+`
${l.words.map(w=>`
${w[0]}
${w[1]}
${w[2]}
`).join("")}
`; } else if(step===2){ app.innerHTML=lessonHeader(l,stepNames,step)+`

Useful patterns

${l.patterns.map(x=>`
${x[0]}
${x[1]}
`).join("")}

Small grammar capsule

${l.grammar}

`; } else if(step===3){ app.innerHTML=lessonHeader(l,stepNames,step)+`

🦊 Maple says

${l.maple.map((x,i)=>`
${x}
`).join("")}

Answer aloud. The goal is confidence, not perfection.

`; } else if(step===4){ const shuffled=[...l.words].sort(()=>Math.random()-.5); app.innerHTML=lessonHeader(l,stepNames,step)+`

Match from memory

Tap each German word and say its meaning aloud.

${shuffled.map(w=>``).join("")}
`; } else if(step===6){finishLesson(l)} } function lessonHeader(l,names,step){return `
Day ${l.day} Β· ${names[step]}

${l.icon} ${l.title}

`} let quizIndex=0,quizCorrect=0,quizAnswers=[]; function startQuiz(){quizIndex=0;quizCorrect=0;quizAnswers=[];renderQuiz()} function renderQuiz(){ const l=currentLesson,q=l.quiz[quizIndex]; app.innerHTML=lessonHeader(l,["","","","","","Quiz",""],5)+`
Question ${quizIndex+1} of ${l.quiz.length}

${q.q}

${q.options.map(o=>``).join("")}
`; } function answerQuiz(btn,answer,correct){ document.querySelectorAll(".quiz-option").forEach(b=>b.disabled=true); const ok=answer===correct;if(ok){quizCorrect++;btn.classList.add("correct")}else{btn.classList.add("wrong");[...document.querySelectorAll(".quiz-option")].find(b=>b.textContent===correct)?.classList.add("correct")} quizAnswers.push({ok,answer,correct}); const l=currentLesson,p=profile(); if(!ok){ const word=l.words.find(w=>w[1]===correct||w[0]===correct); if(word)p.difficult[word[0]]={de:word[0],en:word[1],pron:word[2],count:(p.difficult[word[0]]?.count||0)+1,last:new Date().toISOString()}; } saveState(); document.getElementById("quizNext").innerHTML=`

${ok?"Richtig! πŸŽ‰":"Fast richtig. The correct answer is: "+correct}

`; } function renderJourney(){ const p=profile(); app.innerHTML=`

30-Day Journey

Small steps, practical German and a review every seventh day.

${LESSONS.map(l=>`
${l.icon}
Day ${l.day}: ${l.title}
${l.subtitle}
${p.completed.includes(l.day)?"βœ“ Done":(l.day===nextDay(p)?"Next":"Open")}
`).join("")}`; } function renderVocabulary(){ const all=LESSONS.flatMap(l=>l.words.map(w=>({day:l.day,...{de:w[0],en:w[1],pron:w[2]}}))); app.innerHTML=`

Vocabulary Library

${all.length} curated A1 learning items across the 30-day path.

${vocabHTML(all)}
`; } function vocabHTML(items){return items.map(w=>`
${w.de}
${w.en}
${w.pron} Β· Day ${w.day}
`).join("")} function filterVocab(q){q=q.toLowerCase();const all=LESSONS.flatMap(l=>l.words.map(w=>({day:l.day,de:w[0],en:w[1],pron:w[2]}))).filter(w=>(w.de+" "+w.en).toLowerCase().includes(q));document.getElementById("vocabList").innerHTML=vocabHTML(all)} function renderReview(){ const p=profile(),items=Object.values(p.difficult); app.innerHTML=`

Difficult Words

Words enter this list after an incorrect answer. Mark them mastered after successful review.

${items.length?items.map(w=>`
${w.de}
${w.en}
${w.pron} Β· missed ${w.count} time(s)
`).join(""):`

πŸŽ‰ No difficult words

Complete quizzes and this area will create a personalised review list.

`}`; } function masterWord(de){delete profile().difficult[de];profile().xp+=10;saveState();toast("Word marked as mastered +10 XP");renderReview()} function renderProgress(){ const p=profile(),pct=completedPct(p); const weeks=[p.completed.filter(d=>d<=7).length,p.completed.filter(d=>d>7&&d<=14).length,p.completed.filter(d=>d>14&&d<=21).length,p.completed.filter(d=>d>21).length]; app.innerHTML=`

${p.avatar} ${escapeHTML(p.name)}’s Progress

${pct}% complete

${p.completed.length} lessons Β· ${p.xp} XP Β· ${p.streak}-day streak

Weekly path

${weeks.map((n,i)=>`
Week ${i+1}
${n} completed
`).join("")}

Lesson scores

${Object.keys(p.scores).length?Object.entries(p.scores).map(([d,s])=>`
Day ${d}: ${LESSONS[d-1].title}${s}%
`).join(""):"No quiz scores yet."}
${p.completed.length===30?`

Urkunde

German A1 Family Foundation

This certifies that

${escapeHTML(p.name)}

completed the 30-day family learning journey.

Familie lernt Deutsch Β· ${new Date().toLocaleDateString()}

`:""}`; } function renderFamily(){ const total=state.profiles.reduce((a,p)=>a+p.completed.length,0),xp=state.profiles.reduce((a,p)=>a+p.xp,0); app.innerHTML=`

Family Progress

🌳 Gemeinsam lernen

Together your family has completed ${total} lessons and earned ${xp} XP.

${state.profiles.map(p=>`
${p.avatar}

${escapeHTML(p.name)}

${completedPct(p)}%

${p.completed.length}/30 Β· πŸ”₯ ${p.streak} Β· ⭐ ${p.xp}

`).join("")}

Family learning tree

${"🌿".repeat(Math.min(10,Math.ceil(total/3)))}
🌳

A new leaf appears for every three family lessons.

`; } function renderProfiles(forceCreate=false){ currentView="profiles"; app.innerHTML=`

Profiles & Avatars

Select a learner or create a separate profile. Progress is never mixed between family members.

${state.profiles.map(p=>`
${p.avatar}

${escapeHTML(p.name)}

${p.completed.length}/30 days

`).join("")}

Add family member

Choose an avatar

${avatars.map((a,i)=>``).join("")}
`; } function chooseAvatar(btn,a){document.querySelectorAll(".avatar-choice").forEach(x=>x.classList.remove("selected"));btn.classList.add("selected");document.getElementById("chosenAvatar").value=a} function addProfile(){const name=document.getElementById("newName").value.trim(),a=document.getElementById("chosenAvatar").value;if(!name)return toast("Please enter a name.");const p=newProfile(name,a);state.profiles.push(p);state.activeProfile=p.id;saveState();toast("Profile created");setView("home")} function switchProfile(id){state.activeProfile=id;saveState();toast("Profile selected");setView("home")} function deleteProfile(id){if(!confirm("Delete this learner and all progress?"))return;state.profiles=state.profiles.filter(p=>p.id!==id);if(state.activeProfile===id)state.activeProfile=state.profiles[0]?.id||null;saveState();renderProfiles()} function renderSettings(){ app.innerHTML=`

Settings & Backup

Learning settings



Family backup

Progress is stored in this browser. Export a backup to move or restore it on another family phone.

Install on mobile

Open the deployed website in the phone browser and choose Add to Home Screen. It will behave like a lightweight family learning app.

Storage note

This release uses private browser storage. Profiles on one phone stay together. To combine progress from multiple phones, export the latest family backup and import it on the main family device.

`; } function exportBackup(){const blob=new Blob([JSON.stringify(state,null,2)],{type:"application/json"});const a=document.createElement("a");a.href=URL.createObjectURL(blob);a.download="familie-deutsch-backup.json";a.click();URL.revokeObjectURL(a.href)} function importBackup(file){if(!file)return;const r=new FileReader();r.onload=()=>{try{const x=JSON.parse(r.result);if(!Array.isArray(x.profiles))throw Error();state=x;saveState();toast("Backup imported");setView("home")}catch{toast("Invalid backup file")}};r.readAsText(file)} document.addEventListener("click",e=>{const b=e.target.closest("[data-view]");if(b)setView(b.dataset.view)}); document.getElementById("menuBtn").onclick=openDrawer;document.getElementById("closeDrawer").onclick=closeDrawer;document.getElementById("overlay").onclick=closeDrawer;document.getElementById("profileBtn").onclick=()=>setView("profiles"); fetch("data/lessons.json").then(r=>r.json()).then(x=>{LESSONS=x;state=loadState();render()}).catch(()=>{app.innerHTML="

Unable to load lessons.

Please run this website through a web server rather than opening index.html directly.

"}); if("serviceWorker" in navigator)window.addEventListener("load",()=>navigator.serviceWorker.register("sw.js"));