// Teacher App — full flow with login, richer handbook entry, saved confirmation.
// Built on top of teacher-portal.jsx (TPSchedule, TPSaved still reused; new TPLessonRich here).
// All state is React state. Internationalised via t().

const { useState: tlUseState, useEffect: tlUseEffect, useRef: tlUseRef } = React;

// ── Login screen ───────────────────────────────────────────────────
function TPLogin({ c, dark, lang, onLogin, onLangToggle }) {
  const [email, setEmail] = tlUseState('wlchen@tomleemusic.com');
  const [pw, setPw] = tlUseState('••••••••');
  const [showPw, setShowPw] = tlUseState(false);
  const [err, setErr] = tlUseState('');

  const submit = () => {
    if (!email || !email.includes('@')) {
      setErr(lang === 'zh' ? '請輸入有效的員工電郵' : 'Please enter a valid staff email.');
      return;
    }
    if (!pw) {
      setErr(lang === 'zh' ? '請輸入密碼' : 'Please enter your password.');
      return;
    }
    setErr('');
    onLogin();
  };

  return (
    <div style={{
      background: c.bg, minHeight: '100%', color: c.ink,
      display: 'flex', flexDirection: 'column', position: 'relative',
    }}>
      {/* lang toggle */}
      <div style={{ position: 'absolute', top: 12, right: 20, zIndex: 2 }}>
        <button onClick={onLangToggle} style={{
          background: 'transparent', border: `1px solid ${c.line}`,
          padding: '6px 12px', cursor: 'pointer',
          fontFamily: TL_FONTS.mono, fontSize: 11, letterSpacing: '0.08em',
          color: c.ink2,
        }}>{t('lang.toggle')}</button>
      </div>

      {/* hero / brand */}
      <div style={{ padding: '32px 28px 24px' }}>
        <TLLogo height={72} />
      </div>

      <div style={{ flex: 1, padding: '12px 28px 0', display: 'flex', flexDirection: 'column', justifyContent: 'flex-start' }}>
        <TLLabel color={c.ink3}>{t('login.subtitle')}</TLLabel>
        <h1 style={{
          fontFamily: TL_FONTS.serif, fontWeight: 500, fontSize: 38,
          lineHeight: 1.05, margin: '8px 0 32px', letterSpacing: '-0.02em',
          color: c.ink,
        }}>{t('login.title')}</h1>

        <FieldLabel c={c}>{t('login.email')}</FieldLabel>
        <input
          type="email"
          value={email}
          onChange={e => setEmail(e.target.value)}
          placeholder={t('login.email.ph')}
          autoCapitalize="off"
          autoCorrect="off"
          style={{
            width: '100%', padding: '14px 0', boxSizing: 'border-box',
            fontFamily: TL_FONTS.sans, fontSize: 16, color: c.ink,
            background: 'transparent', border: 'none',
            borderBottom: `1px solid ${c.line}`,
            outline: 'none', marginBottom: 22,
          }}
        />

        <FieldLabel c={c}>{t('login.password')}</FieldLabel>
        <div style={{ display: 'flex', alignItems: 'center', borderBottom: `1px solid ${c.line}`, marginBottom: 8 }}>
          <input
            type={showPw ? 'text' : 'password'}
            value={pw}
            onChange={e => setPw(e.target.value)}
            style={{
              flex: 1, padding: '14px 0', boxSizing: 'border-box',
              fontFamily: TL_FONTS.sans, fontSize: 16, color: c.ink,
              background: 'transparent', border: 'none', outline: 'none',
            }}
          />
          <button onClick={() => setShowPw(!showPw)} style={{
            background: 'transparent', border: 'none', padding: '0 4px',
            cursor: 'pointer', color: c.ink3,
            fontFamily: TL_FONTS.mono, fontSize: 11, letterSpacing: '0.08em',
          }}>{showPw ? 'HIDE' : 'SHOW'}</button>
        </div>

        {err && <div style={{
          fontFamily: TL_FONTS.sans, fontSize: 13, color: '#C0392B',
          marginTop: 12,
        }}>{err}</div>}

        <div style={{ marginTop: 'auto', paddingTop: 32 }}>
          <button onClick={submit} style={{
            width: '100%', padding: '16px',
            background: c.ink, color: c.bg, border: 'none', cursor: 'pointer',
            fontFamily: TL_FONTS.mono, fontSize: 12, letterSpacing: '0.12em', textTransform: 'uppercase',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
          }}>
            {t('login.signin')} <TLIcon name="arrowR" size={14} color={c.bg} />
          </button>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 16 }}>
            <button style={{
              background: 'transparent', border: 'none', padding: 0, cursor: 'pointer',
              fontFamily: TL_FONTS.sans, fontSize: 13, color: c.ink2,
              textDecoration: 'underline', textUnderlineOffset: 3,
            }}>{t('login.forgot')}</button>
            <span style={{
              fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.1em',
              color: c.muted, textTransform: 'uppercase',
            }}><TLIcon name="lock" size={10} color={c.muted} style={{ marginRight: 4, verticalAlign: '-1px' }} /> Secure</span>
          </div>
        </div>
      </div>

      <div style={{ padding: '24px 28px 36px', borderTop: `1px solid ${c.line2}`, marginTop: 28 }}>
        <div style={{ fontFamily: TL_FONTS.sans, fontSize: 12, color: c.ink3, lineHeight: 1.5 }}>
          {t('login.help')}
        </div>
      </div>
    </div>
  );
}

