const { useState, useEffect, useRef, useMemo, useCallback } = React;

const TEACHER_CACHE_KEY = 'piano_teacher_store_v3';
const TEACHER_PIN_SESSION_KEY = 'piano_teacher_pin_v1';
const STUDENT_SAVED_TOKEN_KEY = 'piano_my_student_token_v1';
const STUDENT_CACHE_PREFIX = 'piano_student_cache_v3_';
const MUTE_KEY = 'piano_sound_muted_v1';
const LANG_KEY = 'piano_ui_lang_v1';

const STICKER_OPTIONS = [
  '🎹', '🐰', '🦁', '🐼', '🦊', '🐱', '🐶', '🐨',
  '🦄', '🦖', '🐣', '🐸', '🦋', '🌟', '🌈', '👑',
  '🏆', '🚀', '🎸', '🎻', '🎧', '🍓', '🍦', '🧸'
];

const AVATAR_THEMES = {
  indigo: {
    bg: 'bg-indigo-100',
    ring: 'ring-indigo-400 border-indigo-300',
    dot: 'bg-indigo-500',
    zh: '星空紫藍',
    en: 'Indigo'
  },
  rose: {
    bg: 'bg-rose-100',
    ring: 'ring-rose-400 border-rose-300',
    dot: 'bg-rose-500',
    zh: '蜜桃粉紅',
    en: 'Rose Pink'
  },
  emerald: {
    bg: 'bg-emerald-100',
    ring: 'ring-emerald-400 border-emerald-300',
    dot: 'bg-emerald-500',
    zh: '薄荷翠綠',
    en: 'Mint'
  },
  amber: {
    bg: 'bg-amber-100',
    ring: 'ring-amber-400 border-amber-300',
    dot: 'bg-amber-500',
    zh: '陽光暖黃',
    en: 'Sunny'
  },
  sky: {
    bg: 'bg-sky-100',
    ring: 'ring-sky-400 border-sky-300',
    dot: 'bg-sky-500',
    zh: '晴空粉藍',
    en: 'Sky Blue'
  },
  violet: {
    bg: 'bg-violet-100',
    ring: 'ring-violet-400 border-violet-300',
    dot: 'bg-violet-500',
    zh: '薰衣草紫',
    en: 'Lavender'
  }
};

const QUICK_PIECES_MAP = {
  zh: ['C Major Scale', 'G Major Scale', 'Arpeggio 琶音', 'Hanon 哈農手指練習', 'Sight Reading 視譜'],
  en: ['C Major Scale', 'G Major Scale', 'Arpeggios', 'Hanon Finger Exercise', 'Sight Reading']
};

const HAND_OPTIONS = [
  { value: '右手 RH', zh: '右手 RH', en: 'Right Hand (RH)' },
  { value: '左手 LH', zh: '左手 LH', en: 'Left Hand (LH)' },
  { value: '雙手 HT', zh: '雙手 HT', en: 'Hands Together (HT)' },
  { value: '分手 HS', zh: '分手 HS', en: 'Hands Separate (HS)' },
  { value: '分手 → 雙手', zh: '分手 → 雙手', en: 'HS → HT' }
];

const QUICK_DETAILS_MAP = {
  zh: [
    '慢練開拍子機',
    '注意連音 Legato',
    '留意強弱對比',
    '手腕放鬆唔聳肩',
    '一邊彈一邊數拍子',
    '注意指法準確'
  ],
  en: [
    'Slow practice w/ metronome',
    'Smooth legato',
    'Mind dynamics (p / f)',
    'Keep wrists relaxed',
    'Count beats out loud',
    'Check fingerings carefully'
  ]
};

const PRAISE_MESSAGES = {
  zh: [
    '好叻呀！呢個項目今日達標喇！🌟',
    '太犀利喇！手指愈彈愈靈活！🎉',
    '完美達成目標！老師一定讚你！👏',
    '堅持練習超有型！繼續保持呀！✨'
  ],
  en: [
    'Awesome job! You hit today’s goal for this piece! 🌟',
    'Fantastic work! Your fingers are getting super agile! 🎉',
    'Goal reached! Your teacher will be so proud! 👏',
    'Great consistency! Keep up the amazing practice! ✨'
  ]
};

// ---------- 雙語介面字典 ----------
const I18N = {
  zh: {
    appName: '琴鍵小步',
    appSubtitle: '練琴項目拆解與打卡',
    soundOn: '音效',
    soundMuted: '已靜音',
    soundTooltipOn: '靜音',
    soundTooltipOff: '開啟音效提示',
    // Private Landing (No student list!)
    privateBadge: '🔒 學生私密專屬練琴卡',
    privateTitle: '請使用你嘅專屬練琴連結進入',
    privateSub: '為保護每位同學嘅私隱，請直接點擊老師透過 WhatsApp 發送畀你嘅專屬練琴連結打開個人練琴卡。',
    codeInputLabel: '或者輸入你嘅專屬練琴碼：',
    codeInputPh: '例如：8 位數專屬碼',
    codeSubmitBtn: '進入練琴卡',
    invalidTokenMsg: '搵唔到呢條練琴連結喎！請向老師索取最新嘅專屬練琴連結。',
    loadingStudent: '正在載入你嘅專屬練琴卡…',
    // Teacher Preview Banner
    teacherPreviewBanner: '👀 老師預覽模式（學生實際開啟私密連結時，絕不會顯示此列或任何老師／其他學生入口）',
    backToTeacherBtn: '← 返回老師管理版面',
    // Avatar Customizer
    editAvatarHint: '換頭像',
    avatarModalTitle: '換個靚靚專屬頭像 ✨',
    avatarModalSub: '上載你鍾意嘅相片、寵物相，或者揀個得意貼紙公仔！',
    uploadPhotoBtn: '📸 上載相片 / 影張靚相',
    removePhotoBtn: '轉返用得意貼紙',
    pickStickerLabel: '🐾 或者揀個得意貼紙公仔：',
    pickThemeLabel: '🎨 揀選頭像邊框顏色：',
    saveAvatarBtn: '✨ 儲存我嘅新頭像！',
    toastAvatarSaved: '✨ 新頭像已經換好喇，超得意呀！',
    toastPhotoError: '⚠️ 相片讀取失敗，請換另一張相試下',
    // Student Dashboard
    studentCardTitle: (name) => `${name} 嘅練琴卡`,
    todayHint: (date) => `今日日期：${date} · 撳頭像可以換相片，每練完一次記得撳 +1 打卡呀！`,
    streakUnitShort: '日',
    tasksCountUnit: '項任務',
    streakTitle: '本週連續打卡天數',
    practicedDaysBadge: (d) => `已練 ${d}/7 天`,
    streakDaysLabel: '日連續打卡',
    todayProgressLabel: '今日完成進度',
    allDoneHero: '🏆 今日目標全部完成！',
    completedTasksHero: (done, total) => `已完成 ${done} / ${total} 項任務`,
    todayRepsSummary: (done, goal) => `今日累計打卡：${done} 次（目標共 ${goal} 次）`,
    weekRepsSummary: (total) => `本週總計：${total} 次`,
    teacherNoteLabel: '老師本週小叮囑：',
    noTasksStudentTitle: '老師暫時未加入本週任務',
    noTasksStudentSub: '落堂後老師更新清單就會自動顯示喺呢度喇！',
    doneBadge: '✅ 今日已達標！',
    goalBadge: (n) => `目標 ${n} 次`,
    sectionTag: '段落：',
    handTag: '手別：',
    dailyGoalTag: '每日目標：',
    bonusTag: (n) => `+${n} 超額加練 🌟`,
    undoTooltip: '撤銷一次誤觸',
    btnCheckin: '練完一次 (+1 打卡)',
    btnCheckinDone: '今日已達標！再練一次 (+1 打卡)',
    pwaStudentTip: '喺 iPhone / iPad Safari 撳「加入主畫面」當普通 App 用',
    // Practice Calendar
    calTitle: '📅 練琴打卡月曆',
    calSub: '只要當日打卡任何 1 項任務，就會點亮綠點 🟢',
    calMonthFormat: (y, m) => `${y}年 ${m}月`,
    calBackToCurrent: '返回本月',
    calMonthSummary: (days, reps) => `本月已練 ${days} 日 · 共 ${reps} 次打卡`,
    calWeekCol: '週密度',
    calWeekDayHeaders: ['一', '二', '三', '四', '五', '六', '日'],
    calLegendPracticed: '有練琴打卡',
    calLegendEmpty: '未打卡',
    calZeroWeekStudent: '🕸️ 咦⋯今個星期仲係「零打卡」一片空白喎！部鋼琴就快生蜘蛛網喇 🙈 快啲撳下面「+1 打卡」消滅空白啦！',
    calZeroMonStudent: '🌱 新一週開始喇！今日練完撳一下「+1 打卡」點亮今個星期第一粒綠點啦！',
    calSparseWeekStudent: (d) => `👀 今個星期暫時得 ${d} 粒綠點咋喎，個日曆有啲疏落呀～今日加把勁補返粒綠點啦！`,
    calGoodWeekStudent: (d) => `🎵 今個星期已經點亮咗 ${d} 日綠點，繼續保持密密練呀！`,
    calGreatWeekStudent: (d) => `🔥 嘩！今個星期點亮咗 ${d}/7 日綠點，排得超密超靚呀！老師一定大讚！`,
    calZeroWeekTeacher: (name) => `🕸️ ${name} 今個星期暫時「0 日打卡」，成排空白生蜘蛛網喇！`,
    calSummaryTeacher: (name, d) => `📊 ${name} 今個星期已點亮 ${d}/7 日練琴綠點`,
    calDayDetailPracticed: (date, reps) => `🟢 ${date}：呢日有練琴！共打卡 ${reps} 次 👏`,
    calDayDetailEmptyPast: (date) => `⚪ ${date}：呢日空白冇練琴紀錄 🙈`,
    calDayDetailEmptyToday: (date) => `🎹 今日（${date}）仲未點亮綠點，快啲完成一項練習撳 +1 打卡啦！`,
    calDayDetailFuture: (date) => `🗓️ ${date}：未來日子，到時記得練琴打卡呀！`,
    // Celebration Overlay
    grandHeader: '今日練琴大滿貫 100% 完成！',
    taskDoneHeader: '項目達標完成！',
    grandTitle: (name) => `${name} 今日所有練琴任務 100% 達標！`,
    grandSub: (piece, n, target) => `「${piece}」已完成 ${n}/${target} 次，太叻喇！🌟`,
    taskDoneTitle: (piece, n, target) => `「${piece}」完成 ${n}/${target} 次！`,
    // PWA Guide Modal
    pwaTitle: '加入 iPhone / iPad 主畫面',
    pwaSub: '好似真正 App 一樣全螢幕打開你嘅專屬練琴卡！',
    pwaStep1: '用 iPhone 或 iPad 嘅 Safari 瀏覽器 打開老師發畀你嘅專屬連結。',
    pwaStep2: '撳螢幕底部（iPad 為右上角）嘅 「分享」按鈕 📤。',
    pwaStep3: '向下滑動揀選 「加入主畫面」(Add to Home Screen)，再撳「新增」即完成！',
    gotIt: '明白晒！',
    // Teacher Lock
    lockTitle: '老師管理專區',
    lockSub: '請輸入 4 位數老師密碼進入管理版面（只有老師知道網址 `/teacher` 同密碼）',
    lockErr: '密碼唔正確，請再試一次',
    clearBtn: '清除',
    // Teacher Dashboard
    teacherModeBadge: '👩‍🏫 老師管理模式 · 私密連結派發 & 進度追蹤',
    teacherTitle: '學生練琴進度與任務管理',
    addStudentBtn: '+ 新增學生',
    changePinBtn: '🔑 改密碼',
    lockBtn: '🔒 登出鎖定',
    changePinTitle: '更改老師管理密碼',
    changePinSub: '請設定新嘅 4 位數老師密碼（學生無法進入此頁面）',
    changePinPh: '輸入 4 位數字（例如 2580）',
    savePinBtn: '儲存新密碼',
    toastPinSaved: '🔐 已更新老師管理密碼！',
    toastPinInvalid: '⚠️ 請輸入剛好 4 位數字密碼',
    statStudents: '學生人數',
    statStudentsUnit: '位',
    statWeekCheckins: '全班本週總打卡',
    statAvgRate: '平均本週完成率',
    newStudentModalTitle: '新增學生檔案',
    cancelBtn: '取消',
    studentNameLabel: '學生姓名 *',
    studentNamePh: '例如：Chloe、梓軒',
    studentLevelLabel: '程度 / 備註標籤（選填）',
    studentLevelPh: '例如：Grade 2、初學啟蒙',
    studentLangLabel: '學生慣用介面語言（Local / International School）',
    avatarPickLabel: '預設代表圖示（學生入去後可自己換相片／貼紙）',
    confirmCreateStudent: '確認建立學生',
    selectStudentHeading: '選擇學生查看及派發本週任務',
    selectStudentHint: '點擊學生卡片切換管理',
    managingBadge: '管理中',
    weekTotalLabel: '本週總打卡次數',
    weekRateLabel: '本週目標完成率',
    todayMetShort: (d, t) => `今日達標 ${d}/${t} 項`,
    copyLinkShort: '🔗 複製私密連結',
    previewShort: '預覽畫面 →',
    whatsappZoneBadge: '🔒 家長 WhatsApp 私密連結派發專區（學生只會睇到自己內容）',
    lanToggleOn: (ip) => `📡 已切換同 Wi-Fi 連結 (${ip})`,
    lanToggleOff: '💻 切換為同 Wi-Fi 手機/iPad 測試連結',
    dedicatedLinkTitle: (name) => `${name} 嘅私密專屬連結`,
    studentDefaultLangSwitch: '預設語言：',
    resetTokenBtn: '🔄 重設連結碼',
    confirmResetToken: (name) => `確定要為 ${name} 重新產生新嘅私密連結嗎？舊連結將會即時失效。`,
    toastTokenReset: '🔒 已重新產生私密連結！記得將新連結傳畀家長',
    copyDedicatedLinkBtn: '一鍵複製私密連結',
    copyWhatsappMsgBtn: '複製 WhatsApp 訊息連清單',
    addTaskTitle: (name) => `為 ${name} 加入練琴任務`,
    addTaskSub: '落堂 30 秒快速拆細項目與每日目標次數',
    fieldPiece: '1. 曲目或技巧名稱 *',
    fieldPiecePh: '例如：C Major Scale、Sonatina Op.36 No.1',
    fieldBars: '練習段落 / Bars（選填）',
    fieldBarsPh: '例如：Bars 12–16',
    fieldHand: '練習手別（選填）',
    fieldHandAuto: '自動識別 / 不限',
    fieldDetails: '2. 拆細具體要求 *',
    fieldDetailsPh: '例如：Bars 12–16 右手慢練，注意連音 Legato 同埋句尾收音',
    fieldTarget: '3. 每日目標次數',
    submitAddTask: (name) => `➕ 加入 ${name} 本週任務清單`,
    teacherNoteEditLabel: (name) => `💡 給 ${name} 嘅本週課堂小叮囑（會顯示喺學生打卡版面頂部）`,
    teacherNoteEditPh: '例如：手腕放鬆，注意連音線句尾收音要輕柔！',
    studentTaskListTitle: (name, count) => `${name} 本週練琴任務清單（${count} 項）`,
    studentTaskListSub: '可隨時修改要求、調整次數，或預覽學生私密畫面',
    previewStudentBtn: '👀 預覽學生畫面',
    resetTodayBtn: '重設今日打卡',
    emptyTasksTeacherTitle: '暫無本週練琴任務',
    emptyTasksTeacherSub: (name) => `請喺左邊表單為 ${name} 加入第一項拆解練習！`,
    dailyBadge: (n) => `每日 ${n} 次`,
    todayDoneBadge: (d, t) => `今日進度：${d}/${t} 次`,
    editBtn: '編輯',
    deleteBtn: '刪除',
    saveEditBtn: '儲存修改',
    deleteStudentBtn: '刪除此學生檔案',
    confirmDeleteStudent: (name) => `確定要刪除學生「${name}」及其打卡紀錄嗎？`,
    toastStudentAdded: (name) => `✅ 已新增學生「${name}」並產生專屬私密連結！`,
    toastEnterPiece: '⚠️ 請輸入曲目或技巧名稱',
    toastTaskAdded: (name) => `🎵 已為 ${name} 加入新練琴任務！`,
    toastLinkCopied: (name, sLang) =>
      `🔗 已複製 ${name} 嘅私密連結（${sLang === 'en' ? '英文介面' : '繁中介面'}）！`,
    toastWhatsappCopied: (sLang) =>
      `💬 已複製${sLang === 'en' ? '英文版' : '廣東話版'} WhatsApp 家長訊息連私密連結！`,
    toastResetToday: (name) => `🔄 已重設 ${name} 今日嘅打卡次數`,
    toastTaskUpdated: '✅ 已更新練琴任務內容',
    toastTaskDeleted: '🗑️ 已刪除該項任務',
    toastStudentDeleted: (name) => `已移除學生 ${name}`,
    toastLangSaved: (name, sLang) =>
      `🌐 已將 ${name} 嘅預設語言設為 ${sLang === 'en' ? 'English' : '繁體中文（廣東話）'}`,
    // Practice Countdown Timer
    timerTitle: '⏱️ 練琴倒數計時器',
    timerSub: '揀個時間專心練琴，倒數完會有慶祝音樂提示！',
    timerStart: '▶ 開始計時',
    timerPause: '⏸ 暫停',
    timerResume: '▶ 繼續',
    timerReset: '↺ 重設',
    timerRunningBadge: '專心計時中…',
    timerMinUnit: '分鐘',
    timerDoneTitle: '⏰ 練琴倒數完成！',
    timerDoneSub: (m) => `好叻呀！你已經專心練足 ${m} 分鐘琴喇！👏`,
    // Score Bar, Weekly Quiz & Leaderboard
    myMonthPtsLabel: '本月總積分',
    ptsUnit: '分',
    streakPtsShort: (p) => `🔥 連續練琴 ${p}分`,
    quizPtsShort: (p) => `🎧 音樂問答 ${p}分`,
    openLeaderboardBtn: '🏆 龍虎榜',
    jumpToQuizNew: '🎧 本週音樂問答 (+50分!)',
    jumpToQuizDone: (s) => `🎧 本週問答 (+${s}分 ✓)`,
    rankBadge: (r) => `第 ${r} 名`,
    quizSectionBadge: '🎧 每週音樂聆聽挑戰',
    quizRuleTag: '每答啱 1 題 +10 分（共 50 分）',
    quizOpenYoutubeBtn: '▶️ 喺 YouTube 打開觀看影片',
    quizSubmittedBanner: (c, tot, s) => `🎉 你已完成本週挑戰！答啱 ${c} / ${tot} 題，贏得 +${s} 分！`,
    quizQuestionRight: '✅ 答啱 +10 分',
    quizQuestionWrong: '❌ 答錯 +0 分',
    quizRightAnswerTag: '✓ 正確答案',
    quizYourPickTag: '你嘅選擇',
    quizSubmitBtn: (ans, tot) => `🎯 提交答案睇成績！（已揀 ${ans}/${tot} 題）`,
    quizNeedAllMsg: '⚠️ 請先揀齊全部 5 條題目嘅答案再提交呀！',
    quizDoneToast: (s) => `🎉 提交成功！本週音樂問答獲得 +${s} 分！`,
    lbTitle: '🏆 本月練琴龍虎榜',
    lbSub: '每月月底最高分同學可獲老師特別獎勵！🎁',
    lbRulesTitle: '💡 儲分升榜秘笈',
    lbRule1: '🔥 連續練琴獎賞：每月連續 2 日有練琴 +10 分，連續 3 日再 +10 分，連續 4 日再 +10 分⋯（個 Streak 一斷咗就要重新由第 1 日計過！）',
    lbRule2: '🎧 每週音樂問答：每答啱 1 題即加 10 分（每週最高 +50 分）',
    lbYouBadge: '⭐ 我',
    lbColStreak: '連續練琴',
    lbColQuiz: '音樂問答',
    lbColTotal: '本月總分',
    lbPracticedDays: (d) => `本月練琴 ${d} 日`,
    // Teacher Tabs & Quiz Builder
    tabStudents: '🎹 學生任務與進度',
    tabQuiz: '🎧 每週音樂問答出題',
    tabLeaderboard: '🏆 本月龍虎榜排名',
    tqHeaderTitle: '🎧 發佈每週 YouTube 音樂問答（全班學生同步可見）',
    tqHeaderSub: '附上 YouTube 歌曲連結並設定 5 條選擇題與標準答案；學生答完即刻知啱錯，答啱一題自動 +10 分！',
    tqNewWeekBtn: '✨ 發佈新一週挑戰（保留本月舊週分數）',
    tqQuizTitleLabel: '本週挑戰標題 *',
    tqYoutubeLabel: 'YouTube 歌曲／影片連結 *',
    tqYoutubePh: '貼上 https://www.youtube.com/watch?v=... 或 https://youtu.be/...',
    tqDescLabel: '學生提示語（選填）',
    tqQuestionHeading: (i) => `第 ${i} 題（10 分）`,
    tqQuestionPh: (i) => `輸入第 ${i} 條問題內容…`,
    tqOptionPh: (letter) => `選項 ${letter}`,
    tqMarkCorrect: '設為答案',
    tqIsCorrect: '✓ 正確答案',
    tqSavePublishBtn: '🚀 儲存並發佈本週問答',
    tqStatusHeading: '📊 本週各學生作答成績',
    tqNotSubmitted: '未作答',
    tqSubmittedScore: (c, tot, s) => `答啱 ${c}/${tot} 題 · +${s} 分`,
    toastQuizPublished: '🚀 已發佈每週音樂挑戰！全班學生打開練琴卡即可作答',
    toastNewQuizDraft: '✨ 已建立新一週空白題目卷（舊週得分已保留），填好撳「儲存並發佈」即可！'
  },
  en: {
    appName: 'KeySteps',
    appSubtitle: 'Piano Practice & Check-in',
    soundOn: 'Sound',
    soundMuted: 'Muted',
    soundTooltipOn: 'Mute sound',
    soundTooltipOff: 'Enable sound effects',
    // Private Landing
    privateBadge: '🔒 Private Student Practice Card',
    privateTitle: 'Open Your Private Practice Link',
    privateSub: 'To protect student privacy, please open the personal practice link sent by your piano teacher via WhatsApp.',
    codeInputLabel: 'Or enter your personal practice code:',
    codeInputPh: 'e.g. 8-character code',
    codeSubmitBtn: 'Open My Card',
    invalidTokenMsg: 'Practice link not found! Please ask your teacher for your latest private practice link.',
    loadingStudent: 'Loading your practice card…',
    // Teacher Preview Banner
    teacherPreviewBanner: '👀 Teacher Preview Mode (Students opening their private link never see this bar or any teacher/other-student links)',
    backToTeacherBtn: '← Back to Teacher Dashboard',
    // Avatar Customizer
    editAvatarHint: 'Avatar',
    avatarModalTitle: 'Customize Your Avatar ✨',
    avatarModalSub: 'Upload a fun photo / pet pic, or pick your favorite cute sticker!',
    uploadPhotoBtn: '📸 Upload Photo / Take Selfie',
    removePhotoBtn: 'Use Cute Sticker Instead',
    pickStickerLabel: '🐾 Or pick a fun sticker:',
    pickThemeLabel: '🎨 Choose frame color:',
    saveAvatarBtn: '✨ Save My New Avatar!',
    toastAvatarSaved: '✨ Awesome! Your new avatar is saved!',
    toastPhotoError: '⚠️ Could not load image, please try another photo',
    // Student Dashboard
    studentCardTitle: (name) => `${name}’s Practice Card`,
    todayHint: (date) => `Today: ${date} · Tap your avatar to customize, and tap +1 after each rep!`,
    streakUnitShort: 'd',
    tasksCountUnit: 'tasks',
    streakTitle: 'Practice Streak',
    practicedDaysBadge: (d) => `${d}/7 days this wk`,
    streakDaysLabel: 'day streak',
    todayProgressLabel: 'Today’s Progress',
    allDoneHero: '🏆 All Goals Completed Today!',
    completedTasksHero: (done, total) => `${done} / ${total} tasks completed`,
    todayRepsSummary: (done, goal) => `Today’s check-ins: ${done}x (Goal: ${goal}x)`,
    weekRepsSummary: (total) => `This week: ${total}x`,
    teacherNoteLabel: 'Teacher’s Note: ',
    noTasksStudentTitle: 'No practice tasks assigned yet',
    noTasksStudentSub: 'Your new weekly tasks will appear here right after your lesson!',
    doneBadge: '✅ Goal Reached!',
    goalBadge: (n) => `Goal: ${n}x`,
    sectionTag: 'Section:',
    handTag: 'Hand:',
    dailyGoalTag: 'Daily Goal:',
    bonusTag: (n) => `+${n} Bonus 🌟`,
    undoTooltip: 'Undo last tap (-1)',
    btnCheckin: 'Done Once (+1 Check-in)',
    btnCheckinDone: 'Goal Reached! +1 Bonus Rep',
    pwaStudentTip: 'Tap Share → "Add to Home Screen" in iPhone / iPad Safari to use like an App',
    // Practice Calendar
    calTitle: '📅 Practice Calendar',
    calSub: 'Checking in on ANY task lights up a green dot 🟢 for that day',
    calMonthFormat: (y, m) => {
      const names = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
      return `${names[m - 1]} ${y}`;
    },
    calBackToCurrent: 'This Month',
    calMonthSummary: (days, reps) => `${days} days practiced · ${reps}x check-ins this mo`,
    calWeekCol: 'Wk',
    calWeekDayHeaders: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    calLegendPracticed: 'Practiced',
    calLegendEmpty: 'Missed',
    calZeroWeekStudent: '🕸️ Uh-oh… ZERO check-ins all week! Your piano is growing cobwebs 🙈 Tap "+1 Check-in" below right now to light up today!',
    calZeroMonStudent: '🌱 Fresh week! Finish 1 rep today to light up your very first green dot of the week!',
    calSparseWeekStudent: (d) => `👀 Only ${d} green dot so far this week — looking a bit lonely! Let’s add another dot today!`,
    calGoodWeekStudent: (d) => `🎵 ${d} days lit up this week — nice rhythm, keep those green dots coming!`,
    calGreatWeekStudent: (d) => `🔥 Awesome! ${d}/7 days lit up this week — your calendar is packed with green dots!`,
    calZeroWeekTeacher: (name) => `🕸️ ${name} has 0 check-in days so far this week.`,
    calSummaryTeacher: (name, d) => `📊 ${name} has practiced ${d}/7 days so far this week.`,
    calDayDetailPracticed: (date, reps) => `🟢 ${date}: Practiced! ${reps}x check-ins logged 👏`,
    calDayDetailEmptyPast: (date) => `⚪ ${date}: No practice check-ins logged 🙈`,
    calDayDetailEmptyToday: (date) => `🎹 Today (${date}) isn’t lit up yet — tap +1 below after practicing!`,
    calDayDetailFuture: (date) => `🗓️ ${date}: Upcoming day — keep your streak going!`,
    // Celebration Overlay
    grandHeader: '100% Daily Practice Complete!',
    taskDoneHeader: 'Daily Target Reached!',
    grandTitle: (name) => `${name} finished 100% of today’s piano goals!`,
    grandSub: (piece, n, target) => `"${piece}" completed (${n}/${target}x) — Amazing work! 🌟`,
    taskDoneTitle: (piece, n, target) => `"${piece}" — ${n}/${target}x Done!`,
    // PWA Guide Modal
    pwaTitle: 'Add to iPhone / iPad Home Screen',
    pwaSub: 'Open your private piano card full-screen just like a native app!',
    pwaStep1: 'Open your private practice link in Safari on iPhone or iPad.',
    pwaStep2: 'Tap the Share button 📤 at the bottom (or top-right on iPad).',
    pwaStep3: 'Scroll down and tap "Add to Home Screen", then tap "Add"!',
    gotIt: 'Got it!',
    // Teacher Lock
    lockTitle: 'Teacher Area',
    lockSub: 'Enter 4-digit teacher PIN to manage students (Only accessible via /teacher)',
    lockErr: 'Incorrect PIN, please try again',
    clearBtn: 'Clear',
    // Teacher Dashboard
    teacherModeBadge: '👩‍🏫 Teacher Dashboard · Private Links & Progress',
    teacherTitle: 'Student Practice & Task Manager',
    addStudentBtn: '+ Add Student',
    changePinBtn: '🔑 Change PIN',
    lockBtn: '🔒 Lock',
    changePinTitle: 'Change Teacher PIN',
    changePinSub: 'Set a new 4-digit PIN for /teacher',
    changePinPh: 'Enter 4 digits (e.g. 2580)',
    savePinBtn: 'Save PIN',
    toastPinSaved: '🔐 Teacher PIN updated!',
    toastPinInvalid: '⚠️ Please enter exactly 4 digits',
    statStudents: 'Students',
    statStudentsUnit: '',
    statWeekCheckins: 'Total Check-ins (Wk)',
    statAvgRate: 'Avg Weekly Completion',
    newStudentModalTitle: 'New Student Profile',
    cancelBtn: 'Cancel',
    studentNameLabel: 'Student Name *',
    studentNamePh: 'e.g. Chloe, Ethan',
    studentLevelLabel: 'Grade / Level Note (Optional)',
    studentLevelPh: 'e.g. ABRSM Grade 2, Beginner',
    studentLangLabel: 'Preferred Language (Local / International School)',
    avatarPickLabel: 'Initial Avatar (Students can upload their own photo/sticker!)',
    confirmCreateStudent: 'Create Student',
    selectStudentHeading: 'Select a Student to Manage Tasks',
    selectStudentHint: 'Click a card to switch student',
    managingBadge: 'Selected',
    weekTotalLabel: 'Weekly Check-ins',
    weekRateLabel: 'Weekly Completion',
    todayMetShort: (d, t) => `Today ${d}/${t} done`,
    copyLinkShort: '🔗 Copy Private Link',
    previewShort: 'Preview →',
    whatsappZoneBadge: '🔒 Private Parent WhatsApp Link (Student sees ONLY their own card)',
    lanToggleOn: (ip) => `📡 Using Classroom Wi-Fi IP (${ip})`,
    lanToggleOff: '💻 Switch to Wi-Fi IP for iPad/Phone Test',
    dedicatedLinkTitle: (name) => `${name}’s Private Practice Link`,
    studentDefaultLangSwitch: 'Default Lang:',
    resetTokenBtn: '🔄 Reset Link',
    confirmResetToken: (name) => `Generate a new private link for ${name}? Their previous link will stop working.`,
    toastTokenReset: '🔒 Generated a new private link! Remember to send the updated link to parents.',
    copyDedicatedLinkBtn: 'Copy Private Link',
    copyWhatsappMsgBtn: 'Copy WhatsApp Message + Plan',
    addTaskTitle: (name) => `Add Practice Task for ${name}`,
    addTaskSub: 'Break down pieces, bars, hands & daily reps in 30 seconds',
    fieldPiece: '1. Piece or Skill Name *',
    fieldPiecePh: 'e.g. C Major Scale, Sonatina Op.36 No.1',
    fieldBars: 'Section / Bars (Optional)',
    fieldBarsPh: 'e.g. Bars 12–16',
    fieldHand: 'Hand (Optional)',
    fieldHandAuto: 'Auto-detect / Any',
    fieldDetails: '2. Specific Practice Instructions *',
    fieldDetailsPh: 'e.g. Bars 12–16 RH slow practice, watch legato & phrasing',
    fieldTarget: '3. Daily Target Reps',
    submitAddTask: (name) => `➕ Add to ${name}’s Weekly List`,
    teacherNoteEditLabel: (name) => `💡 Weekly Note for ${name} (Shown at top of student’s card)`,
    teacherNoteEditPh: 'e.g. Keep wrists relaxed and listen for smooth phrase endings!',
    studentTaskListTitle: (name, count) => `${name}’s Weekly Tasks (${count})`,
    studentTaskListSub: 'Edit instructions, adjust daily targets, or preview student view',
    previewStudentBtn: '👀 Preview Student View',
    resetTodayBtn: 'Reset Today',
    emptyTasksTeacherTitle: 'No tasks assigned for this week',
    emptyTasksTeacherSub: (name) => `Use the form on the left to add ${name}’s first practice item!`,
    dailyBadge: (n) => `${n}x / day`,
    todayDoneBadge: (d, t) => `Today: ${d}/${t}x`,
    editBtn: 'Edit',
    deleteBtn: 'Delete',
    saveEditBtn: 'Save Changes',
    deleteStudentBtn: 'Delete Student Profile',
    confirmDeleteStudent: (name) => `Delete student "${name}" and all check-in history?`,
    toastStudentAdded: (name) => `✅ Created "${name}" with a unique private link!`,
    toastEnterPiece: '⚠️ Please enter a piece or skill name',
    toastTaskAdded: (name) => `🎵 Added new practice task for ${name}!`,
    toastLinkCopied: (name, sLang) =>
      `🔗 Copied ${name}’s private link (${sLang === 'en' ? 'English UI' : 'Cantonese UI'})!`,
    toastWhatsappCopied: (sLang) =>
      `💬 Copied ${sLang === 'en' ? 'English' : 'Cantonese'} WhatsApp message + private link!`,
    toastResetToday: (name) => `🔄 Reset today’s check-ins for ${name}`,
    toastTaskUpdated: '✅ Practice task updated',
    toastTaskDeleted: '🗑️ Task removed',
    toastStudentDeleted: (name) => `Removed student ${name}`,
    toastLangSaved: (name, sLang) =>
      `🌐 Set ${name}’s default language to ${sLang === 'en' ? 'English' : '繁體中文 (廣東話)'}`,
    // Practice Countdown Timer
    timerTitle: '⏱️ Practice Countdown Timer',
    timerSub: 'Pick a duration for focused practice — a chime plays when time’s up!',
    timerStart: '▶ Start Timer',
    timerPause: '⏸ Pause',
    timerResume: '▶ Resume',
    timerReset: '↺ Reset',
    timerRunningBadge: 'Focusing…',
    timerMinUnit: 'min',
    timerDoneTitle: '⏰ Practice Timer Complete!',
    timerDoneSub: (m) => `Awesome focus! You completed ${m} minutes of piano practice! 👏`,
    // Score Bar, Weekly Quiz & Leaderboard
    myMonthPtsLabel: 'Monthly Score',
    ptsUnit: 'pts',
    streakPtsShort: (p) => `🔥 Streak ${p} pts`,
    quizPtsShort: (p) => `🎧 Quiz ${p} pts`,
    openLeaderboardBtn: '🏆 Leaderboard',
    jumpToQuizNew: '🎧 Weekly Quiz (+50 pts!)',
    jumpToQuizDone: (s) => `🎧 Quiz (+${s} pts ✓)`,
    rankBadge: (r) => `Rank #${r}`,
    quizSectionBadge: '🎧 Weekly Music Listening Challenge',
    quizRuleTag: '+10 pts per correct answer (50 pts total)',
    quizOpenYoutubeBtn: '▶️ Watch Song on YouTube',
    quizSubmittedBanner: (c, tot, s) => `🎉 Challenge Completed! ${c} / ${tot} correct — You earned +${s} pts!`,
    quizQuestionRight: '✅ Correct +10 pts',
    quizQuestionWrong: '❌ Incorrect +0 pts',
    quizRightAnswerTag: '✓ Correct Answer',
    quizYourPickTag: 'Your Answer',
    quizSubmitBtn: (ans, tot) => `🎯 Submit Answers! (${ans}/${tot} selected)`,
    quizNeedAllMsg: '⚠️ Please choose an answer for all 5 questions before submitting!',
    quizDoneToast: (s) => `🎉 Submitted! You earned +${s} pts on this week’s quiz!`,
    lbTitle: '🏆 Monthly Leaderboard',
    lbSub: 'Top scorer at the end of each month wins a special prize from your teacher! 🎁',
    lbRulesTitle: '💡 How to Earn Points',
    lbRule1: '🔥 Practice Streak: 2 consecutive days = +10 pts, 3 days = +10 more, 4 days = +10 more… (Resets to Day 1 if your streak breaks!)',
    lbRule2: '🎧 Weekly Listening Quiz: +10 pts for every correct answer (up to +50 pts each week)',
    lbYouBadge: '⭐ You',
    lbColStreak: 'Streak',
    lbColQuiz: 'Quiz',
    lbColTotal: 'Total',
    lbPracticedDays: (d) => `${d}d practiced`,
    // Teacher Tabs & Quiz Builder
    tabStudents: '🎹 Student Tasks',
    tabQuiz: '🎧 Weekly YouTube Quiz',
    tabLeaderboard: '🏆 Monthly Leaderboard',
    tqHeaderTitle: '🎧 Weekly YouTube Music Quiz (Visible to All Students)',
    tqHeaderSub: 'Attach a YouTube song link and 5 multiple-choice questions with definite answers (+10 pts per right answer)!',
    tqNewWeekBtn: '✨ New Weekly Quiz (Keep Past Scores)',
    tqQuizTitleLabel: 'Challenge Title *',
    tqYoutubeLabel: 'YouTube Video URL *',
    tqYoutubePh: 'Paste https://www.youtube.com/watch?v=... or https://youtu.be/...',
    tqDescLabel: 'Student Instructions (Optional)',
    tqQuestionHeading: (i) => `Question ${i} (10 pts)`,
    tqQuestionPh: (i) => `Enter Question ${i}…`,
    tqOptionPh: (letter) => `Option ${letter}`,
    tqMarkCorrect: 'Mark Correct',
    tqIsCorrect: '✓ Correct',
    tqSavePublishBtn: '🚀 Save & Publish Weekly Quiz',
    tqStatusHeading: '📊 Student Quiz Results (This Week)',
    tqNotSubmitted: 'Pending',
    tqSubmittedScore: (c, tot, s) => `${c}/${tot} correct · +${s} pts`,
    toastQuizPublished: '🚀 Weekly Music Quiz published to all students!',
    toastNewQuizDraft: '✨ Created a new blank weekly quiz (past scores preserved)!'
  }
};

