// TeacherPortal — mobile flow for logging lesson progress.
// Screens: schedule (date + timeslots) -> lesson detail (attendance + handbook entry) -> saved.
// All state is internal React state. No back navigation needed beyond `back` callbacks.

const { useState, useEffect, useRef } = React;

// ── shared atoms ─────────────────────────────────────────────────
function TLAvatar({ student, size = 36 }) {
  const initials = student.name.split(' ').map(n => n[0]).slice(0, 2).join('');
  return (
    <div style={{
      width: size, height: size, borderRadius: 0,
      background: student.avatar,
      color: '#15140F',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontFamily: TL_FONTS.serif, fontSize: size * 0.42, fontWeight: 500,
      letterSpacing: '0.02em',
      flexShrink: 0,
    }}>{initials}</div>
  );
}

function TLLabel({ children, color, style }) {
  return (
    <div style={{
      fontFamily: TL_FONTS.mono, fontSize: 10, fontWeight: 500,
      letterSpacing: '0.12em', textTransform: 'uppercase',
      color, ...style,
    }}>{children}</div>
  );
}

function TLDivider({ c }) {
  return <div style={{ height: 1, background: c.line, width: '100%' }} />;
}

function TLStatusPill({ status, c }) {
  const map = {
    completed: { label: 'Logged',     bg: c.ink, fg: c.bg },
    pending:   { label: 'Pending',    bg: 'transparent', fg: c.ink, border: c.line },
    upcoming:  { label: 'Upcoming',   bg: 'transparent', fg: c.ink3, border: c.line },
    absent:    { label: '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',
    }}>{s.label}</span>
  );
}

// ── Screen 1 — Schedule (date + lesson list) ───────────────────────
function TPSchedule({ c, dark, onPickLesson }) {
  // Build a strip of 7 days centered on today (Apr 28)
  const days = [
    { d: 26, dow: 'SUN', off: true,  full: 'Sun, Apr 26' },
    { d: 27, dow: 'MON', off: true,  full: 'Mon, Apr 27' },
    { d: 28, dow: 'TUE', today: true, full: 'Tue, Apr 28' },
    { d: 29, dow: 'WED',              full: 'Wed, Apr 29' },
    { d: 30, dow: 'THU',              full: 'Thu, Apr 30' },
    { d:  1, dow: 'FRI', month: 'MAY',full: 'Fri, May 1'  },
    { d:  2, dow: 'SAT',              full: 'Sat, May 2'  },
  ];
  const [selDay, setSelDay] = useState(28);

  return (
    <div style={{ background: c.bg, minHeight: '100%', color: c.ink }}>
      {/* header */}
      <div style={{ padding: '8px 24px 16px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <TLLogo height={36} />
          <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ fontFamily: TL_FONTS.mono, fontSize: 10, color: c.ink3, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Studio 4</span>
            <span style={{ width: 1, height: 12, background: c.line }} />
            <span style={{ fontFamily: TL_FONTS.mono, fontSize: 10, color: c.ink3, letterSpacing: '0.1em', textTransform: 'uppercase' }}>Ms. Chen</span>
          </div>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 18 }}>
          <div>
            <TLLabel color={c.ink3}>Tuesday · April</TLLabel>
            <h1 style={{
              fontFamily: TL_FONTS.serif, fontWeight: 500, fontSize: 40,
              lineHeight: 1, margin: '6px 0 0', letterSpacing: '-0.02em',
            }}>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,
          }}>Teacher</div>
        </div>

        {/* date strip */}
        <div style={{ display: 'flex', gap: 4, margin: '0 -4px' }}>
          {days.map(day => {
            const sel = selDay === day.d;
            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' }}>{day.dow}</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}>6 lessons · 2 logged · 4 to go</TLLabel>
        <TLLabel color={c.accent}>● 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} MIN</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 }}>{student.instrument} · {student.level}</div>
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 6, justifyContent: 'center' }}>
                <TLStatusPill 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}>End of schedule</TLLabel>
      </div>
    </div>
  );
}

