/* ============================================================
   LoginView.jsx — เข้าสู่ระบบ (username / password)
   ============================================================ */

function LoginView({onLogin, credentials, approverRoles}){
  const creds = credentials || defaultCredentials();
  const [username, setUsername] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [err, setErr] = React.useState('');
  const [showDemo, setShowDemo] = React.useState(false);
  const [q, setQ] = React.useState('');

  const submit = (e)=>{
    e && e.preventDefault();
    const res = authenticate(creds, username, password);
    if(!res){ setErr('ชื่อผู้ใช้หรือรหัสผ่านไม่ถูกต้อง'); return; }
    onLogin(res);
  };
  const quick = (u,p)=>{ setUsername(u); setPassword(p); setErr(''); const res=authenticate(creds,u,p); if(res) onLogin(res); };

  const list = TEACHERS.filter(t=> !q || t.short.includes(q) || t.name.includes(q) || (creds[t.id]&&creds[t.id].username.includes(q.toLowerCase())) || t.primary.includes(q));

  return (
    <div className="login-wrap">
      <div className="login-aside">
        <div className="login-crest"><img src="logo.png" alt="ตราโรงเรียนหนองตาคงพิทยาคาร"/></div>
        <h1>ระบบจัดการสอนแทน</h1>
        <div className="la-school">โรงเรียนหนองตาคงพิทยาคาร</div>
        <p className="la-desc">ระบบแจ้งลา จัดครูสอนแทน และติดตามการสอนชดเชย เชื่อมต่อการแจ้งเตือนผ่าน LINE — อ้างอิงตารางสอนภาคเรียนที่ 1 ปีการศึกษา 2569</p>
        <div className="la-feats">
          {[['calendar','แจ้งลา & ขอเปลี่ยนคาบสอน'],['users','ระบบแนะนำครูสอนแทนที่ว่าง'],['bell','แจ้งเตือน & กดรับทราบผ่าน LINE'],['clipboard','บันทึกภาระงานสอนของตนเอง']].map(([ic,tx])=>(
            <div key={tx} className="la-feat"><Icon name={ic} size={17}/>{tx}</div>
          ))}
        </div>
      </div>

      <div className="login-main">
        <div className="login-card">
          <h2>เข้าสู่ระบบ</h2>
          <p className="lc-sub">กรุณาเข้าสู่ระบบด้วยบัญชีของท่าน</p>
          <form onSubmit={submit}>
            <div className="field">
              <label>ชื่อผู้ใช้ (Username)</label>
              <input className="inp" value={username} autoComplete="username"
                onChange={e=>{setUsername(e.target.value);setErr('');}} placeholder="เช่น kru01 หรือ admin"/>
            </div>
            <div className="field">
              <label>รหัสผ่าน (Password)</label>
              <input className="inp" type="password" value={password} autoComplete="current-password"
                onChange={e=>{setPassword(e.target.value);setErr('');}} placeholder="••••••"/>
            </div>
            {err && <div className="login-err"><Icon name="xCircle" size={16}/>{err}</div>}
            <Btn variant="primary" block type="submit" iconRight="chevronRight">เข้าสู่ระบบ</Btn>
          </form>

          <button className="demo-toggle" onClick={()=>setShowDemo(v=>!v)}>
            <Icon name="info" size={15}/> บัญชีสำหรับทดลองใช้งาน (เดโม)
            <Icon name={showDemo?'x':'chevronRight'} size={15} style={{marginLeft:'auto'}}/>
          </button>

          {showDemo && (
            <div className="demo-box">
              <div className="demo-hint">ค่าเริ่มต้น: รหัสผ่านครูทุกท่าน <b>1234</b> · ผู้บริหาร/วิชาการ <b>admin / admin1234</b> — คลิกเพื่อเข้าสู่ระบบทันที (เปลี่ยนได้ภายหลัง)</div>
              <button className="demo-row admin" onClick={()=>quick(creds.admin.username,creds.admin.password)}>
                <span className="av av-sm" style={{background:'var(--brand-800)'}}><Icon name="shield" size={16}/></span>
                <div className="nm"><div className="n1">งานวิชาการ / ผู้บริหาร</div><div className="n2 num">{creds.admin.username}</div></div>
                <Icon name="chevronRight" size={15} style={{color:'var(--ink-3)'}}/>
              </button>
              <div className="demo-hint" style={{margin:'2px 0 7px'}}>ผู้บริหาร / สายอนุมัติการลา (เข้าด้วยบัญชีครูของตน):</div>
              {APPROVERS.map(a=>{
                const tid = (approverRoles||{})[a.role];
                const holder = tid ? TEACHERS.find(t=>t.id===tid) : null;
                if(!holder || !creds[holder.id]) return null;
                return (
                  <button key={a.role} className="demo-row admin" style={{marginBottom:6}} onClick={()=>quick(creds[holder.id].username, creds[holder.id].password)}>
                    <Avatar t={holder} size="sm"/>
                    <div className="nm"><div className="n1">{formalName(holder)} <span className="chair-badge"><Icon name="shield" size={11}/>{a.short}</span></div><div className="n2">{a.title}</div></div>
                    <span className="num demo-user">{creds[holder.id].username}</span>
                  </button>
                );
              })}
              <input className="inp demo-search" value={q} onChange={e=>setQ(e.target.value)} placeholder="ค้นหาชื่อครู / กลุ่มสาระ…"/>
              <div className="demo-list">
                {list.map(t=>(
                  <button key={t.id} className="demo-row" onClick={()=>quick(creds[t.id].username,creds[t.id].password)}>
                    <Avatar t={t} size="sm"/>
                    <div className="nm"><div className="n1">{formalName(t)}</div><div className="n2">{t.primary}</div></div>
                    <span className="num demo-user">{creds[t.id].username}</span>
                  </button>
                ))}
              </div>
            </div>
          )}
        </div>
        <div className="login-foot">© 2569 โรงเรียนหนองตาคงพิทยาคาร · ต้นแบบระบบ</div>
      </div>
    </div>
  );
}

window.LoginView = LoginView;