// ---------- 工具函數 ----------
function randomToken(len = 8) {
  const chars = 'abcdefghjkmnpqrstuvwxyz23456789';
  let out = '';
  for (let i = 0; i < len; i++) {
    out += chars[Math.floor(Math.random() * chars.length)];
  }
  return out;
}

function getLocalDateKey(d = new Date()) {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  const day = String(d.getDate()).padStart(2, '0');
  return `${y}-${m}-${day}`;
}

function addDays(date, offset) {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate() + offset);
}

function getWeekDays(refDate = new Date(), lang = 'zh') {
  const jsDay = refDate.getDay();
  const diffToMonday = jsDay === 0 ? -6 : 1 - jsDay;
  const monday = addDays(refDate, diffToMonday);
  const todayKey = getLocalDateKey(refDate);
  const labels = lang === 'en'
    ? ['M', 'T', 'W', 'T', 'F', 'S', 'S']
    : ['一', '二', '三', '四', '五', '六', '日'];

  return labels.map((label, idx) => {
    const d = addDays(monday, idx);
    const key = getLocalDateKey(d);
    return {
      key,
      label,
      dayNum: d.getDate(),
      monthNum: d.getMonth() + 1,
      isToday: key === todayKey,
      isFuture: key > todayKey
    };
  });
}

function localizeHand(handRaw, lang) {
  if (!handRaw) return '';
  if (lang === 'zh') return handRaw;
  const map = {
    '右手 RH': 'Right Hand (RH)',
    '左手 LH': 'Left Hand (LH)',
    '雙手 HT': 'Hands Together (HT)',
    '分手 HS': 'Hands Separate (HS)',
    '分手 → 雙手': 'HS → HT',
    '左手 LH + 雙手': 'LH + HT'
  };
  if (map[handRaw]) return map[handRaw];
  return handRaw
    .replace(/雙手/g, 'HT')
    .replace(/右手/g, 'RH')
    .replace(/左手/g, 'LH')
    .replace(/分手/g, 'HS');
}

function localizeBars(barsRaw, task, lang) {
  if (lang === 'en' && task && task.barsEn) return task.barsEn;
  if (!barsRaw) return '';
  if (lang === 'en') {
    return barsRaw.replace(/\s*[兩三四1234]\s*個八度/g, '').trim();
  }
  return barsRaw;
}

function localizeTaskPiece(task, lang) {
  if (lang === 'en' && task.pieceEn) return task.pieceEn;
  return task.piece;
}

function localizeTaskDetails(task, lang) {
  if (lang === 'en' && task.detailsEn) return task.detailsEn;
  return task.details;
}

function localizeStudentLevel(student, lang) {
  if (lang === 'en' && student.levelEn) return student.levelEn;
  if (lang === 'en' && student.level === '鋼琴學生') return 'Piano Student';
  return student.level;
}

function localizeStudentNote(student, lang) {
  if (lang === 'en' && student.teacherNoteEn) return student.teacherNoteEn;
  return student.teacherNote;
}

function extractTaskMeta(task, lang = 'zh') {
  let rawBars = (task.bars || '').trim();
  let rawHand = (task.hand || '').trim();
  const text = `${task.piece || ''} ${task.details || ''}`;

  if (!rawBars) {
    const barMatch = text.match(/(Bars?\s*\d+(?:\s*[–\-~至到]\s*\d+)?|第\s*\d+(?:\s*[–\-~至到]\s*\d+)?\s*小節|\d+\s*(?:Octaves?|個八度))/i);
    if (barMatch) rawBars = barMatch[1];
  }
  if (!rawHand) {
    if (/雙手|合手|hands\s*together|\bHT\b/i.test(text)) rawHand = '雙手 HT';
    else if (/右手|right\s*hand|\bRH\b/i.test(text)) rawHand = '右手 RH';
    else if (/左手|left\s*hand|\bLH\b/i.test(text)) rawHand = '左手 LH';
    else if (/分手|左右手分開|hands\s*separate|\bHS\b/i.test(text)) rawHand = '分手 HS';
  }
  return {
    bars: localizeBars(rawBars, task, lang),
    hand: localizeHand(rawHand, lang)
  };
}

function computeStudentStats(student, lang = 'zh') {
  const now = new Date();
  const todayKey = getLocalDateKey(now);
  const tasks = student.tasks || [];
  const logs = student.logs || {};
  const todayLogs = logs[todayKey] || {};

  const dailyTargetSum = tasks.reduce((acc, tk) => acc + (Number(tk.dailyTarget) || 1), 0);
  let todayCappedReps = 0;
  let todayTotalReps = 0;
  let completedTasksToday = 0;

  tasks.forEach((tk) => {
    const count = Number(todayLogs[tk.id] || 0);
    const target = Number(tk.dailyTarget) || 1;
    todayTotalReps += count;
    todayCappedReps += Math.min(count, target);
    if (count >= target) completedTasksToday += 1;
  });

  const todayProgressPct = dailyTargetSum > 0 ? Math.round((todayCappedReps / dailyTargetSum) * 100) : 0;
  const allTasksDoneToday = tasks.length > 0 && completedTasksToday === tasks.length;

  const rawWeekDays = getWeekDays(now, lang);
  let weekTotalCheckins = 0;
  let weekCappedReps = 0;
  let weekPracticedDays = 0;

  const weekDays = rawWeekDays.map((wd) => {
    const dayMap = logs[wd.key] || {};
    let dayTotal = 0;
    let dayCapped = 0;

    tasks.forEach((tk) => {
      const c = Number(dayMap[tk.id] || 0);
      const target = Number(tk.dailyTarget) || 1;
      dayTotal += c;
      dayCapped += Math.min(c, target);
    });

    Object.keys(dayMap).forEach((tid) => {
      if (!tasks.some((tk) => tk.id === tid)) {
        dayTotal += Number(dayMap[tid] || 0);
      }
    });

    weekTotalCheckins += dayTotal;
    weekCappedReps += dayCapped;
    if (dayTotal > 0) weekPracticedDays += 1;

    return {
      ...wd,
      totalReps: dayTotal,
      isPracticed: dayTotal > 0,
      isFullGoal: dailyTargetSum > 0 && dayCapped >= dailyTargetSum
    };
  });

  const weeklyTargetTotal = dailyTargetSum * 7;
  const weekCompletionPct = weeklyTargetTotal > 0
    ? Math.min(100, Math.round((weekCappedReps / weeklyTargetTotal) * 100))
    : 0;

  const hasDayPractice = (dKey) => {
    const dm = logs[dKey];
    if (!dm) return false;
    return Object.values(dm).some((v) => Number(v) > 0);
  };

  let streakDays = 0;
  let cursorOffset = hasDayPractice(todayKey) ? 0 : -1;
  while (cursorOffset > -365) {
    const k = getLocalDateKey(addDays(now, cursorOffset));
    if (hasDayPractice(k)) {
      streakDays += 1;
      cursorOffset -= 1;
    } else {
      break;
    }
  }

  return {
    todayKey,
    totalTasks: tasks.length,
    completedTasksToday,
    todayTotalReps,
    todayCappedReps,
    dailyTargetSum,
    todayProgressPct,
    allTasksDoneToday,
    weekDays,
    weekTotalCheckins,
    weeklyTargetTotal,
    weekCompletionPct,
    weekPracticedDays,
    streakDays
  };
}

// 相片壓縮與正方裁切（避免大檔案並確保 iPhone/iPad 即拍即傳超順暢）
function compressAvatarImage(file, maxSize = 240) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onerror = () => reject(new Error('File read failed'));
    reader.onload = () => {
      const img = new Image();
      img.onerror = () => reject(new Error('Image decode failed'));
      img.onload = () => {
        const canvas = document.createElement('canvas');
        canvas.width = maxSize;
        canvas.height = maxSize;
        const ctx = canvas.getContext('2d');
        const minSide = Math.min(img.width, img.height);
        const sx = (img.width - minSide) / 2;
        const sy = (img.height - minSide) / 2;
        ctx.fillStyle = '#FFFFFF';
        ctx.fillRect(0, 0, maxSize, maxSize);
        ctx.drawImage(img, sx, sy, minSide, minSide, 0, 0, maxSize, maxSize);
        const dataUrl = canvas.toDataURL('image/jpeg', 0.86);
        resolve(dataUrl);
      };
      img.src = reader.result;
    };
    reader.readAsDataURL(file);
  });
}

// ---------- Web Audio 鋼琴與慶祝音效引擎 ----------
const SoundEngine = {
  ctx: null,
  getCtx() {
    if (!this.ctx) {
      const AudioCtx = window.AudioContext || window.webkitAudioContext;
      if (AudioCtx) this.ctx = new AudioCtx();
    }
    if (this.ctx && this.ctx.state === 'suspended') {
      this.ctx.resume().catch(() => {});
    }
    return this.ctx;
  },
  playTone(freq, startTime, duration = 0.35, peakGain = 0.18, type = 'triangle') {
    const ctx = this.getCtx();
    if (!ctx) return;

    const osc = ctx.createOscillator();
    const harmonic = ctx.createOscillator();
    const gain = ctx.createGain();
    const harmGain = ctx.createGain();

    osc.type = type;
    osc.frequency.setValueAtTime(freq, startTime);

    harmonic.type = 'sine';
    harmonic.frequency.setValueAtTime(freq * 2, startTime);

    gain.gain.setValueAtTime(0.0001, startTime);
    gain.gain.linearRampToValueAtTime(peakGain, startTime + 0.015);
    gain.gain.exponentialRampToValueAtTime(0.0008, startTime + duration);

    harmGain.gain.setValueAtTime(0.0001, startTime);
    harmGain.gain.linearRampToValueAtTime(peakGain * 0.25, startTime + 0.012);
    harmGain.gain.exponentialRampToValueAtTime(0.0005, startTime + duration * 0.7);

    osc.connect(gain);
    harmonic.connect(harmGain);
    gain.connect(ctx.destination);
    harmGain.connect(ctx.destination);

    osc.start(startTime);
    harmonic.start(startTime);
    osc.stop(startTime + duration + 0.03);
    harmonic.stop(startTime + duration + 0.03);
  },
  playCheckinStep(stepNumber) {
    const ctx = this.getCtx();
    if (!ctx) return;
    const scale = [523.25, 587.33, 659.25, 698.46, 783.99, 880.0, 987.77, 1046.5];
    const freq = scale[(Math.max(1, stepNumber) - 1) % scale.length];
    const now = ctx.currentTime;
    this.playTone(freq, now, 0.32, 0.2, 'triangle');
  },
  playTaskSuccess() {
    const ctx = this.getCtx();
    if (!ctx) return;
    const now = ctx.currentTime;
    const notes = [
      { f: 523.25, t: 0.0, d: 0.45, g: 0.2 },
      { f: 659.25, t: 0.09, d: 0.45, g: 0.2 },
      { f: 783.99, t: 0.18, d: 0.5, g: 0.22 },
      { f: 1046.5, t: 0.28, d: 0.85, g: 0.26 },
      { f: 1318.5, t: 0.36, d: 0.75, g: 0.14 }
    ];
    notes.forEach((n) => this.playTone(n.f, now + n.t, n.d, n.g, 'triangle'));
  },
  playAllTasksGrandFanfare() {
    const ctx = this.getCtx();
    if (!ctx) return;
    const now = ctx.currentTime;
    const seq = [
      { f: 523.25, t: 0.0, d: 0.25, g: 0.2 },
      { f: 659.25, t: 0.08, d: 0.25, g: 0.2 },
      { f: 783.99, t: 0.16, d: 0.28, g: 0.22 },
      { f: 1046.5, t: 0.26, d: 0.35, g: 0.24 },
      { f: 880.0,  t: 0.44, d: 0.22, g: 0.2 },
      { f: 1046.5, t: 0.56, d: 0.95, g: 0.28 },
      { f: 1318.5, t: 0.58, d: 0.95, g: 0.18 },
      { f: 1567.98, t: 0.60, d: 1.0, g: 0.16 }
    ];
    seq.forEach((n) => this.playTone(n.f, now + n.t, n.d, n.g, 'triangle'));
  },
  playUndo() {
    const ctx = this.getCtx();
    if (!ctx) return;
    const now = ctx.currentTime;
    this.playTone(440, now, 0.16, 0.1, 'sine');
    this.playTone(349.23, now + 0.08, 0.2, 0.09, 'sine');
  }
};

// ---------- 複製文字工具 ----------
async function copyToClipboard(text) {
  if (navigator.clipboard && window.isSecureContext) {
    try {
      await navigator.clipboard.writeText(text);
      return true;
    } catch (_) {}
  }
  const ta = document.createElement('textarea');
  ta.value = text;
  ta.style.position = 'fixed';
  ta.style.left = '-9999px';
  document.body.appendChild(ta);
  ta.focus();
  ta.select();
  let ok = false;
  try {
    ok = document.execCommand('copy');
  } catch (_) {}
  document.body.removeChild(ta);
  return ok;
}

// ---------- URL 解析工具（嚴格區分 /teacher 與私密 token ?s=...） ----------
function parseLocationRoute() {
  const path = window.location.pathname.replace(/\/+$/, '') || '/';
  const params = new URLSearchParams(window.location.search);
  const langParam = params.get('lang');
  const explicitLang = langParam === 'en' || langParam === 'zh' ? langParam : null;
  const isPreview = params.get('preview') === '1';

  if (path === '/teacher') {
    return { mode: 'teacher', token: null, explicitLang, isPreview: false };
  }

  let token = (params.get('s') || params.get('token') || '').trim();
  if (!token && !isPreview) {
    try {
      token = (localStorage.getItem(STUDENT_SAVED_TOKEN_KEY) || '').trim();
    } catch (_) {}
  }

  return { mode: 'student', token: token || null, explicitLang, isPreview };
}

// ---------- 通用學生頭像顯示元件（支援相片或貼紙 + 彩色外框） ----------
function StudentAvatar({ student, sizeClass = 'w-14 h-14 text-3xl', roundedClass = 'rounded-2xl', activeHighlight = false }) {
  const themeKey = (student && student.avatarBg && AVATAR_THEMES[student.avatarBg]) ? student.avatarBg : 'indigo';
  const theme = AVATAR_THEMES[themeKey];
  const hasPhoto = student && student.avatarImage && student.avatarImage.startsWith('data:image/');

  return (
    <div
      className={`${sizeClass} ${roundedClass} overflow-hidden flex items-center justify-center shrink-0 border-2 ring-2 transition ${
        activeHighlight ? 'ring-indigo-500 border-indigo-600' : `${theme.bg} ${theme.ring}`
      }`}
    >
      {hasPhoto ? (
        <img
          src={student.avatarImage}
          alt={student.name}
          className="w-full h-full object-cover"
        />
      ) : (
        <span className="select-none leading-none">{(student && student.avatar) || '🎹'}</span>
      )}
    </div>
  );
}