function FieldLabel({ c, children }) {
  return (
    <div style={{
      fontFamily: TL_FONTS.mono, fontSize: 10, color: c.ink3,
      letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 4,
    }}>{children}</div>
  );
}

// ── Quick-tag chip row ─────────────────────────────────────────────
function TagChip({ c, label, active, onClick }) {
  return (
    <button onClick={onClick} style={{
      padding: '7px 11px', cursor: 'pointer',
      background: active ? c.ink : 'transparent',
      color: active ? c.bg : c.ink2,
      border: `1px solid ${active ? c.ink : c.line}`,
      fontFamily: TL_FONTS.mono, fontSize: 10, letterSpacing: '0.08em',
      textTransform: 'uppercase', whiteSpace: 'nowrap',
    }}>{label}</button>
  );
}

// ── Star rating ───────────────────────────────────────────────────
function StarRating({ c, value, onChange, max = 5 }) {
  return (
    <div style={{ display: 'flex', gap: 4 }}>
      {[...Array(max)].map((_, i) => {
        const v = i + 1;
        const filled = v <= value;
        return (
          <button key={i} onClick={() => onChange(v)} style={{
            background: 'transparent', border: 'none', padding: 2, cursor: 'pointer',
          }}>
            <svg width="22" height="22" viewBox="0 0 24 24">
              <polygon
                points="12,3 14.6,9 21,9.7 16.2,14 17.6,20.5 12,17 6.4,20.5 7.8,14 3,9.7 9.4,9"
                fill={filled ? c.accent : 'transparent'}
                stroke={filled ? c.accent : c.line.replace('rgba(20,20,20,0.10)', '#999').replace('rgba(255,255,255,0.12)', '#666')}
                strokeWidth="1.4" strokeLinejoin="round"
              />
            </svg>
          </button>
        );
      })}
    </div>
  );
}

// ── Mood selector ──────────────────────────────────────────────────
function MoodSelector({ c, value, onChange }) {
  const moods = [
    { id: 'great',  emoji: '◉', label: t('lesson.mood.great') },
    { id: 'good',   emoji: '◎', label: t('lesson.mood.good') },
    { id: 'steady', emoji: '○', label: t('lesson.mood.steady') },
    { id: 'tough',  emoji: '◐', label: t('lesson.mood.tough') },
  ];
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 6 }}>
      {moods.map(m => {
        const sel = value === m.id;
        return (
          <button key={m.id} onClick={() => onChange(m.id)} style={{
            padding: '10px 4px', cursor: 'pointer',
            background: sel ? c.ink : 'transparent',
            color: sel ? c.bg : c.ink2,
            border: `1px solid ${sel ? c.ink : c.line}`,
            display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
          }}>
            <span style={{ fontFamily: TL_FONTS.serif, fontSize: 22, lineHeight: 1 }}>{m.emoji}</span>
            <span style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.08em', textTransform: 'uppercase' }}>{m.label}</span>
          </button>
        );
      })}
    </div>
  );
}

