// Teacher subject/exam/student pages

const TeacherSubjects = ({ onNav }) => {
  const [selected, setSelected] = React.useState(0);
  const subjects = [
    {
      code: 'IT202', name: 'Cơ sở dữ liệu', students: 48, questions: 312,
      progress: 68, nextClass: 'Thứ 3, 14:00 · Phòng A305',
      stage: 'Đang giảng dạy',
      chapters: [
        { n: '01', t: 'Giới thiệu CSDL', done: true, dur: '45 phút' },
        { n: '02', t: 'Mô hình ER', done: true, dur: '90 phút' },
        { n: '03', t: 'SQL cơ bản', done: true, dur: '2 giờ' },
        { n: '04', t: 'JOIN và Subquery', done: false, dur: '2 giờ', current: true },
        { n: '05', t: 'Chuẩn hoá', done: false, dur: '90 phút' },
        { n: '06', t: 'Transaction & ACID', done: false, dur: '90 phút' },
        { n: '07', t: 'View & Index', done: false, dur: '60 phút' },
        { n: '08', t: 'Dự án cuối kỳ', done: false, dur: '3 giờ' },
      ],
      stats: { attend: 93, homework: 87, midterm: 7.8 },
    },
    {
      code: 'IT301', name: 'Lập trình hướng đối tượng', students: 52, questions: 201,
      progress: 45, nextClass: 'Thứ 5, 09:30 · Phòng B201',
      stage: 'Đang giảng dạy',
      chapters: [
        { n: '01', t: 'Tổng quan OOP', done: true, dur: '60 phút' },
        { n: '02', t: 'Class & Object', done: true, dur: '90 phút' },
        { n: '03', t: 'Kế thừa', done: false, dur: '90 phút', current: true },
        { n: '04', t: 'Đa hình', done: false, dur: '90 phút' },
        { n: '05', t: 'Interface & Abstract', done: false, dur: '60 phút' },
      ],
      stats: { attend: 88, homework: 82, midterm: 7.2 },
    },
    {
      code: 'IT303', name: 'Mạng máy tính', students: 42, questions: 174,
      progress: 12, nextClass: 'Thứ 2, 07:00 · Phòng C102',
      stage: 'Chuẩn bị',
      chapters: [
        { n: '01', t: 'Tổng quan mạng', done: true, dur: '60 phút' },
        { n: '02', t: 'Mô hình OSI & TCP/IP', done: false, dur: '90 phút', current: true },
        { n: '03', t: 'Địa chỉ IP', done: false, dur: '90 phút' },
        { n: '04', t: 'Định tuyến', done: false, dur: '2 giờ' },
      ],
      stats: { attend: 90, homework: null, midterm: null },
    },
  ];
  const cur = subjects[selected];

  return (
    <>
      <Topbar title="Môn phụ trách" breadcrumb={['Giảng dạy']}>
        <button className="btn btn-ghost btn-sm"><Icon name="download" size={13} /> Xuất danh sách</button>
        <button className="btn btn-primary btn-sm"><Icon name="plus" size={13} /> Tạo môn mới</button>
      </Topbar>
      <div className="page">
        <div style={{ display: 'grid', gridTemplateColumns: '340px 1fr', gap: 18, alignItems: 'start' }}>
          {/* Subject list */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {subjects.map((s, i) => (
              <button key={s.code} onClick={() => setSelected(i)}
                className="card"
                style={{
                  padding: 16, textAlign: 'left', cursor: 'pointer',
                  border: selected === i ? '1.5px solid var(--ink)' : '1px solid var(--line)',
                  background: selected === i ? 'var(--card)' : 'var(--card)',
                  boxShadow: selected === i ? '0 4px 18px rgba(0,0,0,0.06)' : 'none',
                  transition: 'all 0.15s',
                }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
                  <div style={{ width: 42, height: 42, borderRadius: 10, background: 'var(--accent-soft)', color: 'var(--accent-ink)', display: 'grid', placeItems: 'center', fontFamily: 'var(--serif)', fontSize: 15, fontWeight: 500 }}>
                    {s.code.slice(0, 2)}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 2 }}>{s.name}</div>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{s.code}</div>
                  </div>
                  <span className={`chip ${s.stage === 'Đang giảng dạy' ? 'chip-green' : 'chip-soft'}`} style={{ fontSize: 10 }}>{s.stage}</span>
                </div>
                <div style={{ display: 'flex', gap: 12, fontSize: 11.5, color: 'var(--muted)', marginBottom: 10 }}>
                  <span><Icon name="users" size={11} /> {s.students} HV</span>
                  <span><Icon name="library" size={11} /> {s.questions} câu</span>
                </div>
                <div style={{ height: 4, background: 'var(--bg-2)', borderRadius: 999, overflow: 'hidden' }}>
                  <div style={{ width: `${s.progress}%`, height: '100%', background: 'var(--ink)' }}/>
                </div>
                <div style={{ fontSize: 10.5, color: 'var(--muted)', marginTop: 6, fontFamily: 'var(--mono)' }}>Tiến độ {s.progress}%</div>
              </button>
            ))}
          </div>

          {/* Subject detail */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <div className="card" style={{ padding: 26 }}>
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 18, marginBottom: 22 }}>
                <div style={{ width: 64, height: 64, borderRadius: 14, background: 'var(--accent)', color: '#fff', display: 'grid', placeItems: 'center', fontFamily: 'var(--serif)', fontSize: 22 }}>
                  {cur.code.slice(0, 2)}
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
                    <div className="mono" style={{ fontSize: 12, color: 'var(--muted)' }}>{cur.code}</div>
                    <span className="chip chip-soft" style={{ fontSize: 10 }}>Học kỳ 2 · 2025–2026</span>
                  </div>
                  <div className="serif" style={{ fontSize: 26, marginBottom: 6 }}>{cur.name}</div>
                  <div style={{ fontSize: 13, color: 'var(--muted)' }}>
                    <Icon name="clock" size={12} /> Lớp kế tiếp: <strong style={{ color: 'var(--ink-2)' }}>{cur.nextClass}</strong>
                  </div>
                </div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <button className="btn btn-ghost btn-sm"><Icon name="edit" size={13} /> Chỉnh sửa</button>
                  <button className="btn btn-primary btn-sm"><Icon name="play" size={13} /> Vào lớp</button>
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
                <MiniStat label="Học viên" value={cur.students} icon="users" />
                <MiniStat label="Chuyên cần" value={cur.stats.attend} unit="%" icon="checkCircle" />
                <MiniStat label="BT nộp đúng hạn" value={cur.stats.homework ?? '—'} unit={cur.stats.homework ? '%' : ''} icon="clipboard" />
                <MiniStat label="Điểm giữa kỳ" value={cur.stats.midterm ?? 'Chưa thi'} unit={cur.stats.midterm ? '/10' : ''} icon="award" />
              </div>
            </div>

            <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 18 }}>
              <div className="card" style={{ padding: 22 }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
                  <div className="serif" style={{ fontSize: 18 }}>Chương trình môn học</div>
                  <button className="btn btn-ghost btn-sm"><Icon name="plus" size={12} /> Thêm chương</button>
                </div>
                {cur.chapters.map((c, i) => (
                  <div key={i} style={{ display: 'flex', gap: 12, padding: '12px 0', borderBottom: i < cur.chapters.length - 1 ? '1px solid var(--line)' : 'none', alignItems: 'center' }}>
                    <div style={{
                      width: 30, height: 30, borderRadius: 8,
                      background: c.done ? 'var(--green)' : c.current ? 'var(--accent)' : 'var(--bg-2)',
                      color: c.done || c.current ? '#fff' : 'var(--muted)',
                      display: 'grid', placeItems: 'center', fontSize: 11, fontWeight: 600, fontFamily: 'var(--mono)', flexShrink: 0,
                    }}>
                      {c.done ? <Icon name="check" size={14} /> : c.n}
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13.5, fontWeight: c.current ? 600 : 500 }}>{c.t}</div>
                      <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{c.dur} {c.current && <span style={{ color: 'var(--accent-ink)', fontWeight: 600 }}>· Đang dạy</span>}</div>
                    </div>
                    <button className="btn btn-ghost btn-sm" style={{ padding: 6 }}><Icon name="more" size={13} /></button>
                  </div>
                ))}
              </div>

              <div className="card" style={{ padding: 22 }}>
                <div className="serif" style={{ fontSize: 18, marginBottom: 14 }}>Tài liệu & Hoạt động</div>
                {[
                  { ic: 'video', t: 'Video bài giảng', n: 12, c: 'var(--accent)' },
                  { ic: 'file', t: 'Tài liệu PDF', n: 18, c: 'var(--ink)' },
                  { ic: 'clipboard', t: 'Bài tập về nhà', n: 8, c: 'var(--gold)' },
                  { ic: 'library', t: 'Bài kiểm tra', n: 3, c: 'var(--green)' },
                  { ic: 'users', t: 'Nhóm thảo luận', n: 6, c: 'var(--rose)' },
                ].map((r, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 0', borderBottom: i < 4 ? '1px solid var(--line)' : 'none' }}>
                    <div style={{ width: 32, height: 32, borderRadius: 8, background: 'var(--bg-2)', color: r.c, display: 'grid', placeItems: 'center', flexShrink: 0 }}>
                      <Icon name={r.ic} size={14} />
                    </div>
                    <div style={{ flex: 1, fontSize: 13 }}>{r.t}</div>
                    <span className="mono" style={{ fontSize: 12, color: 'var(--muted)' }}>{r.n}</span>
                    <Icon name="chevronRight" size={13} style={{ color: 'var(--muted)' }}/>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

const MiniStat = ({ label, value, unit, icon }) => (
  <div style={{ padding: '12px 14px', background: 'var(--bg-2)', borderRadius: 10 }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6, fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', letterSpacing: '0.06em', fontWeight: 600 }}>
      <Icon name={icon} size={11} /> {label}
    </div>
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 3 }}>
      <div className="serif" style={{ fontSize: 22 }}>{value}</div>
      {unit && <div style={{ fontSize: 12, color: 'var(--muted)' }}>{unit}</div>}
    </div>
  </div>
);

// ============================================================================

const TeacherExams = () => {
  const [tab, setTab] = React.useState('schedule');
  const exams = [
    {
      id: 'EX-2026-042', title: 'Kiểm tra giữa kỳ · Cơ sở dữ liệu',
      subject: 'IT202', date: '25/04/2026', time: '09:00–10:30',
      duration: 90, questions: 40, students: 48, status: 'scheduled',
      room: 'Online', type: 'Giữa kỳ',
    },
    {
      id: 'EX-2026-041', title: 'Kiểm tra 15 phút · JOIN nâng cao',
      subject: 'IT202', date: '22/04/2026', time: '14:00–14:15',
      duration: 15, questions: 10, students: 48, status: 'scheduled',
      room: 'A305', type: 'Thường xuyên',
    },
    {
      id: 'EX-2026-038', title: 'Kiểm tra chương 2 · OOP',
      subject: 'IT301', date: '20/04/2026', time: '09:30–10:15',
      duration: 45, questions: 20, students: 52, status: 'active', submitted: 18,
      room: 'Online', type: 'Chương',
    },
    {
      id: 'EX-2026-035', title: 'Kiểm tra giữa kỳ · OOP',
      subject: 'IT301', date: '18/04/2026', time: '09:30–11:00',
      duration: 90, questions: 35, students: 52, status: 'graded', avgScore: 7.2, passed: 44,
      room: 'Online', type: 'Giữa kỳ',
    },
    {
      id: 'EX-2026-031', title: 'Kiểm tra đầu khoá · CSDL',
      subject: 'IT202', date: '10/04/2026', time: '09:00–09:30',
      duration: 30, questions: 15, students: 48, status: 'graded', avgScore: 6.5, passed: 38,
      room: 'Online', type: 'Đầu khoá',
    },
  ];
  const filters = {
    schedule: (e) => e.status === 'scheduled',
    active: (e) => e.status === 'active',
    graded: (e) => e.status === 'graded',
    all: () => true,
  };
  const filtered = exams.filter(filters[tab]);

  const statusBadge = (s) => ({
    scheduled: { label: 'Đã lên lịch', chip: 'chip-soft' },
    active: { label: 'Đang diễn ra', chip: 'chip-accent' },
    graded: { label: 'Đã chấm', chip: 'chip-green' },
  }[s]);

  return (
    <>
      <Topbar title="Đề thi & lịch thi" breadcrumb={['Giảng dạy']}>
        <button className="btn btn-ghost btn-sm"><Icon name="calendar" size={13} /> Xem lịch</button>
        <button className="btn btn-primary btn-sm"><Icon name="plus" size={13} /> Tạo đề thi</button>
      </Topbar>
      <div className="page">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 20 }}>
          <StatCard label="Kỳ thi sắp tới" value="2" sub="Gần nhất: 22/04" />
          <StatCard label="Đang diễn ra" value="1" sub="18 HV đã nộp" tone="accent"/>
          <StatCard label="Chờ chấm" value="12" sub="Tự luận IT301" />
          <StatCard label="Tỉ lệ đỗ TB" value="87" unit="%" sub="Học kỳ hiện tại" />
        </div>

        <div className="card" style={{ marginBottom: 18 }}>
          <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--line)', display: 'flex', gap: 4, alignItems: 'center' }}>
            {[
              { id: 'schedule', label: 'Sắp diễn ra', n: 2 },
              { id: 'active', label: 'Đang diễn ra', n: 1 },
              { id: 'graded', label: 'Đã hoàn thành', n: 2 },
              { id: 'all', label: 'Tất cả', n: exams.length },
            ].map(t => (
              <button key={t.id} onClick={() => setTab(t.id)} className="btn btn-sm" style={{
                padding: '7px 14px',
                background: tab === t.id ? 'var(--ink)' : 'transparent',
                color: tab === t.id ? '#fff' : 'var(--ink-2)',
                border: 'none',
              }}>
                {t.label} <span style={{ opacity: 0.6, marginLeft: 4 }}>{t.n}</span>
              </button>
            ))}
            <div style={{ flex: 1 }}/>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 12px', border: '1px solid var(--line-2)', borderRadius: 8 }}>
              <Icon name="search" size={13} style={{ color: 'var(--muted)' }}/>
              <input placeholder="Tìm đề thi..." style={{ border: 'none', outline: 'none', background: 'transparent', fontSize: 12.5, width: 160 }} />
            </div>
          </div>

          <div>
            {filtered.map((e, i) => {
              const b = statusBadge(e.status);
              return (
                <div key={e.id} style={{ padding: '18px 20px', borderBottom: i < filtered.length - 1 ? '1px solid var(--line)' : 'none', display: 'grid', gridTemplateColumns: '1fr 200px 140px 120px', gap: 18, alignItems: 'center' }}>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                      <span className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{e.id}</span>
                      <span className="chip chip-soft" style={{ fontSize: 10 }}>{e.subject}</span>
                      <span className="chip chip-soft" style={{ fontSize: 10 }}>{e.type}</span>
                      <span className={`chip ${b.chip}`} style={{ fontSize: 10 }}>{b.label}</span>
                    </div>
                    <div style={{ fontSize: 15, fontWeight: 600, marginBottom: 4 }}>{e.title}</div>
                    <div style={{ fontSize: 12, color: 'var(--muted)', display: 'flex', gap: 14 }}>
                      <span><Icon name="library" size={11} /> {e.questions} câu</span>
                      <span><Icon name="clock" size={11} /> {e.duration} phút</span>
                      <span><Icon name="users" size={11} /> {e.students} HV</span>
                      <span><Icon name="mapPin" size={11} /> {e.room}</span>
                    </div>
                  </div>

                  <div>
                    <div style={{ fontSize: 16, fontWeight: 600, fontFamily: 'var(--serif)' }}>{e.date}</div>
                    <div style={{ fontSize: 12, color: 'var(--muted)', fontFamily: 'var(--mono)' }}>{e.time}</div>
                  </div>

                  <div>
                    {e.status === 'scheduled' && (
                      <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>
                        <div style={{ color: 'var(--ink-2)', fontWeight: 600, fontSize: 13 }}>Chuẩn bị</div>
                        Gửi nhắc nhở
                      </div>
                    )}
                    {e.status === 'active' && (
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--accent-ink)' }}>{e.submitted}/{e.students} đã nộp</div>
                        <div style={{ height: 3, background: 'var(--bg-2)', borderRadius: 2, marginTop: 5, overflow: 'hidden' }}>
                          <div style={{ width: `${(e.submitted / e.students) * 100}%`, height: '100%', background: 'var(--accent)' }}/>
                        </div>
                      </div>
                    )}
                    {e.status === 'graded' && (
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 600 }}>TB: <span style={{ color: 'var(--green)' }}>{e.avgScore}</span>/10</div>
                        <div style={{ fontSize: 11, color: 'var(--muted)' }}>{e.passed}/{e.students} đỗ</div>
                      </div>
                    )}
                  </div>

                  <div style={{ display: 'flex', gap: 6, justifyContent: 'flex-end' }}>
                    {e.status === 'scheduled' && <button className="btn btn-ghost btn-sm"><Icon name="edit" size={12}/> Sửa</button>}
                    {e.status === 'active' && <button className="btn btn-primary btn-sm"><Icon name="eye" size={12}/> Giám sát</button>}
                    {e.status === 'graded' && <button className="btn btn-ghost btn-sm"><Icon name="chart" size={12}/> Kết quả</button>}
                    <button className="btn btn-ghost btn-sm" style={{ padding: 6 }}><Icon name="more" size={13}/></button>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Mini calendar */}
        <div className="card" style={{ padding: 22 }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
            <div className="serif" style={{ fontSize: 18 }}>Lịch tháng 4/2026</div>
            <div style={{ display: 'flex', gap: 4 }}>
              <button className="btn btn-ghost btn-sm" style={{ padding: 6 }}><Icon name="chevronLeft" size={13}/></button>
              <button className="btn btn-ghost btn-sm">Tháng 4</button>
              <button className="btn btn-ghost btn-sm" style={{ padding: 6 }}><Icon name="chevronRight" size={13}/></button>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 6 }}>
            {['CN','T2','T3','T4','T5','T6','T7'].map(d => (
              <div key={d} style={{ fontSize: 11, color: 'var(--muted)', textAlign: 'center', fontWeight: 600, letterSpacing: '0.06em', padding: 6 }}>{d}</div>
            ))}
            {Array.from({ length: 30 }, (_, i) => {
              const day = i + 1;
              const hasExam = [10, 18, 20, 22, 25].includes(day);
              const examStatus = { 10: 'graded', 18: 'graded', 20: 'active', 22: 'scheduled', 25: 'scheduled' }[day];
              const today = day === 22;
              return (
                <div key={i} style={{
                  aspectRatio: '1.15',
                  padding: 8,
                  background: today ? 'var(--ink)' : hasExam ? 'var(--bg-2)' : 'var(--card)',
                  color: today ? '#fff' : 'var(--ink)',
                  border: '1px solid ' + (today ? 'var(--ink)' : 'var(--line)'),
                  borderRadius: 8,
                  display: 'flex', flexDirection: 'column', justifyContent: 'space-between',
                  fontSize: 13, fontWeight: hasExam ? 600 : 400,
                }}>
                  <span>{day}</span>
                  {hasExam && (
                    <div style={{ display: 'flex', gap: 3 }}>
                      <div style={{
                        width: 6, height: 6, borderRadius: 999,
                        background: examStatus === 'graded' ? 'var(--green)' : examStatus === 'active' ? 'var(--accent)' : 'var(--gold)'
                      }}/>
                    </div>
                  )}
                </div>
              );
            })}
          </div>
          <div style={{ display: 'flex', gap: 16, marginTop: 14, fontSize: 11.5, color: 'var(--muted)' }}>
            <span><span style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--gold)', display: 'inline-block', marginRight: 5 }}/>Đã lên lịch</span>
            <span><span style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--accent)', display: 'inline-block', marginRight: 5 }}/>Đang diễn ra</span>
            <span><span style={{ width: 8, height: 8, borderRadius: 999, background: 'var(--green)', display: 'inline-block', marginRight: 5 }}/>Đã hoàn thành</span>
          </div>
        </div>
      </div>
    </>
  );
};

