// trainer-monitor.jsx — Trainee list (chat-list style with health context)
// Coach opens app → sees a list of every trainee, like a messaging inbox.
// Each row carries: name, latest message OR latest activity, progress this week,
// pending homework count, and time since last activity. Sortable by who needs
// attention most. No abstract "dashboard" — just people, in priority order.

function TrainerMonitor({ dark, openTrainee, go }) {
  const T = tokens(dark);
  const accent = '#FFD66B';
  const ledOk = '#41A55E';
  const ledWarn = '#FFB36B';
  const ledBad = '#E1573B';

  const [filter, setFilter] = React.useState('priority'); // priority | all | unread

  // ── Per-trainee row data — one row per person
  const ROWS = [
    {
      id:'t3', nick:'นิว', name:'ชนิกานต์ ภิรมย์', tone:'#FF8A6B',
      goal:'ลด 4 กก.',
      week:6, totalWeeks:12,
      progress:41, progressDelta:-18,
      tone_kind:'bad',
      lastActive:'4 วันก่อน',
      lastActiveBad:true,
      // last thing that happened — newest signal first
      lastEvent: { kind:'msg-them', text:'พอดีงานยุ่งมาก โทษทีค่ะ', time:'ศ. 14:22', unread:true },
      // homework that needs attention
      pending: [
        { kind:'workout', label:'Lower body', missed:true, when:'พฤ.' },
        { kind:'workout', label:'Cardio Z2', missed:true, when:'ศ.' },
        { kind:'meal', label:'log มื้ออาหาร', missed:true, when:'หาย 3 วัน' },
      ],
      flag:'หาย 4 วัน',
      priority:1,
    },
    {
      id:'t6', nick:'เมธ', name:'วรเมธ คงทรัพย์', tone:'#FFB36B',
      goal:'ลด 8 กก.',
      week:4, totalWeeks:20,
      progress:65, progressDelta:-3,
      tone_kind:'warn',
      lastActive:'1 วันก่อน',
      lastEvent: { kind:'meal', text:'ส่งมื้อเย็น · คาร์บเกินอีก', time:'อา. 19:48', unread:true },
      pending: [
        { kind:'meal', label:'รีวิวมื้อเย็น 3 มื้อ', missed:false, when:'ค้าง' },
        { kind:'msg', label:'ตอบเรื่องคาร์บมื้อเย็น', missed:false, when:'ค้าง' },
      ],
      flag:'ติดคาร์บมื้อเย็น',
      priority:2,
    },
    {
      id:'t1', nick:'มิ้น', name:'มินตรา ใจดี', tone:'#9BE36B',
      goal:'ลด 6 กก.',
      week:9, totalWeeks:16,
      progress:92, progressDelta:+4,
      tone_kind:'good',
      lastActive:'9 นาทีก่อน',
      lastEvent: { kind:'meal', text:'ส่งมื้อกลางวัน · plate balance ดี', time:'12:31', unread:true },
      pending: [
        { kind:'meal', label:'รีวิวมื้อกลางวัน', missed:false, when:'9 นาที' },
      ],
      flag:'streak 12 วัน 🔥',
      priority:3,
    },
    {
      id:'t2', nick:'พี', name:'พีรพล ตันติกุล', tone:'#FFD66B',
      goal:'เพิ่มกล้าม',
      week:11, totalWeeks:24,
      progress:88, progressDelta:+2,
      tone_kind:'good',
      lastActive:'18 นาทีก่อน',
      lastEvent: { kind:'msg-them', text:'พรุ่งนี้ขอเลื่อน session มั้ยคะ', time:'09:23', unread:true },
      pending: [
        { kind:'msg', label:'ตอบเรื่องเลื่อน session', missed:false, when:'18 นาที' },
      ],
      flag:'นัด session 17:00',
      priority:4,
    },
    {
      id:'t5', nick:'แอม', name:'อภิชญา รุ่งโรจน์', tone:'#C49BFF',
      goal:'tone & flexibility',
      week:14, totalWeeks:16,
      progress:95, progressDelta:+1,
      tone_kind:'good',
      lastActive:'30 นาทีก่อน',
      lastEvent: { kind:'meal', text:'ส่งของว่าง · กรีกโยเกิร์ต+ผลไม้', time:'10:42', unread:false },
      pending: [],
      flag:'แพคเกจหมดใน 5 วัน',
      flagKind:'warn',
      priority:5,
    },
    {
      id:'t4', nick:'กร', name:'ธนกร ศรีวิชัย', tone:'#6BC9FF',
      goal:'วิ่ง 10K sub-50',
      week:7, totalWeeks:12,
      progress:78, progressDelta:0,
      tone_kind:'good',
      lastActive:'1 ชม. ก่อน',
      lastEvent: { kind:'workout', text:'จบ Upper body · 38 นาที', time:'08:30', unread:false },
      pending: [],
      flag:'นัด session 17:00',
      priority:6,
    },
  ];

  const sorted = filter==='unread'
    ? ROWS.filter(r=>r.lastEvent.unread || r.pending.some(p=>p.missed))
    : filter==='all'
      ? [...ROWS].sort((a,b)=>a.nick.localeCompare(b.nick,'th'))
      : ROWS; // priority order = original order

  const totalUnread = ROWS.filter(r=>r.lastEvent.unread).length;
  const totalMissed = ROWS.reduce((s,r)=>s+r.pending.filter(p=>p.missed).length, 0);

  const eventIcon = (k) => k==='msg-them'?'💬':k==='msg'?'💬':k==='meal'?'🥗':k==='workout'?'🏋️':'·';

  const Row = ({ r }) => {
    const c = r.tone_kind==='good' ? ledOk : r.tone_kind==='warn' ? ledWarn : ledBad;
    const flagColor = r.flagKind==='warn' ? ledWarn : (r.tone_kind==='bad' ? ledBad : r.tone_kind==='warn' ? ledWarn : T.ink3);
    const unread = r.lastEvent.unread;
    const missedCount = r.pending.filter(p=>p.missed).length;
    const pendingCount = r.pending.length;

    return (
      <button onClick={()=>openTrainee(r.id)} style={{
        width:'100%', padding:'14px 16px', display:'flex', gap:12, alignItems:'flex-start',
        background:'transparent', border:0, cursor:'pointer', textAlign:'left',
        borderBottom:`0.5px solid ${T.line}`, position:'relative',
      }}>
        {/* unread strip */}
        {unread && (
          <div style={{ position:'absolute', left:0, top:14, bottom:14, width:3, borderRadius:'0 2px 2px 0', background:T.brand }}/>
        )}

        {/* avatar with status dot */}
        <div style={{ position:'relative' }}>
          <Avatar name={r.name} tone={r.tone} size={48}/>
          <div style={{
            position:'absolute', bottom:-1, right:-1, width:14, height:14, borderRadius:7,
            background:c, border:`2px solid ${T.bg}`,
          }}/>
        </div>

        <div style={{ flex:1, minWidth:0 }}>
          {/* line 1: name + flag · time */}
          <div style={{ display:'flex', alignItems:'baseline', gap:6, marginBottom:2 }}>
            <span style={{ fontSize:15, fontWeight:700, color:T.ink, letterSpacing:-0.2 }}>{r.nick}</span>
            <span style={{ fontSize:11, color:T.ink3, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', minWidth:0, flex:1 }}>· {r.goal} · สัปดาห์ {r.week}/{r.totalWeeks}</span>
            <span style={{ fontSize:10, color: r.lastActiveBad?ledBad:T.ink3, fontWeight: r.lastActiveBad?700:500, fontFamily:'"JetBrains Mono", monospace', whiteSpace:'nowrap' }}>{r.lastActive}</span>
          </div>

          {/* line 2: flag (status snippet) */}
          <div style={{ display:'flex', alignItems:'center', gap:6, marginBottom:6 }}>
            <span style={{ fontSize:11, color:flagColor, fontWeight:600 }}>{r.flag}</span>
          </div>

          {/* line 3: latest event preview, like a chat bubble snippet */}
          <div style={{
            display:'flex', alignItems:'center', gap:6, marginBottom:8,
            fontSize:12, color: unread?T.ink:T.ink2, fontWeight: unread?600:500,
          }}>
            <span style={{ fontSize:11 }}>{eventIcon(r.lastEvent.kind)}</span>
            <span style={{
              flex:1, minWidth:0, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap',
              fontStyle: r.lastEvent.kind==='msg-them' ? 'italic' : 'normal',
            }}>
              {r.lastEvent.kind==='msg-them' && '"'}{r.lastEvent.text}{r.lastEvent.kind==='msg-them' && '"'}
            </span>
            <span style={{ fontSize:10, color:T.ink3, fontFamily:'"JetBrains Mono", monospace', whiteSpace:'nowrap' }}>{r.lastEvent.time}</span>
          </div>

          {/* line 4: progress bar + delta */}
          <div style={{ display:'flex', alignItems:'center', gap:8, marginBottom: pendingCount>0 ? 8 : 0 }}>
            <div style={{ fontSize:10, color:T.ink3, fontWeight:700, letterSpacing:0.4, textTransform:'uppercase', minWidth:54 }}>ทำตามแผน</div>
            <div style={{ flex:1, height:5, borderRadius:3, background:T.line, overflow:'hidden', position:'relative' }}>
              <div style={{ width:`${r.progress}%`, height:'100%', background:c, borderRadius:3 }}/>
            </div>
            <div style={{ fontSize:11, fontWeight:700, color:c, fontFamily:'"JetBrains Mono", monospace', minWidth:34, textAlign:'right' }}>{r.progress}%</div>
            <div style={{ fontSize:10, color: r.progressDelta>0?ledOk:r.progressDelta<0?ledBad:T.ink3, fontWeight:700, fontFamily:'"JetBrains Mono", monospace', minWidth:30, textAlign:'right' }}>
              {r.progressDelta>0?'↑':r.progressDelta<0?'↓':'·'}{Math.abs(r.progressDelta)}
            </div>
          </div>

          {/* line 5: pending homework chips */}
          {pendingCount>0 && (
            <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
              {r.pending.slice(0,3).map((p,i)=>(
                <div key={i} style={{
                  fontSize:10, padding:'4px 8px', borderRadius:99,
                  background: p.missed ? `${ledBad}15` : T.chip,
                  color: p.missed ? ledBad : T.ink2,
                  fontWeight:600, display:'flex', alignItems:'center', gap:4,
                  border: p.missed ? `0.5px solid ${ledBad}40` : `0.5px solid transparent`,
                }}>
                  <span style={{ fontSize:10 }}>{p.kind==='workout'?'🏋️':p.kind==='meal'?'🥗':'💬'}</span>
                  <span>{p.label}</span>
                  <span style={{ opacity:0.6 }}>· {p.when}</span>
                </div>
              ))}
            </div>
          )}
        </div>

        {/* arrow */}
        <div style={{ alignSelf:'center', fontSize:18, color:T.ink3, marginLeft:4 }}>›</div>
      </button>
    );
  };

  return (
    <div style={{ paddingBottom:120 }}>
      {/* ── Sticky header: status bar + title + filter pinned together */}
      <div style={{
        position:'sticky', top:0, zIndex:20,
        background: T.bg,
        borderBottom: `0.5px solid ${T.line}`,
        backdropFilter: 'saturate(140%) blur(8px)',
        WebkitBackdropFilter: 'saturate(140%) blur(8px)',
      }}>
        <PhoneStatus dark={dark}/>

        {/* Header */}
        <div style={{ padding:'4px 20px 12px', display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
          <div>
            <div style={{ color:T.ink2, fontSize:12, fontWeight:500 }}>วันจันทร์ · 27 เม.ย.</div>
            <div style={{ color:T.ink, fontSize:22, fontWeight:700, letterSpacing:-0.5, lineHeight:1.15, marginTop:2 }}>ลูกเทรนของฉัน</div>
            <div style={{ fontSize:11, color:T.ink2, marginTop:2 }}>
              6 คน · <span style={{ color: totalUnread>0?ledBad:T.ink2, fontWeight:600 }}>{totalUnread} รอตอบ</span> · <span style={{ color: totalMissed>0?ledBad:T.ink2, fontWeight:600 }}>{totalMissed} หายไป</span>
            </div>
          </div>
          <Avatar name="Coach Jin" tone={accent} size={36}/>
        </div>

        {/* Filter bar */}
        <div style={{ padding:'0 16px 10px', display:'flex', gap:6, overflowX:'auto' }}>
          {[
            { k:'priority', l:'ตามลำดับสำคัญ', sub:totalMissed+totalUnread },
            { k:'unread', l:'มีอะไรค้าง', sub:totalUnread },
            { k:'all', l:'ทั้งหมด', sub:6 },
          ].map(f=>{
            const on = filter===f.k;
            return (
              <button key={f.k} onClick={()=>setFilter(f.k)} style={{
                padding:'7px 12px', borderRadius:99,
                background: on ? T.ink : T.card,
                border: on ? 0 : `0.5px solid ${T.line}`,
                color: on ? T.bg : T.ink2,
                fontSize:12, fontWeight:600, cursor:'pointer', whiteSpace:'nowrap',
                display:'flex', alignItems:'center', gap:5,
              }}>
                <span>{f.l}</span>
                <span style={{
                  fontSize:10, padding:'1px 6px', borderRadius:99,
                  background: on ? 'rgba(255,255,255,0.18)' : T.chip,
                  color: on ? T.bg : T.ink2,
                  fontWeight:700, fontFamily:'"JetBrains Mono", monospace',
                }}>{f.sub}</span>
              </button>
            );
          })}
          <div style={{ flex:1 }}/>
          <button style={{
            padding:'7px 10px', borderRadius:99, background:T.card, border:`0.5px solid ${T.line}`,
            color:T.ink2, fontSize:12, fontWeight:600, cursor:'pointer', whiteSpace:'nowrap',
          }}>🔍</button>
        </div>
      </div>

      {/* List */}
      <div style={{ background:T.card, borderTop:`0.5px solid ${T.line}`, borderBottom:`0.5px solid ${T.line}` }}>
        {sorted.map((r,i)=> <Row key={r.id} r={r}/>)}
      </div>

      {/* Footnote */}
      <div style={{ padding:'14px 20px 0', fontSize:11, color:T.ink3, lineHeight:1.6, textAlign:'center' }}>
        แตะคนใดก็ได้ → เปิดโปรไฟล์ · ดูแชท · สั่งการบ้าน · เปลี่ยนแผน
      </div>

      {/* Quick actions strip */}
      <div style={{ padding:'18px 16px 0' }}>
        <div style={{ fontSize:11, fontWeight:700, color:T.ink3, letterSpacing:0.5, textTransform:'uppercase', marginBottom:8, paddingLeft:4 }}>● ปุ่มลัด</div>
        <div style={{ display:'flex', gap:8 }}>
          {[
            { i:'➕', l:'รับลูกเทรนใหม่', sub:'ส่งรหัสเชิญ' },
            { i:'📋', l:'แผนต้นแบบ', sub:'8 templates' },
            { i:'📅', l:'ปฏิทินวันนี้', sub:'2 นัด', go:'cal' },
          ].map((a,i)=>(
            <button key={i} onClick={()=>a.go && go(a.go)} style={{
              flex:1, background:T.card, border:`0.5px solid ${T.line}`, borderRadius:14,
              padding:'12px 10px', cursor:'pointer', textAlign:'left',
            }}>
              <div style={{ fontSize:18, marginBottom:6 }}>{a.i}</div>
              <div style={{ fontSize:11, fontWeight:700, color:T.ink, lineHeight:1.2 }}>{a.l}</div>
              <div style={{ fontSize:10, color:T.ink3, marginTop:2 }}>{a.sub}</div>
            </button>
          ))}
        </div>
      </div>
    </div>
  );
}

window.TrainerMonitor = TrainerMonitor;