// ── Piece row with progress dropdown + minutes ─────────────────────
function PieceRowRich({ c, piece, onChange, onRemove }) {
  const [open, setOpen] = tlUseState(false);
  const markers = TL_PROGRESS_MARKERS;
  const lang = tlLang();

  return (
    <div style={{
      marginBottom: 8, padding: '12px 14px',
      background: c.surface, border: `1px solid ${c.line}`,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 4, height: 28, background: c.accent, flexShrink: 0 }} />
        <input
          value={piece.name}
          onChange={e => onChange({ ...piece, name: e.target.value })}
          placeholder={lang === 'zh' ? '曲目名稱（如：Bach — Minuet in G）' : 'Piece name (e.g. Bach — Minuet in G)'}
          style={{
            flex: 1, minWidth: 0, border: 'none', background: 'transparent', padding: 0,
            fontFamily: TL_FONTS.sans, fontSize: 14, color: c.ink, outline: 'none',
          }}
        />
        <button onClick={onRemove} style={{
          background: 'none', border: 'none', cursor: 'pointer', padding: 4, color: c.ink3,
        }}>
          <TLIcon name="x" size={14} color={c.ink3} />
        </button>
      </div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 10, paddingLeft: 14 }}>
        <button onClick={() => setOpen(!open)} style={{
          padding: '5px 9px', background: 'transparent', border: `1px solid ${c.line}`,
          cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6,
          fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.08em',
          textTransform: 'uppercase', color: c.ink2,
        }}>
          {markers.find(m => m.id === piece.markerId)?.[tlLang()] || markers.find(m => m.id === piece.markerId)?.en || 'Status'}
          <TLIcon name="chevD" size={10} color={c.ink2} />
        </button>
        <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
          <input
            type="number"
            min="0" max="60"
            value={piece.minutes || ''}
            onChange={e => onChange({ ...piece, minutes: e.target.value })}
            placeholder="--"
            style={{
              width: 36, border: `1px solid ${c.line}`, background: 'transparent',
              padding: '4px 6px', fontFamily: TL_FONTS.mono, fontSize: 11,
              color: c.ink, outline: 'none', textAlign: 'center',
            }}
          />
          <span style={{ fontFamily: TL_FONTS.mono, fontSize: 9, color: c.ink3, letterSpacing: '0.08em' }}>
            {tlLang() === 'zh' ? '分鐘' : 'MIN'}
          </span>
        </div>
      </div>
      {open && (
        <div style={{ marginTop: 8, paddingLeft: 14, display: 'flex', flexWrap: 'wrap', gap: 4 }}>
          {markers.map(m => (
            <button key={m.id} onClick={() => { onChange({ ...piece, markerId: m.id }); setOpen(false); }} style={{
              padding: '5px 9px', background: piece.markerId === m.id ? c.ink : 'transparent',
              color: piece.markerId === m.id ? c.bg : c.ink2,
              border: `1px solid ${piece.markerId === m.id ? c.ink : c.line}`,
              cursor: 'pointer',
              fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.08em',
              textTransform: 'uppercase',
            }}>{m[tlLang()] || m.en}</button>
          ))}
        </div>
      )}
    </div>
  );
}

// ── Skill rating row ───────────────────────────────────────────────
function SkillRow({ c, label, value, onChange }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '12px 0', borderBottom: `1px solid ${c.line2}`,
    }}>
      <div style={{ fontFamily: TL_FONTS.sans, fontSize: 14, color: c.ink2 }}>{label}</div>
      <StarRating c={c} value={value} onChange={onChange} />
    </div>
  );
}