// ── Screen 2 — Lesson detail (attendance + handbook) ───────────────
function TPLesson({ c, dark, lesson, onBack, onSave }) {
  const student = TL_STUDENTS.find(s => s.id === lesson.studentId);
  const [attended, setAttended] = useState(true);
  const [showPrev, setShowPrev] = useState(false);
  const [pieces, setPieces] = useState([
    { name: 'Burgmüller — Arabesque, Op.100 No.2', tag: 'Polishing' },
    { name: 'Bach — Minuet in G major', tag: 'Memorising' },
  ]);
  const [technique, setTechnique] = useState('');
  const [homework, setHomework] = useState('');
  const [remark, setRemark] = useState('');

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

  return (
    <div style={{ background: c.bg, minHeight: '100%', color: c.ink, paddingBottom: 120 }}>
      {/* 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} /> Schedule
        </button>
        <TLLabel color={c.ink3}>Lesson · {lesson.time} · {lesson.duration} min</TLLabel>
        <div style={{ display: 'flex', gap: 14, marginTop: 12, alignItems: 'center' }}>
          <TLAvatar student={student} size={56} />
          <div>
            <h2 style={{
              fontFamily: TL_FONTS.serif, fontWeight: 500, fontSize: 28,
              lineHeight: 1.05, margin: 0, letterSpacing: '-0.02em',
            }}>{student.name}</h2>
            <div style={{ fontFamily: TL_FONTS.sans, fontSize: 13, color: c.ink3, marginTop: 4 }}>
              {student.instrument} · {student.level} · Age {student.age}
            </div>
          </div>
        </div>
      </div>

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

      {/* Previous remark — collapsible */}
      <Section c={c} num="02" label="From last lesson">
        <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 }}>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 }}>Homework set</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 }}>Remark</TLLabel>
            <div style={{ fontFamily: TL_FONTS.serif, fontSize: 15, fontStyle: 'italic', color: c.ink, lineHeight: 1.45 }}>
              "{lastEntry.remark}"
            </div>
          </div>
        )}
      </Section>

      {attended && (
        <>
          {/* Pieces */}
          <Section c={c} num="03" label="Pieces practiced">
            {pieces.map((p, i) => (
              <PieceRow 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: '', tag: 'New' }])} 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} /> Add piece
            </button>
          </Section>

          {/* Technique */}
          <Section c={c} num="04" label="Technique notes">
            <TLTextarea c={c} value={technique} onChange={setTechnique}
              placeholder="Scales, posture, exercises. What did we work on technically?" rows={3} />
          </Section>

          {/* Homework */}
          <Section c={c} num="05" label="Homework for next week">
            <TLTextarea c={c} value={homework} onChange={setHomework}
              placeholder="What should they practice? Be specific — tempo, bars, hands." rows={3} />
          </Section>

          {/* Remark */}
          <Section c={c} num="06" label="Remark for parent">
            <TLTextarea c={c} value={remark} onChange={setRemark}
              placeholder="A warm, encouraging note for Sophie's parent. They'll see this on WhatsApp." rows={4} />
            <div style={{ display: 'flex', gap: 8, marginTop: 10 }}>
              <AttachBtn c={c} icon="mic" label="Audio" />
              <AttachBtn c={c} icon="camera" label="Photo" />
              <AttachBtn c={c} icon="paperclip" label="File" />
            </div>
          </Section>
        </>
      )}

      {!attended && (
        <Section c={c} num="03" label="Reason (optional)">
          <TLTextarea c={c} value={remark} onChange={setRemark}
            placeholder="Sick, family event, etc. The parent will get a gentle WhatsApp note." rows={3} />
        </Section>
      )}

      {/* sticky save */}
      <div style={{
        position: 'absolute', bottom: 0, left: 0, right: 0,
        padding: '14px 20px 28px', background: c.bg,
        borderTop: `1px solid ${c.line}`,
        display: 'flex', gap: 10,
      }}>
        <button onClick={onBack} style={{
          padding: '14px 18px', background: 'transparent', color: c.ink,
          border: `1px solid ${c.line}`, cursor: 'pointer',
          fontFamily: TL_FONTS.mono, fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase',
        }}>Save draft</button>
        <button onClick={() => onSave({ attended, pieces, technique, homework, remark })} style={{
          flex: 1, padding: '14px', 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} /> Save & notify parent
        </button>
      </div>
    </div>
  );
}

function Section({ c, num, label, children }) {
  return (
    <div style={{ padding: '24px 24px 8px', borderTop: `1px solid ${c.line2}` }}>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 10, marginBottom: 14 }}>
        <span style={{
          fontFamily: TL_FONTS.mono, fontSize: 10, color: c.muted,
          letterSpacing: '0.1em',
        }}>{num}</span>
        <h3 style={{
          fontFamily: TL_FONTS.serif, fontSize: 18, fontWeight: 500,
          margin: 0, color: c.ink, letterSpacing: '-0.01em',
        }}>{label}</h3>
      </div>
      {children}
    </div>
  );
}

