// trainer-screens.jsx — screens from the trainer (coach) perspective

function TrainerHome({ dark, openTrainee, go }) {
  const T = tokens(dark);
  const atRisk = TRAINEES.filter(t=>t.status==='at-risk' || t.status==='watching');
  const onTrack = TRAINEES.filter(t=>t.status==='on-track');
  return (
    <div style={{ paddingBottom:120 }}>
      <PhoneStatus dark={dark}/>
      <div style={{ padding:'4px 20px 0', display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
        <div>
          <div style={{ color:T.ink2, fontSize:13, fontWeight:500 }}>วันจันทร์ · 27 เม.ย.</div>
          <div style={{ color:T.ink, fontSize:26, fontWeight:700, letterSpacing:-0.5, lineHeight:1.15, marginTop:2 }}>โค้ชจิน 🌿</div>
        </div>
        <div style={{ display:'flex', gap:6 }}>
          <button style={{ width:36, height:36, borderRadius:18, background:T.card, border:`0.5px solid ${T.line}`, display:'flex', alignItems:'center', justifyContent:'center', position:'relative' }}>
            <Icon name="bell" size={18} color={T.ink}/>
            <span style={{ position:'absolute', top:7, right:8, width:8, height:8, borderRadius:4, background:'#FF8273', border:`1.5px solid ${T.card}` }}/>
          </button>
          <Avatar name="Coach Jin" tone="#FFD66B" size={36}/>
        </div>
      </div>

      {/* KPI strip */}
      <div style={{ padding:'14px 16px 0' }}>
        <div style={{ background: dark?'linear-gradient(135deg,#1A2210,#0E1110)':'linear-gradient(135deg,#DDF1A8,#C9F76F)', borderRadius:22, padding:16, border:`0.5px solid ${T.line}` }}>
          <div style={{ fontSize:11, fontWeight:700, letterSpacing:1.5, color:dark?'#C9F76F':'#3D5C0E', textTransform:'uppercase' }}>วันนี้</div>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end', marginTop:8 }}>
            <div>
              <div style={{ fontSize:38, fontWeight:700, color:dark?'#F4F7F4':'#1B2710', fontFamily:'"Plus Jakarta Sans", system-ui', letterSpacing:-1, lineHeight:1 }}>6<span style={{ fontSize:18, color:dark?'rgba(244,247,244,.6)':'rgba(27,39,16,.6)', fontWeight:600 }}> ลูกเทรน</span></div>
              <div style={{ fontSize:13, color:dark?'rgba(244,247,244,.7)':'#3D5C0E', marginTop:2 }}>5 active · 1 ต้องดูแล</div>
            </div>
            <div style={{ display:'flex', gap:8 }}>
              {[{l:'รอตอบ', v:3},{l:'มื้อรอ\nรีวิว', v:5},{l:'นัด\nวันนี้', v:2}].map((k,i)=>(
                <div key={i} style={{ background:dark?'rgba(255,255,255,0.06)':'rgba(255,255,255,0.6)', borderRadius:12, padding:'8px 10px', minWidth:54, textAlign:'center' }}>
                  <div style={{ fontSize:20, fontWeight:700, color:dark?'#F4F7F4':'#1B2710', fontFamily:'"Plus Jakarta Sans", system-ui' }}>{k.v}</div>
                  <div style={{ fontSize:9, color:dark?'rgba(244,247,244,.7)':'#3D5C0E', fontWeight:600, lineHeight:1.1, whiteSpace:'pre' }}>{k.l}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>

      {/* needs attention */}
      <div style={{ padding:'18px 16px 0' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:10 }}>
          <div style={{ fontSize:18, fontWeight:700, color:T.ink, letterSpacing:-0.3 }}>ต้องดูแลก่อน</div>
          <span style={{ fontSize:12, color:T.ink2 }}>{atRisk.length} คน</span>
        </div>
        <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
          {atRisk.map(p=>{
            const danger = p.status==='at-risk';
            return (
              <button key={p.id} onClick={()=>openTrainee(p.id)} style={{
                background:T.card, border:`0.5px solid ${danger?'rgba(255,130,115,0.3)':T.line}`, borderRadius:18, padding:12,
                display:'flex', gap:12, alignItems:'center', textAlign:'left', cursor:'pointer', width:'100%',
              }}>
                <Avatar name={p.name} tone={p.tone} size={44}/>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', gap:6 }}>
                    <div style={{ fontSize:14, fontWeight:700, color:T.ink }}>{p.nick} · {p.name.split(' ')[1]}</div>
                    <Pill kind={danger?'danger':'warn'} dark={dark}>{danger?'หาย 4 วัน':'adherence 65%'}</Pill>
                  </div>
                  <div style={{ fontSize:12, color:T.ink2, marginTop:4, display:'-webkit-box', WebkitLineClamp:1, WebkitBoxOrient:'vertical', overflow:'hidden' }}>{p.notes}</div>
                  <div style={{ display:'flex', gap:6, marginTop:8 }}>
                    <span style={{ fontSize:10, padding:'4px 8px', borderRadius:99, background:T.chip, color:T.ink, fontWeight:600 }}>📞 โทรหา</span>
                    <span style={{ fontSize:10, padding:'4px 8px', borderRadius:99, background:T.chip, color:T.ink, fontWeight:600 }}>💬 ส่งกำลังใจ</span>
                  </div>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* group adherence */}
      <div style={{ padding:'18px 16px 0' }}>
        <div style={{ background:T.card, borderRadius:20, padding:16, border:`0.5px solid ${T.line}` }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
            <div>
              <div style={{ fontSize:11, color:T.ink3, fontWeight:600, letterSpacing:0.5, textTransform:'uppercase' }}>ค่าเฉลี่ยกลุ่ม</div>
              <div style={{ fontSize:32, fontWeight:700, color:T.ink, marginTop:2, fontFamily:'"Plus Jakarta Sans", system-ui', letterSpacing:-1 }}>76<span style={{ fontSize:16, color:T.ink2 }}>%</span></div>
              <div style={{ fontSize:11, color:T.ink2 }}>adherence รายสัปดาห์</div>
            </div>
            <div style={{ display:'flex', flexDirection:'column', alignItems:'flex-end' }}>
              <Pill kind="good" dark={dark}>↑ 4% w/w</Pill>
              <div style={{ marginTop:8 }}>
                <Bars data={[68,72,70,78,75,73,76]} w={120} h={42} color={T.brand} dark={dark}/>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* recent submissions */}
      <div style={{ padding:'18px 16px 0' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:10 }}>
          <div style={{ fontSize:18, fontWeight:700, color:T.ink, letterSpacing:-0.3 }}>ส่งเข้ามาล่าสุด</div>
          <button onClick={()=>go('meals')} style={{ background:'transparent', border:0, color:T.ink2, fontSize:12, fontWeight:600 }}>ดูทั้งหมด →</button>
        </div>
        <div style={{ display:'flex', gap:8, overflow:'auto', padding:'0 0 4px', margin:'0 -16px', paddingLeft:16 }}>
          {[
            {who:TRAINEES[1], tone:'#FFD66B', img:'lunch', label:'มื้อกลางวัน', ago:'5 นาที', score:88},
            {who:TRAINEES[4], tone:'#C49BFF', img:'breakfast', label:'มื้อเช้า', ago:'18 นาที', score:95},
            {who:TRAINEES[3], tone:'#6BC9FF', img:'snack', label:'ของว่าง', ago:'42 นาที', score:62},
            {who:TRAINEES[5], tone:'#FFB36B', img:'lunch', label:'มื้อกลางวัน', ago:'1 ชม.', score:74},
          ].map((s,i)=>(
            <div key={i} style={{ flexShrink:0, width:160, background:T.card, borderRadius:16, border:`0.5px solid ${T.line}`, overflow:'hidden' }}>
              <Placeholder kind={s.img} h={120} label=""/>
              <div style={{ padding:10 }}>
                <div style={{ display:'flex', alignItems:'center', gap:6 }}>
                  <Avatar name={s.who.name} tone={s.tone} size={20}/>
                  <span style={{ fontSize:12, fontWeight:600, color:T.ink }}>{s.who.nick}</span>
                </div>
                <div style={{ fontSize:11, color:T.ink2, marginTop:4 }}>{s.label} · {s.ago}</div>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:8 }}>
                  <Pill kind={s.score>=85?'good':s.score>=70?'warn':'danger'} dark={dark}>{s.score}</Pill>
                  <button style={{ background:T.brand, color:T.brandInk, border:0, padding:'4px 10px', borderRadius:99, fontSize:11, fontWeight:700 }}>รีวิว</button>
                </div>
              </div>
            </div>
          ))}
          <div style={{ width:8, flexShrink:0 }}/>
        </div>
      </div>
    </div>
  );
}

function TrainerRoster({ dark, openTrainee }) {
  const T = tokens(dark);
  const [filter, setFilter] = React.useState('all');
  const active = TRAINEES.filter(t=>!t.archived);
  const archived = TRAINEES.filter(t=>t.archived);
  const ending = active.filter(t=>t.packageEndsIn !== undefined && t.packageEndsIn <= 7);
  const filtered =
    filter==='all'      ? active :
    filter==='risk'     ? active.filter(t=>t.status!=='on-track') :
    filter==='good'     ? active.filter(t=>t.status==='on-track') :
    filter==='ending'   ? ending :
    filter==='archived' ? archived :
    active;
  return (
    <div style={{ paddingBottom:120 }}>
      <PhoneStatus dark={dark}/>
      <div style={{ padding:'4px 20px 12px', display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
        <div>
          <div style={{ color:T.ink, fontSize:28, fontWeight:700, letterSpacing:-0.6 }}>ลูกเทรน</div>
          <div style={{ color:T.ink2, fontSize:13, marginTop:2 }}>{active.length} active · {archived.length} archived</div>
        </div>
        <button style={{ width:40, height:40, borderRadius:20, background:T.brand, color:T.brandInk, border:0, display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon name="plus" size={20} color={T.brandInk} stroke={2.4}/>
        </button>
      </div>

      {/* search */}
      <div style={{ padding:'0 16px 12px' }}>
        <div style={{ background:T.card, border:`0.5px solid ${T.line}`, borderRadius:14, height:40, padding:'0 12px', display:'flex', alignItems:'center', gap:8 }}>
          <Icon name="search" size={18} color={T.ink3}/>
          <span style={{ fontSize:13, color:T.ink3 }}>ค้นหาชื่อ...</span>
        </div>
      </div>

      {/* filter chips */}
      <div style={{ padding:'0 16px 12px', display:'flex', gap:6, overflowX:'auto', WebkitOverflowScrolling:'touch' }}>
        {[
          {id:'all', l:'ทั้งหมด', n:active.length},
          {id:'risk', l:'ต้องดูแล', n:active.filter(t=>t.status!=='on-track').length},
          {id:'good', l:'ทำได้ดี', n:active.filter(t=>t.status==='on-track').length},
          {id:'ending', l:'⏰ ใกล้หมด', n:ending.length, accent:'#FFB36B'},
          {id:'archived', l:'📦 archived', n:archived.length},
        ].map(f=>{
          const on = filter===f.id;
          return (
            <button key={f.id} onClick={()=>setFilter(f.id)} style={{
              padding:'7px 12px', borderRadius:99, fontSize:12, fontWeight:600, cursor:'pointer', whiteSpace:'nowrap', flexShrink:0,
              background: on?T.ink:T.card, color: on?T.bg:T.ink, border:`0.5px solid ${on?'transparent':T.line}`,
            }}>{f.l} · {f.n}</button>
          );
        })}
      </div>

      {/* list */}
      <div style={{ padding:'0 16px', display:'flex', flexDirection:'column', gap:8 }}>
        {filtered.map(p=>{
          const dirArrow = p.currentW < p.startW ? '↓' : p.currentW > p.startW ? '↑' : '·';
          const wDelta = (p.currentW - p.startW).toFixed(1);
          return (
            <button key={p.id} onClick={()=>openTrainee(p.id)} style={{
              background:T.card, border:`0.5px solid ${T.line}`, borderRadius:18, padding:14,
              display:'flex', gap:12, alignItems:'center', textAlign:'left', cursor:'pointer', width:'100%',
              opacity: p.archived ? 0.7 : 1,
            }}>
              <Avatar name={p.name} tone={p.tone} size={48}/>
              <div style={{ flex:1, minWidth:0 }}>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', gap:6 }}>
                  <div style={{ fontSize:14, fontWeight:700, color:T.ink }}>{p.nick} · {p.name}</div>
                  {p.archived && p.archivedReason==='graduated' && <Pill kind="default" dark={dark}>🎓 graduated</Pill>}
                  {p.archived && p.archivedReason!=='graduated' && <Pill kind="default" dark={dark}>📦 archived</Pill>}
                  {!p.archived && p.status==='at-risk' && <Pill kind="danger" dark={dark}>at risk</Pill>}
                  {!p.archived && p.status==='watching' && <Pill kind="warn" dark={dark}>watching</Pill>}
                  {!p.archived && p.packageEndsIn !== undefined && p.packageEndsIn < 0 && <Pill kind="danger" dark={dark}>⏰ หมดแล้ว</Pill>}
                  {!p.archived && p.packageEndsIn !== undefined && p.packageEndsIn >= 0 && p.packageEndsIn <= 7 && <Pill kind="warn" dark={dark}>⏰ {p.packageEndsIn}d</Pill>}
                </div>
                <div style={{ fontSize:12, color:T.ink2, marginTop:2 }}>
                  {p.archived ? `${p.archivedDate} · ${p.notes}` : `${p.goal} · ${p.lastActive} ที่แล้ว`}
                </div>
                <div style={{ display:'flex', gap:10, marginTop:8, alignItems:'center' }}>
                  {!p.archived && (
                    <>
                      <div style={{ display:'flex', alignItems:'center', gap:4 }}>
                        <Icon name="flame" size={12} color={p.streak>0?'#FF8A33':T.ink3}/>
                        <span style={{ fontSize:11, fontWeight:600, color: p.streak>0?T.ink:T.ink3, fontFamily:'"Plus Jakarta Sans", system-ui' }}>{p.streak}</span>
                      </div>
                      <div style={{ display:'flex', alignItems:'center', gap:4 }}>
                        <Icon name="gauge" size={12} color={T.ink2}/>
                        <span style={{ fontSize:11, fontWeight:600, color:T.ink, fontFamily:'"Plus Jakarta Sans", system-ui' }}>{p.adherence}%</span>
                      </div>
                    </>
                  )}
                  <div style={{ display:'flex', alignItems:'center', gap:4 }}>
                    <span style={{ fontSize:11, fontWeight:600, color: wDelta<0?'#41A55E':wDelta>0?'#3F88C5':T.ink2, fontFamily:'"Plus Jakarta Sans", system-ui' }}>{dirArrow} {Math.abs(wDelta)}kg</span>
                  </div>
                  <div style={{ fontSize:10, color:T.ink3, fontFamily:'"JetBrains Mono", monospace', marginLeft:'auto' }}>{p.packageLabel}</div>
                </div>
              </div>
              <Sparkline data={[p.startW, p.startW-0.4, p.startW-0.8, p.startW-1.2, p.currentW+0.4, p.currentW+0.2, p.currentW]} w={64} h={36} color={p.tone} fill={`${p.tone}22`} dot={false}/>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function TrainerTraineeDetail({ dark, traineeId, onBack, openAssign, onRequestMetric, wearable, openCloseSheet }) {
  const T = tokens(dark);
  const p = TRAINEES.find(t=>t.id===traineeId) || TRAINEES[0];
  const setCloseSheet = (s) => openCloseSheet && openCloseSheet(s);

  const isArchived = p.archived;
  const ending = !isArchived && p.packageEndsIn !== undefined;
  const expired = ending && p.packageEndsIn < 0;
  const soon = ending && p.packageEndsIn >= 0 && p.packageEndsIn <= 7;
  const pkgColor = expired ? '#E1573B' : soon ? '#FFB36B' : '#41A55E';
  const pkgLabel = expired
    ? `หมดแล้ว ${Math.abs(p.packageEndsIn)} วัน`
    : soon
    ? `เหลือ ${p.packageEndsIn} วัน`
    : `เหลือ ${p.packageEndsIn} วัน`;

  return (
    <div style={{ paddingBottom:120, background:T.bg, minHeight:'100%', position:'relative' }}>
      <PhoneStatus dark={dark}/>
      {/* hero */}
      <div style={{ padding:'4px 16px 0', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <button onClick={onBack} style={{ width:36, height:36, borderRadius:18, background:T.card, border:`0.5px solid ${T.line}`, display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon name="back" size={18} color={T.ink}/>
        </button>
        <div style={{ display:'flex', gap:6 }}>
          <button style={{ width:36, height:36, borderRadius:18, background:T.card, border:`0.5px solid ${T.line}`, display:'flex', alignItems:'center', justifyContent:'center' }}>
            <Icon name="chat" size={18} color={T.ink}/>
          </button>
          <button onClick={()=>setCloseSheet('menu')} style={{ width:36, height:36, borderRadius:18, background:T.card, border:`0.5px solid ${T.line}`, display:'flex', alignItems:'center', justifyContent:'center', cursor:'pointer', position:'relative' }}>
            <Icon name="more" size={18} color={T.ink}/>
            {(expired || soon) && (
              <span style={{ position:'absolute', top:6, right:6, width:8, height:8, borderRadius:4, background:pkgColor, boxShadow:`0 0 4px ${pkgColor}80`, border:`1px solid ${T.card}` }}/>
            )}
          </button>
        </div>
      </div>
      <div style={{ padding:'12px 20px 0', display:'flex', alignItems:'center', gap:14 }}>
        <Avatar name={p.name} tone={p.tone} size={64} ring dark={dark}/>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:22, fontWeight:700, color:T.ink, letterSpacing:-0.4, lineHeight:1.1 }}>{p.name}</div>
          <div style={{ fontSize:12, color:T.ink2, marginTop:4 }}>เริ่มเทรน {p.joined} · อายุ {p.age}</div>
          <div style={{ display:'flex', gap:6, marginTop:8, flexWrap:'wrap' }}>
            {isArchived ? (
              <Pill kind="default" dark={dark}>{p.archivedReason==='graduated'?'🎓 จบหลักสูตร':'📦 archived'}</Pill>
            ) : (
              <Pill kind={p.status==='on-track'?'good':p.status==='at-risk'?'danger':'warn'} dark={dark}>{p.status}</Pill>
            )}
            <Pill kind="default" dark={dark}>{p.goal}</Pill>
          </div>
        </div>
      </div>

      {/* package status — always visible, color-coded by urgency */}
      {ending && (
        <div style={{ padding:'14px 16px 0' }}>
          <div style={{
            background: expired
              ? (dark?'rgba(225,87,59,0.10)':'rgba(225,87,59,0.06)')
              : soon
              ? (dark?'rgba(255,179,107,0.10)':'rgba(255,179,107,0.10)')
              : T.card,
            borderRadius:14, padding:'12px 14px',
            border:`0.5px solid ${expired?'rgba(225,87,59,0.4)':soon?'rgba(255,179,107,0.4)':T.line}`,
            display:'flex', alignItems:'center', gap:12,
          }}>
            <div style={{
              width:38, height:38, borderRadius:10,
              background: dark?'rgba(255,255,255,0.06)':'rgba(20,24,15,0.04)',
              display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
              fontSize:18,
            }}>📦</div>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ display:'flex', alignItems:'baseline', gap:8 }}>
                <span style={{ fontSize:13, fontWeight:700, color:T.ink }}>แพ็คเกจ {p.packageLabel}</span>
                <span style={{ fontSize:11, fontWeight:700, color:pkgColor, fontFamily:'"JetBrains Mono", monospace' }}>● {pkgLabel}</span>
              </div>
              <div style={{ fontSize:11, color:T.ink2, marginTop:2, lineHeight:1.4 }}>
                {expired
                  ? 'ลูกเทรนยังไม่ต่อแพ็คเกจ — ต้องตัดสินใจเร็ว ๆ'
                  : soon
                  ? 'ใกล้ครบแล้ว — คุยเรื่องต่อ/จบ ภายในสัปดาห์นี้'
                  : `เริ่ม ${p.joined}`}
              </div>
            </div>
            {(expired || soon) && (
              <button onClick={()=>setCloseSheet('menu')} style={{
                background:T.brand, color:T.brandInk, border:0, padding:'8px 12px',
                borderRadius:10, fontSize:11, fontWeight:700, cursor:'pointer', whiteSpace:'nowrap',
              }}>จัดการ →</button>
            )}
          </div>
        </div>
      )}

      {isArchived && (
        <div style={{ padding:'14px 16px 0' }}>
          <div style={{
            background: dark?'rgba(255,255,255,0.04)':'rgba(20,24,15,0.04)',
            borderRadius:14, padding:'12px 14px', border:`0.5px solid ${T.line}`,
            display:'flex', alignItems:'center', gap:12,
          }}>
            <div style={{ width:38, height:38, borderRadius:10, background:dark?'rgba(255,255,255,0.06)':'rgba(20,24,15,0.06)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, fontSize:18 }}>
              {p.archivedReason==='graduated'?'🎓':'📦'}
            </div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:13, fontWeight:700, color:T.ink }}>
                {p.archivedReason==='graduated'?'จบหลักสูตร':'Archived'} · {p.archivedDate}
              </div>
              <div style={{ fontSize:11, color:T.ink2, marginTop:2 }}>{p.notes}</div>
            </div>
            <button onClick={()=>setCloseSheet('renew')} style={{
              background:T.card, border:`0.5px solid ${T.line}`, color:T.ink,
              padding:'8px 12px', borderRadius:10, fontSize:11, fontWeight:700, cursor:'pointer', whiteSpace:'nowrap',
            }}>กลับมาเทรน</button>
          </div>
        </div>
      )}

      {/* stats grid */}
      <div style={{ padding:'16px 16px 0', display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
        <div style={{ background:T.card, borderRadius:16, padding:14, border:`0.5px solid ${T.line}` }}>
          <div style={{ fontSize:10, color:T.ink3, fontWeight:600, letterSpacing:0.5, textTransform:'uppercase' }}>น้ำหนัก</div>
          <div style={{ fontSize:24, fontWeight:700, color:T.ink, marginTop:2, fontFamily:'"Plus Jakarta Sans", system-ui', letterSpacing:-0.5 }}>{p.currentW}<span style={{ fontSize:12, color:T.ink2 }}> kg</span></div>
          <Pill kind="good" dark={dark} style={{ marginTop:6 }}>↓ {(p.startW-p.currentW).toFixed(1)} kg</Pill>
        </div>
        <div style={{ background:T.card, borderRadius:16, padding:14, border:`0.5px solid ${T.line}` }}>
          <div style={{ fontSize:10, color:T.ink3, fontWeight:600, letterSpacing:0.5, textTransform:'uppercase' }}>Adherence</div>
          <div style={{ fontSize:24, fontWeight:700, color:T.ink, marginTop:2, fontFamily:'"Plus Jakarta Sans", system-ui', letterSpacing:-0.5 }}>{p.adherence}<span style={{ fontSize:12, color:T.ink2 }}>%</span></div>
          <div style={{ marginTop:6, marginLeft:-2 }}>
            <Bars data={[80,85,90,88,92,90,p.adherence]} w={100} h={20} color={T.brand} dark={dark}/>
          </div>
        </div>
        <div style={{ background:T.card, borderRadius:16, padding:14, border:`0.5px solid ${T.line}` }}>
          <div style={{ fontSize:10, color:T.ink3, fontWeight:600, letterSpacing:0.5, textTransform:'uppercase' }}>Streak</div>
          <div style={{ fontSize:24, fontWeight:700, color:T.ink, marginTop:2, fontFamily:'"Plus Jakarta Sans", system-ui', letterSpacing:-0.5, display:'flex', alignItems:'center', gap:4 }}>
            <Icon name="flame" size={20} color="#FF8A33"/>{p.streak}<span style={{ fontSize:12, color:T.ink2 }}> วัน</span>
          </div>
        </div>
        <div style={{ background:T.card, borderRadius:16, padding:14, border:`0.5px solid ${T.line}` }}>
          <div style={{ fontSize:10, color:T.ink3, fontWeight:600, letterSpacing:0.5, textTransform:'uppercase' }}>มื้อรอรีวิว</div>
          <div style={{ fontSize:24, fontWeight:700, color:T.ink, marginTop:2, fontFamily:'"Plus Jakarta Sans", system-ui', letterSpacing:-0.5 }}>3<span style={{ fontSize:12, color:T.ink2 }}> มื้อ</span></div>
        </div>
      </div>

      {/* biometrics */}
      <div style={{ padding:'14px 16px 0' }}>
        <TrainerBiometricsPanel dark={dark} onRequest={onRequestMetric} settings={wearable}/>
      </div>

      {/* note */}
      {p.notes && (
        <div style={{ padding:'14px 16px 0' }}>
          <div style={{ background: dark?'rgba(255,179,107,0.08)':'rgba(255,138,51,0.08)', borderRadius:14, padding:'12px 14px', display:'flex', gap:10, alignItems:'flex-start' }}>
            <Icon name="bell" size={16} color={dark?'#FFB36B':'#9C4A0E'}/>
            <div style={{ fontSize:12, color:T.ink, lineHeight:1.4, flex:1 }}>โน้ตส่วนตัว: {p.notes}</div>
          </div>
        </div>
      )}

      {/* current week */}
      <div style={{ padding:'18px 16px 0' }}>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline', marginBottom:10 }}>
          <div style={{ fontSize:13, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase' }}>สัปดาห์นี้</div>
          <button onClick={openAssign} style={{ background:T.brand, color:T.brandInk, border:0, padding:'6px 12px', borderRadius:99, fontSize:11, fontWeight:700, cursor:'pointer', display:'flex', alignItems:'center', gap:4 }}>
            <Icon name="plus" size={12} color={T.brandInk} stroke={2.4}/> สั่งการบ้าน
          </button>
        </div>
        <div style={{ background:T.card, borderRadius:16, padding:'4px 4px', border:`0.5px solid ${T.line}` }}>
          {[
            {d:'จ. 27', t:'Lower body', s:'done', detail:'4×10 squat · ทำครบ'},
            {d:'อ. 28', t:'Cardio Z2', s:'today', detail:'30 min · กำลังจะถึง'},
            {d:'พ. 29', t:'Rest + mobility', s:'planned', detail:'15 min'},
            {d:'พฤ. 30', t:'Upper push', s:'planned', detail:'50 min · 7 ท่า'},
            {d:'ศ. 1', t:'HIIT', s:'planned', detail:'25 min'},
          ].map((s,i,arr)=>(
            <div key={i} style={{ display:'flex', alignItems:'center', gap:12, padding:'10px 12px', borderBottom: i<arr.length-1?`0.5px solid ${T.line}`:0 }}>
              <div style={{ width:42, fontSize:11, fontWeight:700, color:T.ink2, fontFamily:'"Plus Jakarta Sans", system-ui' }}>{s.d}</div>
              <div style={{ width:8, height:8, borderRadius:4, background: s.s==='done'?T.good:s.s==='today'?T.brand:T.ink3 }}/>
              <div style={{ flex:1 }}>
                <div style={{ fontSize:13, fontWeight:600, color:T.ink }}>{s.t}</div>
                <div style={{ fontSize:11, color:T.ink2 }}>{s.detail}</div>
              </div>
              {s.s==='done' && <Icon name="check" size={16} color={T.good} stroke={2.4}/>}
              {s.s==='today' && <Pill kind="brand" dark={dark}>วันนี้</Pill>}
            </div>
          ))}
        </div>
      </div>

      {/* photos */}
      <div style={{ padding:'18px 16px 0' }}>
        <div style={{ fontSize:13, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:10 }}>Body changes</div>
        <div style={{ display:'flex', gap:8 }}>
          {['1 ก.พ.', '1 มี.ค.', '1 เม.ย.', '27 เม.ย.'].map((d,i)=>(
            <div key={i} style={{ flex:1 }}>
              <div style={{ borderRadius:12, overflow:'hidden', height:120 }}>
                <Placeholder kind="body" h={120} label={i===3?'now':''}/>
              </div>
              <div style={{ fontSize:10, color:T.ink2, fontWeight:600, marginTop:4, fontFamily:'"JetBrains Mono", monospace', textAlign:'center' }}>{d}</div>
            </div>
          ))}
        </div>
      </div>

      {/* close / archive sheet — rendered at App level so it pins to phone viewport */}
    </div>
  );
}

function CloseTraineeSheet({ dark, step, setStep, trainee, pickedReason, setPickedReason, pickedPause, setPickedPause, pickedRenew, setPickedRenew }) {
  const T = tokens(dark);
  const close = () => { setStep(null); setPickedReason(null); };
  const isArchived = trainee.archived;

  return (
    <div onClick={close} style={{
      position:'absolute', inset:0, background:'rgba(0,0,0,0.5)',
      display:'flex', alignItems:'flex-end', zIndex:50,
    }}>
      <div onClick={e=>e.stopPropagation()} style={{
        width:'100%', background:T.bg, borderTopLeftRadius:24, borderTopRightRadius:24,
        padding:'8px 0 28px', maxHeight:'88%', overflowY:'auto',
      }}>
        <div style={{ width:36, height:4, background:T.line, borderRadius:2, margin:'8px auto 12px' }}/>

        {step==='menu' && (
          <div style={{ padding:'4px 18px 0' }}>
            <div style={{ fontSize:18, fontWeight:700, color:T.ink, letterSpacing:-0.3 }}>จัดการ {trainee.nick}</div>
            <div style={{ fontSize:12, color:T.ink2, marginTop:4 }}>แพ็คเกจ {trainee.packageLabel} · {trainee.packageEndsIn<0?`หมดเมื่อ ${Math.abs(trainee.packageEndsIn)} วันที่แล้ว`:`เหลือ ${trainee.packageEndsIn} วัน`}</div>

            <div style={{ marginTop:18, display:'flex', flexDirection:'column', gap:8 }}>
              <SheetAction
                dark={dark} icon="↻" iconBg="#41A55E" tone="brand"
                title="ต่อแพ็คเกจ"
                desc="ลูกเทรนตกลงต่ออีกรอบ — เลือกระยะเวลา"
                onClick={()=>setStep('renew')}
              />
              <SheetAction
                dark={dark} icon="🎓" iconBg="rgba(155,227,107,0.2)"
                title="จบหลักสูตร · สำเร็จ"
                desc="ปิดเคสแบบ celebrate — ทำ goal สำเร็จแล้ว"
                onClick={()=>setStep('graduate')}
              />
              <SheetAction
                dark={dark} icon="⏸" iconBg="rgba(255,179,107,0.2)"
                title="หยุดชั่วคราว"
                desc="ลูกเทรนติดงาน/บาดเจ็บ — กลับมาภายใน 1-2 เดือน"
                onClick={()=>setStep('pause')}
              />
              <SheetAction
                dark={dark} icon="📦" iconBg="rgba(225,87,59,0.15)"
                title="ปิดเคส · ไม่ต่อแล้ว"
                desc="เก็บประวัติไว้ ไม่นับใน active list"
                onClick={()=>setStep('archive')}
              />
            </div>

            <button onClick={close} style={{ width:'100%', marginTop:18, padding:'14px 0', borderRadius:14, background:T.card, border:`0.5px solid ${T.line}`, color:T.ink, fontSize:14, fontWeight:600, cursor:'pointer' }}>ยกเลิก</button>
          </div>
        )}

        {step==='graduate' && (
          <div style={{ padding:'4px 18px 0' }}>
            <div style={{ fontSize:32, marginBottom:8 }}>🎓</div>
            <div style={{ fontSize:20, fontWeight:700, color:T.ink, letterSpacing:-0.3 }}>จบหลักสูตรกับ {trainee.nick}</div>
            <div style={{ fontSize:13, color:T.ink2, marginTop:6, lineHeight:1.5 }}>
              สำเร็จ goal <b style={{ color:T.ink }}>{trainee.goal}</b> · เทรนมา <b style={{ color:T.ink }}>{trainee.streak>0?'12 สัปดาห์':'จบครบรอบ'}</b>
            </div>

            <div style={{ marginTop:16, padding:'14px 16px', background:dark?'rgba(155,227,107,0.08)':'rgba(155,227,107,0.10)', borderRadius:14, border:`0.5px solid rgba(155,227,107,0.3)` }}>
              <div style={{ fontSize:11, fontWeight:700, color:dark?'#9BE36B':'#41A55E', letterSpacing:0.5, textTransform:'uppercase', marginBottom:8 }}>จะเกิดอะไร</div>
              <Bullet dark={dark} text="ส่งข้อความขอบคุณ + สรุปผลให้อัตโนมัติ"/>
              <Bullet dark={dark} text="ขอ testimonial + รูปคู่ก่อน-หลัง (เลือกได้)"/>
              <Bullet dark={dark} text="ย้ายไป Alumni — กลับมาเทรนได้ภายหลัง"/>
              <Bullet dark={dark} text="นับเข้า win count ของคุณ (8 → 9)"/>
            </div>

            <div style={{ marginTop:14 }}>
              <div style={{ fontSize:11, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:8 }}>เพิ่มเติม</div>
              <CheckRow dark={dark} label="ขอ testimonial" defaultChecked/>
              <CheckRow dark={dark} label="ขอรูป before/after" defaultChecked/>
              <CheckRow dark={dark} label="เสนอ maintenance plan (ราคาพิเศษ)"/>
            </div>

            <div style={{ display:'flex', gap:8, marginTop:18 }}>
              <button onClick={()=>setStep('menu')} style={{ flex:1, padding:'14px 0', borderRadius:14, background:T.card, border:`0.5px solid ${T.line}`, color:T.ink, fontSize:14, fontWeight:600, cursor:'pointer' }}>← กลับ</button>
              <button onClick={()=>setStep('done')} style={{ flex:2, padding:'14px 0', borderRadius:14, background:T.brand, color:T.brandInk, border:0, fontSize:14, fontWeight:700, cursor:'pointer' }}>🎓 ปิดหลักสูตร</button>
            </div>
          </div>
        )}

        {step==='pause' && (
          <div style={{ padding:'4px 18px 0' }}>
            <div style={{ fontSize:32, marginBottom:8 }}>⏸</div>
            <div style={{ fontSize:20, fontWeight:700, color:T.ink, letterSpacing:-0.3 }}>หยุดชั่วคราว</div>
            <div style={{ fontSize:13, color:T.ink2, marginTop:6, lineHeight:1.5 }}>หยุดนับ adherence + alerts ระหว่าง pause — แต่เก็บ data + slot ไว้</div>

            <div style={{ marginTop:18 }}>
              <div style={{ fontSize:11, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:10 }}>นานเท่าไร</div>
              <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
                {[
                  {id:'1w', label:'1 สัปดาห์', sub:'ไปเที่ยว/พักผ่อน'},
                  {id:'2w', label:'2 สัปดาห์', sub:'ติดงาน/สอบ'},
                  {id:'1mo', label:'1 เดือน', sub:'บาดเจ็บเล็ก'},
                  {id:'custom', label:'กำหนดเอง', sub:'เลือกวัน'},
                ].map(o=>(
                  <button key={o.id} onClick={()=>setPickedPause(o.id)} style={{
                    padding:'12px 12px', borderRadius:12, textAlign:'left',
                    background: pickedPause===o.id ? (dark?'rgba(201,247,111,0.10)':'rgba(155,227,107,0.12)') : T.card,
                    border:`1px solid ${pickedPause===o.id ? T.brand : T.line}`, cursor:'pointer',
                  }}>
                    <div style={{ fontSize:13, fontWeight:700, color:T.ink }}>{o.label}</div>
                    <div style={{ fontSize:10, color:T.ink2, marginTop:2 }}>{o.sub}</div>
                  </button>
                ))}
              </div>
            </div>

            <div style={{ marginTop:16, padding:'12px 14px', background:dark?'rgba(255,179,107,0.08)':'rgba(255,179,107,0.10)', borderRadius:12, border:`0.5px solid rgba(255,179,107,0.3)` }}>
              <div style={{ fontSize:12, color:T.ink, lineHeight:1.5 }}>
                ระหว่าง pause: <b>ไม่ส่ง check-in อัตโนมัติ</b> · <b>ไม่นับใน adherence</b> · จะเตือนคุณ <b>3 วันก่อน</b>กลับมา
              </div>
            </div>

            <div style={{ display:'flex', gap:8, marginTop:18 }}>
              <button onClick={()=>setStep('menu')} style={{ flex:1, padding:'14px 0', borderRadius:14, background:T.card, border:`0.5px solid ${T.line}`, color:T.ink, fontSize:14, fontWeight:600, cursor:'pointer' }}>← กลับ</button>
              <button onClick={()=>setStep('done')} style={{ flex:2, padding:'14px 0', borderRadius:14, background:T.brand, color:T.brandInk, border:0, fontSize:14, fontWeight:700, cursor:'pointer' }}>⏸ หยุดเลย</button>
            </div>
          </div>
        )}

        {step==='archive' && (
          <div style={{ padding:'4px 18px 0' }}>
            <div style={{ fontSize:32, marginBottom:8 }}>📦</div>
            <div style={{ fontSize:20, fontWeight:700, color:T.ink, letterSpacing:-0.3 }}>ปิดเคส · ไม่ต่อแล้ว</div>
            <div style={{ fontSize:13, color:T.ink2, marginTop:6, lineHeight:1.5 }}>เก็บประวัติทั้งหมด แต่ออกจาก active list — กลับมาเทรนได้ทุกเมื่อ</div>

            <div style={{ marginTop:18 }}>
              <div style={{ fontSize:11, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:10 }}>เหตุผล (ช่วยปรับปรุง)</div>
              <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
                {[
                  {id:'budget', label:'งบไม่พอ/เปลี่ยนใจ'},
                  {id:'busy', label:'ติดงาน/ไม่มีเวลา'},
                  {id:'switched', label:'เปลี่ยนไปเทรนที่อื่น'},
                  {id:'goal-met', label:'ทำได้เองแล้ว'},
                  {id:'unhappy', label:'ไม่ตรงใจ/ไม่ชอบ'},
                  {id:'other', label:'อื่น ๆ'},
                ].map(r=>(
                  <button key={r.id} onClick={()=>setPickedReason(r.id)} style={{
                    padding:'12px 14px', borderRadius:12, textAlign:'left',
                    background: pickedReason===r.id ? (dark?'rgba(201,247,111,0.10)':'rgba(155,227,107,0.12)') : T.card,
                    border:`1px solid ${pickedReason===r.id ? T.brand : T.line}`, cursor:'pointer',
                    display:'flex', alignItems:'center', gap:10,
                  }}>
                    <div style={{ width:18, height:18, borderRadius:9, border:`1.5px solid ${pickedReason===r.id?T.brand:T.line}`, display:'flex', alignItems:'center', justifyContent:'center' }}>
                      {pickedReason===r.id && <div style={{ width:8, height:8, borderRadius:4, background:T.brand }}/>}
                    </div>
                    <div style={{ fontSize:13, fontWeight:600, color:T.ink }}>{r.label}</div>
                  </button>
                ))}
              </div>
            </div>

            <div style={{ marginTop:14, padding:'12px 14px', background:T.card, borderRadius:12, border:`0.5px solid ${T.line}` }}>
              <div style={{ fontSize:11, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:6 }}>เก็บไว้แบบไหน</div>
              <CheckRow dark={dark} label="ส่ง message อำลา + สรุปผล" defaultChecked/>
              <CheckRow dark={dark} label="เก็บ data + รูปไว้ (สำหรับกลับมา)" defaultChecked/>
              <CheckRow dark={dark} label="แจ้ง follow-up อีก 30 วัน"/>
            </div>

            <div style={{ display:'flex', gap:8, marginTop:18 }}>
              <button onClick={()=>setStep('menu')} style={{ flex:1, padding:'14px 0', borderRadius:14, background:T.card, border:`0.5px solid ${T.line}`, color:T.ink, fontSize:14, fontWeight:600, cursor:'pointer' }}>← กลับ</button>
              <button disabled={!pickedReason} onClick={()=>setStep('done')} style={{ flex:2, padding:'14px 0', borderRadius:14, background:pickedReason?'#E1573B':T.line, color:'#fff', border:0, fontSize:14, fontWeight:700, cursor:pickedReason?'pointer':'not-allowed', opacity:pickedReason?1:0.5 }}>📦 Archive</button>
            </div>
          </div>
        )}

        {step==='renew' && (
          <div style={{ padding:'4px 18px 0' }}>
            <div style={{ fontSize:32, marginBottom:8 }}>↻</div>
            <div style={{ fontSize:20, fontWeight:700, color:T.ink, letterSpacing:-0.3 }}>{isArchived?'กลับมาเทรน':'ต่อแพ็คเกจ'}</div>
            <div style={{ fontSize:13, color:T.ink2, marginTop:6, lineHeight:1.5 }}>{isArchived?'ดึง '+trainee.nick+' กลับเข้า active list':'ลูกเทรนตกลงต่อแล้ว — เลือกระยะเวลา'}</div>

            <div style={{ marginTop:18 }}>
              <div style={{ fontSize:11, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:10 }}>แพ็คเกจใหม่</div>
              <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                {[
                  {id:'1mo', label:'1 เดือน', price:'฿4,500', sub:'ทดลอง · 4 sessions'},
                  {id:'3mo', label:'3 เดือน', price:'฿12,000', sub:'แนะนำ · 12 sessions · ลด 11%', popular:true},
                  {id:'6mo', label:'6 เดือน', price:'฿22,000', sub:'24 sessions · ลด 18%'},
                ].map(o=>(
                  <button key={o.id} onClick={()=>setPickedRenew(o.id)} style={{
                    padding:'14px 14px', borderRadius:14, textAlign:'left',
                    background: pickedRenew===o.id ? (dark?'rgba(201,247,111,0.10)':'rgba(155,227,107,0.12)') : T.card,
                    border:`1px solid ${pickedRenew===o.id ? T.brand : T.line}`, cursor:'pointer',
                    display:'flex', alignItems:'center', gap:12, position:'relative',
                  }}>
                    <div style={{ width:18, height:18, borderRadius:9, border:`1.5px solid ${pickedRenew===o.id?T.brand:T.line}`, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                      {pickedRenew===o.id && <div style={{ width:8, height:8, borderRadius:4, background:T.brand }}/>}
                    </div>
                    <div style={{ flex:1 }}>
                      <div style={{ fontSize:14, fontWeight:700, color:T.ink, display:'flex', alignItems:'center', gap:6 }}>
                        {o.label}
                        {o.popular && <span style={{ fontSize:9, fontWeight:700, color:T.brandInk, background:T.brand, padding:'2px 6px', borderRadius:4, letterSpacing:0.3 }}>POPULAR</span>}
                      </div>
                      <div style={{ fontSize:11, color:T.ink2, marginTop:2 }}>{o.sub}</div>
                    </div>
                    <div style={{ fontSize:14, fontWeight:700, color:T.ink, fontFamily:'"Plus Jakarta Sans", system-ui' }}>{o.price}</div>
                  </button>
                ))}
              </div>
            </div>

            <div style={{ display:'flex', gap:8, marginTop:18 }}>
              <button onClick={()=>setStep(isArchived?null:'menu')} style={{ flex:1, padding:'14px 0', borderRadius:14, background:T.card, border:`0.5px solid ${T.line}`, color:T.ink, fontSize:14, fontWeight:600, cursor:'pointer' }}>← กลับ</button>
              <button onClick={()=>setStep('done')} style={{ flex:2, padding:'14px 0', borderRadius:14, background:T.brand, color:T.brandInk, border:0, fontSize:14, fontWeight:700, cursor:'pointer' }}>↻ ต่อแพ็คเกจ</button>
            </div>
          </div>
        )}

        {step==='done' && (
          <div style={{ padding:'24px 18px 0', textAlign:'center' }}>
            <div style={{ fontSize:48, marginBottom:8 }}>✓</div>
            <div style={{ fontSize:20, fontWeight:700, color:T.ink, letterSpacing:-0.3 }}>เรียบร้อย</div>
            <div style={{ fontSize:13, color:T.ink2, marginTop:6, lineHeight:1.5, padding:'0 12px' }}>
              บันทึกแล้ว — ส่ง message ให้ {trainee.nick} อัตโนมัติ และอัพเดท roster แล้ว
            </div>
            <button onClick={close} style={{ width:'100%', marginTop:24, padding:'14px 0', borderRadius:14, background:T.brand, color:T.brandInk, border:0, fontSize:14, fontWeight:700, cursor:'pointer' }}>เสร็จ</button>
          </div>
        )}
      </div>
    </div>
  );
}

function SheetAction({ dark, icon, iconBg, title, desc, onClick, tone }) {
  const T = tokens(dark);
  return (
    <button onClick={onClick} style={{
      display:'flex', alignItems:'center', gap:12, padding:'14px 14px',
      background: tone==='brand' ? (dark?'rgba(201,247,111,0.08)':'rgba(155,227,107,0.10)') : T.card,
      border:`0.5px solid ${tone==='brand'?T.brand:T.line}`,
      borderRadius:14, cursor:'pointer', textAlign:'left', width:'100%',
    }}>
      <div style={{ width:38, height:38, borderRadius:10, background:iconBg, display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, fontSize:18 }}>{icon}</div>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontSize:14, fontWeight:700, color:T.ink }}>{title}</div>
        <div style={{ fontSize:11, color:T.ink2, marginTop:2, lineHeight:1.4 }}>{desc}</div>
      </div>
      <div style={{ color:T.ink3, fontSize:18 }}>›</div>
    </button>
  );
}

function Bullet({ dark, text }) {
  const T = tokens(dark);
  return (
    <div style={{ display:'flex', gap:8, alignItems:'flex-start', marginBottom:6 }}>
      <div style={{ width:4, height:4, borderRadius:2, background:T.ink, marginTop:7, flexShrink:0 }}/>
      <div style={{ fontSize:12, color:T.ink, lineHeight:1.5 }}>{text}</div>
    </div>
  );
}

function CheckRow({ dark, label, defaultChecked }) {
  const T = tokens(dark);
  const [on, setOn] = React.useState(!!defaultChecked);
  return (
    <button onClick={()=>setOn(!on)} style={{ display:'flex', alignItems:'center', gap:10, padding:'8px 0', background:'transparent', border:0, cursor:'pointer', width:'100%', textAlign:'left' }}>
      <div style={{ width:20, height:20, borderRadius:6, border:`1.5px solid ${on?T.brand:T.line}`, background:on?T.brand:'transparent', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
        {on && <Icon name="check" size={12} color={T.brandInk} stroke={3}/>}
      </div>
      <div style={{ fontSize:13, color:T.ink }}>{label}</div>
    </button>
  );
}

function TrainerAssign({ dark, onClose }) {
  const T = tokens(dark);
  const [picked, setPicked] = React.useState({lower:true, cardio:false, mobility:false, hiit:false});
  return (
    <div style={{ background:T.bg, minHeight:'100%', paddingBottom:120 }}>
      <PhoneStatus dark={dark}/>
      <div style={{ padding:'4px 16px 0', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <button onClick={onClose} style={{ width:36, height:36, borderRadius:18, background:T.card, border:`0.5px solid ${T.line}`, display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon name="x" size={18} color={T.ink}/>
        </button>
        <div style={{ fontSize:14, fontWeight:700, color:T.ink }}>สั่งการบ้าน</div>
        <button style={{ background:'transparent', border:0, color:T.brand==='#C9F76F'?'#41A55E':T.brand, fontSize:13, fontWeight:700 }}>ส่ง</button>
      </div>

      <div style={{ padding:'14px 20px 0' }}>
        <div style={{ fontSize:24, fontWeight:700, color:T.ink, letterSpacing:-0.5 }}>วันพรุ่งนี้ · มิ้น</div>
        <div style={{ fontSize:13, color:T.ink2, marginTop:2 }}>เลือกแบบและปรับให้พอดี</div>
      </div>

      {/* template picker */}
      <div style={{ padding:'14px 16px 0' }}>
        <div style={{ fontSize:11, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:8 }}>เลือกจากเทมเพลต</div>
        <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
          {[
            {id:'lower', l:'Lower body', sub:'45 min · 6 ท่า', img:'lower'},
            {id:'cardio', l:'Cardio Z2', sub:'30 min · เดินเร็ว', img:'cardio'},
            {id:'mobility', l:'Mobility', sub:'15 min · ยืดเหยียด', img:'progress'},
            {id:'hiit', l:'HIIT', sub:'25 min · 8 รอบ', img:'upper'},
          ].map(t=>{
            const on = picked[t.id];
            return (
              <button key={t.id} onClick={()=>setPicked(p=>({...p, [t.id]:!p[t.id]}))} style={{
                background:T.card, border:`1.5px solid ${on?T.brand:T.line}`, borderRadius:14, padding:8, cursor:'pointer', textAlign:'left',
              }}>
                <div style={{ borderRadius:10, overflow:'hidden' }}>
                  <Placeholder kind={t.img} h={72} label=""/>
                </div>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginTop:8 }}>
                  <div>
                    <div style={{ fontSize:12, fontWeight:700, color:T.ink }}>{t.l}</div>
                    <div style={{ fontSize:10, color:T.ink2, marginTop:2 }}>{t.sub}</div>
                  </div>
                  <div style={{ width:18, height:18, borderRadius:9, background:on?T.brand:'transparent', border:`1.5px solid ${on?T.brand:T.line}`, display:'flex', alignItems:'center', justifyContent:'center' }}>
                    {on && <Icon name="check" size={11} color={T.brandInk} stroke={3}/>}
                  </div>
                </div>
              </button>
            );
          })}
        </div>
      </div>

      {/* meal plan */}
      <div style={{ padding:'18px 16px 0' }}>
        <div style={{ fontSize:11, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:8 }}>คำแนะนำอาหาร</div>
        <div style={{ background:T.card, borderRadius:14, padding:14, border:`0.5px solid ${T.line}` }}>
          <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
            {['คุมคาร์บมื้อเย็น', 'โปรตีน 120g', 'น้ำ 2.5L', 'งดของหวาน'].map((c,i)=>(
              <Pill key={i} kind="default" dark={dark}>{c} ✓</Pill>
            ))}
            <Pill kind="ghost" dark={dark}>+ เพิ่ม</Pill>
          </div>
        </div>
      </div>

      {/* note to trainee */}
      <div style={{ padding:'14px 16px 0' }}>
        <div style={{ fontSize:11, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:8 }}>โน้ตถึงลูกเทรน</div>
        <div style={{ background:T.card, borderRadius:14, padding:14, border:`0.5px solid ${T.line}`, fontSize:13, color:T.ink, lineHeight:1.5 }}>
          "พรุ่งนี้เน้น cardio เบาๆ ให้ขาได้พักจาก lower body วันนี้นะคะ ✨ ถ้ารู้สึกเมื่อยมากบอกได้เลย"
          <div style={{ display:'flex', gap:6, marginTop:10 }}>
            <button style={{ background:T.chip, border:0, padding:'6px 10px', borderRadius:99, fontSize:11, fontWeight:600, color:T.ink, display:'flex', alignItems:'center', gap:4 }}>
              <Icon name="mic" size={12} color={T.ink}/> เสียง
            </button>
            <button style={{ background:T.chip, border:0, padding:'6px 10px', borderRadius:99, fontSize:11, fontWeight:600, color:T.ink, display:'flex', alignItems:'center', gap:4 }}>
              <Icon name="spark" size={12} color={T.ink}/> AI ช่วยร่าง
            </button>
          </div>
        </div>
      </div>

      {/* CTA */}
      <div style={{ padding:'18px 16px 0' }}>
        <button style={{
          width:'100%', height:54, borderRadius:18, border:0, cursor:'pointer',
          background:T.brand, color:T.brandInk, fontSize:16, fontWeight:700, letterSpacing:0.2,
        }}>
          ส่งให้มิ้น (1 รายการ)
        </button>
      </div>
    </div>
  );
}

function TrainerMealReview({ dark }) {
  const T = tokens(dark);
  const [reaction, setReaction] = React.useState(null);
  const queue = [
    {who:TRAINEES[1], img:'lunch', meal:'มื้อกลางวัน', time:'5 นาที', score:88, ai:'plate balance ดี · ข้าวกล้อง อกไก่ สลัด สมส่วน', kcal:620, items:['ข้าวกล้อง 1 ถ้วย','อกไก่ย่าง 120g','สลัดผัก','น้ำสลัดงา']},
    {who:TRAINEES[4], img:'breakfast', meal:'มื้อเช้า', time:'18 นาที', score:95, ai:'protein:carb 1:1 + ผักใบเขียว ✓', kcal:380},
    {who:TRAINEES[3], img:'snack', meal:'ของว่าง', time:'42 นาที', score:62, ai:'น้ำตาล 22g เกินเป้า — ควรลดลง', kcal:280},
  ];
  const m = queue[0];
  return (
    <div style={{ paddingBottom:120, background:T.bg, minHeight:'100%' }}>
      <PhoneStatus dark={dark}/>
      <div style={{ padding:'4px 20px 0', display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
        <div>
          <div style={{ color:T.ink, fontSize:24, fontWeight:700, letterSpacing:-0.5 }}>คิวรีวิว</div>
          <div style={{ color:T.ink2, fontSize:12, marginTop:2 }}>{queue.length} มื้อรอ · 1 / {queue.length}</div>
        </div>
        <Icon name="filter" size={20} color={T.ink2}/>
      </div>

      {/* main card */}
      <div style={{ padding:'14px 16px 0' }}>
        <div style={{ background:T.card, borderRadius:22, border:`0.5px solid ${T.line}`, overflow:'hidden' }}>
          <div style={{ position:'relative' }}>
            <Placeholder kind={m.img} h={220} label=""/>
            <div style={{ position:'absolute', top:12, left:12, display:'flex', gap:8, alignItems:'center' }}>
              <Avatar name={m.who.name} tone={m.who.tone} size={32} ring dark={true}/>
              <div style={{ background:'rgba(14,17,16,0.7)', padding:'4px 10px', borderRadius:99 }}>
                <div style={{ fontSize:11, color:'#fff', fontWeight:700 }}>{m.who.nick}</div>
              </div>
            </div>
            <div style={{ position:'absolute', top:12, right:12 }}>
              <Pill kind={m.score>=85?'good':m.score>=70?'warn':'danger'} dark={dark}>AI · {m.score}/100</Pill>
            </div>
          </div>
          <div style={{ padding:14 }}>
            <div style={{ display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
              <div style={{ fontSize:15, fontWeight:700, color:T.ink }}>{m.meal} · {m.kcal} kcal</div>
              <div style={{ fontSize:11, color:T.ink3, fontFamily:'"JetBrains Mono", monospace' }}>{m.time} ที่แล้ว</div>
            </div>
            {m.items && (
              <div style={{ marginTop:8, display:'flex', flexWrap:'wrap', gap:5 }}>
                {m.items.map((it,i)=><Pill key={i} kind="default" dark={dark}>{it}</Pill>)}
              </div>
            )}
            <div style={{ marginTop:10, padding:10, background:T.chip, borderRadius:10, fontSize:12, color:T.ink2, lineHeight:1.5, display:'flex', gap:6 }}>
              <Icon name="spark" size={14} color={T.ink3}/>
              <span style={{ flex:1 }}><b style={{ color:T.ink }}>AI:</b> {m.ai}</span>
            </div>
          </div>
        </div>
      </div>

      {/* quick reactions */}
      <div style={{ padding:'14px 16px 0' }}>
        <div style={{ fontSize:11, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:8 }}>รีแอ็คเร็ว</div>
        <div style={{ display:'flex', gap:8, flexWrap:'wrap' }}>
          {[
            {e:'👏', l:'plate balance สวย'},
            {e:'🔥', l:'ทำต่อแบบนี้!'},
            {e:'💧', l:'อย่าลืมดื่มน้ำ'},
            {e:'🥗', l:'เพิ่มผักได้'},
            {e:'⚠️', l:'น้ำตาลเยอะ'},
            {e:'💪', l:'โปรตีนพอดี'},
          ].map((r,i)=>{
            const on = reaction===i;
            return (
              <button key={i} onClick={()=>setReaction(i)} style={{
                background: on?T.brand:T.card, border:`1px solid ${on?T.brand:T.line}`, borderRadius:99, padding:'8px 12px', cursor:'pointer',
                display:'flex', alignItems:'center', gap:6, color: on?T.brandInk:T.ink, fontSize:12, fontWeight:600,
              }}>
                <span style={{ fontSize:14 }}>{r.e}</span> {r.l}
              </button>
            );
          })}
        </div>
      </div>

      {/* custom reply */}
      <div style={{ padding:'14px 16px 0' }}>
        <div style={{ background:T.card, borderRadius:14, padding:'10px 12px', border:`0.5px solid ${T.line}`, fontSize:13, color:T.ink3, display:'flex', alignItems:'center', gap:8 }}>
          <span style={{ flex:1 }}>เพิ่มข้อความ...</span>
          <Icon name="mic" size={18} color={T.ink2}/>
          <Icon name="spark" size={18} color={T.ink2}/>
        </div>
      </div>

      {/* actions */}
      <div style={{ padding:'14px 16px 0', display:'flex', gap:8 }}>
        <button style={{ flex:1, height:50, borderRadius:14, border:`0.5px solid ${T.line}`, background:T.card, color:T.ink, fontWeight:600, fontSize:14, cursor:'pointer' }}>
          ข้าม
        </button>
        <button style={{ flex:2, height:50, borderRadius:14, border:0, background:T.brand, color:T.brandInk, fontWeight:700, fontSize:14, cursor:'pointer' }}>
          ส่งกลับ + ถัดไป
        </button>
      </div>

      {/* up next */}
      <div style={{ padding:'18px 16px 0' }}>
        <div style={{ fontSize:11, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:8 }}>ถัดไปในคิว</div>
        <div style={{ display:'flex', gap:8 }}>
          {queue.slice(1).map((q,i)=>(
            <div key={i} style={{ flex:1, background:T.card, borderRadius:12, border:`0.5px solid ${T.line}`, padding:8 }}>
              <div style={{ borderRadius:8, overflow:'hidden' }}><Placeholder kind={q.img} h={70} label=""/></div>
              <div style={{ display:'flex', alignItems:'center', gap:5, marginTop:6 }}>
                <Avatar name={q.who.name} tone={q.who.tone} size={18}/>
                <span style={{ fontSize:11, fontWeight:600, color:T.ink }}>{q.who.nick}</span>
              </div>
              <div style={{ fontSize:10, color:T.ink3, marginTop:2 }}>{q.time}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function TrainerCalendar({ dark }) {
  const T = tokens(dark);
  const [synced, setSynced] = React.useState(true); // demo: start synced
  const [showSync, setShowSync] = React.useState(null); // null | 'setup' | 'settings'
  const [target, setTarget] = React.useState('apple'); // apple | google | outlook
  const [twoWay, setTwoWay] = React.useState(true);
  const [scope, setScope] = React.useState('sessions'); // sessions | all
  const [remind, setRemind] = React.useState('15');
  return (
    <div style={{ paddingBottom:120 }}>
      <PhoneStatus dark={dark}/>
      <div style={{ padding:'4px 20px 12px', display:'flex', justifyContent:'space-between', alignItems:'flex-end' }}>
        <div>
          <div style={{ color:T.ink, fontSize:28, fontWeight:700, letterSpacing:-0.6 }}>ตารางนัด</div>
          <div style={{ color:T.ink2, fontSize:13, marginTop:2 }}>เม.ย. – พ.ค. · สัปดาห์นี้</div>
        </div>
        <button style={{ width:40, height:40, borderRadius:20, background:T.brand, border:0, display:'flex', alignItems:'center', justifyContent:'center' }}>
          <Icon name="plus" size={20} color={T.brandInk} stroke={2.4}/>
        </button>
      </div>

      {/* sync banner — always visible, switches state */}
      <div style={{ padding:'0 16px 12px' }}>
        {synced ? (
          <button onClick={()=>setShowSync('settings')} style={{
            width:'100%', display:'flex', alignItems:'center', gap:10,
            background: dark?'rgba(155,227,107,0.06)':'rgba(155,227,107,0.10)',
            border:`0.5px solid ${dark?'rgba(155,227,107,0.2)':'rgba(155,227,107,0.3)'}`,
            borderRadius:12, padding:'10px 12px', cursor:'pointer', textAlign:'left',
          }}>
            <div style={{ width:28, height:28, borderRadius:8, background:dark?'rgba(255,255,255,0.06)':'rgba(255,255,255,0.6)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, fontSize:14 }}>📅</div>
            <div style={{ flex:1, minWidth:0 }}>
              <div style={{ fontSize:12, fontWeight:700, color:T.ink, display:'flex', alignItems:'center', gap:6 }}>
                <span style={{ width:6, height:6, borderRadius:3, background:'#41A55E', boxShadow:'0 0 4px #41A55E80' }}/>
                Synced กับ {target==='apple'?'iPhone Calendar':target==='google'?'Google Calendar':'Outlook'}
              </div>
              <div style={{ fontSize:10, color:T.ink2, marginTop:1, fontFamily:'"JetBrains Mono", monospace' }}>อัปเดต 2 นาทีที่แล้ว · {twoWay?'2-way':'1-way'} · เตือน {remind}m</div>
            </div>
            <div style={{ fontSize:11, color:T.ink3, fontWeight:600 }}>ตั้งค่า ›</div>
          </button>
        ) : (
          <button onClick={()=>setShowSync('setup')} style={{
            width:'100%', display:'flex', alignItems:'center', gap:10,
            background: T.card, border:`0.5px dashed ${T.line}`,
            borderRadius:12, padding:'12px 12px', cursor:'pointer', textAlign:'left',
          }}>
            <div style={{ width:28, height:28, borderRadius:8, background:dark?'rgba(255,255,255,0.06)':'rgba(20,24,15,0.05)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0, fontSize:14 }}>📅</div>
            <div style={{ flex:1 }}>
              <div style={{ fontSize:12, fontWeight:700, color:T.ink }}>Sync กับ Calendar ในเครื่อง</div>
              <div style={{ fontSize:10, color:T.ink2, marginTop:2 }}>session ทั้งหมดจะขึ้นใน Calendar เครื่อง — ไม่ลืมนัด</div>
            </div>
            <div style={{ fontSize:11, color:T.brand==='#C9F76F'?'#41A55E':T.brand, fontWeight:700 }}>เปิด ›</div>
          </button>
        )}
      </div>

      {/* week strip */}
      <div style={{ padding:'0 16px', display:'flex', gap:6, marginBottom:14 }}>
        {SESSIONS.map((s,i)=>{
          const today = i===0;
          return (
            <div key={i} style={{ flex:1, background: today?T.ink:T.card, borderRadius:14, padding:'10px 6px', textAlign:'center', border:`0.5px solid ${today?'transparent':T.line}` }}>
              <div style={{ fontSize:10, fontWeight:600, color: today?T.bg:T.ink3 }}>{s.day}</div>
              <div style={{ fontSize:18, fontWeight:700, color: today?T.bg:T.ink, marginTop:2, fontFamily:'"Plus Jakarta Sans", system-ui' }}>{s.date}</div>
              <div style={{ display:'flex', gap:2, justifyContent:'center', marginTop:4 }}>
                {s.items.map((_,j)=><div key={j} style={{ width:4, height:4, borderRadius:2, background: today?T.brand:T.ink2 }}/>)}
                {s.items.length===0 && <div style={{ width:4, height:4, borderRadius:2, background:'transparent' }}/>}
              </div>
            </div>
          );
        })}
      </div>

      {/* timeline */}
      <div style={{ padding:'0 16px' }}>
        <div style={{ fontSize:13, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:10 }}>วันนี้ · จันทร์ 27</div>
        <div style={{ display:'flex', flexDirection:'column', gap:8, position:'relative' }}>
          {[
            {time:'07:00', t:'Lower body', who:TRAINEES[0], dur:'45 min', type:'workout', tone:'#9BE36B', done:true},
            {time:'12:30', t:'Meal review', who:TRAINEES[0], dur:'10 min', type:'review', tone:'#FFD66B'},
            {time:'18:00', t:'Check-in call', who:TRAINEES[1], dur:'30 min', type:'call', tone:'#6BC9FF'},
            {time:'19:30', t:'Plan ปรับใหม่', who:TRAINEES[2], dur:'15 min', type:'plan', tone:'#FF8A6B', urgent:true},
          ].map((s,i)=>(
            <div key={i} style={{ display:'flex', gap:12, alignItems:'stretch' }}>
              <div style={{ width:48, fontSize:11, fontFamily:'"JetBrains Mono", monospace', color:T.ink2, fontWeight:600, paddingTop:14 }}>{s.time}</div>
              <div style={{ flex:1, background:T.card, borderRadius:14, padding:'10px 12px', border:`0.5px solid ${s.urgent?'rgba(255,130,115,0.3)':T.line}`, display:'flex', alignItems:'center', gap:10, opacity: s.done?0.55:1 }}>
                <div style={{ width:3, alignSelf:'stretch', borderRadius:2, background:s.tone }}/>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:13, fontWeight:600, color:T.ink, textDecoration: s.done?'line-through':'none', display:'flex', alignItems:'center', gap:6 }}>
                    {s.t}
                    {synced && <span title="synced" style={{ fontSize:10, color:T.ink3 }}>↻</span>}
                  </div>
                  <div style={{ display:'flex', gap:6, alignItems:'center', marginTop:3 }}>
                    <Avatar name={s.who.name} tone={s.who.tone} size={18}/>
                    <span style={{ fontSize:11, color:T.ink2 }}>{s.who.nick} · {s.dur}</span>
                  </div>
                </div>
                {s.urgent && <Pill kind="danger" dark={dark}>ด่วน</Pill>}
                {s.done && <Icon name="check" size={16} color={T.good} stroke={2.4}/>}
              </div>
            </div>
          ))}

          {/* personal calendar block (from 2-way sync) */}
          {synced && twoWay && (
            <div style={{ display:'flex', gap:12, alignItems:'stretch' }}>
              <div style={{ width:48, fontSize:11, fontFamily:'"JetBrains Mono", monospace', color:T.ink3, fontWeight:600, paddingTop:14 }}>20:30</div>
              <div style={{ flex:1, borderRadius:14, padding:'10px 12px', border:`0.5px dashed ${T.line}`, background:dark?'rgba(255,255,255,0.02)':'rgba(20,24,15,0.02)', display:'flex', alignItems:'center', gap:10 }}>
                <div style={{ width:3, alignSelf:'stretch', borderRadius:2, background:T.ink3, opacity:0.5 }}/>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:12, fontWeight:600, color:T.ink2, fontStyle:'italic' }}>มื้อเย็นกับครอบครัว</div>
                  <div style={{ fontSize:10, color:T.ink3, marginTop:2 }}>📅 จาก iPhone Calendar · busy · ไม่นัดได้</div>
                </div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* tomorrow */}
      <div style={{ padding:'18px 16px 0' }}>
        <div style={{ fontSize:13, fontWeight:700, color:T.ink2, letterSpacing:0.5, textTransform:'uppercase', marginBottom:10 }}>พรุ่งนี้ · อังคาร 28</div>
        <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
          {SESSIONS[1].items.map((it,i)=>(
            <div key={i} style={{ background:T.card, borderRadius:14, padding:'10px 12px', border:`0.5px solid ${T.line}`, display:'flex', alignItems:'center', gap:10 }}>
              <div style={{ width:48, fontSize:11, fontFamily:'"JetBrains Mono", monospace', color:T.ink2, fontWeight:600 }}>{it.time}</div>
              <div style={{ flex:1, fontSize:13, fontWeight:600, color:T.ink, display:'flex', alignItems:'center', gap:6 }}>
                {it.title}
                {synced && <span style={{ fontSize:10, color:T.ink3 }}>↻</span>}
              </div>
              <span style={{ fontSize:11, color:T.ink2 }}>{it.who}</span>
            </div>
          ))}
        </div>
      </div>

      {showSync && (
        <CalendarSyncSheet
          dark={dark}
          step={showSync}
          setStep={setShowSync}
          synced={synced} setSynced={setSynced}
          target={target} setTarget={setTarget}
          twoWay={twoWay} setTwoWay={setTwoWay}
          scope={scope} setScope={setScope}
          remind={remind} setRemind={setRemind}
        />
      )}
    </div>
  );
}

Object.assign(window, {
  TrainerHome, TrainerRoster, TrainerTraineeDetail, TrainerAssign, TrainerMealReview, TrainerCalendar, CloseTraineeSheet,
});