// ---------- 學生自訂相片／得意貼紙頭像彈窗 ----------
function AvatarCustomizerModal({ open, student, lang, soundMuted, onSave, onClose, showToast }) {
  const [draftAvatar, setDraftAvatar] = useState('🎹');
  const [draftImage, setDraftImage] = useState(null);
  const [draftBg, setDraftBg] = useState('indigo');
  const [saving, setSaving] = useState(false);
  const fileInputRef = useRef(null);

  useEffect(() => {
    if (open && student) {
      setDraftAvatar(student.avatar || '🎹');
      setDraftImage(student.avatarImage || null);
      setDraftBg(student.avatarBg || 'indigo');
    }
  }, [open, student]);

  if (!open || !student) return null;
  const t = I18N[lang] || I18N.zh;

  const handleFileChange = async (e) => {
    const file = e.target.files && e.target.files[0];
    if (!file) return;
    try {
      const compressed = await compressAvatarImage(file, 240);
      setDraftImage(compressed);
      if (!soundMuted) SoundEngine.playCheckinStep(5);
    } catch (_) {
      showToast(t.toastPhotoError);
    }
    e.target.value = '';
  };

  const handleConfirm = async () => {
    setSaving(true);
    await onSave({
      avatar: draftAvatar,
      avatarImage: draftImage,
      avatarBg: draftBg
    });
    setSaving(false);
    if (!soundMuted) SoundEngine.playTaskSuccess();
    onClose();
  };

  const previewStudent = {
    ...student,
    avatar: draftAvatar,
    avatarImage: draftImage,
    avatarBg: draftBg
  };

  return (
    <div className="fixed inset-0 z-50 bg-black/50 backdrop-blur-xs flex items-end sm:items-center justify-center p-3 sm:p-4" onClick={onClose}>
      <div
        className="bg-white rounded-3xl max-w-md w-full p-5 sm:p-6 shadow-2xl border border-ivory-300 animate-popIn max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-start justify-between gap-2 mb-4">
          <div>
            <h3 className="font-black text-lg sm:text-xl text-ink-900">{t.avatarModalTitle}</h3>
            <p className="text-xs text-ink-500 mt-0.5">{t.avatarModalSub}</p>
          </div>
          <button
            type="button"
            onClick={onClose}
            className="w-8 h-8 rounded-full bg-ivory-200 hover:bg-ivory-300 text-ink-700 font-bold shrink-0"
          >
            ✕
          </button>
        </div>

        {/* 即時大頭像預覽 + 上載相片掣 */}
        <div className="bg-ivory-100 rounded-3xl p-5 border border-ivory-300 flex flex-col items-center text-center">
          <StudentAvatar
            student={previewStudent}
            sizeClass="w-24 h-24 text-5xl shadow-md"
            roundedClass="rounded-3xl"
          />
          <div className="font-black text-base text-ink-900 mt-2.5">{student.name}</div>

          <input
            ref={fileInputRef}
            type="file"
            accept="image/*"
            onChange={handleFileChange}
            className="hidden"
          />

          <div className="flex flex-wrap items-center justify-center gap-2 mt-3">
            <button
              type="button"
              onClick={() => fileInputRef.current && fileInputRef.current.click()}
              className="px-4 py-2.5 rounded-2xl bg-indigo-600 hover:bg-indigo-700 active:scale-95 text-white text-xs sm:text-sm font-extrabold shadow-sm transition"
            >
              {t.uploadPhotoBtn}
            </button>
            {draftImage && (
              <button
                type="button"
                onClick={() => setDraftImage(null)}
                className="px-3.5 py-2.5 rounded-2xl bg-white hover:bg-ivory-200 border border-ivory-300 text-xs font-bold text-ink-700 transition"
              >
                {t.removePhotoBtn}
              </button>
            )}
          </div>
        </div>

        {/* 得意貼紙選擇器 */}
        <div className="mt-4">
          <div className="text-xs font-extrabold text-ink-700 mb-2">{t.pickStickerLabel}</div>
          <div className="grid grid-cols-8 gap-1.5">
            {STICKER_OPTIONS.map((emo, idx) => {
              const selected = !draftImage && draftAvatar === emo;
              return (
                <button
                  key={emo}
                  type="button"
                  onClick={() => {
                    setDraftImage(null);
                    setDraftAvatar(emo);
                    if (!soundMuted) SoundEngine.playCheckinStep((idx % 8) + 1);
                  }}
                  className={`aspect-square rounded-xl text-xl flex items-center justify-center transition ${
                    selected
                      ? 'bg-indigo-600 text-white ring-2 ring-indigo-300 scale-105 shadow-xs'
                      : 'bg-ivory-100 hover:bg-ivory-200 border border-ivory-200'
                  }`}
                >
                  {emo}
                </button>
              );
            })}
          </div>
        </div>

        {/* 邊框顏色主題 */}
        <div className="mt-4">
          <div className="text-xs font-extrabold text-ink-700 mb-2">{t.pickThemeLabel}</div>
          <div className="grid grid-cols-3 gap-2">
            {Object.entries(AVATAR_THEMES).map(([key, th]) => {
              const active = draftBg === key;
              return (
                <button
                  key={key}
                  type="button"
                  onClick={() => {
                    setDraftBg(key);
                    if (!soundMuted) SoundEngine.playCheckinStep(3);
                  }}
                  className={`py-2 px-2 rounded-xl border text-xs font-bold flex items-center justify-center gap-1.5 transition ${
                    active
                      ? 'border-indigo-600 bg-indigo-50 text-indigo-800 ring-2 ring-indigo-200'
                      : 'border-ivory-300 bg-white hover:bg-ivory-100 text-ink-700'
                  }`}
                >
                  <span className={`w-3.5 h-3.5 rounded-full ${th.dot}`} />
                  <span className="truncate">{lang === 'en' ? th.en : th.zh}</span>
                </button>
              );
            })}
          </div>
        </div>

        <button
          type="button"
          disabled={saving}
          onClick={handleConfirm}
          className="mt-5 w-full py-3.5 rounded-2xl bg-emerald-600 hover:bg-emerald-700 active:scale-[0.98] text-white font-black text-base shadow-md transition"
        >
          {t.saveAvatarBtn}
        </button>
      </div>
    </div>
  );
}

// ---------- 練琴打卡月曆元件 (Practice Calendar — 有打卡即點亮綠點 + 每週疏密對比) ----------
function PracticeCalendar({ student, lang, isTeacherView = false }) {
  const now = new Date();
  const todayKey = getLocalDateKey(now);
  const curYear = now.getFullYear();
  const curMonth = now.getMonth();

  const [viewYm, setViewYm] = useState({ year: curYear, month: curMonth });
  const [selectedDay, setSelectedDay] = useState(null);

  // 切換學生時重設回當前月份
  useEffect(() => {
    setViewYm({ year: curYear, month: curMonth });
    setSelectedDay(null);
  }, [student && student.id, curYear, curMonth]);

  const t = I18N[lang] || I18N.zh;
  const logs = (student && student.logs) || {};
  const tasks = (student && student.tasks) || [];
  const dailyTargetSum = tasks.reduce((acc, tk) => acc + (Number(tk.dailyTarget) || 1), 0);

  const isViewingCurrentMonth = viewYm.year === curYear && viewYm.month === curMonth;

  // 建立整月星期一至日網格
  const calendarData = useMemo(() => {
    const firstOfMonth = new Date(viewYm.year, viewYm.month, 1);
    const lastOfMonth = new Date(viewYm.year, viewYm.month + 1, 0);

    const firstDow = firstOfMonth.getDay();
    const offsetToMon = firstDow === 0 ? -6 : 1 - firstDow;
    const gridStart = new Date(viewYm.year, viewYm.month, 1 + offsetToMon);

    const lastDow = lastOfMonth.getDay();
    const offsetToSun = lastDow === 0 ? 0 : 7 - lastDow;
    const gridEnd = new Date(viewYm.year, viewYm.month, lastOfMonth.getDate() + offsetToSun);

    const weeks = [];
    let monthPracticedDays = 0;
    let monthTotalReps = 0;

    let cursor = new Date(gridStart.getFullYear(), gridStart.getMonth(), gridStart.getDate());
    while (cursor <= gridEnd) {
      const row = [];
      for (let i = 0; i < 7; i++) {
        const dKey = getLocalDateKey(cursor);
        const inMonth = cursor.getMonth() === viewYm.month;
        const isToday = dKey === todayKey;
        const isFuture = dKey > todayKey;
        const dayLog = logs[dKey] || {};

        let totalReps = 0;
        let cappedReps = 0;
        Object.entries(dayLog).forEach(([tid, val]) => {
          const n = Number(val) || 0;
          totalReps += n;
          const matchedTask = tasks.find((tk) => tk.id === tid);
          if (matchedTask) {
            cappedReps += Math.min(n, Number(matchedTask.dailyTarget) || 1);
          }
        });

        const hasPracticed = totalReps > 0;
        const isFullGoal = hasPracticed && dailyTargetSum > 0 && cappedReps >= dailyTargetSum;

        if (inMonth && hasPracticed) {
          monthPracticedDays += 1;
          monthTotalReps += totalReps;
        }

        row.push({
          key: dKey,
          dayNum: cursor.getDate(),
          inMonth,
          isToday,
          isFuture,
          totalReps,
          hasPracticed,
          isFullGoal
        });

        cursor = addDays(cursor, 1);
      }

      const practicedInWeek = row.filter((c) => c.hasPracticed).length;
      const elapsedInWeek = row.filter((c) => !c.isFuture).length;
      const containsToday = row.some((c) => c.isToday);

      weeks.push({
        weekKey: row[0].key,
        days: row,
        practicedInWeek,
        elapsedInWeek,
        containsToday
      });
    }

    return { weeks, monthPracticedDays, monthTotalReps };
  }, [viewYm.year, viewYm.month, logs, tasks, dailyTargetSum, todayKey]);

  // 計算「本星期」嘅打卡疏密提示語
  const currentWeekBanner = useMemo(() => {
    if (!student) return null;
    const stats = computeStudentStats(student, lang);
    const jsDow = now.getDay();
    const elapsedDays = jsDow === 0 ? 7 : jsDow; // Mon=1 .. Sun=7
    const practiced = stats.weekPracticedDays;

    if (isTeacherView) {
      if (practiced === 0 && elapsedDays >= 2) {
        return {
          tone: 'rose',
          text: t.calZeroWeekTeacher(student.name)
        };
      }
      return {
        tone: practiced >= 4 ? 'emerald' : 'neutral',
        text: t.calSummaryTeacher(student.name, practiced)
      };
    }

    if (practiced === 0) {
      if (elapsedDays === 1) {
        return { tone: 'indigo', text: t.calZeroMonStudent };
      }
      return { tone: 'rose', text: t.calZeroWeekStudent };
    }
    if (practiced === 1 && elapsedDays >= 4) {
      return { tone: 'amber', text: t.calSparseWeekStudent(practiced) };
    }
    if (practiced >= 5) {
      return { tone: 'emerald', text: t.calGreatWeekStudent(practiced) };
    }
    return { tone: 'indigo', text: t.calGoodWeekStudent(practiced) };
  }, [student, lang, isTeacherView, t]);

  if (!student) return null;

  const shiftMonth = (delta) => {
    setSelectedDay(null);
    setViewYm((prev) => {
      const d = new Date(prev.year, prev.month + delta, 1);
      return { year: d.getFullYear(), month: d.getMonth() };
    });
  };

  const bannerStyles = {
    rose: 'bg-rose-50 border-rose-300 text-rose-900',
    amber: 'bg-amber-50 border-amber-300 text-amber-950',
    emerald: 'bg-emerald-50 border-emerald-300 text-emerald-950',
    indigo: 'bg-indigo-50/80 border-indigo-200 text-indigo-950',
    neutral: 'bg-ivory-100 border-ivory-300 text-ink-700'
  };

  return (
    <div className="bg-white rounded-3xl p-5 sm:p-6 shadow-sm border border-ivory-300 mb-5">
      {/* 標題與月份切換器 */}
      <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 mb-3.5">
        <div>
          <div className="flex items-center gap-2 flex-wrap">
            <h2 className="text-base sm:text-lg font-black text-ink-900">{t.calTitle}</h2>
            <span className="px-2.5 py-0.5 rounded-full bg-emerald-100 text-emerald-800 text-xs font-extrabold">
              {t.calMonthSummary(calendarData.monthPracticedDays, calendarData.monthTotalReps)}
            </span>
          </div>
          <p className="text-xs text-ink-500 mt-0.5">{t.calSub}</p>
        </div>

        <div className="flex items-center gap-1.5 self-start sm:self-auto">
          {!isViewingCurrentMonth && (
            <button
              type="button"
              onClick={() => {
                setViewYm({ year: curYear, month: curMonth });
                setSelectedDay(null);
              }}
              className="px-2.5 py-1.5 rounded-xl bg-indigo-50 hover:bg-indigo-100 text-indigo-700 text-xs font-extrabold transition mr-1"
            >
              {t.calBackToCurrent}
            </button>
          )}
          <button
            type="button"
            onClick={() => shiftMonth(-1)}
            className="w-8 h-8 rounded-xl bg-ivory-100 hover:bg-ivory-200 border border-ivory-300 text-sm font-black text-ink-700 flex items-center justify-center transition"
            aria-label="Previous Month"
          >
            ‹
          </button>
          <div className="min-w-[104px] text-center font-black text-sm text-ink-900">
            {t.calMonthFormat(viewYm.year, viewYm.month + 1)}
          </div>
          <button
            type="button"
            onClick={() => shiftMonth(1)}
            className="w-8 h-8 rounded-xl bg-ivory-100 hover:bg-ivory-200 border border-ivory-300 text-sm font-black text-ink-700 flex items-center justify-center transition"
            aria-label="Next Month"
          >
            ›
          </button>
        </div>
      </div>

      {/* 本週疏密提示橫幅（如果成個星期零打卡會顯示蜘蛛網提示 🕸️！） */}
      {isViewingCurrentMonth && currentWeekBanner && (
        <div className={`rounded-2xl px-3.5 py-2.5 mb-4 border text-xs sm:text-sm font-bold leading-relaxed ${
          bannerStyles[currentWeekBanner.tone] || bannerStyles.neutral
        }`}>
          {currentWeekBanner.text}
        </div>
      )}

      {/* 星期標題列 + 右側「週密度」欄 */}
      <div className="grid grid-cols-8 gap-1 sm:gap-1.5 text-center mb-1.5">
        {t.calWeekDayHeaders.map((h, i) => (
          <div key={i} className="text-[11px] font-extrabold text-ink-500 py-1">
            {h}
          </div>
        ))}
        <div className="text-[10px] sm:text-[11px] font-extrabold text-ink-500 py-1">
          {t.calWeekCol}
        </div>
      </div>

      {/* 每週橫列（一眼睇晒個個星期練得密唔密！） */}
      <div className="space-y-1.5">
        {calendarData.weeks.map((wk) => {
          const isZeroShameWeek = wk.elapsedInWeek >= 2 && wk.practicedInWeek === 0;
          return (
            <div
              key={wk.weekKey}
              className={`grid grid-cols-8 gap-1 sm:gap-1.5 items-center rounded-2xl p-1 transition ${
                wk.containsToday
                  ? isZeroShameWeek
                    ? 'bg-rose-50/70 ring-1 ring-rose-200'
                    : 'bg-indigo-50/45 ring-1 ring-indigo-200/80'
                  : ''
              }`}
            >
              {wk.days.map((cell) => {
                const isSelected = selectedDay && selectedDay.key === cell.key;
                return (
                  <button
                    key={cell.key}
                    type="button"
                    onClick={() => setSelectedDay(cell)}
                    className={`h-11 sm:h-12 rounded-xl flex flex-col items-center justify-center gap-0.5 border transition relative ${
                      !cell.inMonth ? 'opacity-40 ' : ''
                    }${
                      isSelected ? 'ring-2 ring-indigo-600 scale-105 z-10 ' : ''
                    }${
                      cell.hasPracticed
                        ? cell.isToday
                          ? 'bg-emerald-100 border-emerald-500 text-emerald-950 shadow-2xs'
                          : 'bg-emerald-50/95 border-emerald-300 text-emerald-950 hover:bg-emerald-100/80'
                        : cell.isToday
                        ? 'bg-white border-2 border-dashed border-indigo-500 text-indigo-700'
                        : cell.isFuture
                        ? 'bg-ivory-50/60 border-transparent text-ink-400'
                        : 'bg-ivory-100/80 border-ivory-200 text-ink-500 hover:bg-ivory-200/60'
                    }`}
                  >
                    <span className={`text-xs sm:text-sm leading-none ${
                      cell.hasPracticed || cell.isToday ? 'font-black' : 'font-semibold'
                    }`}>
                      {cell.dayNum}
                    </span>

                    {/* 打卡圓點指示器：有打卡即亮起鮮明綠點！ */}
                    {cell.hasPracticed ? (
                      <span
                        className={`w-2.5 h-2.5 rounded-full bg-emerald-500 shadow-2xs ${
                          cell.isFullGoal ? 'ring-2 ring-emerald-200' : ''
                        }`}
                      />
                    ) : cell.isFuture ? (
                      <span className="w-1.5 h-1.5 rounded-full bg-transparent" />
                    ) : (
                      <span className="w-2 h-2 rounded-full border border-stone-300 bg-white/70" />
                    )}
                  </button>
                );
              })}

              {/* 第 8 欄：該星期練琴密度徽章 */}
              <div className="flex items-center justify-center">
                {wk.elapsedInWeek === 0 ? (
                  <span className="text-[11px] font-bold text-ink-400">—</span>
                ) : isZeroShameWeek ? (
                  <span
                    className="px-1.5 py-1 rounded-lg bg-rose-100 border border-rose-200 text-rose-700 text-[10px] sm:text-xs font-black whitespace-nowrap"
                    title="0 check-ins this week"
                  >
                    🕸️ 0/7
                  </span>
                ) : wk.practicedInWeek >= 5 ? (
                  <span className="px-1.5 py-1 rounded-lg bg-emerald-100 border border-emerald-300 text-emerald-800 text-[10px] sm:text-xs font-black whitespace-nowrap">
                    🔥 {wk.practicedInWeek}/7
                  </span>
                ) : wk.practicedInWeek >= 3 ? (
                  <span className="px-1.5 py-1 rounded-lg bg-teal-50 border border-teal-200 text-teal-800 text-[10px] sm:text-xs font-extrabold whitespace-nowrap">
                    {wk.practicedInWeek}/7
                  </span>
                ) : (
                  <span className="px-1.5 py-1 rounded-lg bg-amber-100/90 border border-amber-200 text-amber-900 text-[10px] sm:text-xs font-extrabold whitespace-nowrap">
                    {wk.practicedInWeek}/7
                  </span>
                )}
              </div>
            </div>
          );
        })}
      </div>

      {/* 點擊單日查看詳情列 / 圖例 */}
      <div className="mt-3.5 pt-3 border-t border-ivory-200 flex flex-col sm:flex-row sm:items-center justify-between gap-2 text-xs">
        {selectedDay ? (
          <div className="font-bold text-ink-800">
            {selectedDay.hasPracticed
              ? t.calDayDetailPracticed(selectedDay.key, selectedDay.totalReps)
              : selectedDay.isToday
              ? t.calDayDetailEmptyToday(selectedDay.key)
              : selectedDay.isFuture
              ? t.calDayDetailFuture(selectedDay.key)
              : t.calDayDetailEmptyPast(selectedDay.key)}
          </div>
        ) : (
          <div className="flex items-center gap-4 text-ink-500 font-semibold">
            <span className="inline-flex items-center gap-1.5">
              <span className="w-2.5 h-2.5 rounded-full bg-emerald-500 inline-block" />
              <span>{t.calLegendPracticed}</span>
            </span>
            <span className="inline-flex items-center gap-1.5">
              <span className="w-2 h-2 rounded-full border border-stone-300 bg-white inline-block" />
              <span>{t.calLegendEmpty}</span>
            </span>
          </div>
        )}
      </div>
    </div>
  );
}