// ============================================================================

const TeacherStudents = () => {
  const [selectedSubject, setSelectedSubject] = React.useState('all');
  const [selectedStudent, setSelectedStudent] = React.useState(null);

  const students = [
    { id: 'SV20210142', name: 'Nguyễn Minh An', av: 'MA', subject: 'IT202', class: 'CĐ-CNTT22A', avg: 8.4, attend: 96, progress: 78, last: '2 giờ trước', status: 'good' },
    { id: 'SV20210158', name: 'Trần Hoàng Bảo', av: 'HB', subject: 'IT202', class: 'CĐ-CNTT22A', avg: 7.2, attend: 89, progress: 65, last: 'Hôm nay', status: 'good' },
    { id: 'SV20210163', name: 'Lê Thị Cẩm Ly', av: 'CL', subject: 'IT202', class: 'CĐ-CNTT22B', avg: 9.1, attend: 100, progress: 92, last: '30 phút trước', status: 'top' },
    { id: 'SV20210171', name: 'Phạm Đức Duy', av: 'DD', subject: 'IT301', class: 'CĐ-CNTT22A', avg: 5.8, attend: 72, progress: 42, last: '3 ngày trước', status: 'warn' },
    { id: 'SV20210184', name: 'Hoàng Quỳnh Giang', av: 'QG', subject: 'IT202', class: 'CĐ-CNTT22B', avg: 8.7, attend: 94, progress: 81, last: '1 giờ trước', status: 'good' },
    { id: 'SV20210192', name: 'Vũ Gia Huy', av: 'GH', subject: 'IT301', class: 'CĐ-CNTT22A', avg: 6.4, attend: 80, progress: 55, last: 'Hôm qua', status: 'good' },
    { id: 'SV20210201', name: 'Đặng Thu Hương', av: 'TH', subject: 'IT303', class: 'CĐ-CNTT22B', avg: 9.3, attend: 98, progress: 88, last: '15 phút trước', status: 'top' },
    { id: 'SV20210215', name: 'Bùi Văn Khánh', av: 'VK', subject: 'IT202', class: 'CĐ-CNTT22A', avg: 4.9, attend: 65, progress: 28, last: '5 ngày trước', status: 'risk' },
    { id: 'SV20210223', name: 'Ngô Thị Lan', av: 'TL', subject: 'IT301', class: 'CĐ-CNTT22B', avg: 7.8, attend: 92, progress: 70, last: '4 giờ trước', status: 'good' },
    { id: 'SV20210234', name: 'Lý Minh Nhật', av: 'MN', subject: 'IT303', class: 'CĐ-CNTT22A', avg: 8.1, attend: 88, progress: 75, last: 'Hôm nay', status: 'good' },
    { id: 'SV20210245', name: 'Trương Phương Oanh', av: 'PO', subject: 'IT202', class: 'CĐ-CNTT22B', avg: 7.5, attend: 91, progress: 68, last: '6 giờ trước', status: 'good' },
    { id: 'SV20210256', name: 'Đỗ Hữu Phong', av: 'HP', subject: 'IT301', class: 'CĐ-CNTT22A', avg: 5.2, attend: 70, progress: 38, last: '2 ngày trước', status: 'warn' },
  ];

  const filtered = selectedSubject === 'all' ? students : students.filter(s => s.subject === selectedSubject);
  const stats = {
    total: filtered.length,
    avgScore: (filtered.reduce((a, s) => a + s.avg, 0) / filtered.length).toFixed(1),
    avgAttend: Math.round(filtered.reduce((a, s) => a + s.attend, 0) / filtered.length),
    risk: filtered.filter(s => s.status === 'risk' || s.status === 'warn').length,
  };

  const statusTag = (s) => ({
    top: { label: 'Xuất sắc', color: 'var(--green)', bg: 'var(--green-soft)' },
    good: { label: 'Tốt', color: 'var(--ink-2)', bg: 'var(--bg-2)' },
    warn: { label: 'Cần chú ý', color: 'var(--gold-ink)', bg: 'var(--gold-soft)' },
    risk: { label: 'Nguy cơ trượt', color: 'var(--rose)', bg: 'var(--rose-soft)' },
  }[s]);

  if (selectedStudent) {
    const st = students.find(x => x.id === selectedStudent);
    const tag = statusTag(st.status);
    return (
      <>
        <Topbar title={st.name} breadcrumb={['Giảng dạy', 'Học viên']}>
          <button className="btn btn-ghost btn-sm" onClick={() => setSelectedStudent(null)}><Icon name="chevronLeft" size={13}/> Quay lại</button>
          <button className="btn btn-ghost btn-sm"><Icon name="send" size={13}/> Nhắn tin</button>
          <button className="btn btn-primary btn-sm"><Icon name="file" size={13}/> Xem hồ sơ đầy đủ</button>
        </Topbar>
        <div className="page">
          <div className="card" style={{ padding: 26, marginBottom: 18, display: 'flex', gap: 22, alignItems: 'center' }}>
            <div style={{ width: 80, height: 80, borderRadius: 999, background: 'var(--accent-soft)', color: 'var(--accent-ink)', display: 'grid', placeItems: 'center', fontFamily: 'var(--serif)', fontSize: 30 }}>{st.av}</div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 4 }}>
                <span className="mono" style={{ fontSize: 12, color: 'var(--muted)' }}>{st.id}</span>
                <span style={{ padding: '3px 9px', background: tag.bg, color: tag.color, fontSize: 11, fontWeight: 600, borderRadius: 5 }}>{tag.label}</span>
              </div>
              <div className="serif" style={{ fontSize: 28, marginBottom: 4 }}>{st.name}</div>
              <div style={{ fontSize: 13, color: 'var(--muted)' }}>{st.class} · {st.subject} · Hoạt động gần nhất: {st.last}</div>
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14, minWidth: 360 }}>
              <MiniStat label="Điểm TB" value={st.avg} unit="/10" icon="award" />
              <MiniStat label="Chuyên cần" value={st.attend} unit="%" icon="checkCircle" />
              <MiniStat label="Tiến độ" value={st.progress} unit="%" icon="trending" />
            </div>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 18 }}>
            <div className="card" style={{ padding: 22 }}>
              <div className="serif" style={{ fontSize: 18, marginBottom: 14 }}>Điểm các bài kiểm tra</div>
              {[
                { t: 'Kiểm tra đầu khoá', d: '10/04', s: 7.0, max: 10 },
                { t: 'Bài tập chương 1', d: '12/04', s: 8.5, max: 10 },
                { t: 'Kiểm tra 15 phút · SQL', d: '15/04', s: 9.0, max: 10 },
                { t: 'Bài tập chương 2', d: '17/04', s: 8.0, max: 10 },
                { t: 'Kiểm tra giữa kỳ · OOP', d: '18/04', s: 7.5, max: 10, pending: false },
              ].map((e, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 0', borderBottom: i < 4 ? '1px solid var(--line)' : 'none' }}>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13.5, fontWeight: 500 }}>{e.t}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{e.d}</div>
                  </div>
                  <div style={{ width: 120, height: 6, background: 'var(--bg-2)', borderRadius: 999, overflow: 'hidden' }}>
                    <div style={{ width: `${(e.s / e.max) * 100}%`, height: '100%', background: e.s >= 8 ? 'var(--green)' : e.s >= 5 ? 'var(--accent)' : 'var(--rose)' }}/>
                  </div>
                  <div className="mono" style={{ fontSize: 14, fontWeight: 600, width: 48, textAlign: 'right', color: e.s >= 8 ? 'var(--green)' : e.s >= 5 ? 'var(--ink)' : 'var(--rose)' }}>{e.s.toFixed(1)}</div>
                </div>
              ))}
            </div>

            <div className="card" style={{ padding: 22 }}>
              <div className="serif" style={{ fontSize: 18, marginBottom: 14 }}>Hoạt động gần đây</div>
              {[
                { ic: 'video', t: 'Xem video bài giảng', s: 'Chương 4 · JOIN nâng cao', time: '2 giờ trước' },
                { ic: 'clipboard', t: 'Nộp bài tập', s: 'Bài tập chương 4', time: '1 ngày trước' },
                { ic: 'send', t: 'Đặt câu hỏi', s: '"Thầy ơi khi nào dùng RIGHT JOIN?"', time: '2 ngày trước' },
                { ic: 'checkCircle', t: 'Làm xong kiểm tra 15 phút', s: '9.0/10 điểm', time: '5 ngày trước' },
              ].map((a, i) => (
                <div key={i} style={{ display: 'flex', gap: 10, padding: '11px 0', borderBottom: i < 3 ? '1px solid var(--line)' : 'none' }}>
                  <div style={{ width: 30, height: 30, borderRadius: 8, background: 'var(--bg-2)', display: 'grid', placeItems: 'center', flexShrink: 0 }}><Icon name={a.ic} size={13}/></div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{a.t}</div>
                    <div style={{ fontSize: 11.5, color: 'var(--muted)' }}>{a.s} · {a.time}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </>
    );
  }

  return (
    <>
      <Topbar title="Học viên" breadcrumb={['Giảng dạy']}>
        <button className="btn btn-ghost btn-sm"><Icon name="download" size={13}/> Xuất Excel</button>
        <button className="btn btn-primary btn-sm"><Icon name="send" size={13}/> Gửi thông báo</button>
      </Topbar>
      <div className="page">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 20 }}>
          <StatCard label="Tổng học viên" value={stats.total} sub={selectedSubject === 'all' ? 'Toàn bộ môn phụ trách' : `Môn ${selectedSubject}`} />
          <StatCard label="Điểm TB" value={stats.avgScore} unit="/10" sub="Học kỳ hiện tại" />
          <StatCard label="Chuyên cần TB" value={stats.avgAttend} unit="%" sub="Từ đầu khoá" />
          <StatCard label="Cần quan tâm" value={stats.risk} sub="HV có nguy cơ trượt" tone="rose" />
        </div>

        <div className="card">
          <div style={{ padding: 16, borderBottom: '1px solid var(--line)', display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '7px 12px', border: '1px solid var(--line-2)', borderRadius: 8, flex: 1, maxWidth: 320 }}>
              <Icon name="search" size={14} style={{ color: 'var(--muted)' }}/>
              <input placeholder="Tìm học viên, mã SV, lớp..." style={{ border: 'none', outline: 'none', background: 'transparent', flex: 1 }} />
            </div>
            <div style={{ display: 'flex', gap: 4, padding: 3, background: 'var(--bg-2)', borderRadius: 8 }}>
              {[{ v: 'all', l: 'Tất cả' }, { v: 'IT202', l: 'IT202' }, { v: 'IT301', l: 'IT301' }, { v: 'IT303', l: 'IT303' }].map(s => (
                <button key={s.v} onClick={() => setSelectedSubject(s.v)} className="btn btn-sm" style={{
                  padding: '5px 12px', border: 'none',
                  background: selectedSubject === s.v ? 'var(--card)' : 'transparent',
                  color: 'var(--ink)', fontWeight: selectedSubject === s.v ? 600 : 400,
                  boxShadow: selectedSubject === s.v ? '0 1px 3px rgba(0,0,0,0.08)' : 'none',
                }}>{s.l}</button>
              ))}
            </div>
            <button className="btn btn-ghost btn-sm"><Icon name="filter" size={13}/> Trạng thái</button>
            <button className="btn btn-ghost btn-sm"><Icon name="filter" size={13}/> Sắp xếp</button>
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: '1.8fr 100px 120px 100px 100px 110px 100px 48px', padding: '12px 16px', fontSize: 11, color: 'var(--muted)', textTransform: 'uppercase', fontWeight: 600, letterSpacing: '0.08em', borderBottom: '1px solid var(--line)' }}>
            <div>Học viên</div><div>Môn</div><div>Lớp</div><div>Điểm TB</div><div>Chuyên cần</div><div>Tiến độ</div><div>Trạng thái</div><div></div>
          </div>
          {filtered.map((s, i) => {
            const tag = statusTag(s.status);
            return (
              <div key={s.id} onClick={() => setSelectedStudent(s.id)} style={{ display: 'grid', gridTemplateColumns: '1.8fr 100px 120px 100px 100px 110px 100px 48px', padding: '14px 16px', borderBottom: i < filtered.length - 1 ? '1px solid var(--line)' : 'none', alignItems: 'center', fontSize: 13, cursor: 'pointer', transition: 'background 0.1s' }}
                onMouseEnter={e => e.currentTarget.style.background = 'var(--bg-2)'}
                onMouseLeave={e => e.currentTarget.style.background = 'transparent'}
              >
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, minWidth: 0 }}>
                  <div style={{ width: 34, height: 34, borderRadius: 999, background: 'var(--accent-soft)', color: 'var(--accent-ink)', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 600, flexShrink: 0 }}>{s.av}</div>
                  <div style={{ minWidth: 0 }}>
                    <div style={{ fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{s.name}</div>
                    <div className="mono" style={{ fontSize: 11, color: 'var(--muted)' }}>{s.id} · {s.last}</div>
                  </div>
                </div>
                <div><span className="chip chip-soft" style={{ fontSize: 10 }}>{s.subject}</span></div>
                <div style={{ fontSize: 12, color: 'var(--muted)' }}>{s.class}</div>
                <div className="mono" style={{ fontWeight: 600, color: s.avg >= 8 ? 'var(--green)' : s.avg >= 5 ? 'var(--ink)' : 'var(--rose)' }}>{s.avg.toFixed(1)}</div>
                <div style={{ fontSize: 12 }}>
                  <div style={{ fontWeight: 600, marginBottom: 3 }}>{s.attend}%</div>
                  <div style={{ height: 3, background: 'var(--bg-2)', borderRadius: 2, overflow: 'hidden' }}>
                    <div style={{ width: `${s.attend}%`, height: '100%', background: s.attend >= 85 ? 'var(--green)' : s.attend >= 70 ? 'var(--gold)' : 'var(--rose)' }}/>
                  </div>
                </div>
                <div>
                  <div style={{ height: 6, background: 'var(--bg-2)', borderRadius: 999, overflow: 'hidden' }}>
                    <div style={{ width: `${s.progress}%`, height: '100%', background: 'var(--ink)' }}/>
                  </div>
                  <div style={{ fontSize: 10.5, color: 'var(--muted)', marginTop: 3, fontFamily: 'var(--mono)' }}>{s.progress}%</div>
                </div>
                <div>
                  <span style={{ padding: '3px 8px', background: tag.bg, color: tag.color, fontSize: 10.5, fontWeight: 600, borderRadius: 4, whiteSpace: 'nowrap' }}>{tag.label}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'flex-end' }}>
                  <Icon name="chevronRight" size={14} style={{ color: 'var(--muted)' }}/>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
};

Object.assign(window, { TeacherSubjects, TeacherExams, TeacherStudents });