// ── Lesson detail (rich) ───────────────────────────────────────────
function TPLessonRich({ c, dark, lesson, onBack, onSave }) {
  const student = TL_STUDENTS.find(s => s.id === lesson.studentId);
  const [attended, setAttended] = tlUseState(true);
  const [showPrev, setShowPrev] = tlUseState(false);
  const [pieces, setPieces] = tlUseState([
    { name: 'Burgmüller — Arabesque, Op.100 No.2', markerId: 'polish', minutes: 15 },
    { name: 'Bach — Minuet in G major',            markerId: 'memo',   minutes: 12 },
  ]);
  const [technique, setTechnique] = tlUseState('');
  const [homework, setHomework] = tlUseState('');
  const [remark, setRemark] = tlUseState('');
  const [nextFocus, setNextFocus] = tlUseState('');
  const [absentReason, setAbsentReason] = tlUseState('');
  const [skills, setSkills] = tlUseState({ tone: 4, rhythm: 4, posture: 3, musicality: 4 });
  const [mood, setMood] = tlUseState('good');
  const [tags, setTags] = tlUseState(['focused']);

  const lastEntry = TL_HANDBOOK_S1.find(h => h.attended);
  const lang = tlLang();

  const toggleTag = (id) => setTags(tags.includes(id) ? tags.filter(x => x !== id) : [...tags, id]);

  return (
    <div style={{ background: c.bg, minHeight: '100%', color: c.ink, paddingBottom: 0 }}>
      {/* header */}
      <div style={{ padding: '8px 24px 20px', borderBottom: `1px solid ${c.line}` }}>
        <button onClick={onBack} style={{
          background: 'none', border: 'none', color: c.ink3, cursor: 'pointer',
          padding: 0, marginBottom: 14, display: 'flex', alignItems: 'center', gap: 6,
          fontFamily: TL_FONTS.mono, fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase',
        }}>
          <TLIcon name="chevL" size={14} color={c.ink3} /> {t('lesson.back')}
        </button>
        <TLLabel color={c.ink3}>{t('lesson.lessonOf', { time: lesson.time, dur: lesson.duration })}</TLLabel>
        <div style={{ display: 'flex', gap: 14, marginTop: 12, alignItems: 'center' }}>
          <TLAvatar student={student} size={56} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <h2 style={{
              fontFamily: TL_FONTS.serif, fontWeight: 500, fontSize: 26,
              lineHeight: 1.05, margin: 0, letterSpacing: '-0.02em',
            }}>{student.name}</h2>
            <div style={{ fontFamily: TL_FONTS.sans, fontSize: 13, color: c.ink3, marginTop: 4 }}>
              {lang === 'zh' ? lesson.subjectZh : lesson.subject} · {student.level} · {lang === 'zh' ? '' : 'Age '}{student.age}{lang === 'zh' ? ' 歲' : ''}
            </div>
          </div>
        </div>
      </div>

      {/* Attendance */}
      <Section c={c} num="01" label={t('lesson.attendance')}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
          <AttendBtn c={c} active={attended === true}  onClick={() => setAttended(true)}  icon="check" label={t('lesson.attended')} />
          <AttendBtn c={c} active={attended === false} onClick={() => setAttended(false)} icon="x"     label={t('lesson.absentBtn')} />
        </div>
      </Section>

      {/* Previous remark */}
      <Section c={c} num="02" label={t('lesson.fromLast')}>
        <button onClick={() => setShowPrev(!showPrev)} style={{
          width: '100%', textAlign: 'left', padding: '14px 16px',
          background: c.surface, border: `1px solid ${c.line}`, cursor: 'pointer',
          display: 'flex', alignItems: 'center', gap: 12, color: c.ink,
        }}>
          <div style={{ flex: 1 }}>
            <div style={{ fontFamily: TL_FONTS.mono, fontSize: 10, letterSpacing: '0.1em', color: c.ink3, marginBottom: 4 }}>
              {lastEntry.dateLabel.toUpperCase()}
            </div>
            <div style={{ fontFamily: TL_FONTS.sans, fontSize: 14, color: c.ink2, lineHeight: 1.4 }}>
              {showPrev ? '' : lastEntry.remark.slice(0, 60) + '…'}
            </div>
          </div>
          <TLIcon name={showPrev ? 'chevD' : 'chevR'} size={16} color={c.ink3} />
        </button>
        {showPrev && (
          <div style={{ marginTop: 8, padding: '16px 18px', background: c.surface, border: `1px solid ${c.line}` }}>
            <TLLabel color={c.ink3} style={{ marginBottom: 8 }}>{t('lesson.pieces')}</TLLabel>
            {lastEntry.pieces.map((p, i) => (
              <div key={i} style={{ fontFamily: TL_FONTS.sans, fontSize: 13, marginBottom: 4, color: c.ink }}>
                · {p.name} <span style={{ color: c.ink3 }}>— {p.progress}</span>
              </div>
            ))}
            <TLLabel color={c.ink3} style={{ marginTop: 14, marginBottom: 6 }}>{t('lesson.homeworkSet')}</TLLabel>
            <div style={{ fontFamily: TL_FONTS.sans, fontSize: 13, color: c.ink2, lineHeight: 1.5 }}>{lastEntry.homework}</div>
            <TLLabel color={c.ink3} style={{ marginTop: 14, marginBottom: 6 }}>{t('lesson.remark')}</TLLabel>
            <div style={{ fontFamily: TL_FONTS.serif, fontSize: 15, fontStyle: 'italic', color: c.ink, lineHeight: 1.45 }}>
              "{lastEntry.remark}"
            </div>
          </div>
        )}
      </Section>

      {attended ? (
        <>
          {/* Mood */}
          <Section c={c} num="03" label={t('lesson.mood')}>
            <MoodSelector c={c} value={mood} onChange={setMood} />
          </Section>

          {/* Pieces */}
          <Section c={c} num="04" label={t('lesson.pieces')}>
            {pieces.map((p, i) => (
              <PieceRowRich key={i} c={c} piece={p}
                onChange={(np) => setPieces(pieces.map((x, j) => j === i ? np : x))}
                onRemove={() => setPieces(pieces.filter((_, j) => j !== i))}
              />
            ))}
            <button onClick={() => setPieces([...pieces, { name: '', markerId: 'new', minutes: '' }])} style={{
              width: '100%', padding: '12px', background: 'transparent',
              border: `1px dashed ${c.line}`, color: c.ink3, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
              fontFamily: TL_FONTS.mono, fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase',
            }}>
              <TLIcon name="plus" size={12} color={c.ink3} /> {t('lesson.addPiece')}
            </button>
          </Section>

          {/* Skill ratings */}
          <Section c={c} num="05" label={t('lesson.skillRating')}>
            <div style={{ borderTop: `1px solid ${c.line2}` }}>
              <SkillRow c={c} label={t('lesson.skill.tone')}       value={skills.tone}       onChange={(v) => setSkills({ ...skills, tone: v })} />
              <SkillRow c={c} label={t('lesson.skill.rhythm')}     value={skills.rhythm}     onChange={(v) => setSkills({ ...skills, rhythm: v })} />
              <SkillRow c={c} label={t('lesson.skill.posture')}    value={skills.posture}    onChange={(v) => setSkills({ ...skills, posture: v })} />
              <SkillRow c={c} label={t('lesson.skill.musicality')} value={skills.musicality} onChange={(v) => setSkills({ ...skills, musicality: v })} />
            </div>
          </Section>

          {/* Technique */}
          <Section c={c} num="06" label={t('lesson.technique')}>
            <TLTextarea c={c} value={technique} onChange={setTechnique}
              placeholder={t('lesson.technique.ph')} rows={3} />
          </Section>

          {/* Homework */}
          <Section c={c} num="07" label={t('lesson.homework')}>
            <TLTextarea c={c} value={homework} onChange={setHomework}
              placeholder={t('lesson.homework.ph')} rows={3} />
          </Section>

          {/* Tags */}
          <Section c={c} num="08" label={t('lesson.tags')}>
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
              {TL_LESSON_TAGS.map(tag => (
                <TagChip key={tag.id} c={c} active={tags.includes(tag.id)}
                  onClick={() => toggleTag(tag.id)}
                  label={lang === 'zh' ? tag.zh : tag.en}
                />
              ))}
            </div>
          </Section>

          {/* Next focus */}
          <Section c={c} num="09" label={t('lesson.nextFocus')}>
            <TLTextarea c={c} value={nextFocus} onChange={setNextFocus}
              placeholder={t('lesson.nextFocus.ph')} rows={2} />
          </Section>

          {/* Remark */}
          <Section c={c} num="10" label={t('lesson.remark')}>
            <TLTextarea c={c} value={remark} onChange={setRemark}
              placeholder={t('lesson.remark.ph')} rows={4} />
            <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
              <AttachBtn c={c} icon="mic"       label={t('lesson.attach.audio')} />
              <AttachBtn c={c} icon="camera"    label={t('lesson.attach.photo')} />
              <AttachBtn c={c} icon="paperclip" label={t('lesson.attach.file')} />
            </div>
          </Section>
        </>
      ) : (
        <Section c={c} num="03" label={t('lesson.reasonAbsent')}>
          <TLTextarea c={c} value={absentReason} onChange={setAbsentReason}
            placeholder={t('lesson.absent.ph')} rows={3} />
        </Section>
      )}

      {/* sticky save */}
      <div style={{
        position: 'sticky', bottom: 0, left: 0, right: 0, zIndex: 5,
        padding: '14px 20px 28px', background: c.bg,
        borderTop: `1px solid ${c.line}`,
        display: 'flex', gap: 10, marginTop: 24,
      }}>
        <button onClick={onBack} style={{
          padding: '14px 16px', background: 'transparent', color: c.ink,
          border: `1px solid ${c.line}`, cursor: 'pointer',
          fontFamily: TL_FONTS.mono, fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase',
          whiteSpace: 'nowrap',
        }}>{t('lesson.draft')}</button>
        <button onClick={() => onSave({ attended, pieces, technique, homework, remark, nextFocus, skills, mood, tags })} style={{
          flex: 1, padding: '14px 12px', background: c.ink, color: c.bg,
          border: 'none', cursor: 'pointer',
          fontFamily: TL_FONTS.mono, fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        }}>
          <TLIcon name="check" size={14} color={c.bg} /> {t('lesson.save')}
        </button>
      </div>
    </div>
  );
}