function AttendBtn({ c, active, onClick, icon, label }) {
  const isAbsent = icon === 'x';
  return (
    <button onClick={onClick} style={{
      padding: '16px', cursor: 'pointer',
      background: active ? (isAbsent ? '#C0392B' : c.ink) : 'transparent',
      color: active ? (isAbsent ? '#FFFFFF' : c.bg) : c.ink2,
      border: `1px solid ${active ? 'transparent' : c.line}`,
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
      fontFamily: TL_FONTS.sans, fontSize: 14, fontWeight: 500,
    }}>
      <TLIcon name={icon} size={16} color={active ? (isAbsent ? '#FFFFFF' : c.bg) : c.ink2} />
      {label}
    </button>
  );
}

function PieceRow({ c, piece, onChange, onRemove }) {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8,
      padding: '12px 14px', background: c.surface, border: `1px solid ${c.line}`,
    }}>
      <div style={{ width: 4, height: 28, background: c.ink, flexShrink: 0 }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <input
          value={piece.name}
          onChange={e => onChange({ ...piece, name: e.target.value })}
          placeholder="Piece name"
          style={{
            width: '100%', border: 'none', background: 'transparent', padding: 0,
            fontFamily: TL_FONTS.sans, fontSize: 14, color: c.ink,
            outline: 'none',
          }}
        />
        <div style={{ fontFamily: TL_FONTS.mono, fontSize: 10, color: c.ink3, marginTop: 2, letterSpacing: '0.06em' }}>
          {piece.tag.toUpperCase()}
        </div>
      </div>
      <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>
  );
}

function TLTextarea({ c, value, onChange, placeholder, rows = 3 }) {
  return (
    <textarea
      value={value}
      onChange={e => onChange(e.target.value)}
      placeholder={placeholder}
      rows={rows}
      style={{
        width: '100%', padding: '14px 16px', boxSizing: 'border-box',
        fontFamily: TL_FONTS.sans, fontSize: 14, color: c.ink, lineHeight: 1.5,
        background: c.surface, border: `1px solid ${c.line}`,
        outline: 'none', resize: 'none',
      }}
    />
  );
}

function AttachBtn({ c, icon, label }) {
  return (
    <button style={{
      flex: 1, padding: '10px', background: 'transparent',
      border: `1px solid ${c.line}`, cursor: 'pointer',
      display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6,
      color: c.ink2, fontFamily: TL_FONTS.mono, fontSize: 10,
      letterSpacing: '0.1em', textTransform: 'uppercase',
    }}>
      <TLIcon name={icon} size={13} color={c.ink2} />
      {label}
    </button>
  );
}

// ── Screen 3 — Saved confirmation ──────────────────────────────────
function TPSaved({ c, lesson, onDone }) {
  const student = TL_STUDENTS.find(s => s.id === lesson.studentId);
  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}>Lesson logged · 14:23</TLLabel>
        <h1 style={{
          fontFamily: TL_FONTS.serif, fontSize: 36, fontWeight: 500,
          lineHeight: 1.05, margin: '10px 0 16px', letterSpacing: '-0.02em',
        }}>Handbook saved for {student.name.split(' ')[0]}.</h1>
        <p style={{
          fontFamily: TL_FONTS.sans, fontSize: 15, color: c.ink2, lineHeight: 1.55, margin: 0, maxWidth: 320,
        }}>
          {student.parent} will receive the summary on WhatsApp shortly. They can tap the link to read your full remark and listen to the audio.
        </p>

        <div style={{ marginTop: 32, padding: '18px 20px', background: c.surface, border: `1px solid ${c.line}` }}>
          <TLLabel color={c.ink3} style={{ marginBottom: 10 }}>Sent to</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,
      }}>
        Next lesson <TLIcon name="arrowR" size={14} color={c.bg} />
      </button>
    </div>
  );
}

// ── Container ──────────────────────────────────────────────────────
function TeacherPortal({ dark }) {
  const c = TL_TOKENS[dark ? 'dark' : 'light'];
  const [screen, setScreen] = useState('schedule'); // schedule | lesson | saved
  const [activeLesson, setActiveLesson] = useState(null);

  return (
    <div style={{ height: '100%', position: 'relative', background: c.bg, overflow: 'hidden' }}>
      <div style={{ height: '100%', overflow: 'auto' }}>
        {screen === 'schedule' && (
          <TPSchedule c={c} dark={dark} onPickLesson={(l) => { setActiveLesson(l); setScreen('lesson'); }} />
        )}
        {screen === 'lesson' && (
          <TPLesson c={c} dark={dark} lesson={activeLesson}
            onBack={() => setScreen('schedule')}
            onSave={() => setScreen('saved')}
          />
        )}
        {screen === 'saved' && (
          <TPSaved c={c} lesson={activeLesson} onDone={() => setScreen('schedule')} />
        )}
      </div>
    </div>
  );
}

Object.assign(window, { TeacherPortal });