// ---------- 煙花與星星鼓勵動畫 Overlay ----------
function CelebrationOverlay({ event, lang, onDismiss }) {
  const canvasRef = useRef(null);
  const t = I18N[lang] || I18N.zh;

  useEffect(() => {
    if (!event) return;
    const canvas = canvasRef.current;
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    const dpr = window.devicePixelRatio || 1;

    const resize = () => {
      canvas.width = window.innerWidth * dpr;
      canvas.height = window.innerHeight * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();

    const colors = ['#10B981', '#F59E0B', '#4F46E5', '#EC4899', '#06B6D4', '#FBBF24', '#8B5CF6'];
    const particles = [];
    const burstOrigins = event.isGrand
      ? [
          { x: window.innerWidth * 0.25, y: window.innerHeight * 0.42 },
          { x: window.innerWidth * 0.5, y: window.innerHeight * 0.35 },
          { x: window.innerWidth * 0.75, y: window.innerHeight * 0.42 }
        ]
      : [
          { x: window.innerWidth * 0.35, y: window.innerHeight * 0.45 },
          { x: window.innerWidth * 0.65, y: window.innerHeight * 0.45 }
        ];

    burstOrigins.forEach((origin) => {
      const count = event.isGrand ? 52 : 45;
      for (let i = 0; i < count; i++) {
        const angle = (Math.PI * 2 * i) / count + (Math.random() - 0.5) * 0.35;
        const speed = 4 + Math.random() * 9.5;
        particles.push({
          x: origin.x,
          y: origin.y,
          vx: Math.cos(angle) * speed,
          vy: Math.sin(angle) * speed - 3.2,
          size: 5 + Math.random() * 7,
          color: colors[Math.floor(Math.random() * colors.length)],
          shape: i % 3 === 0 ? 'star' : i % 7 === 0 ? 'circle' : 'ribbon',
          rot: Math.random() * Math.PI * 2,
          vRot: (Math.random() - 0.5) * 0.22,
          alpha: 1,
          decay: 0.011 + Math.random() * 0.009
        });
      }
    });

    const drawStar = (cx, cy, spikes, outerR, innerR) => {
      let rot = (Math.PI / 2) * 3;
      const step = Math.PI / spikes;
      ctx.beginPath();
      ctx.moveTo(cx, cy - outerR);
      for (let i = 0; i < spikes; i++) {
        ctx.lineTo(cx + Math.cos(rot) * outerR, cy + Math.sin(rot) * outerR);
        rot += step;
        ctx.lineTo(cx + Math.cos(rot) * innerR, cy + Math.sin(rot) * innerR);
        rot += step;
      }
      ctx.closePath();
      ctx.fill();
    };

    let rafId;
    const render = () => {
      ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
      let alive = 0;

      particles.forEach((p) => {
        if (p.alpha <= 0) return;
        alive += 1;
        p.x += p.vx;
        p.y += p.vy;
        p.vy += 0.22;
        p.vx *= 0.985;
        p.rot += p.vRot;
        p.alpha -= p.decay;

        ctx.save();
        ctx.globalAlpha = Math.max(0, p.alpha);
        ctx.translate(p.x, p.y);
        ctx.rotate(p.rot);
        ctx.fillStyle = p.color;

        if (p.shape === 'star') {
          drawStar(0, 0, 5, p.size * 1.15, p.size * 0.5);
        } else if (p.shape === 'circle') {
          ctx.beginPath();
          ctx.arc(0, 0, p.size * 0.6, 0, Math.PI * 2);
          ctx.fill();
        } else {
          ctx.fillRect(-p.size * 0.7, -p.size * 0.35, p.size * 1.4, p.size * 0.7);
        }
        ctx.restore();
      });

      if (alive > 0) {
        rafId = requestAnimationFrame(render);
      }
    };

    rafId = requestAnimationFrame(render);
    const timer = setTimeout(() => onDismiss(), 3600);

    return () => {
      cancelAnimationFrame(rafId);
      clearTimeout(timer);
    };
  }, [event, onDismiss]);

  if (!event) return null;

  return (
    <div className="fixed inset-0 z-50 pointer-events-none flex flex-col items-center justify-start pt-20 px-4">
      <canvas ref={canvasRef} className="fixed inset-0 w-full h-full pointer-events-none" />
      <div
        onClick={onDismiss}
        className={`pointer-events-auto cursor-pointer max-w-md w-full rounded-3xl p-5 shadow-2xl border-2 animate-popIn backdrop-blur-md ${
          event.isGrand
            ? 'bg-gradient-to-r from-emerald-600 to-teal-600 border-amber-300 text-white'
            : 'bg-white/95 border-emerald-400 text-ink-900'
        }`}
      >
        <div className="flex items-center gap-3.5">
          <div className="text-4xl shrink-0">{event.isGrand ? '🏆' : '🎉'}</div>
          <div className="flex-1 min-w-0">
            <div className={`text-xs font-bold uppercase tracking-wider ${event.isGrand ? 'text-amber-200' : 'text-emerald-600'}`}>
              {event.isGrand ? t.grandHeader : t.taskDoneHeader}
            </div>
            <div className="font-extrabold text-base sm:text-lg leading-snug mt-0.5 break-words">
              {event.title}
            </div>
            <div className={`text-sm mt-0.5 ${event.isGrand ? 'text-emerald-50' : 'text-ink-700'}`}>
              {event.subtitle}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ---------- PWA 加入主畫面教學彈窗 ----------
function PwaGuideModal({ open, lang, onClose }) {
  if (!open) return null;
  const t = I18N[lang] || I18N.zh;

  return (
    <div className="fixed inset-0 z-50 bg-black/45 backdrop-blur-xs flex items-end sm:items-center justify-center p-4" onClick={onClose}>
      <div
        className="bg-white rounded-3xl max-w-md w-full p-6 shadow-2xl border border-ivory-300 animate-popIn"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between mb-4">
          <div className="flex items-center gap-3">
            <img src="/icons/icon-180.png" alt="App Icon" className="w-12 h-12 rounded-2xl shadow-sm" />
            <div>
              <h3 className="font-extrabold text-lg text-ink-900">{t.pwaTitle}</h3>
              <p className="text-xs text-ink-500">{t.pwaSub}</p>
            </div>
          </div>
          <button onClick={onClose} className="w-8 h-8 rounded-full bg-ivory-200 text-ink-700 font-bold hover:bg-ivory-300">✕</button>
        </div>

        <div className="space-y-3 text-sm text-ink-700 bg-ivory-100 rounded-2xl p-4 border border-ivory-300">
          {[t.pwaStep1, t.pwaStep2, t.pwaStep3].map((stepText, idx) => (
            <div key={idx} className="flex items-start gap-3">
              <span className="w-6 h-6 rounded-full bg-indigo-600 text-white font-bold text-xs flex items-center justify-center shrink-0 mt-0.5">
                {idx + 1}
              </span>
              <p className="font-medium">{stepText}</p>
            </div>
          ))}
        </div>

        <button
          onClick={onClose}
          className="mt-5 w-full py-3.5 rounded-2xl bg-indigo-600 hover:bg-indigo-700 text-white font-bold text-base transition"
        >
          {t.gotIt}
        </button>
      </div>
    </div>
  );
}

// ---------- 老師密碼鎖版面（只在 /teacher 出現） ----------
function TeacherPinLock({ lang, onVerifyPin }) {
  const [pin, setPin] = useState('');
  const [error, setError] = useState(false);
  const [checking, setChecking] = useState(false);
  const t = I18N[lang] || I18N.zh;

  const submitPin = useCallback(async (candidate) => {
    if (checking) return;
    setChecking(true);
    const ok = await onVerifyPin(candidate);
    setChecking(false);
    if (!ok) {
      setError(true);
      SoundEngine.playUndo();
      setTimeout(() => {
        setPin('');
        setError(false);
      }, 460);
    }
  }, [checking, onVerifyPin]);

  const handleDigit = useCallback((d) => {
    if (pin.length >= 4 || checking) return;
    const next = pin + d;
    setPin(next);
    setError(false);
    if (next.length === 4) {
      setTimeout(() => submitPin(next), 80);
    }
  }, [pin, checking, submitPin]);

  const handleBackspace = useCallback(() => {
    setPin((prev) => prev.slice(0, -1));
    setError(false);
  }, []);

  useEffect(() => {
    const onKeyDown = (e) => {
      if (/^[0-9]$/.test(e.key)) {
        handleDigit(e.key);
      } else if (e.key === 'Backspace') {
        handleBackspace();
      } else if (e.key === 'Enter' && pin.length === 4) {
        submitPin(pin);
      }
    };
    window.addEventListener('keydown', onKeyDown);
    return () => window.removeEventListener('keydown', onKeyDown);
  }, [handleDigit, handleBackspace, pin, submitPin]);

  return (
    <div className="max-w-md mx-auto mt-6 sm:mt-12 px-4 pb-12">
      <div className={`bg-white rounded-3xl p-6 sm:p-8 shadow-xl border border-ivory-300 text-center ${error ? 'animate-shake border-rose-400' : ''}`}>
        <div className="w-16 h-16 mx-auto rounded-2xl bg-indigo-50 text-indigo-600 flex items-center justify-center text-3xl mb-4 shadow-inner">
          🔐
        </div>
        <h1 className="text-2xl font-extrabold text-ink-900">{t.lockTitle}</h1>
        <p className="text-xs sm:text-sm text-ink-500 mt-1.5 leading-relaxed">{t.lockSub}</p>

        <div className="flex justify-center gap-3.5 my-6">
          {[0, 1, 2, 3].map((idx) => {
            const filled = idx < pin.length;
            return (
              <div
                key={idx}
                className={`w-12 h-14 rounded-2xl border-2 flex items-center justify-center text-2xl font-black transition-all ${
                  error
                    ? 'border-rose-400 bg-rose-50 text-rose-600'
                    : filled
                    ? 'border-indigo-600 bg-indigo-50 text-indigo-700 scale-105'
                    : 'border-ivory-300 bg-ivory-100 text-ink-400'
                }`}
              >
                {filled ? '•' : ''}
              </div>
            );
          })}
        </div>

        {error && <p className="text-xs font-bold text-rose-600 mb-4">{t.lockErr}</p>}

        <div className="grid grid-cols-3 gap-3 max-w-[280px] mx-auto">
          {['1', '2', '3', '4', '5', '6', '7', '8', '9'].map((n) => (
            <button
              key={n}
              type="button"
              onClick={() => handleDigit(n)}
              className="h-14 rounded-2xl bg-ivory-100 hover:bg-indigo-50 active:scale-95 border border-ivory-300 text-xl font-bold text-ink-900 transition"
            >
              {n}
            </button>
          ))}
          <button
            type="button"
            onClick={() => { setPin(''); setError(false); }}
            className="h-14 rounded-2xl bg-ivory-100 hover:bg-ivory-200 active:scale-95 border border-ivory-300 text-sm font-semibold text-ink-700 transition"
          >
            {t.clearBtn}
          </button>
          <button
            type="button"
            onClick={() => handleDigit('0')}
            className="h-14 rounded-2xl bg-ivory-100 hover:bg-indigo-50 active:scale-95 border border-ivory-300 text-xl font-bold text-ink-900 transition"
          >
            0
          </button>
          <button
            type="button"
            onClick={handleBackspace}
            className="h-14 rounded-2xl bg-ivory-100 hover:bg-ivory-200 active:scale-95 border border-ivory-300 text-lg font-semibold text-ink-700 transition"
          >
            ⌫
          </button>
        </div>
      </div>
    </div>
  );
}

// ---------- 私密提示頁（當網址冇帶私密 ?s=... 時顯示，完全不公開學生名單） ----------
function PrivateLinkLanding({ lang, invalidToken, onEnterToken }) {
  const [codeInput, setCodeInput] = useState('');
  const t = I18N[lang] || I18N.zh;

  const handleSubmit = (e) => {
    e.preventDefault();
    let cleaned = codeInput.trim();
    if (!cleaned) return;
    // 若家長直接貼上整條網址，自動抽取當中嘅 s= 參數
    try {
      if (cleaned.includes('?')) {
        const u = new URL(cleaned, window.location.origin);
        const extracted = u.searchParams.get('s') || u.searchParams.get('token');
        if (extracted) cleaned = extracted;
      }
    } catch (_) {}
    onEnterToken(cleaned);
  };

  return (
    <div className="max-w-md mx-auto px-4 pt-10 pb-16">
      <div className="bg-white rounded-3xl p-6 sm:p-8 shadow-md border border-ivory-300 text-center">
        <div className="w-16 h-16 mx-auto rounded-2xl bg-indigo-50 text-indigo-600 flex items-center justify-center text-3xl mb-4">
          🎹
        </div>
        <div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-ivory-200 text-ink-700 text-xs font-extrabold mb-3">
          <span>{t.privateBadge}</span>
        </div>
        <h1 className="text-xl sm:text-2xl font-black text-ink-900 leading-snug">
          {t.privateTitle}
        </h1>
        <p className="text-sm text-ink-500 mt-2 leading-relaxed">
          {t.privateSub}
        </p>

        {invalidToken && (
          <div className="mt-4 p-3 rounded-2xl bg-rose-50 border border-rose-200 text-xs font-bold text-rose-700">
            {t.invalidTokenMsg}
          </div>
        )}

        <form onSubmit={handleSubmit} className="mt-6 pt-5 border-t border-ivory-200 text-left">
          <label className="block text-xs font-extrabold text-ink-700 mb-2">
            {t.codeInputLabel}
          </label>
          <div className="flex gap-2">
            <input
              type="text"
              value={codeInput}
              onChange={(e) => setCodeInput(e.target.value)}
              placeholder={t.codeInputPh}
              className="flex-1 min-w-0 px-3.5 py-3 rounded-2xl bg-ivory-100 border border-ivory-300 text-sm font-bold text-ink-900 focus:bg-white focus:outline-none focus:border-indigo-500"
            />
            <button
              type="submit"
              className="px-4 py-3 rounded-2xl bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-extrabold shrink-0 shadow-xs transition"
            >
              {t.codeSubmitBtn}
            </button>
          </div>
        </form>
      </div>
    </div>
  );
}

// ---------- YouTube 解析與月度積分／龍虎榜計算輔助 ----------
function extractYoutubeId(url) {
  if (!url || typeof url !== 'string') return null;
  const trimmed = url.trim();
  const patterns = [
    /(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/shorts\/)([A-Za-z0-9_-]{11})/,
    /[?&]v=([A-Za-z0-9_-]{11})/
  ];
  for (const p of patterns) {
    const m = trimmed.match(p);
    if (m && m[1]) return m[1];
  }
  return null;
}

function getCurrentMonthKey(d = new Date()) {
  const y = d.getFullYear();
  const m = String(d.getMonth() + 1).padStart(2, '0');
  return `${y}-${m}`;
}

function shiftMonthKey(monthKey, delta) {
  const parts = (monthKey || getCurrentMonthKey()).split('-');
  const y = Number(parts[0]) || new Date().getFullYear();
  const m = (Number(parts[1]) || 1) - 1;
  const next = new Date(y, m + delta, 1);
  return getCurrentMonthKey(next);
}

// 與後端一致：每月 1 號起計，連續 2 日練琴 +10 分，連續 3 日再 +10 分，一斷咗即重新計過
function computeMonthlyScoreClient(student, quizzes = [], monthKey = getCurrentMonthKey()) {
  const parts = monthKey.split('-');
  const year = Number(parts[0]);
  const month = Number(parts[1]);
  const lastDay = new Date(year, month, 0).getDate();
  const logs = (student && student.logs) || {};

  let consec = 0;
  let maxStreak = 0;
  let practicedDays = 0;
  let streakPoints = 0;

  for (let dayNum = 1; dayNum <= lastDay; dayNum++) {
    const dKey = `${year}-${String(month).padStart(2, '0')}-${String(dayNum).padStart(2, '0')}`;
    const dayLog = logs[dKey];
    const practiced = dayLog && Object.values(dayLog).some((v) => Number(v) > 0);
    if (practiced) {
      practicedDays += 1;
      consec += 1;
      if (consec > maxStreak) maxStreak = consec;
      if (consec >= 2) streakPoints += 10;
    } else {
      consec = 0;
    }
  }

  const submissions = (student && student.quizSubmissions) || {};
  let quizPoints = 0;
  (quizzes || []).forEach((qz) => {
    const qzMonth = qz.monthKey || (qz.createdAt ? qz.createdAt.slice(0, 7) : '');
    if (qzMonth === monthKey && submissions[qz.id]) {
      quizPoints += Number(submissions[qz.id].score || 0);
    }
  });

  return {
    monthKey,
    streakPoints,
    quizPoints,
    totalPoints: streakPoints + quizPoints,
    practicedDays,
    maxStreak
  };
}

function buildLeaderboardClient(students = [], quizzes = [], monthKey = getCurrentMonthKey(), viewerId = null) {
  const entries = students.map((st) => {
    const sc = computeMonthlyScoreClient(st, quizzes, monthKey);
    return {
      id: st.id,
      name: st.name,
      avatar: st.avatar || '🎹',
      avatarBg: st.avatarBg || 'indigo',
      avatarImage: st.avatarImage || null,
      level: st.level,
      levelEn: st.levelEn,
      isMe: Boolean(viewerId && st.id === viewerId),
      ...sc
    };
  });

  entries.sort((a, b) => {
    if (b.totalPoints !== a.totalPoints) return b.totalPoints - a.totalPoints;
    if (b.streakPoints !== a.streakPoints) return b.streakPoints - a.streakPoints;
    if (b.practicedDays !== a.practicedDays) return b.practicedDays - a.practicedDays;
    return String(a.name).localeCompare(String(b.name));
  });

  let curRank = 1;
  entries.forEach((e, idx) => {
    if (idx > 0 && e.totalPoints < entries[idx - 1].totalPoints) {
      curRank = idx + 1;
    }
    e.rank = curRank;
  });

  return { monthKey, entries };
}

// ---------- 1. 練琴倒數計時器元件 (Practice Countdown Timer) ----------
function PracticeTimer({ lang, soundMuted, onTimerFinished }) {
  const [presetMinutes, setPresetMinutes] = useState(15);
  const [remainingSec, setRemainingSec] = useState(15 * 60);
  const [running, setRunning] = useState(false);
  const endTimeRef = useRef(null);

  const t = I18N[lang] || I18N.zh;
  const totalSec = Math.max(60, presetMinutes * 60);

  useEffect(() => {
    if (!running) return;
    endTimeRef.current = Date.now() + remainingSec * 1000;

    const interval = setInterval(() => {
      const diffSec = Math.max(0, Math.ceil((endTimeRef.current - Date.now()) / 1000));
      setRemainingSec(diffSec);
      if (diffSec <= 0) {
        clearInterval(interval);
        setRunning(false);
        if (!soundMuted) SoundEngine.playAllTasksGrandFanfare();
        if (onTimerFinished) onTimerFinished(presetMinutes);
      }
    }, 250);

    return () => clearInterval(interval);
  }, [running]);

  const selectPreset = (mins) => {
    setRunning(false);
    setPresetMinutes(mins);
    setRemainingSec(mins * 60);
  };

  const adjustMinutes = (delta) => {
    if (running) return;
    const nextMins = Math.min(90, Math.max(1, presetMinutes + delta));
    setPresetMinutes(nextMins);
    setRemainingSec(nextMins * 60);
  };

  const handleToggleStart = () => {
    if (!running && remainingSec <= 0) {
      setRemainingSec(presetMinutes * 60);
    }
    if (!soundMuted) SoundEngine.playCheckinStep(running ? 2 : 5);
    setRunning((v) => !v);
  };

  const handleReset = () => {
    setRunning(false);
    setRemainingSec(presetMinutes * 60);
  };

  const mm = String(Math.floor(remainingSec / 60)).padStart(2, '0');
  const ss = String(remainingSec % 60).padStart(2, '0');
  const pct = Math.min(100, Math.max(0, ((totalSec - remainingSec) / totalSec) * 100));
  const isStarted = remainingSec < totalSec;

  return (
    <>
      <div className={`rounded-3xl p-4 sm:p-5 border-2 mb-5 transition-all ${
        running
          ? 'bg-indigo-950 text-white border-indigo-500 shadow-lg shadow-indigo-200/60'
          : 'bg-white text-ink-900 border-ivory-300 shadow-sm'
      }`}>
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div className="min-w-0">
            <div className="flex items-center gap-2">
              <h2 className="font-black text-base sm:text-lg">{t.timerTitle}</h2>
              {running && (
                <span className="px-2.5 py-0.5 rounded-full bg-emerald-500 text-ink-900 text-[11px] font-black animate-pulse">
                  {t.timerRunningBadge}
                </span>
              )}
            </div>
            <p className={`text-xs mt-0.5 ${running ? 'text-indigo-200' : 'text-ink-500'}`}>
              {t.timerSub}
            </p>

            {/* 分鐘預設按鈕 */}
            <div className="flex items-center gap-1.5 flex-wrap mt-3">
              {[5, 10, 15, 20, 30].map((m) => {
                const active = presetMinutes === m;
                return (
                  <button
                    key={m}
                    type="button"
                    disabled={running}
                    onClick={() => selectPreset(m)}
                    className={`px-2.5 py-1 rounded-xl text-xs font-extrabold transition ${
                      active
                        ? running
                          ? 'bg-white text-indigo-950'
                          : 'bg-indigo-600 text-white'
                        : running
                        ? 'bg-white/10 text-indigo-200 opacity-50 cursor-not-allowed'
                        : 'bg-ivory-100 hover:bg-ivory-200 text-ink-700 border border-ivory-300'
                    }`}
                  >
                    {m} {t.timerMinUnit}
                  </button>
                );
              })}

              {!running && (
                <div className="inline-flex items-center gap-1 ml-1">
                  <button
                    type="button"
                    onClick={() => adjustMinutes(-1)}
                    className="w-7 h-7 rounded-lg bg-ivory-100 hover:bg-ivory-200 border border-ivory-300 text-xs font-black text-ink-700"
                  >
                    -1
                  </button>
                  <button
                    type="button"
                    onClick={() => adjustMinutes(+1)}
                    className="w-7 h-7 rounded-lg bg-ivory-100 hover:bg-ivory-200 border border-ivory-300 text-xs font-black text-ink-700"
                  >
                    +1
                  </button>
                </div>
              )}
            </div>
          </div>

          {/* 倒數大數字與開始／暫停／重設掣 */}
          <div className="flex items-center justify-between sm:justify-end gap-3 shrink-0">
            <div className={`font-mono font-black text-3xl sm:text-4xl tracking-tight tabular-nums ${
              running ? 'text-amber-300' : 'text-indigo-700'
            }`}>
              {mm}:{ss}
            </div>

            <div className="flex items-center gap-2">
              <button
                type="button"
                onClick={handleToggleStart}
                className={`px-4 py-2.5 rounded-2xl font-black text-xs sm:text-sm shadow-xs active:scale-95 transition ${
                  running
                    ? 'bg-amber-400 hover:bg-amber-300 text-ink-900'
                    : 'bg-indigo-600 hover:bg-indigo-700 text-white'
                }`}
              >
                {running ? t.timerPause : isStarted ? t.timerResume : t.timerStart}
              </button>
              {(running || isStarted) && (
                <button
                  type="button"
                  onClick={handleReset}
                  className={`px-3 py-2.5 rounded-2xl text-xs font-bold transition ${
                    running
                      ? 'bg-white/15 hover:bg-white/25 text-white'
                      : 'bg-ivory-100 hover:bg-ivory-200 border border-ivory-300 text-ink-700'
                  }`}
                >
                  {t.timerReset}
                </button>
              )}
            </div>
          </div>
        </div>

        {/* 倒數進度條 */}
        {(running || isStarted) && (
          <div className={`mt-3.5 h-2 rounded-full overflow-hidden ${running ? 'bg-white/15' : 'bg-ivory-200'}`}>
            <div
              className="h-full rounded-full bg-gradient-to-r from-emerald-400 to-amber-300 transition-all duration-300"
              style={{ width: `${pct}%` }}
            />
          </div>
        )}
      </div>

      {/* 當學生向下滑動睇樂譜任務時，右下角浮動迷你倒數提示 */}
      {running && (
        <div className="fixed bottom-4 right-4 z-40 bg-indigo-950/95 text-white border border-indigo-400/60 px-3.5 py-2 rounded-2xl shadow-xl flex items-center gap-2 text-xs font-black backdrop-blur-xs">
          <span className="animate-spin">⏱️</span>
          <span className="font-mono text-amber-300 text-sm tabular-nums">{mm}:{ss}</span>
          <button
            type="button"
            onClick={handleToggleStart}
            className="px-2 py-0.5 rounded-lg bg-white/15 hover:bg-white/25 text-[11px]"
          >
            {t.timerPause}
          </button>
        </div>
      )}
    </>
  );
}

// ---------- 2. 每週 YouTube 音樂聆聽挑戰卡 (5 條選擇題即時批改) ----------
function WeeklyQuizCard({ quiz, lang, soundMuted, onSubmitQuiz, showToast }) {
  const [selectedAnswers, setSelectedAnswers] = useState({});
  const [submitting, setSubmitting] = useState(false);

  const quizId = quiz && quiz.id;
  useEffect(() => {
    setSelectedAnswers({});
  }, [quizId]);

  if (!quiz) return null;
  const t = I18N[lang] || I18N.zh;
  const questions = quiz.questions || [];
  const submission = quiz.submission || null;
  const videoId = extractYoutubeId(quiz.youtubeUrl);
  const answeredCount = Object.keys(selectedAnswers).length;
  const optionLetters = ['A', 'B', 'C', 'D'];

  const handleSelectOption = (qIdx, optIdx) => {
    if (submission || submitting) return;
    if (!soundMuted) SoundEngine.playCheckinStep((optIdx % 5) + 1);
    setSelectedAnswers((prev) => ({ ...prev, [qIdx]: optIdx }));
  };

  const handleSubmit = async () => {
    if (submission || submitting) return;
    if (answeredCount < questions.length) {
      showToast(t.quizNeedAllMsg);
      return;
    }
    setSubmitting(true);
    const ordered = questions.map((_, idx) => Number(selectedAnswers[idx]));
    await onSubmitQuiz(quiz.id, ordered);
    setSubmitting(false);
  };

  return (
    <div className="bg-white rounded-3xl p-5 sm:p-6 shadow-md border-2 border-indigo-200 mt-6">
      <div className="flex items-center justify-between gap-2 flex-wrap mb-2">
        <span className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-indigo-100 text-indigo-800 text-xs font-extrabold">
          {t.quizSectionBadge}
        </span>
        <span className={`px-3 py-1 rounded-full text-xs font-extrabold ${
          submission
            ? 'bg-emerald-600 text-white'
            : 'bg-amber-100 text-amber-900 border border-amber-300'
        }`}>
          {submission ? `+${submission.score} ${t.ptsUnit} ✓` : t.quizRuleTag}
        </span>
      </div>

      <h2 className="text-lg sm:text-xl font-black text-ink-900 leading-snug mt-1">
        {quiz.title}
      </h2>
      {quiz.description && (
        <p className="text-xs sm:text-sm text-ink-600 mt-1 leading-relaxed">{quiz.description}</p>
      )}

      {/* 已完成成績橫幅 */}
      {submission && (
        <div className="mt-4 rounded-2xl p-4 bg-gradient-to-r from-emerald-600 to-teal-600 text-white font-extrabold text-sm sm:text-base shadow-sm">
          {t.quizSubmittedBanner(submission.correctCount, submission.totalQuestions, submission.score)}
        </div>
      )}

      {/* YouTube 嵌入式播放器 + 直接打開按鈕 */}
      {quiz.youtubeUrl && (
        <div className="mt-4">
          {videoId && (
            <div className="relative w-full overflow-hidden rounded-2xl bg-black shadow-sm border border-ivory-300" style={{ paddingTop: '56.25%' }}>
              <iframe
                src={`https://www.youtube-nocookie.com/embed/${videoId}?rel=0`}
                title={quiz.title}
                className="absolute inset-0 w-full h-full border-0"
                allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
                allowFullScreen
              />
            </div>
          )}
          <div className="mt-2.5 flex justify-end">
            <a
              href={quiz.youtubeUrl}
              target="_blank"
              rel="noopener noreferrer"
              className="inline-flex items-center gap-1.5 px-3.5 py-2 rounded-xl bg-rose-50 hover:bg-rose-100 border border-rose-200 text-rose-700 text-xs font-extrabold transition"
            >
              {t.quizOpenYoutubeBtn}
            </a>
          </div>
        </div>
      )}

      {/* 5 條選擇題列表 */}
      <div className="mt-5 space-y-4">
        {questions.map((q, qIdx) => {
          const submittedPick = submission && Array.isArray(submission.answers) ? submission.answers[qIdx] : null;
          const correctIdx = typeof q.correctIndex === 'number' ? q.correctIndex : null;
          const isCorrect = submission && submittedPick === correctIdx;

          return (
            <div
              key={q.id || qIdx}
              className={`rounded-2xl p-4 border-2 transition ${
                submission
                  ? isCorrect
                    ? 'bg-emerald-50/70 border-emerald-300'
                    : 'bg-rose-50/60 border-rose-200'
                  : 'bg-ivory-50 border-ivory-300'
              }`}
            >
              <div className="flex items-start justify-between gap-2 mb-3">
                <div className="font-extrabold text-sm sm:text-base text-ink-900 leading-snug">
                  {q.question}
                </div>
                {submission && (
                  <span className={`px-2.5 py-0.5 rounded-full text-[11px] font-black shrink-0 whitespace-nowrap ${
                    isCorrect ? 'bg-emerald-600 text-white' : 'bg-rose-600 text-white'
                  }`}>
                    {isCorrect ? t.quizQuestionRight : t.quizQuestionWrong}
                  </span>
                )}
              </div>

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                {(q.options || []).map((optText, optIdx) => {
                  const pickedBeforeSubmit = !submission && selectedAnswers[qIdx] === optIdx;
                  const isThisCorrect = submission && optIdx === correctIdx;
                  const isThisWrongPick = submission && optIdx === submittedPick && optIdx !== correctIdx;

                  let btnClass = 'bg-white hover:bg-indigo-50/60 border-ivory-300 text-ink-800';
                  if (pickedBeforeSubmit) {
                    btnClass = 'bg-indigo-600 border-indigo-600 text-white ring-2 ring-indigo-200';
                  } else if (isThisCorrect) {
                    btnClass = 'bg-emerald-600 border-emerald-600 text-white shadow-xs';
                  } else if (isThisWrongPick) {
                    btnClass = 'bg-rose-100 border-rose-400 text-rose-900';
                  } else if (submission) {
                    btnClass = 'bg-white/70 border-ivory-200 text-ink-500';
                  }

                  return (
                    <button
                      key={optIdx}
                      type="button"
                      disabled={Boolean(submission)}
                      onClick={() => handleSelectOption(qIdx, optIdx)}
                      className={`text-left px-3.5 py-2.5 rounded-xl border-2 text-xs sm:text-sm font-bold flex items-center justify-between gap-2 transition ${btnClass}`}
                    >
                      <span className="flex items-center gap-2 min-w-0">
                        <span className={`w-6 h-6 rounded-lg flex items-center justify-center text-xs font-black shrink-0 ${
                          pickedBeforeSubmit || isThisCorrect
                            ? 'bg-white/25 text-white'
                            : isThisWrongPick
                            ? 'bg-rose-600 text-white'
                            : 'bg-ivory-200 text-ink-700'
                        }`}>
                          {optionLetters[optIdx] || optIdx + 1}
                        </span>
                        <span className="break-words">{optText}</span>
                      </span>

                      {isThisCorrect && (
                        <span className="text-[11px] font-black bg-white/20 px-2 py-0.5 rounded-md shrink-0">
                          {t.quizRightAnswerTag}
                        </span>
                      )}
                      {isThisWrongPick && (
                        <span className="text-[11px] font-black text-rose-700 shrink-0">
                          ✗ {t.quizYourPickTag}
                        </span>
                      )}
                    </button>
                  );
                })}
              </div>
            </div>
          );
        })}
      </div>

      {!submission && (
        <button
          type="button"
          disabled={submitting}
          onClick={handleSubmit}
          className={`mt-5 w-full py-4 rounded-2xl font-black text-base shadow-md active:scale-[0.98] transition ${
            answeredCount === questions.length
              ? 'bg-indigo-600 hover:bg-indigo-700 text-white shadow-indigo-200'
              : 'bg-ivory-200 hover:bg-ivory-300 text-ink-700'
          }`}
        >
          {t.quizSubmitBtn(answeredCount, questions.length)}
        </button>
      )}
    </div>
  );
}

// ---------- 3. 本月龍虎榜展示面板與彈窗 (Monthly Leaderboard) ----------
function LeaderboardBoard({ leaderboard, lang, onShiftMonth }) {
  const t = I18N[lang] || I18N.zh;
  const monthKey = (leaderboard && leaderboard.monthKey) || getCurrentMonthKey();
  const entries = (leaderboard && leaderboard.entries) || [];
  const parts = monthKey.split('-');
  const y = Number(parts[0]) || new Date().getFullYear();
  const m = Number(parts[1]) || 1;
  const isCurrentMonth = monthKey === getCurrentMonthKey();

  const rankMedal = (rank) => {
    if (rank === 1) return '🥇';
    if (rank === 2) return '🥈';
    if (rank === 3) return '🥉';
    return `#${rank}`;
  };

  return (
    <div>
      {/* 月份切換列 */}
      <div className="flex items-center justify-between gap-2 bg-ivory-100 rounded-2xl p-3 border border-ivory-300 mb-4">
        <button
          type="button"
          onClick={() => onShiftMonth && onShiftMonth(-1)}
          className="w-9 h-9 rounded-xl bg-white hover:bg-ivory-200 border border-ivory-300 font-black text-base text-ink-700"
        >
          ‹
        </button>
        <div className="text-center">
          <div className="font-black text-base sm:text-lg text-ink-900">
            {t.calMonthFormat(y, m)} · {t.lbTitle}
          </div>
          <div className="text-[11px] font-semibold text-ink-500">{t.lbSub}</div>
        </div>
        <button
          type="button"
          disabled={isCurrentMonth}
          onClick={() => onShiftMonth && onShiftMonth(+1)}
          className={`w-9 h-9 rounded-xl border font-black text-base ${
            isCurrentMonth
              ? 'bg-ivory-100 border-ivory-200 text-ink-300 cursor-not-allowed'
              : 'bg-white hover:bg-ivory-200 border-ivory-300 text-ink-700'
          }`}
        >
          ›
        </button>
      </div>

      {/* 前三名頒獎台卡片 */}
      {entries.length > 0 && (
        <div className="grid grid-cols-3 gap-2.5 mb-5 items-end">
          {[entries[1], entries[0], entries[2]].map((item, podiumPos) => {
            if (!item) return <div key={podiumPos} />;
            const isFirst = podiumPos === 1;
            return (
              <div
                key={item.id}
                className={`rounded-3xl p-3 sm:p-4 text-center border-2 flex flex-col items-center relative ${
                  isFirst
                    ? 'bg-gradient-to-b from-amber-50 to-white border-amber-400 shadow-md pt-5 pb-5'
                    : 'bg-white border-ivory-300 shadow-2xs'
                } ${item.isMe ? 'ring-2 ring-indigo-500' : ''}`}
              >
                <div className={`text-2xl sm:text-3xl mb-1 ${isFirst ? 'animate-bounce' : ''}`}>
                  {isFirst ? '👑' : rankMedal(item.rank)}
                </div>
                <StudentAvatar
                  student={item}
                  sizeClass={isFirst ? 'w-14 h-14 sm:w-16 sm:h-16 text-3xl' : 'w-11 h-11 sm:w-13 sm:h-13 text-2xl'}
                  roundedClass="rounded-2xl"
                />
                <div className="font-black text-xs sm:text-sm text-ink-900 mt-2 truncate max-w-full">
                  {item.name}
                </div>
                <div className={`font-black mt-0.5 ${isFirst ? 'text-lg sm:text-xl text-amber-700' : 'text-sm sm:text-base text-indigo-700'}`}>
                  {item.totalPoints} <span className="text-[11px]">{t.ptsUnit}</span>
                </div>
                {item.isMe && (
                  <span className="mt-1 px-2 py-0.5 rounded-full bg-indigo-600 text-white text-[10px] font-black">
                    {t.lbYouBadge}
                  </span>
                )}
              </div>
            );
          })}
        </div>
      )}

      {/* 完整排行榜列表（純積分排行，絕無點擊進入其他學生頁面嘅連結，保障私隱） */}
      <div className="bg-white rounded-3xl border border-ivory-300 overflow-hidden shadow-2xs">
        <div className="divide-y divide-ivory-200">
          {entries.map((entry) => (
            <div
              key={entry.id}
              className={`p-3.5 sm:p-4 flex items-center justify-between gap-3 ${
                entry.isMe ? 'bg-indigo-50/80' : 'hover:bg-ivory-50'
              }`}
            >
              <div className="flex items-center gap-3 min-w-0">
                <div className="w-8 text-center font-black text-base sm:text-lg text-ink-700 shrink-0">
                  {rankMedal(entry.rank)}
                </div>
                <StudentAvatar
                  student={entry}
                  sizeClass="w-11 h-11 text-2xl"
                  roundedClass="rounded-2xl"
                />
                <div className="min-w-0">
                  <div className="flex items-center gap-1.5 flex-wrap">
                    <span className="font-black text-sm sm:text-base text-ink-900 truncate">
                      {entry.name}
                    </span>
                    {entry.isMe && (
                      <span className="px-2 py-0.5 rounded-full bg-indigo-600 text-white text-[10px] font-black">
                        {t.lbYouBadge}
                      </span>
                    )}
                  </div>
                  <div className="flex items-center gap-2 flex-wrap text-[11px] font-bold text-ink-500 mt-0.5">
                    <span className="text-amber-700">{t.streakPtsShort(entry.streakPoints)}</span>
                    <span>·</span>
                    <span className="text-indigo-700">{t.quizPtsShort(entry.quizPoints)}</span>
                    <span className="hidden sm:inline">· {t.lbPracticedDays(entry.practicedDays)}</span>
                  </div>
                </div>
              </div>

              <div className="text-right shrink-0">
                <div className="text-xl sm:text-2xl font-black text-ink-900">
                  {entry.totalPoints}
                </div>
                <div className="text-[10px] font-extrabold text-ink-500">{t.ptsUnit}</div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* 計分規則說明卡 */}
      <div className="mt-4 rounded-2xl p-4 bg-amber-50/80 border border-amber-200 text-xs text-amber-950 space-y-1.5">
        <div className="font-extrabold text-sm">{t.lbRulesTitle}</div>
        <p className="leading-relaxed">{t.lbRule1}</p>
        <p className="leading-relaxed">{t.lbRule2}</p>
      </div>
    </div>
  );
}

function LeaderboardModal({ open, leaderboard, lang, onShiftMonth, onClose }) {
  if (!open) return null;
  const t = I18N[lang] || I18N.zh;

  return (
    <div className="fixed inset-0 z-50 bg-black/55 backdrop-blur-xs flex items-end sm:items-center justify-center p-3 sm:p-4" onClick={onClose}>
      <div
        className="bg-ivory-50 rounded-3xl max-w-xl w-full p-5 sm:p-6 shadow-2xl border border-ivory-300 animate-popIn max-h-[90vh] overflow-y-auto"
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between mb-3">
          <h3 className="font-black text-xl text-ink-900">{t.lbTitle}</h3>
          <button
            type="button"
            onClick={onClose}
            className="w-8 h-8 rounded-full bg-ivory-200 hover:bg-ivory-300 text-ink-700 font-bold"
          >
            ✕
          </button>
        </div>

        <LeaderboardBoard
          leaderboard={leaderboard}
          lang={lang}
          onShiftMonth={onShiftMonth}
        />
      </div>
    </div>
  );
}

// ---------- 4. 老師後台：每週 YouTube 5 題選擇題發佈器 ----------
function createBlankFiveQuestions() {
  return [1, 2, 3, 4, 5].map((num) => ({
    id: `q${num}`,
    question: '',
    options: ['', '', '', ''],
    correctIndex: 0
  }));
}

function TeacherQuizManager({ quizzes = [], students = [], lang, onSaveQuizzes, showToast }) {
  const t = I18N[lang] || I18N.zh;
  const activeQuiz = useMemo(
    () => quizzes.find((q) => q.active) || quizzes[quizzes.length - 1] || null,
    [quizzes]
  );

  const [quizId, setQuizId] = useState(() => (activeQuiz ? activeQuiz.id : `quiz-${getCurrentMonthKey()}-${Date.now().toString().slice(-4)}`));
  const [monthKey, setMonthKey] = useState(() => (activeQuiz && activeQuiz.monthKey) || getCurrentMonthKey());
  const [title, setTitle] = useState(() => (activeQuiz ? activeQuiz.title : ''));
  const [youtubeUrl, setYoutubeUrl] = useState(() => (activeQuiz ? activeQuiz.youtubeUrl : ''));
  const [description, setDescription] = useState(() => (activeQuiz ? activeQuiz.description || '' : ''));
  const [questions, setQuestions] = useState(() => {
    if (activeQuiz && Array.isArray(activeQuiz.questions) && activeQuiz.questions.length === 5) {
      return activeQuiz.questions.map((q, idx) => ({
        id: q.id || `q${idx + 1}`,
        question: q.question || '',
        options: Array.isArray(q.options) && q.options.length === 4 ? [...q.options] : ['', '', '', ''],
        correctIndex: Number(q.correctIndex) || 0
      }));
    }
    return createBlankFiveQuestions();
  });

  const previewVideoId = extractYoutubeId(youtubeUrl);
  const optionLetters = ['A', 'B', 'C', 'D'];

  const handleStartNewWeek = () => {
    const newMonth = getCurrentMonthKey();
    const newId = `quiz-${newMonth}-${Date.now().toString().slice(-5)}`;
    setQuizId(newId);
    setMonthKey(newMonth);
    setTitle('');
    setYoutubeUrl('');
    setDescription('');
    setQuestions(createBlankFiveQuestions());
    showToast(t.toastNewQuizDraft);
  };

  const updateQuestionField = (qIdx, field, val) => {
    setQuestions((prev) =>
      prev.map((q, i) => (i === qIdx ? { ...q, [field]: val } : q))
    );
  };

  const updateOptionText = (qIdx, optIdx, val) => {
    setQuestions((prev) =>
      prev.map((q, i) => {
        if (i !== qIdx) return q;
        const nextOpts = [...q.options];
        nextOpts[optIdx] = val;
        return { ...q, options: nextOpts };
      })
    );
  };

  const handlePublish = (e) => {
    e.preventDefault();
    if (!title.trim() || !youtubeUrl.trim()) return;

    const newQuizObj = {
      id: quizId,
      monthKey: monthKey || getCurrentMonthKey(),
      active: true,
      createdAt: new Date().toISOString(),
      title: title.trim(),
      youtubeUrl: youtubeUrl.trim(),
      description: description.trim(),
      questions: questions.map((q, i) => ({
        id: q.id || `q${i + 1}`,
        question: q.question.trim() || `Question ${i + 1}`,
        options: q.options.map((opt, oi) => opt.trim() || `Option ${optionLetters[oi]}`),
        correctIndex: Number(q.correctIndex) || 0
      }))
    };

    const exists = quizzes.some((qz) => qz.id === quizId);
    let nextQuizzes;
    if (exists) {
      nextQuizzes = quizzes.map((qz) =>
        qz.id === quizId ? newQuizObj : { ...qz, active: false }
      );
    } else {
      nextQuizzes = [...quizzes.map((qz) => ({ ...qz, active: false })), newQuizObj];
    }

    onSaveQuizzes(nextQuizzes);
    showToast(t.toastQuizPublished);
  };

  return (
    <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
      {/* 左側：YouTube + 5 題選擇題編輯表單 */}
      <form onSubmit={handlePublish} className="lg:col-span-8 bg-white rounded-3xl p-5 sm:p-6 shadow-sm border border-ivory-300 space-y-5">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-3 pb-4 border-b border-ivory-200">
          <div>
            <h2 className="text-xl font-black text-ink-900">{t.tqHeaderTitle}</h2>
            <p className="text-xs text-ink-500 mt-1">{t.tqHeaderSub}</p>
          </div>
          <button
            type="button"
            onClick={handleStartNewWeek}
            className="px-4 py-2.5 rounded-2xl bg-amber-100 hover:bg-amber-200 text-amber-950 text-xs font-extrabold shrink-0 transition"
          >
            {t.tqNewWeekBtn}
          </button>
        </div>

        <div className="space-y-4">
          <div>
            <label className="block text-xs font-extrabold text-ink-700 mb-1.5">{t.tqQuizTitleLabel}</label>
            <input
              type="text"
              required
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              placeholder="例如：本週音樂聆聽挑戰：莫札特《土耳其進行曲》"
              className="w-full px-4 py-3 rounded-2xl bg-ivory-100 border border-ivory-300 text-sm font-bold focus:bg-white focus:outline-none focus:border-indigo-500"
            />
          </div>

          <div>
            <label className="block text-xs font-extrabold text-ink-700 mb-1.5">{t.tqYoutubeLabel}</label>
            <input
              type="url"
              required
              value={youtubeUrl}
              onChange={(e) => setYoutubeUrl(e.target.value)}
              placeholder={t.tqYoutubePh}
              className="w-full px-4 py-3 rounded-2xl bg-ivory-100 border border-ivory-300 text-sm font-mono focus:bg-white focus:outline-none focus:border-indigo-500"
            />
            {previewVideoId && (
              <div className="mt-3 relative w-full overflow-hidden rounded-2xl bg-black border border-ivory-300" style={{ paddingTop: '42%' }}>
                <iframe
                  src={`https://www.youtube-nocookie.com/embed/${previewVideoId}?rel=0`}
                  title="YouTube Preview"
                  className="absolute inset-0 w-full h-full border-0"
                  allowFullScreen
                />
              </div>
            )}
          </div>

          <div>
            <label className="block text-xs font-extrabold text-ink-700 mb-1.5">{t.tqDescLabel}</label>
            <input
              type="text"
              value={description}
              onChange={(e) => setDescription(e.target.value)}
              placeholder="例如：聽完首歌之後答齊 5 題，每題 10 分！"
              className="w-full px-4 py-2.5 rounded-2xl bg-ivory-100 border border-ivory-300 text-sm font-medium focus:bg-white focus:outline-none focus:border-indigo-500"
            />
          </div>
        </div>

        {/* 5 條題目設定 */}
        <div className="space-y-4 pt-2">
          {questions.map((q, qIdx) => (
            <div key={q.id || qIdx} className="rounded-2xl p-4 bg-ivory-50 border border-ivory-300 space-y-3">
              <div className="flex items-center justify-between">
                <span className="px-2.5 py-0.5 rounded-lg bg-indigo-100 text-indigo-800 text-xs font-black">
                  {t.tqQuestionHeading(qIdx + 1)}
                </span>
              </div>

              <input
                type="text"
                required
                value={q.question}
                onChange={(e) => updateQuestionField(qIdx, 'question', e.target.value)}
                placeholder={t.tqQuestionPh(qIdx + 1)}
                className="w-full px-3.5 py-2.5 rounded-xl bg-white border border-ivory-300 text-sm font-bold focus:outline-none focus:border-indigo-500"
              />

              <div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5">
                {q.options.map((optVal, optIdx) => {
                  const isCorrect = Number(q.correctIndex) === optIdx;
                  return (
                    <div
                      key={optIdx}
                      className={`flex items-center gap-2 p-2 rounded-xl border-2 transition ${
                        isCorrect ? 'bg-emerald-50 border-emerald-400' : 'bg-white border-ivory-200'
                      }`}
                    >
                      <span className={`w-6 h-6 rounded-lg flex items-center justify-center text-xs font-black shrink-0 ${
                        isCorrect ? 'bg-emerald-600 text-white' : 'bg-ivory-200 text-ink-700'
                      }`}>
                        {optionLetters[optIdx]}
                      </span>
                      <input
                        type="text"
                        required
                        value={optVal}
                        onChange={(e) => updateOptionText(qIdx, optIdx, e.target.value)}
                        placeholder={t.tqOptionPh(optionLetters[optIdx])}
                        className="flex-1 min-w-0 bg-transparent text-xs sm:text-sm font-semibold focus:outline-none"
                      />
                      <button
                        type="button"
                        onClick={() => updateQuestionField(qIdx, 'correctIndex', optIdx)}
                        className={`px-2 py-1 rounded-lg text-[11px] font-extrabold shrink-0 transition ${
                          isCorrect
                            ? 'bg-emerald-600 text-white'
                            : 'bg-ivory-100 hover:bg-emerald-50 text-ink-600 hover:text-emerald-700'
                        }`}
                      >
                        {isCorrect ? t.tqIsCorrect : t.tqMarkCorrect}
                      </button>
                    </div>
                  );
                })}
              </div>
            </div>
          ))}
        </div>

        <button
          type="submit"
          className="w-full py-4 rounded-2xl bg-indigo-600 hover:bg-indigo-700 active:scale-[0.98] text-white font-black text-base shadow-md shadow-indigo-200 transition"
        >
          {t.tqSavePublishBtn}
        </button>
      </form>

      {/* 右側：各學生本週問答作答狀況 */}
      <div className="lg:col-span-4 bg-white rounded-3xl p-5 sm:p-6 shadow-sm border border-ivory-300">
        <h3 className="font-black text-base sm:text-lg text-ink-900 mb-3">{t.tqStatusHeading}</h3>
        <div className="space-y-2.5">
          {students.map((st) => {
            const sub = (st.quizSubmissions && st.quizSubmissions[quizId]) || null;
            return (
              <div
                key={st.id}
                className="p-3 rounded-2xl bg-ivory-50 border border-ivory-200 flex items-center justify-between gap-2"
              >
                <div className="flex items-center gap-2.5 min-w-0">
                  <StudentAvatar student={st} sizeClass="w-9 h-9 text-lg" roundedClass="rounded-xl" />
                  <span className="font-extrabold text-sm text-ink-900 truncate">{st.name}</span>
                </div>
                {sub ? (
                  <span className="px-2.5 py-1 rounded-full bg-emerald-100 text-emerald-800 text-xs font-black shrink-0">
                    {t.tqSubmittedScore(sub.correctCount, sub.totalQuestions, sub.score)}
                  </span>
                ) : (
                  <span className="px-2.5 py-1 rounded-full bg-ivory-200 text-ink-500 text-xs font-bold shrink-0">
                    {t.tqNotSubmitted}
                  </span>
                )}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ---------- 學生私密打卡版面 (Student View — 連計時器、每週 YouTube 挑戰及龍虎榜) ----------
function StudentView({
  student,
  currentQuiz,
  myMonthlyScore,
  leaderboard,
  loading,
  invalidToken,
  lang,
  soundMuted,
  onEnterToken,
  onAdjustCheckin,
  onSubmitQuiz,
  onShiftLeaderboardMonth,
  onTimerFinished,
  onSaveAvatar,
  onOpenPwaGuide,
  showToast
}) {
  const [justCompletedTaskId, setJustCompletedTaskId] = useState(null);
  const [avatarModalOpen, setAvatarModalOpen] = useState(false);
  const [leaderboardOpen, setLeaderboardOpen] = useState(false);
  const quizSectionRef = useRef(null);
  const t = I18N[lang] || I18N.zh;

  if (loading) {
    return (
      <div className="max-w-md mx-auto px-4 pt-16 text-center text-ink-500 font-bold text-sm">
        <div className="text-4xl mb-3 animate-bounce">🎹</div>
        {t.loadingStudent}
      </div>
    );
  }

  if (!student) {
    return (
      <PrivateLinkLanding
        lang={lang}
        invalidToken={invalidToken}
        onEnterToken={onEnterToken}
      />
    );
  }

  const stats = computeStudentStats(student, lang);
  const todayLogs = (student.logs && student.logs[stats.todayKey]) || {};
  const displayLevel = localizeStudentLevel(student, lang);
  const displayNote = localizeStudentNote(student, lang);

  const scoreObj = myMonthlyScore || computeMonthlyScoreClient(student, currentQuiz ? [currentQuiz] : [], getCurrentMonthKey());
  const myEntry = leaderboard && Array.isArray(leaderboard.entries)
    ? leaderboard.entries.find((e) => e.isMe || e.id === student.id)
    : null;
  const quizSubmission = currentQuiz && currentQuiz.submission;

  const scrollToQuiz = () => {
    if (quizSectionRef.current) {
      quizSectionRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
    }
  };

  const handleTapPlusOne = (task) => {
    const prevCount = Number(todayLogs[task.id] || 0);
    const nextCount = prevCount + 1;
    const target = Number(task.dailyTarget) || 1;

    if (nextCount === target) {
      setJustCompletedTaskId(task.id);
      setTimeout(() => setJustCompletedTaskId(null), 650);
    }
    onAdjustCheckin(task, +1);
  };

  return (
    <div className="max-w-2xl mx-auto px-4 pt-4 pb-20">
      {/* 學生個人頁頂：可點擊上載頭像／換貼紙！（絕無切換學生按鈕） */}
      <div className="flex items-center gap-3.5 sm:gap-4 mb-5">
        <button
          type="button"
          onClick={() => setAvatarModalOpen(true)}
          className="relative group shrink-0 focus:outline-none"
          title={t.avatarModalTitle}
        >
          <StudentAvatar
            student={student}
            sizeClass="w-16 h-16 sm:w-20 sm:h-20 text-4xl sm:text-5xl shadow-sm group-hover:scale-105"
            roundedClass="rounded-3xl"
          />
          <span className="absolute -bottom-1.5 -right-1.5 px-2 py-0.5 rounded-full bg-indigo-600 text-white text-[10px] font-extrabold shadow-md border-2 border-white flex items-center gap-0.5">
            <span>📷</span>
            <span>{t.editAvatarHint}</span>
          </span>
        </button>

        <div className="min-w-0 flex-1">
          <div className="flex items-center gap-2 flex-wrap">
            <h1 className="text-xl sm:text-2xl font-black text-ink-900 truncate">
              {t.studentCardTitle(student.name)}
            </h1>
            {displayLevel && (
              <span className="px-2.5 py-0.5 rounded-full bg-indigo-100 text-indigo-800 text-xs font-bold">
                {displayLevel}
              </span>
            )}
          </div>
          <p className="text-xs text-ink-500 mt-1 leading-relaxed">
            {t.todayHint(stats.todayKey)}
          </p>
        </div>
      </div>

      {/* 本月積分條 + 龍虎榜按鈕 + 每週音樂問答捷徑 */}
      <div className="bg-gradient-to-r from-indigo-950 via-indigo-900 to-violet-900 text-white rounded-3xl p-4 sm:p-5 shadow-md mb-5 flex flex-col sm:flex-row sm:items-center justify-between gap-3.5">
        <div className="flex items-center gap-3.5">
          <div className="w-12 h-12 rounded-2xl bg-amber-400/20 border border-amber-300/40 flex items-center justify-center text-2xl shrink-0">
            🏆
          </div>
          <div>
            <div className="flex items-center gap-2 flex-wrap">
              <span className="text-xs font-bold text-indigo-200">{t.myMonthPtsLabel}</span>
              {myEntry && (
                <span className="px-2 py-0.5 rounded-full bg-amber-400 text-ink-900 text-[11px] font-black">
                  {t.rankBadge(myEntry.rank)}
                </span>
              )}
            </div>
            <div className="flex items-baseline gap-2 mt-0.5">
              <span className="text-2xl sm:text-3xl font-black text-amber-300">
                {scoreObj.totalPoints}
              </span>
              <span className="text-xs font-extrabold text-indigo-200">{t.ptsUnit}</span>
              <span className="text-[11px] font-semibold text-indigo-200 ml-1">
                ({t.streakPtsShort(scoreObj.streakPoints)} · {t.quizPtsShort(scoreObj.quizPoints)})
              </span>
            </div>
          </div>
        </div>

        <div className="flex items-center gap-2 flex-wrap">
          {currentQuiz && (
            <button
              type="button"
              onClick={scrollToQuiz}
              className={`px-3.5 py-2.5 rounded-2xl text-xs font-black shadow-xs active:scale-95 transition ${
                quizSubmission
                  ? 'bg-emerald-500/25 hover:bg-emerald-500/35 border border-emerald-300/40 text-emerald-100'
                  : 'bg-white hover:bg-indigo-50 text-indigo-950 shadow-md'
              }`}
            >
              {quizSubmission ? t.jumpToQuizDone(quizSubmission.score) : t.jumpToQuizNew}
            </button>
          )}

          <button
            type="button"
            onClick={() => setLeaderboardOpen(true)}
            className="px-4 py-2.5 rounded-2xl bg-amber-400 hover:bg-amber-300 text-ink-900 text-xs sm:text-sm font-black shadow-md active:scale-95 transition flex items-center gap-1.5"
          >
            <span>{t.openLeaderboardBtn}</span>
            <span>→</span>
          </button>
        </div>
      </div>

      {/* 頂部重點指標卡：本週連續打卡天數 + 今日完成進度條 */}
      <div className={`rounded-3xl p-5 sm:p-6 shadow-md border-2 mb-5 transition-colors duration-500 ${
        stats.allTasksDoneToday
          ? 'bg-gradient-to-br from-emerald-600 via-emerald-600 to-teal-700 border-emerald-400 text-white'
          : 'bg-white border-ivory-300 text-ink-900'
      }`}>
        <div className="grid grid-cols-1 sm:grid-cols-12 gap-5 items-center">
          <div className={`sm:col-span-5 flex flex-col justify-between p-4 rounded-2xl ${
            stats.allTasksDoneToday ? 'bg-white/15 backdrop-blur-xs' : 'bg-amber-50/80 border border-amber-200/80'
          }`}>
            <div className="flex items-center justify-between gap-2 flex-wrap">
              <span className={`text-xs font-bold whitespace-nowrap ${stats.allTasksDoneToday ? 'text-emerald-50' : 'text-amber-900'}`}>
                {t.streakTitle}
              </span>
              <span className={`text-[11px] font-bold px-2 py-0.5 rounded-full whitespace-nowrap ${
                stats.allTasksDoneToday ? 'bg-amber-400 text-ink-900' : 'bg-amber-200/80 text-amber-950'
              }`}>
                {t.practicedDaysBadge(stats.weekPracticedDays)}
              </span>
            </div>

            <div className="flex items-baseline gap-2 my-2">
              <span className="text-3xl">🔥</span>
              <span className={`text-4xl font-black tracking-tight ${stats.allTasksDoneToday ? 'text-white' : 'text-amber-700'}`}>
                {stats.streakDays}
              </span>
              <span className={`text-base font-bold ${stats.allTasksDoneToday ? 'text-emerald-50' : 'text-amber-900'}`}>
                {t.streakDaysLabel}
              </span>
            </div>

            <div className="grid grid-cols-7 gap-1 mt-1">
              {stats.weekDays.map((wd) => (
                <div key={wd.key} className="flex flex-col items-center gap-1">
                  <span className={`text-[11px] font-bold ${
                    stats.allTasksDoneToday
                      ? wd.isToday ? 'text-amber-200 underline' : 'text-emerald-100'
                      : wd.isToday ? 'text-indigo-700 font-black' : 'text-ink-500'
                  }`}>
                    {wd.label}
                  </span>
                  <div className={`w-7 h-7 rounded-full flex items-center justify-center text-xs font-black transition-all ${
                    wd.isFullGoal
                      ? 'bg-emerald-500 text-white shadow-xs ring-2 ring-white/70'
                      : wd.isPracticed
                      ? 'bg-amber-400 text-ink-900'
                      : wd.isToday
                      ? stats.allTasksDoneToday
                        ? 'bg-white/25 text-white'
                        : 'bg-white border-2 border-dashed border-indigo-400 text-indigo-600'
                      : stats.allTasksDoneToday
                      ? 'bg-white/10 text-white/50'
                      : 'bg-white/80 border border-ivory-300 text-ink-400'
                  }`}>
                    {wd.isFullGoal ? '★' : wd.isPracticed ? '✓' : wd.dayNum}
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div className="sm:col-span-7 flex flex-col justify-center">
            <div className="flex items-end justify-between mb-2">
              <div>
                <div className={`text-xs font-bold ${stats.allTasksDoneToday ? 'text-emerald-100' : 'text-ink-500'}`}>
                  {t.todayProgressLabel}
                </div>
                <div className="text-xl sm:text-2xl font-black mt-0.5">
                  {stats.allTasksDoneToday
                    ? t.allDoneHero
                    : t.completedTasksHero(stats.completedTasksToday, stats.totalTasks)}
                </div>
              </div>
              <div className="text-right">
                <span className={`text-3xl font-black ${stats.allTasksDoneToday ? 'text-amber-300' : 'text-indigo-600'}`}>
                  {stats.todayProgressPct}%
                </span>
              </div>
            </div>

            <div className={`h-4 rounded-full overflow-hidden p-0.5 ${
              stats.allTasksDoneToday ? 'bg-black/20' : 'bg-ivory-200 inner-shadow'
            }`}>
              <div
                className={`h-full rounded-full transition-all duration-500 ease-out ${
                  stats.allTasksDoneToday
                    ? 'bg-gradient-to-r from-amber-300 via-yellow-200 to-white'
                    : 'bg-gradient-to-r from-indigo-600 to-violet-500'
                }`}
                style={{ width: `${Math.max(stats.todayProgressPct, stats.todayTotalReps > 0 ? 6 : 0)}%` }}
              />
            </div>

            <div className={`flex items-center justify-between gap-2 flex-wrap text-xs font-semibold mt-2.5 ${
              stats.allTasksDoneToday ? 'text-emerald-50' : 'text-ink-500'
            }`}>
              <span>{t.todayRepsSummary(stats.todayTotalReps, stats.dailyTargetSum)}</span>
              <span>{t.weekRepsSummary(stats.weekTotalCheckins)}</span>
            </div>
          </div>
        </div>
      </div>

      {/* 練琴打卡月曆：一眼睇晒每個星期練得密唔密，打卡任何一項即點亮綠點！ */}
      <PracticeCalendar student={student} lang={lang} isTeacherView={false} />

      {/* 老師本週叮囑 */}
      {displayNote && (
        <div className="bg-amber-50/90 border border-amber-200 rounded-2xl px-4 py-3.5 mb-5 flex items-start gap-3 shadow-2xs">
          <span className="text-xl shrink-0 mt-0.5">💡</span>
          <div className="text-sm text-amber-950 leading-relaxed">
            <span className="font-extrabold">{t.teacherNoteLabel}</span>
            {displayNote}
          </div>
        </div>
      )}

      {/* 練琴倒數計時器（專心練琴好幫手） */}
      <PracticeTimer
        lang={lang}
        soundMuted={soundMuted}
        onTimerFinished={onTimerFinished}
      />

      {/* 任務卡清單 */}
      {(student.tasks || []).length === 0 ? (
        <div className="bg-white rounded-3xl p-10 text-center border border-ivory-300">
          <div className="text-4xl mb-2">🎼</div>
          <p className="font-bold text-ink-700">{t.noTasksStudentTitle}</p>
          <p className="text-xs text-ink-500 mt-1">{t.noTasksStudentSub}</p>
        </div>
      ) : (
        <div className="space-y-4">
          {student.tasks.map((task, index) => {
            const count = Number(todayLogs[task.id] || 0);
            const target = Math.max(1, Number(task.dailyTarget) || 1);
            const isDone = count >= target;
            const bonusCount = Math.max(0, count - target);
            const { bars, hand } = extractTaskMeta(task, lang);
            const displayPiece = localizeTaskPiece(task, lang);
            const displayDetails = localizeTaskDetails(task, lang);
            const isAnimating = justCompletedTaskId === task.id;

            return (
              <div
                key={task.id}
                className={`rounded-3xl p-5 sm:p-6 border-2 transition-all duration-300 ${
                  isAnimating ? 'animate-cardCelebrate ' : ''
                }${
                  isDone
                    ? 'bg-emerald-50/95 border-emerald-400 shadow-md shadow-emerald-100/70'
                    : 'bg-white border-ivory-300 shadow-sm hover:border-indigo-200'
                }`}
              >
                <div className="flex items-start justify-between gap-3">
                  <div className="flex items-start gap-3 min-w-0">
                    <div className={`w-8 h-8 rounded-xl font-black text-sm flex items-center justify-center shrink-0 mt-0.5 ${
                      isDone ? 'bg-emerald-600 text-white' : 'bg-indigo-100 text-indigo-700'
                    }`}>
                      {isDone ? '✓' : index + 1}
                    </div>
                    <div className="min-w-0">
                      <h2 className={`text-lg sm:text-xl font-black leading-snug ${
                        isDone ? 'text-emerald-950' : 'text-ink-900'
                      }`}>
                        {displayPiece}
                      </h2>
                    </div>
                  </div>

                  <span className={`px-3 py-1 rounded-full text-xs font-extrabold shrink-0 ${
                    isDone
                      ? 'bg-emerald-600 text-white shadow-xs'
                      : 'bg-ivory-200 text-ink-700'
                  }`}>
                    {isDone ? t.doneBadge : t.goalBadge(target)}
                  </span>
                </div>

                <div className="flex flex-wrap gap-2 mt-3.5">
                  {bars && (
                    <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-xl text-xs sm:text-sm font-extrabold ${
                      isDone
                        ? 'bg-emerald-200/70 text-emerald-950'
                        : 'bg-amber-100 text-amber-900 border border-amber-200'
                    }`}>
                      <span>📍 {t.sectionTag}</span>
                      <span>{bars}</span>
                    </span>
                  )}
                  {hand && (
                    <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-xl text-xs sm:text-sm font-extrabold ${
                      isDone
                        ? 'bg-emerald-200/70 text-emerald-950'
                        : 'bg-violet-100 text-violet-900 border border-violet-200'
                    }`}>
                      <span>✋ {t.handTag}</span>
                      <span>{hand}</span>
                    </span>
                  )}
                  <span className={`inline-flex items-center gap-1.5 px-3 py-1 rounded-xl text-xs sm:text-sm font-extrabold ${
                    isDone
                      ? 'bg-emerald-200/70 text-emerald-950'
                      : 'bg-sky-100 text-sky-900 border border-sky-200'
                  }`}>
                    <span>🎯 {t.dailyGoalTag}</span>
                    <span>{target}{lang === 'en' ? 'x' : ' 次'}</span>
                  </span>
                </div>

                <div className={`mt-3.5 rounded-2xl p-3.5 text-sm sm:text-base leading-relaxed font-medium ${
                  isDone
                    ? 'bg-white/80 text-emerald-950 border border-emerald-200'
                    : 'bg-ivory-100 text-ink-900 border border-ivory-200'
                }`}>
                  {displayDetails}
                </div>

                <div className="mt-4 flex items-center justify-between gap-3 flex-wrap">
                  <div className="flex items-center gap-1.5 flex-wrap">
                    {Array.from({ length: Math.min(target, 12) }).map((_, i) => {
                      const filled = i < count;
                      return (
                        <span
                          key={i}
                          className={`w-7 h-7 rounded-lg flex items-center justify-center text-sm font-bold transition-all duration-300 ${
                            filled
                              ? isDone
                                ? 'bg-emerald-500 text-white scale-105 shadow-2xs'
                                : 'bg-indigo-600 text-white scale-105 shadow-2xs'
                              : 'bg-ivory-200 text-ink-400'
                          }`}
                        >
                          {filled ? '★' : i + 1}
                        </span>
                      );
                    })}
                    {bonusCount > 0 && (
                      <span className="px-2 py-1 rounded-lg bg-amber-400 text-ink-900 text-xs font-black">
                        {t.bonusTag(bonusCount)}
                      </span>
                    )}
                  </div>

                  <div className="text-right ml-auto">
                    <span className={`text-2xl font-black ${isDone ? 'text-emerald-700' : 'text-indigo-700'}`}>
                      {count}
                    </span>
                    <span className="text-sm font-bold text-ink-500">
                      {' '}/ {target}{lang === 'en' ? 'x' : ' 次'}
                    </span>
                  </div>
                </div>

                <div className="mt-4 flex items-stretch gap-2.5">
                  {count > 0 && (
                    <button
                      type="button"
                      onClick={() => onAdjustCheckin(task, -1)}
                      title={t.undoTooltip}
                      className={`px-3.5 rounded-2xl border font-bold text-sm active:scale-95 transition shrink-0 ${
                        isDone
                          ? 'bg-white/80 hover:bg-white border-emerald-300 text-emerald-800'
                          : 'bg-ivory-100 hover:bg-ivory-200 border-ivory-300 text-ink-500'
                      }`}
                    >
                      -1
                    </button>
                  )}

                  <button
                    type="button"
                    onClick={() => handleTapPlusOne(task)}
                    className={`flex-1 min-h-[58px] py-3.5 px-5 rounded-2xl font-black text-base sm:text-lg shadow-md active:scale-[0.97] transition-all flex items-center justify-center gap-2.5 ${
                      isDone
                        ? 'bg-emerald-600 hover:bg-emerald-700 text-white shadow-emerald-200'
                        : 'bg-indigo-600 hover:bg-indigo-700 text-white shadow-indigo-200'
                    }`}
                  >
                    <span className="text-xl">{isDone ? '🌟' : '🎹'}</span>
                    <span>{isDone ? t.btnCheckinDone : t.btnCheckin}</span>
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* 每週 YouTube 音樂聆聽挑戰（答啱每題 +10 分！） */}
      {currentQuiz && (
        <div ref={quizSectionRef} className="scroll-mt-20">
          <WeeklyQuizCard
            quiz={currentQuiz}
            lang={lang}
            soundMuted={soundMuted}
            onSubmitQuiz={onSubmitQuiz}
            showToast={showToast}
          />
        </div>
      )}

      <div className="mt-8 text-center">
        <button
          type="button"
          onClick={onOpenPwaGuide}
          className="inline-flex items-center gap-2 px-4 py-2.5 rounded-2xl bg-white hover:bg-ivory-100 border border-ivory-300 text-xs font-bold text-ink-700 shadow-2xs transition"
        >
          <span>📲</span>
          <span>{t.pwaStudentTip}</span>
        </button>
      </div>

      {/* 本月龍虎榜彈窗 */}
      <LeaderboardModal
        open={leaderboardOpen}
        leaderboard={leaderboard}
        lang={lang}
        onShiftMonth={onShiftLeaderboardMonth}
        onClose={() => setLeaderboardOpen(false)}
      />

      {/* 頭像相片／貼紙自訂彈窗 */}
      <AvatarCustomizerModal
        open={avatarModalOpen}
        student={student}
        lang={lang}
        soundMuted={soundMuted}
        onSave={onSaveAvatar}
        onClose={() => setAvatarModalOpen(false)}
        showToast={showToast}
      />
    </div>
  );
}

// ---------- 老師管理版面 (Teacher View — 僅可透過 /teacher + 密碼進入) ----------
function TeacherView({
  students,
  quizzes,
  selectedStudentId,
  lang,
  onSelectStudent,
  onAddStudent,
  onDeleteStudent,
  onRegenerateToken,
  onUpdateStudentLang,
  onUpdateStudentNote,
  onAddTask,
  onUpdateTask,
  onDeleteTask,
  onResetTodayLogs,
  onSaveQuizzes,
  onChangeTeacherPin,
  onPreviewStudent,
  onLockTeacher,
  serverMeta,
  showToast
}) {
  const t = I18N[lang] || I18N.zh;
  const [teacherTab, setTeacherTab] = useState('students');
  const [lbMonthKey, setLbMonthKey] = useState(() => getCurrentMonthKey());

  const teacherLeaderboard = useMemo(
    () => buildLeaderboardClient(students || [], quizzes || [], lbMonthKey, null),
    [students, quizzes, lbMonthKey]
  );

  const activeStudent = useMemo(
    () => students.find((s) => s.id === selectedStudentId) || students[0] || null,
    [students, selectedStudentId]
  );

  // 新增學生表單狀態
  const [addingStudent, setAddingStudent] = useState(false);
  const [newStudentName, setNewStudentName] = useState('');
  const [newStudentLevel, setNewStudentLevel] = useState('');
  const [newStudentLang, setNewStudentLang] = useState('zh');
  const [newStudentAvatar, setNewStudentAvatar] = useState('🎹');

  // 更改老師密碼狀態
  const [changingPin, setChangingPin] = useState(false);
  const [newPinValue, setNewPinValue] = useState('');

  // 新增任務表單狀態
  const [piece, setPiece] = useState('');
  const [bars, setBars] = useState('');
  const [hand, setHand] = useState('');
  const [details, setDetails] = useState('');
  const [dailyTarget, setDailyTarget] = useState(3);

  // 編輯任務狀態
  const [editingTaskId, setEditingTaskId] = useState(null);
  const [editDraft, setEditDraft] = useState(null);

  // 連結網域切換
  const [useLanIp, setUseLanIp] = useState(false);

  const lanIp = serverMeta && serverMeta.lanIp;
  const isLocalhost = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1';

  const activeTaskHelperLang = activeStudent?.preferredLang === 'en' || lang === 'en' ? 'en' : 'zh';

  const getStudentShareUrl = (student) => {
    if (!student) return '';
    const sLang = student.preferredLang === 'en' ? 'en' : 'zh';
    const origin = useLanIp && lanIp && isLocalhost
      ? `${window.location.protocol}//${lanIp}:${window.location.port || 3000}`
      : window.location.origin;
    return `${origin}/?s=${encodeURIComponent(student.token)}&lang=${sLang}`;
  };

  const handleCreateStudent = (e) => {
    e.preventDefault();
    const trimmed = newStudentName.trim();
    if (!trimmed) return;
    onAddStudent({
      name: trimmed,
      level: newStudentLevel.trim() || (newStudentLang === 'en' ? 'Piano Student' : '鋼琴學生'),
      preferredLang: newStudentLang,
      avatar: newStudentAvatar
    });
    setNewStudentName('');
    setNewStudentLevel('');
    setNewStudentLang('zh');
    setAddingStudent(false);
    showToast(t.toastStudentAdded(trimmed));
  };

  const handleSavePin = (e) => {
    e.preventDefault();
    const cleaned = newPinValue.trim();
    if (!/^\d{4}$/.test(cleaned)) {
      showToast(t.toastPinInvalid);
      return;
    }
    onChangeTeacherPin(cleaned);
    setNewPinValue('');
    setChangingPin(false);
    showToast(t.toastPinSaved);
  };

  const handleCreateTask = (e) => {
    e.preventDefault();
    if (!activeStudent) return;
    const cleanPiece = piece.trim();
    const cleanDetails = details.trim();
    if (!cleanPiece) {
      showToast(t.toastEnterPiece);
      return;
    }
    const fallbackDetail = activeTaskHelperLang === 'en'
      ? `${bars ? bars + ' · ' : ''}${hand ? localizeHand(hand, 'en') + ' · ' : ''}Slow & steady practice as discussed in lesson`.trim()
      : `${bars ? bars + ' ' : ''}${hand ? hand + ' ' : ''}請按老師課堂指示慢練`.trim();

    onAddTask(activeStudent.id, {
      piece: cleanPiece,
      bars: bars.trim(),
      hand: hand.trim(),
      details: cleanDetails || fallbackDetail,
      dailyTarget: Math.max(1, Number(dailyTarget) || 3)
    });

    setPiece('');
    setBars('');
    setHand('');
    setDetails('');
    setDailyTarget(3);
    showToast(t.toastTaskAdded(activeStudent.name));
  };

  const handleCopyLink = async (student) => {
    const url = getStudentShareUrl(student);
    const sLang = student.preferredLang === 'en' ? 'en' : 'zh';
    await copyToClipboard(url);
    showToast(t.toastLinkCopied(student.name, sLang));
  };

  const handleCopyWhatsAppMsg = async (student) => {
    const url = getStudentShareUrl(student);
    const sLang = student.preferredLang === 'en' ? 'en' : 'zh';

    if (sLang === 'en') {
      const taskLines = (student.tasks || [])
        .map((tk, i) => {
          const pName = localizeTaskPiece(tk, 'en');
          const { bars: bText, hand: hText } = extractTaskMeta(tk, 'en');
          const meta = [bText, hText].filter(Boolean).join(' · ');
          return `${i + 1}. ${pName}${meta ? ` (${meta})` : ''} — ${tk.dailyTarget}x daily\n   👉 ${localizeTaskDetails(tk, 'en')}`;
        })
        .join('\n');

      const msg = `🎹 [${student.name}'s Weekly Piano Practice Plan & Check-in]\n\nHi! Here are ${student.name}'s piano practice goals for this week:\n${
        taskLines || '(Open the link below to view this week’s tasks)'
      }\n\n🔒 Private Practice Check-in Link:\n${url}\n\n(Open on iPhone or iPad to tap "+1 Check-in" after each rep and customize your avatar! Tap Share → "Add to Home Screen" in Safari to save it as an app.)`;

      await copyToClipboard(msg);
      showToast(t.toastWhatsappCopied('en'));
    } else {
      const taskLines = (student.tasks || [])
        .map((tk, i) => {
          const meta = [tk.bars, tk.hand].filter(Boolean).join(' · ');
          return `${i + 1}. ${tk.piece}${meta ? `（${meta}）` : ''} — 每日 ${tk.dailyTarget} 次\n   👉 ${tk.details}`;
        })
        .join('\n');

      const msg = `🎹【${student.name} 本週練琴重點與專屬打卡連結】\n\n家長你好！以下係 ${student.name} 今個星期嘅練琴拆解目標：\n${
        taskLines || '（請打開連結查看最新任務）'
      }\n\n🔒 學生私密練琴打卡連結：\n${url}\n\n（喺手機或 iPad 打開後，小朋友仲可以自己上載相片／換得意頭像，每練完一次撳「+1 打卡」就會自動紀錄進度，亦可以撳 Safari「加入主畫面」當 App 用㗎！）`;

      await copyToClipboard(msg);
      showToast(t.toastWhatsappCopied('zh'));
    }
  };

  const appendDetailChip = (chipText) => {
    const sep = activeTaskHelperLang === 'en' ? ', ' : '，';
    setDetails((prev) => {
      if (!prev.trim()) return chipText;
      if (prev.includes(chipText)) return prev;
      return `${prev}${sep}${chipText}`;
    });
  };

  const studioSummary = useMemo(() => {
    let totalWeekReps = 0;
    let avgPctSum = 0;
    students.forEach((s) => {
      const st = computeStudentStats(s, lang);
      totalWeekReps += st.weekTotalCheckins;
      avgPctSum += st.weekCompletionPct;
    });
    return {
      studentCount: students.length,
      totalWeekReps,
      avgCompletionPct: students.length > 0 ? Math.round(avgPctSum / students.length) : 0
    };
  }, [students, lang]);

  return (
    <div className="max-w-5xl mx-auto px-4 pt-3 pb-20">
      {/* 老師管理頁頂標題與總覽數據 */}
      <div className="bg-white rounded-3xl p-5 sm:p-6 shadow-sm border border-ivory-300 mb-6">
        <div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4">
          <div>
            <div className="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-indigo-50 text-indigo-700 text-xs font-extrabold mb-2">
              <span>{t.teacherModeBadge}</span>
            </div>
            <h1 className="text-2xl sm:text-3xl font-black text-ink-900">{t.teacherTitle}</h1>
          </div>

          <div className="flex items-center gap-2 flex-wrap">
            <button
              type="button"
              onClick={() => { setAddingStudent((v) => !v); setChangingPin(false); }}
              className="px-4 py-2.5 rounded-2xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs sm:text-sm font-bold shadow-xs transition"
            >
              {t.addStudentBtn}
            </button>
            <button
              type="button"
              onClick={() => { setChangingPin((v) => !v); setAddingStudent(false); }}
              className="px-3.5 py-2.5 rounded-2xl bg-ivory-100 hover:bg-ivory-200 border border-ivory-300 text-ink-700 text-xs sm:text-sm font-bold transition"
            >
              {t.changePinBtn}
            </button>
            <button
              type="button"
              onClick={onLockTeacher}
              className="px-3.5 py-2.5 rounded-2xl bg-ivory-100 hover:bg-rose-50 border border-ivory-300 text-ink-700 hover:text-rose-700 text-xs sm:text-sm font-bold transition"
            >
              {t.lockBtn}
            </button>
          </div>
        </div>

        <div className="grid grid-cols-3 gap-3 mt-5 pt-4 border-t border-ivory-200">
          <div className="bg-ivory-100 rounded-2xl p-3 sm:p-4">
            <div className="text-xs font-bold text-ink-500">{t.statStudents}</div>
            <div className="text-xl sm:text-2xl font-black text-ink-900 mt-0.5">
              {studioSummary.studentCount} {t.statStudentsUnit}
            </div>
          </div>
          <div className="bg-ivory-100 rounded-2xl p-3 sm:p-4">
            <div className="text-xs font-bold text-ink-500">{t.statWeekCheckins}</div>
            <div className="text-xl sm:text-2xl font-black text-indigo-600 mt-0.5">
              {studioSummary.totalWeekReps}{lang === 'en' ? 'x' : ' 次'}
            </div>
          </div>
          <div className="bg-ivory-100 rounded-2xl p-3 sm:p-4">
            <div className="text-xs font-bold text-ink-500">{t.statAvgRate}</div>
            <div className="text-xl sm:text-2xl font-black text-emerald-600 mt-0.5">
              {studioSummary.avgCompletionPct}%
            </div>
          </div>
        </div>

        {/* 更改老師密碼表單 */}
        {changingPin && (
          <form onSubmit={handleSavePin} className="mt-5 p-4 sm:p-5 rounded-2xl bg-amber-50/80 border border-amber-200 animate-popIn">
            <div className="flex items-center justify-between mb-2">
              <h3 className="font-extrabold text-amber-950 text-base">{t.changePinTitle}</h3>
              <button type="button" onClick={() => setChangingPin(false)} className="text-xs font-bold text-ink-500">
                {t.cancelBtn}
              </button>
            </div>
            <p className="text-xs text-amber-900 mb-3">{t.changePinSub}</p>
            <div className="flex gap-2 max-w-xs">
              <input
                type="password"
                inputMode="numeric"
                maxLength={4}
                value={newPinValue}
                onChange={(e) => setNewPinValue(e.target.value.replace(/\D/g, '').slice(0, 4))}
                placeholder={t.changePinPh}
                className="flex-1 px-3.5 py-2.5 rounded-xl bg-white border border-amber-300 text-sm font-black tracking-widest focus:outline-none focus:border-indigo-500"
              />
              <button
                type="submit"
                className="px-4 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-xs font-extrabold shrink-0"
              >
                {t.savePinBtn}
              </button>
            </div>
          </form>
        )}

        {/* 新增學生展開表單 */}
        {addingStudent && (
          <form onSubmit={handleCreateStudent} className="mt-5 p-4 sm:p-5 rounded-2xl bg-indigo-50/70 border border-indigo-200 animate-popIn">
            <div className="flex items-center justify-between mb-3">
              <h3 className="font-extrabold text-indigo-950 text-base">{t.newStudentModalTitle}</h3>
              <button type="button" onClick={() => setAddingStudent(false)} className="text-xs font-bold text-ink-500 hover:text-ink-900">
                {t.cancelBtn}
              </button>
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
              <div>
                <label className="block text-xs font-bold text-ink-700 mb-1">{t.studentNameLabel}</label>
                <input
                  type="text"
                  required
                  value={newStudentName}
                  onChange={(e) => setNewStudentName(e.target.value)}
                  placeholder={t.studentNamePh}
                  className="w-full px-3.5 py-2.5 rounded-xl bg-white border border-ivory-300 text-sm font-semibold focus:outline-none focus:border-indigo-500"
                />
              </div>
              <div>
                <label className="block text-xs font-bold text-ink-700 mb-1">{t.studentLevelLabel}</label>
                <input
                  type="text"
                  value={newStudentLevel}
                  onChange={(e) => setNewStudentLevel(e.target.value)}
                  placeholder={t.studentLevelPh}
                  className="w-full px-3.5 py-2.5 rounded-xl bg-white border border-ivory-300 text-sm font-semibold focus:outline-none focus:border-indigo-500"
                />
              </div>
            </div>

            <div className="mt-3">
              <label className="block text-xs font-bold text-ink-700 mb-1.5">{t.studentLangLabel}</label>
              <div className="inline-flex rounded-xl bg-white p-1 border border-ivory-300 gap-1 flex-wrap">
                <button
                  type="button"
                  onClick={() => setNewStudentLang('zh')}
                  className={`px-3.5 py-1.5 rounded-lg text-xs font-extrabold transition ${
                    newStudentLang === 'zh' ? 'bg-indigo-600 text-white' : 'text-ink-700 hover:bg-ivory-100'
                  }`}
                >
                  🇭🇰 繁體中文（廣東話 · Local）
                </button>
                <button
                  type="button"
                  onClick={() => setNewStudentLang('en')}
                  className={`px-3.5 py-1.5 rounded-lg text-xs font-extrabold transition ${
                    newStudentLang === 'en' ? 'bg-indigo-600 text-white' : 'text-ink-700 hover:bg-ivory-100'
                  }`}
                >
                  🇬🇧 English（International）
                </button>
              </div>
            </div>

            <div className="mt-3">
              <label className="block text-xs font-bold text-ink-700 mb-1.5">{t.avatarPickLabel}</label>
              <div className="flex flex-wrap gap-2">
                {STICKER_OPTIONS.slice(0, 12).map((emo) => (
                  <button
                    key={emo}
                    type="button"
                    onClick={() => setNewStudentAvatar(emo)}
                    className={`w-10 h-10 rounded-xl text-xl flex items-center justify-center transition ${
                      newStudentAvatar === emo
                        ? 'bg-indigo-600 text-white ring-2 ring-indigo-300 scale-105'
                        : 'bg-white border border-ivory-300 hover:bg-ivory-100'
                    }`}
                  >
                    {emo}
                  </button>
                ))}
              </div>
            </div>
            <div className="mt-4 flex justify-end">
              <button
                type="submit"
                className="px-5 py-2.5 rounded-xl bg-indigo-600 hover:bg-indigo-700 text-white text-sm font-bold shadow-xs"
              >
                {t.confirmCreateStudent}
              </button>
            </div>
          </form>
        )}
      </div>

      {/* 老師後台三大功能分頁切換（1. 學生任務與進度 | 2. 每週 YouTube 音樂問答 | 3. 本月龍虎榜） */}
      <div className="grid grid-cols-3 gap-2 bg-ivory-200/90 p-1.5 rounded-2xl border border-ivory-300 mb-6">
        {[
          { key: 'students', label: t.tabStudents },
          { key: 'quiz', label: t.tabQuiz },
          { key: 'leaderboard', label: t.tabLeaderboard }
        ].map((tb) => {
          const active = teacherTab === tb.key;
          return (
            <button
              key={tb.key}
              type="button"
              onClick={() => setTeacherTab(tb.key)}
              className={`py-2.5 px-2 sm:px-4 rounded-xl text-xs sm:text-sm font-black transition ${
                active
                  ? 'bg-white text-indigo-700 shadow-sm'
                  : 'text-ink-600 hover:text-ink-900'
              }`}
            >
              {tb.label}
            </button>
          );
        })}
      </div>

      {teacherTab === 'quiz' && (
        <TeacherQuizManager
          quizzes={quizzes || []}
          students={students || []}
          lang={lang}
          onSaveQuizzes={onSaveQuizzes}
          showToast={showToast}
        />
      )}

      {teacherTab === 'leaderboard' && (
        <div className="max-w-2xl mx-auto bg-white rounded-3xl p-5 sm:p-6 shadow-sm border border-ivory-300">
          <LeaderboardBoard
            leaderboard={teacherLeaderboard}
            lang={lang}
            onShiftMonth={(delta) => setLbMonthKey((prev) => shiftMonthKey(prev, delta))}
          />
        </div>
      )}

      {teacherTab === 'students' && (
        <>
      {/* 所有學生卡片一覽（同步顯示學生自己上載嘅相片／貼紙頭像！） */}
      <div className="mb-6">
        <div className="flex items-center justify-between mb-3 px-1">
          <h2 className="text-base font-extrabold text-ink-900">{t.selectStudentHeading}</h2>
          <span className="text-xs text-ink-500 font-medium">{t.selectStudentHint}</span>
        </div>

        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
          {students.map((st) => {
            const stStats = computeStudentStats(st, lang);
            const isSelected = activeStudent && activeStudent.id === st.id;
            const sPref = st.preferredLang === 'en' ? 'EN' : '繁中';

            return (
              <div
                key={st.id}
                onClick={() => onSelectStudent(st.id)}
                className={`cursor-pointer rounded-3xl p-5 transition-all border-2 ${
                  isSelected
                    ? 'bg-white border-indigo-600 ring-4 ring-indigo-100 shadow-md'
                    : 'bg-white/90 hover:bg-white border-ivory-300 hover:border-indigo-300 shadow-2xs'
                }`}
              >
                <div className="flex items-start justify-between gap-2">
                  <div className="flex items-center gap-3 min-w-0">
                    <StudentAvatar
                      student={st}
                      sizeClass="w-12 h-12 text-2xl"
                      roundedClass="rounded-2xl"
                      activeHighlight={isSelected}
                    />
                    <div className="min-w-0">
                      <div className="flex items-center gap-1.5 flex-wrap">
                        <h3 className="font-black text-lg text-ink-900">{st.name}</h3>
                        <span className={`px-1.5 py-0.5 rounded-md text-[10px] font-extrabold whitespace-nowrap shrink-0 ${
                          st.preferredLang === 'en'
                            ? 'bg-sky-100 text-sky-800'
                            : 'bg-ivory-200 text-ink-700'
                        }`}>
                          {sPref}
                        </span>
                        {isSelected && (
                          <span className="px-2 py-0.5 rounded-full bg-indigo-100 text-indigo-700 text-[11px] font-extrabold whitespace-nowrap shrink-0">
                            {t.managingBadge}
                          </span>
                        )}
                      </div>
                      <p className="text-xs text-ink-500 truncate">
                        {localizeStudentLevel(st, lang)} · {st.tasks.length} {t.tasksCountUnit}
                      </p>
                    </div>
                  </div>

                  {stStats.streakDays > 0 && (
                    <span className="px-2 py-0.5 rounded-full bg-amber-100 text-amber-800 text-xs font-extrabold shrink-0">
                      🔥 {stStats.streakDays}{t.streakUnitShort}
                    </span>
                  )}
                </div>

                <div className="grid grid-cols-2 gap-2.5 mt-4 bg-ivory-100 rounded-2xl p-3 border border-ivory-200">
                  <div>
                    <div className="text-[11px] font-bold text-ink-500">{t.weekTotalLabel}</div>
                    <div className="text-xl font-black text-ink-900 mt-0.5">
                      {stStats.weekTotalCheckins}{' '}
                      <span className="text-xs font-bold text-ink-500">{lang === 'en' ? 'x' : '次'}</span>
                    </div>
                  </div>
                  <div>
                    <div className="text-[11px] font-bold text-ink-500">{t.weekRateLabel}</div>
                    <div className={`text-xl font-black mt-0.5 ${
                      stStats.weekCompletionPct >= 70
                        ? 'text-emerald-600'
                        : stStats.weekCompletionPct >= 40
                        ? 'text-indigo-600'
                        : 'text-amber-600'
                    }`}>
                      {stStats.weekCompletionPct}%
                    </div>
                  </div>
                </div>

                <div className="mt-3">
                  <div className="h-2.5 rounded-full bg-ivory-200 overflow-hidden">
                    <div
                      className={`h-full rounded-full transition-all duration-500 ${
                        stStats.weekCompletionPct >= 70
                          ? 'bg-emerald-500'
                          : stStats.weekCompletionPct >= 40
                          ? 'bg-indigo-600'
                          : 'bg-amber-500'
                      }`}
                      style={{ width: `${stStats.weekCompletionPct}%` }}
                    />
                  </div>
                  <div className="flex justify-between items-center text-[11px] font-semibold text-ink-500 mt-1.5">
                    <span>{t.practicedDaysBadge(stStats.weekPracticedDays)}</span>
                    <span>{t.todayMetShort(stStats.completedTasksToday, stStats.totalTasks)}</span>
                  </div>
                </div>

                <div className="mt-3.5 pt-3 border-t border-ivory-200 flex items-center gap-2">
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      handleCopyLink(st);
                    }}
                    className="flex-1 py-2 px-3 rounded-xl bg-indigo-50 hover:bg-indigo-100 text-indigo-700 text-xs font-extrabold transition text-center"
                  >
                    {t.copyLinkShort}
                  </button>
                  <button
                    type="button"
                    onClick={(e) => {
                      e.stopPropagation();
                      onPreviewStudent(st);
                    }}
                    className="py-2 px-3 rounded-xl bg-ivory-100 hover:bg-ivory-200 text-ink-700 text-xs font-bold transition"
                  >
                    {t.previewShort}
                  </button>
                </div>
              </div>
            );
          })}
        </div>
      </div>

      {/* 當前選中學生詳細管理區 */}
      {activeStudent && (
        <div className="space-y-6">
          {/* 私密連結派發區 */}
          <div className="bg-gradient-to-r from-indigo-950 via-indigo-900 to-violet-900 rounded-3xl p-5 sm:p-6 text-white shadow-lg">
            <div className="flex flex-col lg:flex-row lg:items-center justify-between gap-4">
              <div className="min-w-0 flex-1">
                <div className="flex items-center gap-2 flex-wrap text-indigo-200 text-xs font-bold">
                  <span>{t.whatsappZoneBadge}</span>
                  {lanIp && isLocalhost && (
                    <button
                      type="button"
                      onClick={() => setUseLanIp((v) => !v)}
                      className="px-2.5 py-0.5 rounded-full bg-white/15 hover:bg-white/25 text-white text-[11px] font-bold transition"
                    >
                      {useLanIp ? t.lanToggleOn(lanIp) : t.lanToggleOff}
                    </button>
                  )}
                </div>

                <div className="flex items-center gap-3 flex-wrap mt-2">
                  <StudentAvatar
                    student={activeStudent}
                    sizeClass="w-10 h-10 text-xl"
                    roundedClass="rounded-xl"
                  />
                  <h3 className="text-xl font-black">
                    {t.dedicatedLinkTitle(activeStudent.name)}
                  </h3>

                  <div className="inline-flex items-center gap-1 bg-black/30 border border-white/15 rounded-xl p-1">
                    <span className="text-[11px] font-semibold text-indigo-200 pl-1.5 pr-1">
                      {t.studentDefaultLangSwitch}
                    </span>
                    <button
                      type="button"
                      onClick={() => {
                        onUpdateStudentLang(activeStudent.id, 'zh');
                        showToast(t.toastLangSaved(activeStudent.name, 'zh'));
                      }}
                      className={`px-2.5 py-1 rounded-lg text-xs font-extrabold transition ${
                        activeStudent.preferredLang !== 'en'
                          ? 'bg-white text-indigo-950 shadow-2xs'
                          : 'text-indigo-200 hover:text-white'
                      }`}
                    >
                      🇭🇰 繁中
                    </button>
                    <button
                      type="button"
                      onClick={() => {
                        onUpdateStudentLang(activeStudent.id, 'en');
                        showToast(t.toastLangSaved(activeStudent.name, 'en'));
                      }}
                      className={`px-2.5 py-1 rounded-lg text-xs font-extrabold transition ${
                        activeStudent.preferredLang === 'en'
                          ? 'bg-white text-indigo-950 shadow-2xs'
                          : 'text-indigo-200 hover:text-white'
                      }`}
                    >
                      🇬🇧 EN
                    </button>
                  </div>
                </div>

                <div className="mt-2.5 flex items-center gap-2">
                  <div className="flex-1 min-w-0 bg-black/25 border border-white/15 rounded-xl px-3.5 py-2 font-mono text-xs sm:text-sm text-indigo-100 truncate">
                    {getStudentShareUrl(activeStudent)}
                  </div>
                  <button
                    type="button"
                    onClick={() => {
                      if (window.confirm(t.confirmResetToken(activeStudent.name))) {
                        onRegenerateToken(activeStudent.id);
                        showToast(t.toastTokenReset);
                      }
                    }}
                    className="px-3 py-2 rounded-xl bg-white/10 hover:bg-white/20 border border-white/15 text-xs font-bold text-indigo-100 shrink-0 transition"
                  >
                    {t.resetTokenBtn}
                  </button>
                </div>
              </div>

              <div className="flex flex-col sm:flex-row gap-2.5 shrink-0">
                <button
                  type="button"
                  onClick={() => handleCopyLink(activeStudent)}
                  className="px-5 py-3.5 rounded-2xl bg-white hover:bg-indigo-50 text-indigo-950 font-black text-sm shadow-md active:scale-95 transition flex items-center justify-center gap-2"
                >
                  <span>🔗</span>
                  <span>{t.copyDedicatedLinkBtn}</span>
                </button>
                <button
                  type="button"
                  onClick={() => handleCopyWhatsAppMsg(activeStudent)}
                  className="px-5 py-3.5 rounded-2xl bg-emerald-500 hover:bg-emerald-400 text-ink-900 font-black text-sm shadow-md active:scale-95 transition flex items-center justify-center gap-2"
                >
                  <span>💬</span>
                  <span>{t.copyWhatsappMsgBtn}</span>
                </button>
              </div>
            </div>
          </div>

          <div className="grid grid-cols-1 lg:grid-cols-12 gap-6 items-start">
            {/* 左欄：落堂快速加入「本週練琴任務」表單 */}
            <div className="lg:col-span-5 bg-white rounded-3xl p-5 sm:p-6 shadow-sm border border-ivory-300">
              <div className="flex items-center gap-2.5 mb-4">
                <span className="w-9 h-9 rounded-xl bg-indigo-100 text-indigo-700 flex items-center justify-center text-lg font-bold">➕</span>
                <div>
                  <h3 className="font-black text-lg text-ink-900">{t.addTaskTitle(activeStudent.name)}</h3>
                  <p className="text-xs text-ink-500">{t.addTaskSub}</p>
                </div>
              </div>

              <form onSubmit={handleCreateTask} className="space-y-4">
                <div>
                  <label className="block text-xs font-extrabold text-ink-700 mb-1.5">
                    {t.fieldPiece}
                  </label>
                  <input
                    type="text"
                    required
                    value={piece}
                    onChange={(e) => setPiece(e.target.value)}
                    placeholder={t.fieldPiecePh}
                    className="w-full px-4 py-3 rounded-2xl bg-ivory-100 border border-ivory-300 text-sm font-semibold text-ink-900 focus:bg-white focus:outline-none focus:border-indigo-500"
                  />
                  <div className="flex flex-wrap gap-1.5 mt-2">
                    {(QUICK_PIECES_MAP[activeTaskHelperLang] || QUICK_PIECES_MAP.zh).map((qp) => (
                      <button
                        key={qp}
                        type="button"
                        onClick={() => setPiece(qp)}
                        className="px-2.5 py-1 rounded-lg bg-ivory-100 hover:bg-indigo-50 border border-ivory-300 text-xs font-semibold text-ink-700 hover:text-indigo-700 transition"
                      >
                        + {qp}
                      </button>
                    ))}
                  </div>
                </div>

                <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
                  <div>
                    <label className="block text-xs font-extrabold text-ink-700 mb-1.5">
                      {t.fieldBars}
                    </label>
                    <input
                      type="text"
                      value={bars}
                      onChange={(e) => setBars(e.target.value)}
                      placeholder={t.fieldBarsPh}
                      className="w-full px-3.5 py-2.5 rounded-xl bg-ivory-100 border border-ivory-300 text-sm font-semibold text-ink-900 focus:bg-white focus:outline-none focus:border-indigo-500"
                    />
                  </div>
                  <div>
                    <label className="block text-xs font-extrabold text-ink-700 mb-1.5">
                      {t.fieldHand}
                    </label>
                    <select
                      value={hand}
                      onChange={(e) => setHand(e.target.value)}
                      className="w-full px-3 py-2.5 rounded-xl bg-ivory-100 border border-ivory-300 text-sm font-semibold text-ink-900 focus:bg-white focus:outline-none focus:border-indigo-500"
                    >
                      <option value="">{t.fieldHandAuto}</option>
                      {HAND_OPTIONS.map((ho) => (
                        <option key={ho.value} value={ho.value}>
                          {lang === 'en' ? ho.en : ho.zh}
                        </option>
                      ))}
                    </select>
                  </div>
                </div>

                <div>
                  <label className="block text-xs font-extrabold text-ink-700 mb-1.5">
                    {t.fieldDetails}
                  </label>
                  <textarea
                    rows="3"
                    value={details}
                    onChange={(e) => setDetails(e.target.value)}
                    placeholder={t.fieldDetailsPh}
                    className="w-full px-4 py-3 rounded-2xl bg-ivory-100 border border-ivory-300 text-sm font-semibold text-ink-900 focus:bg-white focus:outline-none focus:border-indigo-500"
                  />
                  <div className="flex flex-wrap gap-1.5 mt-1.5">
                    {(QUICK_DETAILS_MAP[activeTaskHelperLang] || QUICK_DETAILS_MAP.zh).map((qd) => (
                      <button
                        key={qd}
                        type="button"
                        onClick={() => appendDetailChip(qd)}
                        className="px-2.5 py-1 rounded-lg bg-ivory-100 hover:bg-amber-50 border border-ivory-300 text-xs font-semibold text-ink-700 hover:text-amber-900 transition"
                      >
                        + {qd}
                      </button>
                    ))}
                  </div>
                </div>

                <div>
                  <label className="block text-xs font-extrabold text-ink-700 mb-1.5">
                    {t.fieldTarget}
                  </label>
                  <div className="flex items-center gap-3 flex-wrap">
                    <div className="flex items-center bg-ivory-100 border border-ivory-300 rounded-2xl p-1">
                      <button
                        type="button"
                        onClick={() => setDailyTarget((n) => Math.max(1, Number(n) - 1))}
                        className="w-10 h-10 rounded-xl bg-white hover:bg-ivory-200 font-black text-lg text-ink-900 shadow-2xs"
                      >
                        −
                      </button>
                      <span className="w-16 text-center font-black text-lg text-indigo-700">
                        {dailyTarget}{lang === 'en' ? 'x' : ' 次'}
                      </span>
                      <button
                        type="button"
                        onClick={() => setDailyTarget((n) => Math.min(30, Number(n) + 1))}
                        className="w-10 h-10 rounded-xl bg-white hover:bg-ivory-200 font-black text-lg text-ink-900 shadow-2xs"
                      >
                        +
                      </button>
                    </div>

                    <div className="flex gap-1.5 flex-wrap">
                      {[3, 5, 7, 10].map((preset) => (
                        <button
                          key={preset}
                          type="button"
                          onClick={() => setDailyTarget(preset)}
                          className={`px-3 py-2 rounded-xl text-xs font-extrabold transition ${
                            Number(dailyTarget) === preset
                              ? 'bg-indigo-600 text-white'
                              : 'bg-ivory-100 hover:bg-ivory-200 text-ink-700 border border-ivory-300'
                          }`}
                        >
                          {preset}{lang === 'en' ? 'x' : '次'}
                        </button>
                      ))}
                    </div>
                  </div>
                </div>

                <button
                  type="submit"
                  className="w-full py-4 rounded-2xl bg-indigo-600 hover:bg-indigo-700 active:scale-[0.98] text-white font-black text-base shadow-md shadow-indigo-200 transition"
                >
                  {t.submitAddTask(activeStudent.name)}
                </button>
              </form>
            </div>

            {/* 右欄：打卡月曆、本週任務清單與老師小叮囑 */}
            <div className="lg:col-span-7 space-y-5">
              <PracticeCalendar student={activeStudent} lang={lang} isTeacherView={true} />

              <div className="bg-white rounded-3xl p-5 shadow-sm border border-ivory-300">
                <label className="block text-xs font-extrabold text-ink-700 mb-1.5">
                  {t.teacherNoteEditLabel(activeStudent.name)}
                </label>
                <input
                  type="text"
                  value={localizeStudentNote(activeStudent, lang) || ''}
                  onChange={(e) => onUpdateStudentNote(activeStudent.id, e.target.value)}
                  placeholder={t.teacherNoteEditPh}
                  className="w-full px-4 py-2.5 rounded-xl bg-amber-50/60 border border-amber-200 text-sm font-semibold text-ink-900 focus:bg-white focus:outline-none focus:border-indigo-500"
                />
              </div>

              <div className="bg-white rounded-3xl p-5 sm:p-6 shadow-sm border border-ivory-300">
                <div className="flex items-center justify-between gap-2 flex-wrap mb-4">
                  <div>
                    <h3 className="font-black text-lg text-ink-900">
                      {t.studentTaskListTitle(activeStudent.name, activeStudent.tasks.length)}
                    </h3>
                    <p className="text-xs text-ink-500">{t.studentTaskListSub}</p>
                  </div>

                  <div className="flex items-center gap-2">
                    <button
                      type="button"
                      onClick={() => onPreviewStudent(activeStudent)}
                      className="px-3.5 py-2 rounded-xl bg-indigo-50 hover:bg-indigo-100 text-indigo-700 text-xs font-extrabold transition"
                    >
                      {t.previewStudentBtn}
                    </button>
                    {activeStudent.tasks.length > 0 && (
                      <button
                        type="button"
                        onClick={() => {
                          onResetTodayLogs(activeStudent.id);
                          showToast(t.toastResetToday(activeStudent.name));
                        }}
                        className="px-3 py-2 rounded-xl bg-ivory-100 hover:bg-ivory-200 text-ink-700 text-xs font-bold transition"
                      >
                        {t.resetTodayBtn}
                      </button>
                    )}
                  </div>
                </div>

                {activeStudent.tasks.length === 0 ? (
                  <div className="py-10 text-center bg-ivory-100 rounded-2xl border border-dashed border-ivory-300">
                    <p className="text-sm font-bold text-ink-700">{t.emptyTasksTeacherTitle}</p>
                    <p className="text-xs text-ink-500 mt-1">{t.emptyTasksTeacherSub(activeStudent.name)}</p>
                  </div>
                ) : (
                  <div className="space-y-3">
                    {activeStudent.tasks.map((task, idx) => {
                      const todayKey = getLocalDateKey();
                      const todayDone = Number((activeStudent.logs?.[todayKey]?.[task.id]) || 0);
                      const isDoneToday = todayDone >= task.dailyTarget;
                      const { bars: metaBars, hand: metaHand } = extractTaskMeta(task, lang);
                      const isEditing = editingTaskId === task.id && editDraft;

                      if (isEditing) {
                        return (
                          <div key={task.id} className="rounded-2xl p-4 bg-indigo-50/70 border-2 border-indigo-300 space-y-3">
                            <div className="grid grid-cols-1 sm:grid-cols-3 gap-2.5">
                              <input
                                type="text"
                                value={editDraft.piece}
                                onChange={(e) => setEditDraft({ ...editDraft, piece: e.target.value })}
                                placeholder={t.fieldPiecePh}
                                className="sm:col-span-2 px-3 py-2 rounded-xl bg-white border border-ivory-300 text-sm font-bold"
                              />
                              <div className="flex items-center gap-1.5 bg-white border border-ivory-300 rounded-xl px-2.5 py-1.5">
                                <span className="text-xs font-bold text-ink-500">{lang === 'en' ? 'Goal' : '每日'}</span>
                                <input
                                  type="number"
                                  min="1"
                                  max="30"
                                  value={editDraft.dailyTarget}
                                  onChange={(e) => setEditDraft({ ...editDraft, dailyTarget: Math.max(1, Number(e.target.value) || 1) })}
                                  className="w-12 text-center font-black text-sm text-indigo-700 focus:outline-none"
                                />
                                <span className="text-xs font-bold text-ink-500">{lang === 'en' ? 'x' : '次'}</span>
                              </div>
                            </div>
                            <div className="grid grid-cols-2 gap-2.5">
                              <input
                                type="text"
                                value={editDraft.bars || ''}
                                onChange={(e) => setEditDraft({ ...editDraft, bars: e.target.value })}
                                placeholder={t.fieldBarsPh}
                                className="px-3 py-2 rounded-xl bg-white border border-ivory-300 text-xs font-semibold"
                              />
                              <input
                                type="text"
                                value={editDraft.hand || ''}
                                onChange={(e) => setEditDraft({ ...editDraft, hand: e.target.value })}
                                placeholder="RH / LH / HT / HS"
                                className="px-3 py-2 rounded-xl bg-white border border-ivory-300 text-xs font-semibold"
                              />
                            </div>
                            <textarea
                              rows="2"
                              value={editDraft.details}
                              onChange={(e) => setEditDraft({ ...editDraft, details: e.target.value })}
                              className="w-full px-3 py-2 rounded-xl bg-white border border-ivory-300 text-sm font-medium"
                            />
                            <div className="flex justify-end gap-2">
                              <button
                                type="button"
                                onClick={() => { setEditingTaskId(null); setEditDraft(null); }}
                                className="px-3.5 py-1.5 rounded-xl bg-white border border-ivory-300 text-xs font-bold text-ink-700"
                              >
                                {t.cancelBtn}
                              </button>
                              <button
                                type="button"
                                onClick={() => {
                                  const cleaned = { ...editDraft };
                                  delete cleaned.pieceEn;
                                  delete cleaned.barsEn;
                                  delete cleaned.detailsEn;
                                  onUpdateTask(activeStudent.id, task.id, cleaned);
                                  setEditingTaskId(null);
                                  setEditDraft(null);
                                  showToast(t.toastTaskUpdated);
                                }}
                                className="px-4 py-1.5 rounded-xl bg-indigo-600 text-white text-xs font-bold"
                              >
                                {t.saveEditBtn}
                              </button>
                            </div>
                          </div>
                        );
                      }

                      return (
                        <div
                          key={task.id}
                          className={`rounded-2xl p-4 border transition ${
                            isDoneToday
                              ? 'bg-emerald-50/60 border-emerald-300'
                              : 'bg-ivory-50 border-ivory-300'
                          }`}
                        >
                          <div className="flex items-start justify-between gap-3">
                            <div className="min-w-0">
                              <div className="flex items-center gap-2 flex-wrap">
                                <span className="w-6 h-6 rounded-lg bg-indigo-100 text-indigo-700 text-xs font-black flex items-center justify-center">
                                  {idx + 1}
                                </span>
                                <h4 className="font-extrabold text-base text-ink-900">
                                  {localizeTaskPiece(task, lang)}
                                </h4>
                                <span className="px-2.5 py-0.5 rounded-full bg-indigo-100 text-indigo-800 text-xs font-extrabold">
                                  {t.dailyBadge(task.dailyTarget)}
                                </span>
                                <span className={`px-2.5 py-0.5 rounded-full text-xs font-bold ${
                                  isDoneToday ? 'bg-emerald-600 text-white' : 'bg-ivory-200 text-ink-700'
                                }`}>
                                  {t.todayDoneBadge(todayDone, task.dailyTarget)}
                                </span>
                              </div>

                              {(metaBars || metaHand) && (
                                <div className="flex flex-wrap gap-1.5 mt-2">
                                  {metaBars && (
                                    <span className="px-2 py-0.5 rounded-md bg-amber-100 text-amber-900 text-xs font-bold">
                                      📍 {metaBars}
                                    </span>
                                  )}
                                  {metaHand && (
                                    <span className="px-2 py-0.5 rounded-md bg-violet-100 text-violet-900 text-xs font-bold">
                                      ✋ {metaHand}
                                    </span>
                                  )}
                                </div>
                              )}

                              <p className="text-sm text-ink-700 mt-2 leading-relaxed">
                                {localizeTaskDetails(task, lang)}
                              </p>
                            </div>

                            <div className="flex items-center gap-1.5 shrink-0">
                              <button
                                type="button"
                                onClick={() => {
                                  setEditingTaskId(task.id);
                                  setEditDraft({
                                    ...task,
                                    piece: localizeTaskPiece(task, lang),
                                    bars: localizeBars(task.bars || '', task, lang),
                                    details: localizeTaskDetails(task, lang)
                                  });
                                }}
                                className="px-2.5 py-1.5 rounded-xl bg-white hover:bg-indigo-50 border border-ivory-300 text-xs font-bold text-ink-700"
                              >
                                {t.editBtn}
                              </button>
                              <button
                                type="button"
                                onClick={() => {
                                  onDeleteTask(activeStudent.id, task.id);
                                  showToast(t.toastTaskDeleted);
                                }}
                                className="px-2.5 py-1.5 rounded-xl bg-white hover:bg-rose-50 border border-ivory-300 text-xs font-bold text-rose-600"
                              >
                                {t.deleteBtn}
                              </button>
                            </div>
                          </div>
                        </div>
                      );
                    })}
                  </div>
                )}

                {students.length > 1 && (
                  <div className="mt-6 pt-4 border-t border-ivory-200 flex justify-end">
                    <button
                      type="button"
                      onClick={() => {
                        if (window.confirm(t.confirmDeleteStudent(activeStudent.name))) {
                          onDeleteStudent(activeStudent.id);
                          showToast(t.toastStudentDeleted(activeStudent.name));
                        }
                      }}
                      className="text-xs font-semibold text-ink-500 hover:text-rose-600 transition"
                    >
                      {t.deleteStudentBtn}
                    </button>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      )}
        </>
      )}
    </div>
  );
}

// ---------- 主應用程式 App ----------
function App() {
  const [route, setRoute] = useState(() => parseLocationRoute());

  const [lang, setLang] = useState(() => {
    const r = parseLocationRoute();
    if (r.explicitLang) return r.explicitLang;
    try {
      const saved = localStorage.getItem(LANG_KEY);
      if (saved === 'en' || saved === 'zh') return saved;
    } catch (_) {}
    return 'zh';
  });

  // 學生端單人私密狀態（只載入對應 token 嘅唯一一位學生）
  const [studentProfile, setStudentProfile] = useState(() => {
    const r = parseLocationRoute();
    if (r.mode === 'student' && r.token) {
      try {
        const cached = localStorage.getItem(STUDENT_CACHE_PREFIX + r.token);
        if (cached) return JSON.parse(cached);
      } catch (_) {}
    }
    return null;
  });
  const [studentLoading, setStudentLoading] = useState(() => {
    const r = parseLocationRoute();
    return r.mode === 'student' && Boolean(r.token) && !studentProfile;
  });
  const [invalidToken, setInvalidToken] = useState(false);
  const [studentQuiz, setStudentQuiz] = useState(null);
  const [studentMonthlyScore, setStudentMonthlyScore] = useState(null);
  const [studentLeaderboard, setStudentLeaderboard] = useState(null);

  // 老師端全班管理狀態（必須經 /api/teacher/verify 解鎖先會載入）
  const [teacherPin, setTeacherPin] = useState(() => {
    try {
      return sessionStorage.getItem(TEACHER_PIN_SESSION_KEY) || '';
    } catch (_) {
      return '';
    }
  });
  const [teacherStore, setTeacherStore] = useState(null);
  const [serverMeta, setServerMeta] = useState(null);
  const [teacherSelectedId, setTeacherSelectedId] = useState('jayden');

  const [soundMuted, setSoundMuted] = useState(() => {
    try {
      return localStorage.getItem(MUTE_KEY) === 'true';
    } catch (_) {
      return false;
    }
  });
  const [celebrationEvent, setCelebrationEvent] = useState(null);
  const [toastMsg, setToastMsg] = useState(null);
  const [pwaGuideOpen, setPwaGuideOpen] = useState(false);

  const toastTimerRef = useRef(null);
  const t = I18N[lang] || I18N.zh;

  useEffect(() => {
    document.title = lang === 'en'
      ? 'KeySteps — Piano Practice & Check-in'
      : '琴鍵小步 — 練琴項目拆解與打卡';
    document.documentElement.lang = lang === 'en' ? 'en' : 'zh-HK';
  }, [lang]);

  const showToast = useCallback((msg) => {
    setToastMsg(msg);
    if (toastTimerRef.current) clearTimeout(toastTimerRef.current);
    toastTimerRef.current = setTimeout(() => setToastMsg(null), 3200);
  }, []);

  const changeLanguage = useCallback((nextLang) => {
    setLang(nextLang);
    try {
      localStorage.setItem(LANG_KEY, nextLang);
    } catch (_) {}
    const params = new URLSearchParams(window.location.search);
    if (params.has('lang')) {
      params.set('lang', nextLang);
      const qs = params.toString();
      window.history.replaceState({}, '', `${window.location.pathname}${qs ? '?' + qs : ''}`);
    }
  }, []);

  // 載入單一學生私密資料（連同本週問答及安全版龍虎榜）
  const applyStudentBundle = useCallback((data, tok, isPreviewMode = false, explicitLangParam = null) => {
    if (!data || !data.ok || !data.student) return;
    setStudentProfile(data.student);
    if ('currentQuiz' in data) setStudentQuiz(data.currentQuiz || null);
    if ('myMonthlyScore' in data) setStudentMonthlyScore(data.myMonthlyScore || null);
    if ('leaderboard' in data) setStudentLeaderboard(data.leaderboard || null);
    setInvalidToken(false);
    try {
      localStorage.setItem(STUDENT_CACHE_PREFIX + tok, JSON.stringify(data.student));
      if (!isPreviewMode) {
        localStorage.setItem(STUDENT_SAVED_TOKEN_KEY, tok);
      }
    } catch (_) {}
    if (!explicitLangParam && data.student.preferredLang) {
      setLang(data.student.preferredLang);
    }
  }, []);

  const loadStudentByToken = useCallback(async (tok, isPreviewMode = false, explicitLangParam = null) => {
    if (!tok) {
      setStudentProfile(null);
      setStudentQuiz(null);
      setStudentMonthlyScore(null);
      setStudentLeaderboard(null);
      setStudentLoading(false);
      return;
    }
    setStudentLoading((prev) => (!studentProfile || studentProfile.token !== tok ? true : prev));
    try {
      const res = await fetch(`/api/student?s=${encodeURIComponent(tok)}`, { cache: 'no-store' });
      if (res.ok) {
        const data = await res.json();
        applyStudentBundle(data, tok, isPreviewMode, explicitLangParam);
      } else if (res.status === 404) {
        setStudentProfile(null);
        setInvalidToken(true);
        if (!isPreviewMode) {
          try {
            localStorage.removeItem(STUDENT_SAVED_TOKEN_KEY);
          } catch (_) {}
        }
      }
    } catch (_) {
      // 離線狀態沿用本機快取
    } finally {
      setStudentLoading(false);
    }
  }, [applyStudentBundle]);

  // 載入老師管理資料（需有效密碼）
  const loadTeacherData = useCallback(async (pinToUse) => {
    if (!pinToUse) return false;
    try {
      const res = await fetch('/api/teacher/data', {
        headers: { 'X-Teacher-Pin': pinToUse },
        cache: 'no-store'
      });
      if (!res.ok) {
        if (res.status === 401) {
          setTeacherPin('');
          setTeacherStore(null);
          try {
            sessionStorage.removeItem(TEACHER_PIN_SESSION_KEY);
          } catch (_) {}
        }
        return false;
      }
      const data = await res.json();
      if (data && Array.isArray(data.students)) {
        if (data.serverMeta) setServerMeta(data.serverMeta);
        const clean = { ...data };
        delete clean.serverMeta;
        setTeacherStore(clean);
        try {
          localStorage.setItem(TEACHER_CACHE_KEY, JSON.stringify(clean));
        } catch (_) {}
        return true;
      }
    } catch (_) {}
    return false;
  }, []);

  // 路由及聚焦同步
  useEffect(() => {
    if (route.mode === 'student') {
      loadStudentByToken(route.token, route.isPreview, route.explicitLang);
    } else if (route.mode === 'teacher' && teacherPin) {
      loadTeacherData(teacherPin);
    }
  }, [route.mode, route.token, route.isPreview, route.explicitLang, teacherPin, loadStudentByToken, loadTeacherData]);

  useEffect(() => {
    const onFocus = () => {
      if (route.mode === 'student' && route.token) {
        loadStudentByToken(route.token, route.isPreview, route.explicitLang || lang);
      } else if (route.mode === 'teacher' && teacherPin) {
        loadTeacherData(teacherPin);
      }
    };
    const onPopState = () => {
      const nextR = parseLocationRoute();
      setRoute(nextR);
      if (nextR.explicitLang) setLang(nextR.explicitLang);
    };
    window.addEventListener('focus', onFocus);
    window.addEventListener('popstate', onPopState);
    return () => {
      window.removeEventListener('focus', onFocus);
      window.removeEventListener('popstate', onPopState);
    };
  }, [route, teacherPin, lang, loadStudentByToken, loadTeacherData]);

  // 老師密碼驗證
  const handleVerifyTeacherPin = useCallback(async (candidatePin) => {
    try {
      const res = await fetch('/api/teacher/verify', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ pin: candidatePin })
      });
      if (!res.ok) return false;
      const data = await res.json();
      if (data && data.ok && data.store) {
        if (data.store.serverMeta) setServerMeta(data.store.serverMeta);
        const clean = { ...data.store };
        delete clean.serverMeta;
        setTeacherPin(candidatePin);
        setTeacherStore(clean);
        if (clean.students && clean.students[0]) {
          setTeacherSelectedId((prev) =>
            clean.students.some((s) => s.id === prev) ? prev : clean.students[0].id
          );
        }
        try {
          sessionStorage.setItem(TEACHER_PIN_SESSION_KEY, candidatePin);
        } catch (_) {}
        return true;
      }
    } catch (_) {}
    return false;
  }, []);

  // 老師端儲存更新
  const commitTeacherStore = useCallback((updater) => {
    setTeacherStore((prev) => {
      if (!prev) return prev;
      const next = typeof updater === 'function' ? updater(prev) : updater;
      const stamped = { ...next, updatedAt: new Date().toISOString() };
      const pinHeader = teacherPin;
      fetch('/api/teacher/data', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Teacher-Pin': pinHeader
        },
        body: JSON.stringify(stamped)
      }).catch(() => {});
      return stamped;
    });
  }, [teacherPin]);

  // 學生端輸入專屬碼進入
  const handleEnterStudentToken = useCallback((tok) => {
    const cleanTok = tok.trim();
    if (!cleanTok) return;
    window.history.pushState({}, '', `/?s=${encodeURIComponent(cleanTok)}`);
    setRoute({ mode: 'student', token: cleanTok, explicitLang: null, isPreview: false });
  }, []);

  // 學生端 +1 / -1 打卡
  const handleStudentCheckin = useCallback((task, delta) => {
    if (!studentProfile) return;
    const todayKey = getLocalDateKey();
    const curDict = I18N[lang] || I18N.zh;
    const praisePool = PRAISE_MESSAGES[lang] || PRAISE_MESSAGES.zh;
    const displayPiece = localizeTaskPiece(task, lang);

    const prevLogs = studentProfile.logs || {};
    const prevToday = prevLogs[todayKey] || {};
    const oldCount = Number(prevToday[task.id] || 0);
    const newCount = Math.max(0, oldCount + delta);

    const optimisticStudent = {
      ...studentProfile,
      logs: {
        ...prevLogs,
        [todayKey]: {
          ...prevToday,
          [task.id]: newCount
        }
      }
    };

    setStudentProfile(optimisticStudent);
    try {
      localStorage.setItem(STUDENT_CACHE_PREFIX + studentProfile.token, JSON.stringify(optimisticStudent));
    } catch (_) {}

    if (delta > 0) {
      const target = Math.max(1, Number(task.dailyTarget) || 1);
      if (newCount === target) {
        const afterStats = computeStudentStats(optimisticStudent, lang);
        if (afterStats.allTasksDoneToday) {
          if (!soundMuted) SoundEngine.playAllTasksGrandFanfare();
          setCelebrationEvent({
            id: Date.now(),
            isGrand: true,
            title: curDict.grandTitle(optimisticStudent.name),
            subtitle: curDict.grandSub(displayPiece, newCount, target)
          });
        } else {
          if (!soundMuted) SoundEngine.playTaskSuccess();
          const praise = praisePool[Math.floor(Math.random() * praisePool.length)];
          setCelebrationEvent({
            id: Date.now(),
            isGrand: false,
            title: curDict.taskDoneTitle(displayPiece, newCount, target),
            subtitle: praise
          });
        }
      } else {
        if (!soundMuted) SoundEngine.playCheckinStep(newCount);
      }
    } else if (delta < 0 && !soundMuted) {
      SoundEngine.playUndo();
    }

    fetch('/api/student/checkin', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        token: studentProfile.token,
        taskId: task.id,
        dateKey: todayKey,
        delta
      })
    })
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => {
        if (data && data.ok && data.student) {
          applyStudentBundle(data, data.student.token, route.isPreview, lang);
        }
      })
      .catch(() => {});
  }, [studentProfile, lang, soundMuted, applyStudentBundle, route.isPreview]);

  // 學生端提交每週音樂問答答案
  const handleSubmitStudentQuiz = useCallback(async (quizId, orderedAnswers) => {
    if (!studentProfile) return;
    const curDict = I18N[lang] || I18N.zh;
    try {
      const res = await fetch('/api/student/quiz', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          token: studentProfile.token,
          quizId,
          answers: orderedAnswers
        })
      });
      if (res.ok) {
        const data = await res.json();
        applyStudentBundle(data, studentProfile.token, route.isPreview, lang);
        const sub = data.currentQuiz && data.currentQuiz.submission;
        if (sub) {
          if (!soundMuted) {
            if (sub.correctCount >= 4) SoundEngine.playAllTasksGrandFanfare();
            else SoundEngine.playTaskSuccess();
          }
          setCelebrationEvent({
            id: Date.now(),
            isGrand: sub.correctCount === sub.totalQuestions,
            title: curDict.quizSubmittedBanner(sub.correctCount, sub.totalQuestions, sub.score),
            subtitle: curDict.quizDoneToast(sub.score)
          });
        }
      }
    } catch (_) {}
  }, [studentProfile, lang, soundMuted, applyStudentBundle, route.isPreview]);

  // 學生端喺龍虎榜彈窗切換月份
  const handleShiftStudentLeaderboardMonth = useCallback(async (delta) => {
    if (!studentProfile) return;
    const curMonth = (studentLeaderboard && studentLeaderboard.monthKey) || getCurrentMonthKey();
    const targetMonth = shiftMonthKey(curMonth, delta);
    try {
      const res = await fetch(
        `/api/student/leaderboard?s=${encodeURIComponent(studentProfile.token)}&month=${encodeURIComponent(targetMonth)}`,
        { cache: 'no-store' }
      );
      if (res.ok) {
        const data = await res.json();
        if (data && data.ok && data.leaderboard) {
          setStudentLeaderboard(data.leaderboard);
        }
      }
    } catch (_) {}
  }, [studentProfile, studentLeaderboard]);

  // 練琴倒數計時器完成提示
  const handleTimerFinished = useCallback((mins) => {
    const curDict = I18N[lang] || I18N.zh;
    setCelebrationEvent({
      id: Date.now(),
      isGrand: true,
      title: curDict.timerDoneTitle,
      subtitle: curDict.timerDoneSub(mins)
    });
  }, [lang]);

  // 學生端儲存自訂相片／貼紙頭像
  const handleSaveStudentAvatar = useCallback(async ({ avatar, avatarImage, avatarBg }) => {
    if (!studentProfile) return;
    const optimistic = {
      ...studentProfile,
      avatar,
      avatarImage,
      avatarBg
    };
    setStudentProfile(optimistic);
    try {
      localStorage.setItem(STUDENT_CACHE_PREFIX + studentProfile.token, JSON.stringify(optimistic));
    } catch (_) {}

    try {
      const res = await fetch('/api/student/avatar', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          token: studentProfile.token,
          avatar,
          avatarImage,
          avatarBg
        })
      });
      if (res.ok) {
        const data = await res.json();
        if (data && data.ok && data.student) {
          setStudentProfile(data.student);
          try {
            localStorage.setItem(STUDENT_CACHE_PREFIX + data.student.token, JSON.stringify(data.student));
          } catch (_) {}
        }
      }
    } catch (_) {}
    showToast((I18N[lang] || I18N.zh).toastAvatarSaved);
  }, [studentProfile, lang, showToast]);

  // 老師管理操作
  const handleAddStudent = useCallback(({ name, level, preferredLang, avatar }) => {
    const slugBase = name
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, '') || `student${Date.now().toString().slice(-4)}`;

    commitTeacherStore((prev) => {
      let uniqueId = slugBase;
      let counter = 2;
      while (prev.students.some((s) => s.id === uniqueId)) {
        uniqueId = `${slugBase}${counter++}`;
      }
      const isEn = preferredLang === 'en';
      const newStudent = {
        id: uniqueId,
        token: randomToken(8),
        name,
        avatar: avatar || '🎹',
        avatarBg: 'indigo',
        avatarImage: null,
        preferredLang: isEn ? 'en' : 'zh',
        level,
        teacherNote: isEn
          ? 'Practice slowly, count steady beats, and keep your wrists relaxed!'
          : '記得慢練數拍子，手腕放鬆呀！',
        tasks: [],
        logs: {}
      };
      setTeacherSelectedId(uniqueId);
      return { ...prev, students: [...prev.students, newStudent] };
    });
  }, [commitTeacherStore]);

  const handleDeleteStudent = useCallback((studentId) => {
    commitTeacherStore((prev) => {
      const remaining = prev.students.filter((s) => s.id !== studentId);
      if (remaining.length > 0 && teacherSelectedId === studentId) {
        setTeacherSelectedId(remaining[0].id);
      }
      return { ...prev, students: remaining };
    });
  }, [commitTeacherStore, teacherSelectedId]);

  const handleRegenerateToken = useCallback((studentId) => {
    commitTeacherStore((prev) => ({
      ...prev,
      students: prev.students.map((s) =>
        s.id === studentId ? { ...s, token: randomToken(8) } : s
      )
    }));
  }, [commitTeacherStore]);

  const handleUpdateStudentLang = useCallback((studentId, nextPrefLang) => {
    commitTeacherStore((prev) => ({
      ...prev,
      students: prev.students.map((s) =>
        s.id === studentId ? { ...s, preferredLang: nextPrefLang } : s
      )
    }));
  }, [commitTeacherStore]);

  const handleUpdateStudentNote = useCallback((studentId, note) => {
    commitTeacherStore((prev) => ({
      ...prev,
      students: prev.students.map((s) => {
        if (s.id !== studentId) return s;
        const copy = { ...s, teacherNote: note };
        delete copy.teacherNoteEn;
        return copy;
      })
    }));
  }, [commitTeacherStore]);

  const handleAddTask = useCallback((studentId, taskData) => {
    const newTask = {
      id: `t-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`,
      ...taskData
    };
    commitTeacherStore((prev) => ({
      ...prev,
      students: prev.students.map((s) =>
        s.id === studentId ? { ...s, tasks: [...(s.tasks || []), newTask] } : s
      )
    }));
  }, [commitTeacherStore]);

  const handleUpdateTask = useCallback((studentId, taskId, updatedFields) => {
    commitTeacherStore((prev) => ({
      ...prev,
      students: prev.students.map((s) =>
        s.id === studentId
          ? {
              ...s,
              tasks: s.tasks.map((tk) => {
                if (tk.id !== taskId) return tk;
                const merged = { ...tk, ...updatedFields };
                delete merged.pieceEn;
                delete merged.barsEn;
                delete merged.detailsEn;
                return merged;
              })
            }
          : s
      )
    }));
  }, [commitTeacherStore]);

  const handleDeleteTask = useCallback((studentId, taskId) => {
    commitTeacherStore((prev) => ({
      ...prev,
      students: prev.students.map((s) =>
        s.id === studentId
          ? { ...s, tasks: s.tasks.filter((tk) => tk.id !== taskId) }
          : s
      )
    }));
  }, [commitTeacherStore]);

  const handleResetTodayLogs = useCallback((studentId) => {
    const todayKey = getLocalDateKey();
    commitTeacherStore((prev) => ({
      ...prev,
      students: prev.students.map((s) => {
        if (s.id !== studentId) return s;
        const nextLogs = { ...(s.logs || {}) };
        delete nextLogs[todayKey];
        return { ...s, logs: nextLogs };
      })
    }));
  }, [commitTeacherStore]);

  const handleSaveTeacherQuizzes = useCallback((nextQuizzes) => {
    commitTeacherStore((prev) => ({
      ...prev,
      quizzes: nextQuizzes
    }));
  }, [commitTeacherStore]);

  const handleChangeTeacherPin = useCallback((nextPin) => {
    setTeacherStore((prev) => {
      if (!prev) return prev;
      const stamped = { ...prev, teacherPin: nextPin, updatedAt: new Date().toISOString() };
      fetch('/api/teacher/data', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Teacher-Pin': teacherPin
        },
        body: JSON.stringify(stamped)
      }).then(() => {
        setTeacherPin(nextPin);
        try {
          sessionStorage.setItem(TEACHER_PIN_SESSION_KEY, nextPin);
        } catch (_) {}
      }).catch(() => {});
      return stamped;
    });
  }, [teacherPin]);

  const handlePreviewStudentFromTeacher = useCallback((st) => {
    if (!st) return;
    const sLang = st.preferredLang === 'en' ? 'en' : 'zh';
    setLang(sLang);
    setStudentProfile(st);
    const previewUrl = `/?s=${encodeURIComponent(st.token)}&lang=${sLang}&preview=1`;
    window.history.pushState({}, '', previewUrl);
    setRoute({ mode: 'student', token: st.token, explicitLang: sLang, isPreview: true });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, []);

  const handleReturnToTeacher = useCallback(() => {
    window.history.pushState({}, '', '/teacher');
    setRoute({ mode: 'teacher', token: null, explicitLang: null, isPreview: false });
    window.scrollTo({ top: 0, behavior: 'smooth' });
  }, []);

  const toggleSound = () => {
    setSoundMuted((prev) => {
      const next = !prev;
      try {
        localStorage.setItem(MUTE_KEY, String(next));
      } catch (_) {}
      return next;
    });
  };

  // 只有當老師已經喺當前瀏覽器驗證密碼，並且撳「預覽學生畫面 (preview=1)」時，先顯示頂部老師返回提示列；真實學生絕不會見到！
  const showTeacherPreviewBar = route.mode === 'student' && route.isPreview && Boolean(teacherPin);

  return (
    <div className="min-h-screen flex flex-col">
      {showTeacherPreviewBar && (
        <div className="bg-indigo-950 text-indigo-100 px-4 py-2 text-xs font-bold flex items-center justify-between gap-3 z-50">
          <span className="truncate">{t.teacherPreviewBanner}</span>
          <button
            type="button"
            onClick={handleReturnToTeacher}
            className="px-3 py-1 rounded-lg bg-white text-indigo-950 font-extrabold shrink-0 hover:bg-indigo-50 transition"
          >
            {t.backToTeacherBtn}
          </button>
        </div>
      )}

      {/* 頂部導覽列：學生版面完全無「老師管理」及「切換學生」按鈕！ */}
      <header className="sticky top-0 z-40 backdrop-blur-md bg-ivory-100/90 border-b border-ivory-300 safe-top">
        <div className="max-w-5xl mx-auto px-4 py-2.5 flex items-center justify-between gap-2">
          <div className="flex items-center gap-2.5 text-left min-w-0">
            <img src="/icons/icon.svg" alt={t.appName} className="w-9 h-9 rounded-xl shadow-xs shrink-0" />
            <div className="min-w-0">
              <div className="font-black text-base sm:text-lg text-ink-900 leading-none truncate">{t.appName}</div>
              <div className="text-[11px] font-semibold text-ink-500 mt-0.5 truncate">{t.appSubtitle}</div>
            </div>
          </div>

          <div className="flex items-center gap-1.5 sm:gap-2 shrink-0">
            {/* 語言切換掣（繁中 | EN） */}
            <div
              className="h-9 p-0.5 rounded-xl bg-ivory-200/90 border border-ivory-300 flex items-center text-xs font-extrabold"
              role="group"
              aria-label="Language Switcher"
            >
              <button
                type="button"
                onClick={() => changeLanguage('zh')}
                className={`h-full px-2.5 rounded-lg transition ${
                  lang === 'zh'
                    ? 'bg-white text-indigo-700 shadow-2xs'
                    : 'text-ink-600 hover:text-ink-900'
                }`}
              >
                繁中
              </button>
              <button
                type="button"
                onClick={() => changeLanguage('en')}
                className={`h-full px-2.5 rounded-lg transition ${
                  lang === 'en'
                    ? 'bg-white text-indigo-700 shadow-2xs'
                    : 'text-ink-600 hover:text-ink-900'
                }`}
              >
                EN
              </button>
            </div>

            {/* 音效開關 */}
            <button
              type="button"
              onClick={toggleSound}
              title={soundMuted ? t.soundTooltipOff : t.soundTooltipOn}
              className="h-9 px-2.5 rounded-xl bg-white hover:bg-ivory-200 border border-ivory-300 text-xs font-bold text-ink-700 flex items-center gap-1 transition"
            >
              <span>{soundMuted ? '🔇' : '🔊'}</span>
              <span className="hidden md:inline">{soundMuted ? t.soundMuted : t.soundOn}</span>
            </button>
          </div>
        </div>
      </header>

      {/* 主內容區 */}
      <main className="flex-1">
        {route.mode === 'teacher' ? (
          teacherPin && teacherStore ? (
            <TeacherView
              students={teacherStore.students}
              quizzes={teacherStore.quizzes || []}
              selectedStudentId={teacherSelectedId}
              lang={lang}
              onSelectStudent={(id) => setTeacherSelectedId(id)}
              onAddStudent={handleAddStudent}
              onDeleteStudent={handleDeleteStudent}
              onRegenerateToken={handleRegenerateToken}
              onUpdateStudentLang={handleUpdateStudentLang}
              onUpdateStudentNote={handleUpdateStudentNote}
              onAddTask={handleAddTask}
              onUpdateTask={handleUpdateTask}
              onDeleteTask={handleDeleteTask}
              onResetTodayLogs={handleResetTodayLogs}
              onSaveQuizzes={handleSaveTeacherQuizzes}
              onChangeTeacherPin={handleChangeTeacherPin}
              onPreviewStudent={handlePreviewStudentFromTeacher}
              onLockTeacher={() => {
                setTeacherPin('');
                setTeacherStore(null);
                try {
                  sessionStorage.removeItem(TEACHER_PIN_SESSION_KEY);
                } catch (_) {}
              }}
              serverMeta={serverMeta}
              showToast={showToast}
            />
          ) : (
            <TeacherPinLock
              lang={lang}
              onVerifyPin={handleVerifyTeacherPin}
            />
          )
        ) : (
          <StudentView
            student={studentProfile}
            currentQuiz={studentQuiz}
            myMonthlyScore={studentMonthlyScore}
            leaderboard={studentLeaderboard}
            loading={studentLoading}
            invalidToken={invalidToken}
            lang={lang}
            soundMuted={soundMuted}
            onEnterToken={handleEnterStudentToken}
            onAdjustCheckin={handleStudentCheckin}
            onSubmitQuiz={handleSubmitStudentQuiz}
            onShiftLeaderboardMonth={handleShiftStudentLeaderboardMonth}
            onTimerFinished={handleTimerFinished}
            onSaveAvatar={handleSaveStudentAvatar}
            onOpenPwaGuide={() => setPwaGuideOpen(true)}
            showToast={showToast}
          />
        )}
      </main>

      <CelebrationOverlay
        event={celebrationEvent}
        lang={lang}
        onDismiss={() => setCelebrationEvent(null)}
      />

      <PwaGuideModal open={pwaGuideOpen} lang={lang} onClose={() => setPwaGuideOpen(false)} />

      {toastMsg && (
        <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 px-4 w-full max-w-md pointer-events-none">
          <div className="bg-ink-900/95 text-white text-xs sm:text-sm font-bold px-4 py-3 rounded-2xl shadow-xl text-center animate-popIn">
            {toastMsg}
          </div>
        </div>
      )}
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