// ── Saved confirmation, i18n version ──────────────────────────────
function TPSavedRich({ c, lesson, onDone }) {
  const student = TL_STUDENTS.find(s => s.id === lesson.studentId);
  const firstName = student.name.split(' ')[0];
  return (
    <div style={{
      background: c.bg, color: c.ink, minHeight: '100%',
      display: 'flex', flexDirection: 'column', padding: '40px 28px',
      position: 'relative',
    }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
        <div style={{
          width: 56, height: 56, background: c.ink, color: c.bg,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: 28,
        }}>
          <TLIcon name="check" size={28} color={c.bg} stroke={2} />
        </div>
        <TLLabel color={c.ink3}>{t('saved.justLogged')} · {lesson.time}</TLLabel>
        <h1 style={{
          fontFamily: TL_FONTS.serif, fontSize: 34, fontWeight: 500,
          lineHeight: 1.05, margin: '10px 0 16px', letterSpacing: '-0.02em',
        }}>{t('saved.title', { name: firstName })}</h1>
        <p style={{
          fontFamily: TL_FONTS.sans, fontSize: 15, color: c.ink2, lineHeight: 1.55, margin: 0, maxWidth: 320,
        }}>{t('saved.body', { parent: student.parent })}</p>

        <div style={{ marginTop: 32, padding: '18px 20px', background: c.surface, border: `1px solid ${c.line}` }}>
          <TLLabel color={c.ink3} style={{ marginBottom: 10 }}>{t('saved.sentTo')}</TLLabel>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
            <div style={{
              width: 36, height: 36, background: '#25D366', color: 'white',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <TLIcon name="msg" size={18} color="white" />
            </div>
            <div>
              <div style={{ fontFamily: TL_FONTS.sans, fontSize: 14, color: c.ink, fontWeight: 500 }}>{student.parent}</div>
              <div style={{ fontFamily: TL_FONTS.mono, fontSize: 11, color: c.ink3, marginTop: 2 }}>{student.parentPhone}</div>
            </div>
          </div>
        </div>
      </div>

      <button onClick={onDone} style={{
        padding: '16px', background: c.ink, color: c.bg, border: 'none', cursor: 'pointer',
        fontFamily: TL_FONTS.mono, fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      }}>
        {t('saved.next')} <TLIcon name="arrowR" size={14} color={c.bg} />
      </button>
    </div>
  );
}

// ── Schedule with bigger logo + lang toggle + per-lesson subject ──
function TPScheduleRich({ c, dark, onPickLesson, onLangToggle, onLogout }) {
  const days = [
    { d: 26, dow: 'SUN', off: true  },
    { d: 27, dow: 'MON', off: true  },
    { d: 28, dow: 'TUE', today: true },
    { d: 29, dow: 'WED' },
    { d: 30, dow: 'THU' },
    { d:  1, dow: 'FRI', month: 'MAY' },
    { d:  2, dow: 'SAT' },
  ];
  const [selDay, setSelDay] = tlUseState(28);
  const lang = tlLang();
  const teacher = TL_TEACHERS[0];
  const done = TL_SCHEDULE_TODAY.filter(l => l.status === 'completed').length;
  const togo = TL_SCHEDULE_TODAY.length - done;

  return (
    <div style={{ background: c.bg, minHeight: '100%', color: c.ink }}>
      {/* header — bigger logo */}
      <div style={{ padding: '8px 24px 16px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 18 }}>
          <TLLogo height={56} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <button onClick={onLangToggle} style={{
              background: 'transparent', border: `1px solid ${c.line}`,
              padding: '6px 10px', cursor: 'pointer',
              fontFamily: TL_FONTS.mono, fontSize: 10, letterSpacing: '0.08em',
              color: c.ink2,
            }}>{t('lang.toggle')}</button>
            <button onClick={onLogout} style={{
              background: 'transparent', border: 'none', padding: 6, cursor: 'pointer',
              color: c.ink3,
            }}>
              <TLIcon name="user" size={18} color={c.ink3} />
            </button>
          </div>
        </div>

        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          fontFamily: TL_FONTS.mono, fontSize: 10, color: c.ink3,
          letterSpacing: '0.1em', textTransform: 'uppercase', marginBottom: 16,
        }}>
          <span>{lang === 'zh' ? teacher.studioZh : teacher.studio}</span>
          <span style={{ width: 1, height: 10, background: c.line }} />
          <span>{lang === 'zh' ? teacher.nameZh : teacher.name}</span>
          <span style={{ width: 1, height: 10, background: c.line }} />
          <span>{(lang === 'zh' ? teacher.instrumentsZh : teacher.instruments).join(' · ')}</span>
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18 }}>
          <div>
            <TLLabel color={c.ink3}>{lang === 'zh' ? '星期二 · 四月' : 'Tuesday · April'}</TLLabel>
            <h1 style={{
              fontFamily: TL_FONTS.serif, fontWeight: 500, fontSize: 40,
              lineHeight: 1, margin: '6px 0 0', letterSpacing: '-0.02em',
            }}>{t('sched.today')}</h1>
          </div>
          <div style={{
            padding: '4px 8px', background: c.accent, color: c.accentInk,
            fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.1em', textTransform: 'uppercase', fontWeight: 600,
          }}>{t('role.teacher')}</div>
        </div>

        {/* date strip */}
        <div style={{ display: 'flex', gap: 4, margin: '0 -4px' }}>
          {days.map(day => {
            const sel = selDay === day.d;
            const dowKey = 'dow.' + day.dow;
            return (
              <button
                key={day.dow + day.d}
                onClick={() => setSelDay(day.d)}
                style={{
                  flex: 1, padding: '10px 0', border: 'none',
                  background: sel ? c.ink : 'transparent',
                  color: sel ? c.bg : (day.off ? c.muted : c.ink),
                  fontFamily: TL_FONTS.sans, cursor: 'pointer',
                  display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                  borderRadius: 0,
                }}
              >
                <span style={{ fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.1em' }}>{t(dowKey)}</span>
                <span style={{ fontFamily: TL_FONTS.serif, fontSize: 22, fontWeight: 500, lineHeight: 1 }}>{day.d}</span>
                {day.today && !sel && <span style={{ width: 4, height: 4, borderRadius: '50%', background: c.accent, marginTop: 2 }} />}
                {!day.today && <span style={{ width: 4, height: 4, marginTop: 2 }} />}
              </button>
            );
          })}
        </div>
      </div>

      {/* count */}
      <div style={{ padding: '20px 24px 8px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <TLLabel color={c.ink3}>{t('sched.summary', { n: TL_SCHEDULE_TODAY.length, done, todo: togo })}</TLLabel>
        <TLLabel color={c.accent}>{t('sched.live')}</TLLabel>
      </div>

      {/* lessons */}
      <div>
        {TL_SCHEDULE_TODAY.map((lesson, i) => {
          const student = TL_STUDENTS.find(s => s.id === lesson.studentId);
          const isNext = lesson.status === 'pending' && !TL_SCHEDULE_TODAY.slice(0, i).some(l => l.status === 'pending');
          return (
            <button
              key={lesson.id}
              onClick={() => onPickLesson(lesson)}
              style={{
                width: '100%', display: 'flex', gap: 16, alignItems: 'stretch',
                padding: '18px 24px', background: isNext ? c.surface : 'transparent',
                border: 'none', borderTop: `1px solid ${c.line}`,
                borderBottom: i === TL_SCHEDULE_TODAY.length - 1 ? `1px solid ${c.line}` : 'none',
                cursor: 'pointer', textAlign: 'left', color: c.ink,
                position: 'relative',
              }}
            >
              {isNext && <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 3, background: c.accent }} />}
              <div style={{ width: 56, flexShrink: 0 }}>
                <div style={{ fontFamily: TL_FONTS.serif, fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em' }}>{lesson.time}</div>
                <div style={{ fontFamily: TL_FONTS.mono, fontSize: 10, color: c.ink3, marginTop: 2 }}>
                  {lesson.duration} {t('sched.minShort')}
                </div>
              </div>
              <TLAvatar student={student} size={44} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontFamily: TL_FONTS.sans, fontSize: 16, fontWeight: 500, marginBottom: 2 }}>{student.name}</div>
                <div style={{ fontFamily: TL_FONTS.sans, fontSize: 13, color: c.ink3 }}>
                  {lang === 'zh' ? lesson.subjectZh : lesson.subject} · {student.level}
                </div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6, justifyContent: 'center' }}>
                <TLStatusPillI18n status={lesson.status} c={c} />
                {isNext && <TLIcon name="chevR" size={16} color={c.ink} />}
              </div>
            </button>
          );
        })}
      </div>

      <div style={{ padding: '32px 24px 100px', textAlign: 'center' }}>
        <TLLabel color={c.muted}>{t('sched.endOfDay')}</TLLabel>
      </div>
    </div>
  );
}

function TLStatusPillI18n({ status, c }) {
  const map = {
    completed: { key: 'status.completed', bg: c.ink, fg: c.bg },
    pending:   { key: 'status.pending',   bg: 'transparent', fg: c.ink, border: c.line },
    upcoming:  { key: 'status.upcoming',  bg: 'transparent', fg: c.ink3, border: c.line },
    absent:    { key: 'status.absent',    bg: 'transparent', fg: '#C0392B', border: '#C0392B' },
  };
  const s = map[status];
  return (
    <span style={{
      fontFamily: TL_FONTS.mono, fontSize: 9, letterSpacing: '0.1em',
      textTransform: 'uppercase', padding: '4px 8px',
      background: s.bg, color: s.fg,
      border: s.border ? `1px solid ${s.border}` : 'none',
    }}>{t(s.key)}</span>
  );
}

// ── Container — login → schedule → lesson → saved ─────────────────
function TeacherApp({ dark, onLangChange }) {
  const c = TL_TOKENS[dark ? 'dark' : 'light'];
  const [screen, setScreen] = tlUseState('login');
  const [activeLesson, setActiveLesson] = tlUseState(null);
  const [, force] = tlUseState(0);

  const lang = tlLang();
  const toggleLang = () => {
    window.__tlLang = (window.__tlLang === 'zh' ? 'en' : 'zh');
    if (onLangChange) onLangChange(window.__tlLang);
    force(x => x + 1);
  };

  return (
    <div style={{ height: '100%', position: 'relative', background: c.bg, overflow: 'hidden' }}>
      <div style={{ height: '100%', overflow: 'auto' }} className="tl-noscroll">
        {screen === 'login' && (
          <TPLogin c={c} dark={dark} lang={lang}
            onLogin={() => setScreen('schedule')}
            onLangToggle={toggleLang}
          />
        )}
        {screen === 'schedule' && (
          <TPScheduleRich c={c} dark={dark}
            onPickLesson={(l) => { setActiveLesson(l); setScreen('lesson'); }}
            onLangToggle={toggleLang}
            onLogout={() => setScreen('login')}
          />
        )}
        {screen === 'lesson' && (
          <TPLessonRich c={c} dark={dark} lesson={activeLesson}
            onBack={() => setScreen('schedule')}
            onSave={() => setScreen('saved')}
          />
        )}
        {screen === 'saved' && (
          <TPSavedRich c={c} lesson={activeLesson} onDone={() => setScreen('schedule')} />
        )}
      </div>
    </div>
  );
}

Object.assign(window, {
  TeacherApp, TPLogin, TPScheduleRich, TPLessonRich, TPSavedRich,
});
