// ============ Student screens ============
const { useState, useEffect, useRef } = React;

const StudentHome = ({ me, onOpen, onNav }) => {
  const myWorks = DATA.works.filter(w => w.owners.includes(me.id));
  const reviewed = myWorks.filter(w => w.status === 'graded');
  const pending = myWorks.filter(w => w.status !== 'graded');
  const recent = [...DATA.works].reverse().slice(0,8);

  return (
    <div className="content">
      {/* hero */}
      <div className="card" style={{padding:'28px 32px', marginBottom:24, background:'linear-gradient(115deg, var(--brand-500), var(--brand-700))', color:'white', border:'none', position:'relative', overflow:'hidden'}}>
        <div style={{position:'absolute', right:-40, top:-40, width:240, height:240, borderRadius:'50%', background:'radial-gradient(circle, var(--warm-500), transparent 70%)', opacity:.5}}></div>
        <div style={{position:'relative'}}>
          <div className="mono" style={{fontSize:11, opacity:.7, letterSpacing:'.08em', textTransform:'uppercase'}}>สวัสดีตอนเช้า · GOOD MORNING</div>
          <div style={{fontFamily:'var(--font-serif)', fontSize:'clamp(28px, 4vw, 44px)', lineHeight:1.1, letterSpacing:'-.02em', marginTop:6, fontWeight:300}}>
            {me.name.split(' ').slice(1).join(' ')}<span style={{opacity:.7}}> ·</span> <em style={{fontWeight:400}}>keep creating.</em>
          </div>
          <div style={{marginTop:14, display:'flex', gap:24, fontSize:13, flexWrap:'wrap'}}>
            <div><span style={{opacity:.6}}>ผลงานสะสม · </span><strong>{myWorks.length}</strong> ชิ้น</div>
            <div><span style={{opacity:.6}}>ครูตรวจแล้ว · </span><strong>{reviewed.length}</strong></div>
            <div><span style={{opacity:.6}}>รอตรวจ · </span><strong>{pending.length}</strong></div>
          </div>
          <div style={{marginTop:18, display:'flex', gap:8, flexWrap:'wrap'}}>
            <button className="btn btn-warm" onClick={()=>onNav('upload')}><Icon name="upload" size={14} /> อัปโหลดผลงานใหม่</button>
            <button className="btn" style={{background:'rgba(255,255,255,.15)', color:'white'}} onClick={()=>onNav('gallery')}><Icon name="gallery" size={14} /> ดูผลงานทั้งหมด</button>
          </div>
        </div>
      </div>

      {/* progression timeline + sidebar */}
      <div style={{display:'grid', gridTemplateColumns:'1.5fr 1fr', gap:24}} className="dash-grid">
        <div>
          <div className="row between" style={{marginBottom:14}}>
            <div>
              <div style={{fontSize:17, fontWeight:600}}>พัฒนาการของฉัน <span className="tag-en">· my progression</span></div>
              <div className="muted" style={{fontSize:12.5}}>เรียงจากผลงานชิ้นแรกถึงปัจจุบัน · เพื่อให้เห็นการเติบโต</div>
            </div>
            <button className="btn btn-ghost sm" onClick={()=>onNav('gallery')}>ดูทั้งหมด <Icon name="arrow" size={12} /></button>
          </div>

          <div className="timeline">
            {myWorks.map((w, i) => (
              <div key={w.id} className="tl-item">
                <div className="tl-mark"></div>
                <div className="tl-date">ชิ้นที่ {i+1} · {H.fmtDate(w.date)} · {H.typeLabel(w.type)}</div>
                <div className="work-card" style={{maxWidth:380}} onClick={()=>onOpen(w)}>
                  <div className="work-thumb" style={{aspectRatio:'16/9'}}>
                    <div className={`thumb-bg ${w.thumb}`}></div>
                    <div className="corner"><span className="type-badge"><span aria-hidden>{H.typeIcon(w.type)}</span> {H.typeLabel(w.type)}</span></div>
                  </div>
                  <div className="meta">
                    <div className="title">{w.title}</div>
                    <div className="by tag-en">{w.titleEn}</div>
                    <div className="footer">
                      <span className="mono">{H.fmtDate(w.date)}</span>
                      {w.status === 'graded' ? <span style={{color:'var(--green-500)',marginLeft:'auto',fontWeight:600}}>✓ ตรวจแล้ว</span> : <span style={{color:'var(--warm-600)',marginLeft:'auto'}}>รอตรวจ</span>}
                    </div>
                  </div>
                </div>
              </div>
            ))}
            {myWorks.length === 0 && <Empty title="ยังไม่มีผลงาน" sub="Upload your first piece to begin." />}
          </div>
        </div>

        <div className="col" style={{gap:18}}>
          <div className="card card-pad">
            <div style={{fontSize:14, fontWeight:600, marginBottom:12}}>กิจกรรมล่าสุด <span className="tag-en">· activity</span></div>
            <div className="col" style={{gap:10}}>
              {DATA.activity.map((a,i)=>{
                const who = H.person(a.who);
                return (
                  <div key={i} className="row" style={{gap:10}}>
                    <Avatar person={who} size="sm" />
                    <div style={{flex:1, fontSize:12.5, lineHeight:1.4}}>
                      <strong>{who.name.split(' ').slice(-1)[0]}</strong> <span className="muted">{a.what}</span> <strong>"{a.target}"</strong>
                      <div className="muted mono" style={{fontSize:10.5}}>{a.when}</div>
                    </div>
                  </div>
                );
              })}
            </div>
          </div>

          <div className="card card-pad" style={{background:'var(--warm-100)', borderColor:'var(--warm-200)'}}>
            <div className="row" style={{gap:8, marginBottom:8}}>
              <Icon name="sparkle" size={16} />
              <strong style={{fontSize:13}}>งานที่ต้องส่ง · Pending</strong>
            </div>
            {pending.length === 0 ? (
              <div className="muted" style={{fontSize:12.5}}>ไม่มีงานค้าง — เยี่ยมมาก!</div>
            ) : (
              <div className="col" style={{gap:8}}>
                {pending.slice(0,3).map(w=>(
                  <button key={w.id} className="row between" onClick={()=>onOpen(w)}
                    style={{padding:10, background:'white', borderRadius:10, border:'1px solid var(--warm-200)', textAlign:'left', cursor:'pointer'}}>
                    <div>
                      <div style={{fontSize:13, fontWeight:600}}>{w.title}</div>
                      <div className="muted mono" style={{fontSize:10.5}}>{H.fmtDate(w.date)} · {H.typeLabel(w.type)}</div>
                    </div>
                    <Icon name="arrow" size={14} />
                  </button>
                ))}
              </div>
            )}
          </div>

          <div className="card card-pad">
            <div style={{fontSize:14, fontWeight:600, marginBottom:10}}>ฟีดเพื่อน <span className="tag-en">· classmates</span></div>
            <div className="col" style={{gap:8}}>
              {recent.slice(0,4).map(w=>(
                <button key={w.id} className="row" onClick={()=>onOpen(w)} style={{gap:10, padding:6, borderRadius:10, textAlign:'left'}}>
                  <div style={{width:44, height:44, borderRadius:8, overflow:'hidden', position:'relative', flexShrink:0}}>
                    <div className={`thumb-bg ${w.thumb}`}></div>
                  </div>
                  <div style={{flex:1, minWidth:0}}>
                    <div style={{fontSize:12.5, fontWeight:600, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{w.title}</div>
                    <div className="muted" style={{fontSize:11}}>{w.owners.map(id=>H.person(id).name.split(' ').slice(-1)[0]).join(', ')}</div>
                  </div>
                </button>
              ))}
            </div>
          </div>
        </div>
      </div>

      <style>{`@media (max-width:900px){.dash-grid{grid-template-columns:1fr !important}}`}</style>
    </div>
  );
};

// --- Upload ---
const StudentUpload = ({ me, onDone }) => {
  const [step, setStep] = useState(1);
  const [title, setTitle] = useState('');
  const [titleEn, setTitleEn] = useState('');
  const [type, setType] = useState('sketch');
  const [desc, setDesc] = useState('');
  const [asGroup, setAsGroup] = useState(false);
  const [group, setGroup] = useState('');
  const [file, setFile] = useState(null);
  const [progress, setProgress] = useState(0);

  const myGroups = DATA.groups.filter(g => g.members.includes(me.id));

  const [submitErr, setSubmitErr] = useState('');

  const submit = async () => {
    setSubmitErr('');
    setStep(3);
    setProgress(10);
    try {
      let ownerUserIds = [me.id];
      if (asGroup && group) {
        const g = H.byId(DATA.groups, group);
        if (g) ownerUserIds = g.members;
      }
      setProgress(40);
      await window.DB.createWork({
        title,
        titleEn,
        classId: me.classId,
        type,
        description: desc,
        ownerUserIds,
        file,
      });
      setProgress(100);
      setTimeout(()=> onDone && onDone(), 600);
    } catch (e) {
      console.error(e);
      setSubmitErr(e.message || String(e));
      setStep(2);
      setProgress(0);
    }
  };

  return (
    <div className="content" style={{maxWidth:780, margin:'0 auto'}}>
      <div className="row" style={{gap:6, marginBottom:18}}>
        <span className={`chip ${step>=1?'':'neutral'}`}>1 · ไฟล์</span>
        <span style={{width:24, height:1, background:'var(--line)'}}></span>
        <span className={`chip ${step>=2?'':'neutral'}`}>2 · รายละเอียด</span>
        <span style={{width:24, height:1, background:'var(--line)'}}></span>
        <span className={`chip ${step>=3?'':'neutral'}`}>3 · ส่ง</span>
      </div>

      {step === 1 && (
        <div className="card card-pad col" style={{gap:18}}>
          <div>
            <div style={{fontFamily:'var(--font-serif)', fontSize:32}}>เลือกไฟล์ผลงาน <em className="muted">· Choose file</em></div>
            <div className="muted" style={{fontSize:13}}>รองรับ: รูปภาพ, วิดีโอ, PDF, ไฟล์งาน — ขนาดไม่เกิน 200MB</div>
          </div>
          <label className="dropzone">
            <Icon name="upload" size={32} stroke={1.3} />
            <div style={{fontSize:15, fontWeight:600}}>{file ? file.name : 'ลากไฟล์มาวางที่นี่ หรือกดเพื่อเลือก'}</div>
            <div className="muted" style={{fontSize:12}}>Drag & drop, or click to browse</div>
            <input type="file" hidden onChange={e=>setFile(e.target.files[0])} />
            {!file && <div className="row" style={{gap:6, marginTop:6}}>
              {['🖼 รูป','▶ วิดีโอ','📄 PDF','✏ สเก็ตช์','📦 ZIP'].map(x=>(
                <span key={x} className="chip neutral" style={{fontSize:10.5}}>{x}</span>
              ))}
            </div>}
          </label>
          {file && (
            <div className="row" style={{padding:'10px 14px', background:'var(--brand-50)', borderRadius:10, gap:10}}>
              <Icon name="file" size={20} />
              <div style={{flex:1, minWidth:0}}>
                <div style={{fontSize:13, fontWeight:600, whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis'}}>{file.name}</div>
                <div className="muted mono" style={{fontSize:10.5}}>{(file.size/1024/1024).toFixed(2)} MB</div>
              </div>
              <button className="btn-ghost" style={{padding:6}} onClick={()=>setFile(null)}><Icon name="x" size={14} /></button>
            </div>
          )}
          <div className="row between">
            <div className="muted" style={{fontSize:12}}>ขั้นที่ 1 จาก 3</div>
            <button className="btn btn-brand" disabled={!file} onClick={()=>setStep(2)} style={{opacity:file?1:.5}}>ถัดไป <Icon name="arrow" size={14} /></button>
          </div>
        </div>
      )}

      {step === 2 && (
        <div className="card card-pad col" style={{gap:14}}>
          <div>
            <div style={{fontFamily:'var(--font-serif)', fontSize:32}}>รายละเอียดผลงาน <em className="muted">· Details</em></div>
            <div className="muted" style={{fontSize:13}}>กรอกข้อมูลให้ครูและเพื่อนรู้จักผลงานของคุณ</div>
          </div>
          <div className="row" style={{gap:12, flexWrap:'wrap'}}>
            <div className="field" style={{flex:'1 1 240px'}}>
              <label>ชื่อผลงาน · Title (ภาษาไทย)</label>
              <input className="input" value={title} onChange={e=>setTitle(e.target.value)} placeholder="เช่น พอร์ตเทรตเพื่อน" />
            </div>
            <div className="field" style={{flex:'1 1 240px'}}>
              <label>Title (English)</label>
              <input className="input" value={titleEn} onChange={e=>setTitleEn(e.target.value)} placeholder="e.g. Portrait of a Friend" />
            </div>
          </div>
          <div className="field">
            <label>ประเภทผลงาน · Type</label>
            <div className="row wrap" style={{gap:6}}>
              {[
                ['sketch','✏ Sketch / สเก็ตช์'],
                ['painting','🎨 Painting / วาดระบายสี'],
                ['illustration','✦ Illustration / ภาพประกอบ'],
                ['storyboard','☷ Storyboard'],
                ['animation','▶ Animation / แอนิเมชัน'],
                ['video','■ Video'],
                ['document','📄 Document'],
              ].map(([v,l])=>(
                <button key={v} className={`chip ${type===v?'':'neutral'}`}
                  style={{cursor:'pointer', padding:'6px 12px', fontSize:12.5}}
                  onClick={()=>setType(v)}>{l}</button>
              ))}
            </div>
          </div>
          <div className="field">
            <label>คำอธิบาย · Description</label>
            <textarea className="textarea" rows={4} value={desc} onChange={e=>setDesc(e.target.value)} placeholder="เล่าให้ฟังหน่อย — ใช้เทคนิคอะไร, ได้แรงบันดาลใจจากไหน…" />
          </div>
          <div className="field">
            <label>ส่งในนามของ · Submit as</label>
            <div className="seg" style={{alignSelf:'flex-start'}}>
              <button className={!asGroup?'on':''} onClick={()=>setAsGroup(false)}><Icon name="user" size={12} /> รายบุคคล</button>
              <button className={asGroup?'on':''} onClick={()=>setAsGroup(true)}><Icon name="users" size={12} /> งานกลุ่ม</button>
            </div>
            {asGroup && (
              <div style={{marginTop:10}}>
                <select className="select" value={group} onChange={e=>setGroup(e.target.value)}>
                  <option value="">— เลือกกลุ่มของคุณ —</option>
                  {myGroups.map(g=><option key={g.id} value={g.id}>{g.name} ({g.members.length} คน)</option>)}
                </select>
                {myGroups.length === 0 && (
                  <div className="muted" style={{fontSize:11.5, marginTop:6}}>ยังไม่มีกลุ่ม — ครูจะเป็นคนกำหนดกลุ่มให้</div>
                )}
              </div>
            )}
          </div>
          <div className="row between">
            <button className="btn btn-ghost" onClick={()=>setStep(1)}><Icon name="arrowLeft" size={14} /> ย้อนกลับ</button>
            <button className="btn btn-brand" onClick={submit} disabled={!title}>ส่งผลงาน <Icon name="arrow" size={14} /></button>
          </div>
          {submitErr && (
            <div style={{fontSize:12.5, color:'oklch(0.45 0.18 25)', background:'oklch(0.97 0.04 25)', border:'1px solid oklch(0.85 0.08 25)', padding:'10px 12px', borderRadius:10}}>
              อัปโหลดไม่สำเร็จ: {submitErr}
            </div>
          )}
        </div>
      )}

      {step === 3 && (
        <div className="card card-pad col" style={{gap:18, alignItems:'center', textAlign:'center', padding:48}}>
          {progress < 100 ? (
            <>
              <div style={{width:64, height:64, borderRadius:99, background:'var(--brand-50)', display:'grid', placeItems:'center'}}>
                <Icon name="upload" size={28} stroke={1.4} />
              </div>
              <div style={{fontFamily:'var(--font-serif)', fontSize:28}}>กำลังอัปโหลด…</div>
              <div className="pbar" style={{width:'100%', maxWidth:400}}><div style={{width:progress+'%'}}></div></div>
              <div className="muted mono" style={{fontSize:12}}>{progress}% · {file?.name}</div>
            </>
          ) : (
            <>
              <div style={{width:72, height:72, borderRadius:99, background:'var(--green-500)', color:'white', display:'grid', placeItems:'center'}}>
                <Icon name="check" size={36} stroke={2} />
              </div>
              <div style={{fontFamily:'var(--font-serif)', fontSize:32}}>ส่งสำเร็จ! <em className="muted">Submitted.</em></div>
              <div className="muted" style={{fontSize:13.5}}>ผลงาน "<strong>{title}</strong>" ถูกเพิ่มเข้าระบบแล้ว ครูจะตรวจให้เร็วๆ นี้</div>
            </>
          )}
        </div>
      )}
    </div>
  );
};

// --- Gallery (the main filter view) ---
const Gallery = ({ me, role, onOpen }) => {
  const [view, setView] = useState('class');   // class | individual | group
  const [classFilter, setClassFilter] = useState(role==='student' ? me.classId : 'p5-1');
  const [groupFilter, setGroupFilter] = useState('all');
  const [personFilter, setPersonFilter] = useState('all');
  const [typeFilter, setTypeFilter] = useState('all');
  const [sortOrder, setSortOrder] = useState('asc'); // asc = oldest first (for progression)

  let works = [...DATA.works];

  if (view === 'class') {
    works = works.filter(w => w.classId === classFilter);
  } else if (view === 'individual') {
    if (personFilter === 'all') {
      works = works.filter(w => w.classId === classFilter && w.owners.length === 1);
    } else {
      works = works.filter(w => w.owners.length === 1 && w.owners[0] === personFilter);
    }
  } else if (view === 'group') {
    if (groupFilter === 'all') {
      works = works.filter(w => w.owners.length > 1);
    } else {
      const g = H.byId(DATA.groups, groupFilter);
      works = works.filter(w => w.owners.length > 1 && w.owners.every(o => g.members.includes(o)) && w.owners.length === g.members.length);
    }
  }

  if (typeFilter !== 'all') works = works.filter(w => w.type === typeFilter);

  works.sort((a,b)=> sortOrder==='asc' ? a.date.localeCompare(b.date) : b.date.localeCompare(a.date));

  const studentsInClass = DATA.students.filter(s => s.classId === classFilter);

  return (
    <div className="content">
      <div className="row between" style={{marginBottom:18, flexWrap:'wrap', gap:12}}>
        <div>
          <div style={{fontSize:20, fontWeight:600}}>คลังผลงาน <span className="tag-en">· gallery</span></div>
          <div className="muted" style={{fontSize:12.5}}>เรียงจาก{sortOrder==='asc'?'เก่า → ใหม่ (เห็นพัฒนาการ)':'ใหม่ → เก่า'}  · {works.length} ผลงาน</div>
        </div>
        <div className="row" style={{gap:8}}>
          <button className="btn btn-outline sm" onClick={()=>setSortOrder(sortOrder==='asc'?'desc':'asc')}>
            <Icon name="filter" size={12} /> {sortOrder==='asc'?'เก่า → ใหม่':'ใหม่ → เก่า'}
          </button>
        </div>
      </div>

      <div className="filters">
        <Seg value={view} onChange={setView} options={[
          { value:'class', label:'รายห้อง · Class'},
          { value:'individual', label:'รายบุคคล · Individual'},
          { value:'group', label:'รายกลุ่ม · Group'},
        ]} />

        <div style={{width:1, height:24, background:'var(--line)'}}></div>

        {(view === 'class' || view === 'individual') && (
          <select className="select" style={{padding:'6px 10px', fontSize:12.5, height:32, width:'auto'}}
            value={classFilter} onChange={e=>setClassFilter(e.target.value)}>
            {DATA.classes.map(c => <option key={c.id} value={c.id}>{c.label}</option>)}
          </select>
        )}

        {view === 'individual' && (
          <select className="select" style={{padding:'6px 10px', fontSize:12.5, height:32, width:'auto'}}
            value={personFilter} onChange={e=>setPersonFilter(e.target.value)}>
            <option value="all">นักเรียนทั้งหมด</option>
            {studentsInClass.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
          </select>
        )}

        {view === 'group' && (
          <select className="select" style={{padding:'6px 10px', fontSize:12.5, height:32, width:'auto'}}
            value={groupFilter} onChange={e=>setGroupFilter(e.target.value)}>
            <option value="all">ทุกกลุ่ม</option>
            {DATA.groups.map(g => <option key={g.id} value={g.id}>{g.name} ({H.cls(g.classId).label})</option>)}
          </select>
        )}

        <select className="select" style={{padding:'6px 10px', fontSize:12.5, height:32, width:'auto'}}
          value={typeFilter} onChange={e=>setTypeFilter(e.target.value)}>
          <option value="all">ทุกประเภท</option>
          <option value="sketch">Sketch</option>
          <option value="painting">Painting</option>
          <option value="illustration">Illustration</option>
          <option value="storyboard">Storyboard</option>
          <option value="animation">Animation</option>
        </select>
      </div>

      {/* progression-aware view when sorted ASC and filtered to one person/group */}
      {sortOrder === 'asc' && (view==='individual' && personFilter!=='all' || view==='group' && groupFilter!=='all') ? (
        <div className="timeline">
          {works.map((w, i) => (
            <div key={w.id} className="tl-item">
              <div className="tl-mark"></div>
              <div className="tl-date">{i===0?'จุดเริ่มต้น · ':''}ชิ้นที่ {i+1} · {H.fmtDate(w.date)}</div>
              <div onClick={()=>onOpen(w)} style={{cursor:'pointer'}}>
                <WorkCard work={w} onClick={()=>onOpen(w)} />
              </div>
            </div>
          ))}
          {works.length === 0 && <Empty title="ยังไม่มีผลงานในมุมมองนี้" />}
        </div>
      ) : (
        <div className="work-grid">
          {works.map(w => <WorkCard key={w.id} work={w} onClick={()=>onOpen(w)} />)}
          {works.length === 0 && <div style={{gridColumn:'1/-1'}}><Empty title="ไม่พบผลงานตามตัวกรอง" /></div>}
        </div>
      )}
    </div>
  );
};

// --- Profile ---
const StudentProfile = ({ me, onOpen }) => {
  const myWorks = DATA.works.filter(w => w.owners.includes(me.id));
  const myGroups = DATA.groups.filter(g => g.members.includes(me.id));
  const cls = H.cls(me.classId);
  const [photoUrl, setPhotoUrl] = useState(me.photo || null);
  const [showPwModal, setShowPwModal] = useState(false);
  const fileRef = useRef(null);

  const onPhotoChange = async (e) => {
    const f = e.target.files?.[0]; if (!f) return;
    const tempUrl = URL.createObjectURL(f);
    setPhotoUrl(tempUrl);
    try {
      const url = await window.DB.uploadAvatar(f);
      setPhotoUrl(url);
      me.photo = url;
    } catch (err) {
      console.error(err);
      alert('อัปโหลดรูปโปรไฟล์ไม่สำเร็จ: ' + (err.message || err));
      setPhotoUrl(me.photo || null);
    }
  };

  return (
    <div className="content">
      <div className="card card-pad" style={{marginBottom:20}}>
        <div className="row" style={{gap:18, flexWrap:'wrap'}}>
          {/* avatar with edit affordance */}
          <div style={{position:'relative', flexShrink:0}}>
            {photoUrl ? (
              <img src={photoUrl} alt="profile" style={{width:96, height:96, borderRadius:'50%', objectFit:'cover', display:'block', border:'3px solid var(--paper)', boxShadow:'var(--shadow-2)'}} />
            ) : (
              <div style={{width:96, height:96, borderRadius:'50%', background:me.color, display:'grid', placeItems:'center', color:'white', fontSize:36, fontWeight:600}}>{me.initial}</div>
            )}
            <button onClick={()=>fileRef.current?.click()}
              title="เปลี่ยนรูปโปรไฟล์"
              style={{position:'absolute', right:-4, bottom:-4, width:34, height:34, borderRadius:'50%', background:'var(--ink)', color:'var(--paper)', display:'grid', placeItems:'center', border:'3px solid var(--paper)', cursor:'pointer'}}>
              <Icon name="edit" size={14} />
            </button>
            <input type="file" accept="image/*" ref={fileRef} hidden onChange={onPhotoChange} />
          </div>

          <div style={{flex:1, minWidth:200}}>
            <div style={{fontFamily:'var(--font-serif)', fontWeight:300, fontSize:36, lineHeight:1.1}}>{me.name}</div>
            <div className="tag-en" style={{fontSize:17, fontWeight:300}}>{me.nameEn}</div>
            <div className="row wrap" style={{gap:8, marginTop:10}}>
              <span className="chip">{cls.label}</span>
              <span className="chip neutral">ID: {me.id}</span>
              <span className="chip neutral">{me.email}</span>
            </div>
          </div>
          <div className="row" style={{gap:18, alignSelf:'flex-end', flexWrap:'wrap'}}>
            <div><div className="muted mono" style={{fontSize:10.5, textTransform:'uppercase'}}>ผลงาน</div><div style={{fontFamily:'var(--font-serif)', fontSize:32, fontWeight:300}}>{myWorks.length}</div></div>
            <div><div className="muted mono" style={{fontSize:10.5, textTransform:'uppercase'}}>กลุ่ม</div><div style={{fontFamily:'var(--font-serif)', fontSize:32, fontWeight:300}}>{myGroups.length}</div></div>
          </div>
        </div>

        {/* account actions */}
        <div className="row wrap" style={{gap:8, marginTop:18, paddingTop:18, borderTop:'1px solid var(--line)'}}>
          <button className="btn btn-outline" onClick={()=>fileRef.current?.click()}><Icon name="image" size={14} /> เปลี่ยนรูปโปรไฟล์</button>
          <button className="btn btn-outline" onClick={()=>setShowPwModal(true)}><Icon name="settings" size={14} /> เปลี่ยนรหัสผ่าน</button>
        </div>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'2fr 1fr', gap:20}} className="dash-grid">
        <div>
          <div style={{fontSize:15, fontWeight:600, marginBottom:12}}>ผลงานของฉัน <span className="tag-en">· my works</span></div>
          <div className="work-grid">
            {myWorks.map(w => <WorkCard key={w.id} work={w} onClick={()=>onOpen(w)} />)}
            {myWorks.length === 0 && <div style={{gridColumn:'1/-1'}}><Empty /></div>}
          </div>
        </div>
        <div className="col" style={{gap:18}}>
          <div className="card card-pad">
            <div style={{fontSize:14, fontWeight:600, marginBottom:12}}>กลุ่มของฉัน <span className="tag-en">· my groups</span></div>
            {myGroups.length === 0 ? <div className="muted" style={{fontSize:12.5}}>ยังไม่ได้อยู่ในกลุ่ม</div> :
              <div className="col" style={{gap:10}}>
                {myGroups.map(g=>(
                  <div key={g.id} className="row" style={{padding:10, background:'var(--brand-50)', borderRadius:10, gap:10}}>
                    <div style={{width:32, height:32, borderRadius:8, background:g.color}}></div>
                    <div style={{flex:1}}>
                      <div style={{fontSize:13, fontWeight:600}}>{g.name}</div>
                      <div className="muted" style={{fontSize:11}}>{g.members.length} คน · {H.cls(g.classId).label}</div>
                    </div>
                    <AvatarStack ids={g.members} max={3} />
                  </div>
                ))}
              </div>
            }
          </div>
        </div>
      </div>

      {showPwModal && <ChangePasswordModal me={me} onClose={()=>setShowPwModal(false)} />}
    </div>
  );
};

// shared password change modal (used by both student & teacher)
const ChangePasswordModal = ({ me, onClose }) => {
  const [oldPw, setOldPw] = useState('');
  const [newPw, setNewPw] = useState('');
  const [confirmPw, setConfirmPw] = useState('');
  const [error, setError] = useState('');
  const [done, setDone] = useState(false);

  const save = () => {
    setError('');
    if (!oldPw || !newPw) return setError('กรุณากรอกรหัสผ่านให้ครบ');
    if (newPw.length < 6) return setError('รหัสผ่านใหม่ต้องยาวอย่างน้อย 6 ตัวอักษร');
    if (newPw !== confirmPw) return setError('รหัสผ่านใหม่และยืนยันไม่ตรงกัน');
    setDone(true);
    setTimeout(onClose, 1200);
  };

  return (
    <Modal onClose={onClose}>
      <div className="modal-head">
        <strong>เปลี่ยนรหัสผ่าน · Change Password</strong>
        <span className="muted" style={{fontSize:12}}>{me.name}</span>
        <div className="spacer" style={{flex:1}}></div>
        <button className="btn-ghost" style={{padding:6}} onClick={onClose}><Icon name="x" size={16} /></button>
      </div>
      {done ? (
        <div style={{padding:48, textAlign:'center'}}>
          <div style={{width:60, height:60, margin:'0 auto', borderRadius:99, background:'var(--green-500)', color:'white', display:'grid', placeItems:'center'}}><Icon name="check" size={28} stroke={2} /></div>
          <div style={{fontSize:18, fontWeight:600, marginTop:14}}>เปลี่ยนรหัสผ่านสำเร็จ</div>
          <div className="muted" style={{fontSize:13, marginTop:4}}>Password updated successfully</div>
        </div>
      ) : (
        <div style={{padding:20, display:'flex', flexDirection:'column', gap:14, maxWidth:480}}>
          <div className="field">
            <label>รหัสผ่านเดิม · Current Password</label>
            <input className="input" type="password" value={oldPw} onChange={e=>setOldPw(e.target.value)} autoFocus />
          </div>
          <div className="field">
            <label>รหัสผ่านใหม่ · New Password</label>
            <input className="input" type="password" value={newPw} onChange={e=>setNewPw(e.target.value)} />
            <div className="muted" style={{fontSize:11, marginTop:2}}>อย่างน้อย 6 ตัวอักษร</div>
          </div>
          <div className="field">
            <label>ยืนยันรหัสผ่านใหม่ · Confirm</label>
            <input className="input" type="password" value={confirmPw} onChange={e=>setConfirmPw(e.target.value)} />
          </div>
          {error && <div style={{fontSize:12, color:'var(--red-500)', padding:'8px 10px', background:'oklch(0.96 0.03 25)', borderRadius:8}}>{error}</div>}
          <div className="row between" style={{marginTop:4}}>
            <button className="btn btn-ghost" onClick={onClose}>ยกเลิก</button>
            <button className="btn btn-brand" onClick={save}><Icon name="check" size={12} /> บันทึก</button>
          </div>
        </div>
      )}
    </Modal>
  );
};

window.ChangePasswordModal = ChangePasswordModal;


Object.assign(window, { StudentHome, StudentUpload, Gallery, StudentProfile });
