// ============ Admin screens ============
const { useState, useRef } = React;

const AdminHome = ({ onNav }) => {
  const totalUsers = DATA.students.length + DATA.teachers.length + 1; // +1 admin
  const totalWorks = DATA.works.length;
  const storage = 4.7; // GB mock

  const byClass = DATA.classes.map(c => ({
    cls: c,
    students: DATA.students.filter(s => s.classId === c.id).length,
    works: DATA.works.filter(w => w.classId === c.id).length,
    groups: DATA.groups.filter(g => g.classId === c.id).length,
  }));

  return (
    <div className="content">
      <div className="row between" style={{marginBottom:20, flexWrap:'wrap', gap:10}}>
        <div>
          <div className="mono muted" style={{fontSize:11, letterSpacing:'.06em', textTransform:'uppercase'}}>Admin Dashboard · ผู้ดูแลระบบ</div>
          <div style={{fontFamily:'var(--font-serif)', fontSize:38, lineHeight:1.1, marginTop:4}}>ภาพรวมระบบ <em className="muted">— system overview.</em></div>
        </div>
        <div className="row" style={{gap:8}}>
          <span className="chip"><span className="live-dot"></span> ระบบปกติ · All systems normal</span>
        </div>
      </div>

      <div className="stat-grid" style={{marginBottom:24}}>
        <div className="stat-card brand">
          <div className="label">ผู้ใช้งานทั้งหมด</div>
          <div className="num">{totalUsers}</div>
          <div className="delta">+2 สัปดาห์นี้</div>
        </div>
        <div className="stat-card">
          <div className="label">ผลงานในระบบ</div>
          <div className="num">{totalWorks}</div>
          <div className="delta">+5 วันนี้</div>
        </div>
        <div className="stat-card">
          <div className="label">ห้องเรียน · Classes</div>
          <div className="num">{DATA.classes.length}</div>
          <div className="delta muted">ป.5: 2 · ป.6: 2</div>
        </div>
        <div className="stat-card warm">
          <div className="label">พื้นที่ใช้งาน</div>
          <div className="num">{storage}<span style={{fontSize:18, opacity:.6}}>GB</span></div>
          <div className="delta">จาก 50 GB</div>
        </div>
      </div>

      <div style={{display:'grid', gridTemplateColumns:'1fr 1fr', gap:20}} className="dash-grid">
        <div className="card card-pad">
          <div className="row between" style={{marginBottom:14}}>
            <div style={{fontSize:15, fontWeight:600}}>ห้องเรียน <span className="tag-en">· classes</span></div>
            <button className="btn btn-outline sm"><Icon name="plus" size={12} /> เพิ่มห้อง</button>
          </div>
          <table className="tbl">
            <thead>
              <tr><th>ห้อง</th><th>นักเรียน</th><th>ผลงาน</th><th>กลุ่ม</th><th></th></tr>
            </thead>
            <tbody>
              {byClass.map(b => (
                <tr key={b.cls.id}>
                  <td>
                    <div style={{fontWeight:600, fontSize:13}}>{b.cls.label}</div>
                    <div className="muted mono" style={{fontSize:10.5}}>ระดับ ป.{b.cls.grade}</div>
                  </td>
                  <td className="mono" style={{fontSize:13}}>{b.students}</td>
                  <td className="mono" style={{fontSize:13}}>{b.works}</td>
                  <td className="mono" style={{fontSize:13}}>{b.groups}</td>
                  <td><button className="btn btn-ghost sm"><Icon name="edit" size={12} /></button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div className="card card-pad">
          <div className="row between" style={{marginBottom:14}}>
            <div style={{fontSize:15, fontWeight:600}}>สิทธิ์การใช้งาน <span className="tag-en">· roles</span></div>
          </div>
          <div className="col" style={{gap:10}}>
            {[
              { role:'นักเรียน · Student', count: DATA.students.length, perms:['อัปโหลด','คอมเมนต์เพื่อน','ดูผลงานในห้อง'], color:'var(--brand-500)' },
              { role:'ครู · Teacher', count: DATA.teachers.length, perms:['ตรวจ + ให้คะแนน','จัดกลุ่ม','แก้ไขการส่ง','ดูทุกห้อง'], color:'var(--warm-500)' },
              { role:'ผู้ดูแล · Admin', count: 1, perms:['จัดการผู้ใช้','จัดการห้อง','ตั้งค่าระบบ','สำรองข้อมูล'], color:'var(--ink)' },
            ].map(r => (
              <div key={r.role} className="row" style={{padding:14, background:'var(--paper)', borderRadius:12, border:'1px solid var(--line)', gap:14}}>
                <div style={{width:38, height:38, borderRadius:10, background:r.color, color:'white', display:'grid', placeItems:'center', flexShrink:0}}>
                  <Icon name={r.role.includes('นักเรียน')?'user':r.role.includes('ครู')?'users':'settings'} size={18} />
                </div>
                <div style={{flex:1}}>
                  <div className="row" style={{gap:8, alignItems:'baseline'}}>
                    <strong style={{fontSize:13}}>{r.role}</strong>
                    <span className="muted mono" style={{fontSize:11}}>{r.count} คน</span>
                  </div>
                  <div className="row wrap" style={{gap:4, marginTop:6}}>
                    {r.perms.map(p => <span key={p} className="chip neutral" style={{fontSize:10.5}}>{p}</span>)}
                  </div>
                </div>
                <button className="btn btn-ghost sm"><Icon name="settings" size={12} /></button>
              </div>
            ))}
          </div>
        </div>

        <div className="card card-pad" style={{gridColumn:'1/-1'}}>
          <div className="row between" style={{marginBottom:12}}>
            <div style={{fontSize:15, fontWeight:600}}>กิจกรรมระบบ <span className="tag-en">· audit log</span></div>
          </div>
          <table className="tbl">
            <thead>
              <tr><th>เวลา</th><th>ผู้ใช้</th><th>การกระทำ</th><th>เป้าหมาย</th><th>IP</th></tr>
            </thead>
            <tbody>
              {[
                ['14:32', 't1', 'ให้คะแนน', 'ผลงาน w08 (Short Comic)', '10.0.1.45'],
                ['14:21', 's01', 'อัปโหลด', 'ผลงาน w04 (Cartoon Character)', '10.0.1.21'],
                ['13:58', 't1', 'สร้างกลุ่ม', 'กลุ่มไฟฉาย (ป.6/1)', '10.0.1.45'],
                ['12:11', 'admin', 'เข้าสู่ระบบ', 'Admin panel', '10.0.1.2'],
                ['11:44', 's07', 'คอมเมนต์', 'ผลงาน w08', '10.0.1.28'],
              ].map((row, i) => (
                <tr key={i}>
                  <td className="mono" style={{fontSize:11.5, color:'var(--muted)'}}>{row[0]}</td>
                  <td>
                    {row[1] === 'admin' ? <span className="chip">Admin</span> : (
                      <div className="row" style={{gap:6}}>
                        <Avatar person={H.person(row[1])} size="sm" />
                        <span style={{fontSize:12.5}}>{H.person(row[1]).name}</span>
                      </div>
                    )}
                  </td>
                  <td><span className="chip neutral">{row[2]}</span></td>
                  <td style={{fontSize:12.5}}>{row[3]}</td>
                  <td className="mono" style={{fontSize:11, color:'var(--muted)'}}>{row[4]}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
};

// --- Users management ---
const AdminUsers = () => {
  const [filter, setFilter] = useState('all'); // all | student | teacher
  const [q, setQ] = useState('');
  const [showAdd, setShowAdd] = useState(false);
  const [editing, setEditing] = useState(null);

  let users = [
    ...DATA.students.map(s => ({...s, role:'student'})),
    ...DATA.teachers.map(t => ({...t, role:'teacher'})),
  ];
  if (filter !== 'all') users = users.filter(u => u.role === filter);
  if (q) users = users.filter(u => u.name.includes(q) || (u.nameEn||'').toLowerCase().includes(q.toLowerCase()) || u.id.includes(q));

  return (
    <div className="content">
      <div className="row between" style={{marginBottom:18, flexWrap:'wrap', gap:10}}>
        <div>
          <div style={{fontSize:20, fontWeight:600}}>ผู้ใช้งาน <span className="tag-en">· users</span></div>
          <div className="muted" style={{fontSize:12.5}}>จัดการบัญชี, รหัสผ่าน, รูปโปรไฟล์ของนักเรียนและครู · {users.length} คน</div>
        </div>
        <div className="row" style={{gap:8}}>
          <button className="btn btn-outline"><Icon name="download" size={12} /> ส่งออก CSV</button>
          <button className="btn btn-brand" onClick={()=>setShowAdd(true)}><Icon name="plus" size={14} /> เพิ่มผู้ใช้</button>
        </div>
      </div>

      <div className="filters">
        <Seg value={filter} onChange={setFilter} options={[
          {value:'all', label:'ทั้งหมด · All'},
          {value:'student', label:'นักเรียน · Students'},
          {value:'teacher', label:'ครู · Teachers'},
        ]} />
        <div style={{flex:1, minWidth:200, position:'relative'}}>
          <Icon name="search" size={14} style={{position:'absolute', left:12, top:'50%', transform:'translateY(-50%)', color:'var(--muted)'}} />
          <input className="input" placeholder="ค้นหาชื่อ, ID, อีเมล…" value={q} onChange={e=>setQ(e.target.value)} style={{paddingLeft:36}} />
        </div>
      </div>

      <div className="card" style={{overflow:'hidden'}}>
        <table className="tbl">
          <thead>
            <tr>
              <th>ชื่อ</th>
              <th>User ID</th>
              <th>บทบาท</th>
              <th>ห้อง</th>
              <th>ผลงาน</th>
              <th>สถานะ</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {users.map(u => {
              const workCount = u.role === 'student' ? DATA.works.filter(w => w.owners.includes(u.id)).length : '—';
              return (
                <tr key={u.id}>
                  <td>
                    <div className="row" style={{gap:10}}>
                      {u.photo ? (
                        <img src={u.photo} alt="" className="avatar sm" style={{objectFit:'cover'}} />
                      ) : (
                        <Avatar person={u} size="sm" />
                      )}
                      <div>
                        <div style={{fontWeight:600, fontSize:13}}>{u.name}</div>
                        <div className="muted tag-en" style={{fontSize:11}}>{u.nameEn}</div>
                      </div>
                    </div>
                  </td>
                  <td className="mono" style={{fontSize:11.5}}>{u.id}</td>
                  <td>
                    <span className="chip" style={{background: u.role==='teacher'?'var(--warm-100)':'var(--brand-50)', color: u.role==='teacher'?'var(--warm-700)':'var(--brand-700)'}}>
                      {u.role === 'teacher' ? 'ครู · Teacher' : 'นักเรียน · Student'}
                    </span>
                  </td>
                  <td>{u.classId ? <span className="chip neutral">{H.cls(u.classId).label}</span> : <span className="muted">—</span>}</td>
                  <td className="mono" style={{fontSize:12}}>{workCount}</td>
                  <td><span className="chip" style={{background:'oklch(0.95 0.05 150)', color:'oklch(0.4 0.13 150)'}}><span className="live-dot" style={{background:'oklch(0.6 0.14 150)'}}></span>Active</span></td>
                  <td>
                    <div className="row" style={{gap:4}}>
                      <button className="btn btn-outline sm" onClick={()=>setEditing(u)}><Icon name="edit" size={12} /> จัดการ</button>
                      <button className="btn btn-ghost sm" style={{color:'var(--red-500)'}}><Icon name="trash" size={12} /></button>
                    </div>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>

      {showAdd && (
        <Modal onClose={()=>setShowAdd(false)}>
          <div className="modal-head">
            <strong>เพิ่มผู้ใช้ใหม่ · Add User</strong>
            <div className="spacer" style={{flex:1}}></div>
            <button className="btn-ghost" style={{padding:6}} onClick={()=>setShowAdd(false)}><Icon name="x" size={16} /></button>
          </div>
          <div style={{padding:20, display:'flex', flexDirection:'column', gap:14}}>
            <div className="field">
              <label>บทบาท · Role</label>
              <div className="seg" style={{alignSelf:'flex-start'}}>
                <button className="on">นักเรียน</button>
                <button>ครู</button>
              </div>
            </div>
            <div className="row" style={{gap:12}}>
              <div className="field" style={{flex:1}}><label>ชื่อ-สกุล (ไทย)</label><input className="input" placeholder="ด.ช./ด.ญ. ..." /></div>
              <div className="field" style={{flex:1}}><label>Name (English)</label><input className="input" placeholder="First L." /></div>
            </div>
            <div className="row" style={{gap:12}}>
              <div className="field" style={{flex:1}}><label>User ID</label><input className="input" placeholder="s13" /></div>
              <div className="field" style={{flex:1}}>
                <label>ห้อง</label>
                <select className="select">{DATA.classes.map(c=><option key={c.id}>{c.label}</option>)}</select>
              </div>
            </div>
            <div className="row" style={{gap:12}}>
              <div className="field" style={{flex:1}}><label>รหัสผ่านเริ่มต้น · Initial Password</label><input className="input" type="password" placeholder="••••••••" /></div>
              <div className="field" style={{flex:1}}><label>อีเมล · Email</label><input className="input" placeholder="@cmuds.ac.th" /></div>
            </div>
            <div className="row between" style={{marginTop:6}}>
              <button className="btn btn-ghost" onClick={()=>setShowAdd(false)}>ยกเลิก</button>
              <button className="btn btn-brand" onClick={()=>setShowAdd(false)}><Icon name="check" size={12} /> สร้างบัญชี</button>
            </div>
          </div>
        </Modal>
      )}

      {editing && <AdminEditUserModal user={editing} onClose={()=>setEditing(null)} />}
    </div>
  );
};

// --- Admin edit-user modal: change ID, password, profile photo ---
const AdminEditUserModal = ({ user, onClose }) => {
  const [name, setName] = useState(user.name);
  const [nameEn, setNameEn] = useState(user.nameEn || '');
  const [userId, setUserId] = useState(user.id);
  const [email, setEmail] = useState(user.email || '');
  const [classId, setClassId] = useState(user.classId || '');
  const [newPw, setNewPw] = useState('');
  const [confirmPw, setConfirmPw] = useState('');
  const [photoUrl, setPhotoUrl] = useState(user.photo || null);
  const [removePhoto, setRemovePhoto] = useState(false);
  const [msg, setMsg] = useState('');
  const fileRef = useRef(null);

  const onPhoto = (e) => {
    const f = e.target.files?.[0]; if (!f) return;
    setRemovePhoto(false);
    setPhotoUrl(URL.createObjectURL(f));
  };

  const save = () => {
    if (newPw && newPw !== confirmPw) {
      setMsg('error:รหัสผ่านใหม่ไม่ตรงกัน');
      return;
    }
    // persist to in-memory data
    user.name = name;
    user.nameEn = nameEn;
    user.id = userId;
    user.email = email;
    if (user.role === 'student') user.classId = classId;
    if (photoUrl && !removePhoto) user.photo = photoUrl;
    if (removePhoto) user.photo = null;
    setMsg('ok:บันทึกข้อมูลสำเร็จ');
    setTimeout(onClose, 900);
  };

  const resetPw = () => {
    const tmp = 'cmuds-'+Math.random().toString(36).slice(2,7);
    setNewPw(tmp); setConfirmPw(tmp);
    setMsg('info:รหัสผ่านชั่วคราว — แจ้งให้ผู้ใช้เปลี่ยนใหม่ทันที');
  };

  const isErr = msg.startsWith('error');
  const isOk = msg.startsWith('ok');
  const isInfo = msg.startsWith('info');

  return (
    <Modal onClose={onClose}>
      <div className="modal-head">
        <strong>จัดการผู้ใช้ · Manage User</strong>
        <span className="muted" style={{fontSize:12}}>{user.name}</span>
        <div className="spacer" style={{flex:1}}></div>
        <span className="chip neutral">{user.role === 'teacher' ? 'ครู · Teacher' : 'นักเรียน · Student'}</span>
        <button className="btn-ghost" style={{padding:6}} onClick={onClose}><Icon name="x" size={16} /></button>
      </div>
      <div style={{padding:20, display:'flex', flexDirection:'column', gap:16, maxHeight:'78vh', overflow:'auto'}}>
        {/* photo */}
        <section>
          <div className="mono muted" style={{fontSize:11, letterSpacing:'.06em', textTransform:'uppercase', marginBottom:10}}>รูปโปรไฟล์ · Profile Photo</div>
          <div className="row" style={{gap:14, alignItems:'center'}}>
            <div style={{position:'relative'}}>
              {photoUrl && !removePhoto ? (
                <img src={photoUrl} alt="" style={{width:80, height:80, borderRadius:'50%', objectFit:'cover', display:'block', border:'2px solid var(--paper)', boxShadow:'var(--shadow-1)'}} />
              ) : (
                <div style={{width:80, height:80, borderRadius:'50%', background:user.color, display:'grid', placeItems:'center', color:'white', fontSize:28, fontWeight:600}}>{user.initial}</div>
              )}
            </div>
            <div className="col" style={{gap:6}}>
              <div className="row" style={{gap:6}}>
                <button className="btn btn-outline sm" onClick={()=>fileRef.current?.click()}><Icon name="upload" size={12} /> อัปโหลดรูปใหม่</button>
                {(photoUrl || user.photo) && !removePhoto && (
                  <button className="btn btn-danger sm" onClick={()=>{setPhotoUrl(null); setRemovePhoto(true);}}><Icon name="trash" size={12} /> ลบรูป</button>
                )}
              </div>
              <input type="file" accept="image/*" hidden ref={fileRef} onChange={onPhoto} />
              <div className="muted" style={{fontSize:11}}>PNG / JPG ขนาดไม่เกิน 5MB</div>
            </div>
          </div>
        </section>

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

        {/* info */}
        <section>
          <div className="mono muted" style={{fontSize:11, letterSpacing:'.06em', textTransform:'uppercase', marginBottom:10}}>ข้อมูลผู้ใช้ · User Info</div>
          <div className="row" style={{gap:12, flexWrap:'wrap'}}>
            <div className="field" style={{flex:'1 1 220px'}}>
              <label>ชื่อ-สกุล (ไทย)</label>
              <input className="input" value={name} onChange={e=>setName(e.target.value)} />
            </div>
            <div className="field" style={{flex:'1 1 220px'}}>
              <label>Name (English)</label>
              <input className="input" value={nameEn} onChange={e=>setNameEn(e.target.value)} />
            </div>
          </div>
          <div className="row" style={{gap:12, flexWrap:'wrap', marginTop:12}}>
            <div className="field" style={{flex:'1 1 220px'}}>
              <label>อีเมล · Email</label>
              <input className="input" value={email} onChange={e=>setEmail(e.target.value)} />
            </div>
            {user.role === 'student' && (
              <div className="field" style={{flex:'1 1 220px'}}>
                <label>ห้อง · Class</label>
                <select className="select" value={classId} onChange={e=>setClassId(e.target.value)}>
                  {DATA.classes.map(c=><option key={c.id} value={c.id}>{c.label}</option>)}
                </select>
              </div>
            )}
          </div>
        </section>

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

        {/* credentials — highlight box */}
        <section style={{padding:14, background:'var(--brand-50)', borderRadius:14, border:'1px solid var(--brand-100)'}}>
          <div className="row between" style={{marginBottom:10}}>
            <div>
              <div className="mono" style={{fontSize:11, letterSpacing:'.06em', textTransform:'uppercase', color:'var(--brand-700)', fontWeight:600}}>เปลี่ยน User ID & รหัสผ่าน</div>
              <div className="muted" style={{fontSize:11.5, marginTop:2}}>Change credentials · ใช้ระวัง ผู้ใช้จะต้องเข้าสู่ระบบใหม่ทันที</div>
            </div>
            <button className="btn btn-outline sm" onClick={resetPw}><Icon name="sparkle" size={12} /> สร้างรหัสผ่านชั่วคราว</button>
          </div>
          <div className="field" style={{marginBottom:10}}>
            <label>User ID</label>
            <input className="input" value={userId} onChange={e=>setUserId(e.target.value)} style={{fontFamily:'var(--font-mono)'}} />
          </div>
          <div className="row" style={{gap:12, flexWrap:'wrap'}}>
            <div className="field" style={{flex:'1 1 200px'}}>
              <label>รหัสผ่านใหม่ · New Password</label>
              <input className="input" type="text" placeholder="เว้นว่างไว้หากไม่เปลี่ยน" value={newPw} onChange={e=>setNewPw(e.target.value)} style={{fontFamily:'var(--font-mono)'}} />
            </div>
            <div className="field" style={{flex:'1 1 200px'}}>
              <label>ยืนยัน · Confirm</label>
              <input className="input" type="text" value={confirmPw} onChange={e=>setConfirmPw(e.target.value)} style={{fontFamily:'var(--font-mono)'}} />
            </div>
          </div>
        </section>

        {msg && (
          <div style={{
            fontSize:12.5, padding:'10px 12px', borderRadius:10,
            background: isErr?'oklch(0.96 0.03 25)':isOk?'oklch(0.95 0.05 150)':'var(--warm-100)',
            color: isErr?'var(--red-500)':isOk?'oklch(0.4 0.13 150)':'var(--warm-700)',
          }}>
            <Icon name={isErr?'x':isOk?'check':'sparkle'} size={12} /> {msg.split(':')[1]}
          </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>
  );
};

// --- Admin classes settings ---
const AdminClasses = () => (
  <div className="content">
    <div style={{marginBottom:18}}>
      <div style={{fontSize:20, fontWeight:600}}>ห้องเรียน <span className="tag-en">· classes & subjects</span></div>
      <div className="muted" style={{fontSize:12.5}}>จัดการห้องเรียนและวิชา</div>
    </div>

    <div style={{display:'grid', gridTemplateColumns:'repeat(auto-fill, minmax(260px, 1fr))', gap:16}}>
      {DATA.classes.map(c => {
        const s = DATA.students.filter(x => x.classId === c.id);
        const w = DATA.works.filter(x => x.classId === c.id);
        return (
          <div key={c.id} className="card card-pad">
            <div className="row between" style={{marginBottom:10}}>
              <div>
                <div style={{fontFamily:'var(--font-serif)', fontSize:32, lineHeight:1}}>{c.label}</div>
                <div className="muted mono" style={{fontSize:11, marginTop:4}}>Grade {c.grade} · Room {c.room}</div>
              </div>
              <button className="btn btn-ghost sm"><Icon name="settings" size={14} /></button>
            </div>
            <div className="row" style={{gap:16, marginTop:14}}>
              <div><div className="muted mono" style={{fontSize:10}}>นักเรียน</div><div style={{fontWeight:600, fontSize:16}}>{s.length}</div></div>
              <div><div className="muted mono" style={{fontSize:10}}>ผลงาน</div><div style={{fontWeight:600, fontSize:16}}>{w.length}</div></div>
              <div><div className="muted mono" style={{fontSize:10}}>ครู</div><div style={{fontWeight:600, fontSize:16}}>1</div></div>
            </div>
            <div className="row wrap" style={{gap:4, marginTop:12}}>
              <AvatarStack ids={s.slice(0,5).map(x=>x.id)} max={5} />
            </div>
          </div>
        );
      })}
      <button className="card card-pad" style={{display:'grid', placeItems:'center', minHeight:180, border:'1.5px dashed var(--brand-300)', background:'var(--brand-50)', cursor:'pointer'}}>
        <div style={{textAlign:'center', color:'var(--brand-700)'}}>
          <Icon name="plus" size={28} />
          <div style={{fontWeight:600, marginTop:8}}>เพิ่มห้องใหม่</div>
          <div className="tag-en" style={{fontSize:12}}>Add a class</div>
        </div>
      </button>
    </div>
  </div>
);

Object.assign(window, { AdminHome, AdminUsers, AdminClasses });
