// Login / Register page
function LoginPage({ go, onLogin }) {
  const [mode, setMode] = React.useState('login');
  const [stuId, setStuId] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [err, setErr] = React.useState('');

  const [busy, setBusy] = React.useState(false);

  async function submit(e){
    e.preventDefault();
    setErr('');
    if (!stuId || !pw) { setErr('กรุณากรอกข้อมูลให้ครบทุกช่อง'); return; }
    setBusy(true);
    try {
      await window.api.login(stuId.trim(), pw);
      await onLogin();
      go('dashboard');
    } catch (err) {
      if (err.status === 401) {
        setErr(`ไม่สามารถเข้าสู่ระบบด้วยรหัสนักศึกษา ${stuId} ได้ กรุณาตรวจสอบรหัสและรหัสผ่านอีกครั้ง`);
      } else {
        setErr('เกิดข้อผิดพลาดในการเชื่อมต่อระบบ กรุณาลองใหม่');
      }
    } finally {
      setBusy(false);
    }
  }

  async function submitRegister(e){
    e.preventDefault();
    setErr('');
    const form = e.currentTarget;
    const studentId = form.elements['studentId']?.value?.trim();
    const name = [form.elements['firstName']?.value, form.elements['lastName']?.value].filter(Boolean).join(' ').trim();
    const email = form.elements['email']?.value?.trim();
    const password = form.elements['regPassword']?.value || '';
    if (!studentId || !password || password.length < 8) {
      setErr('กรุณากรอกรหัสนักศึกษาและรหัสผ่านอย่างน้อย 8 ตัวอักษร'); return;
    }
    setBusy(true);
    try {
      await window.api.register({ studentId, name, email, password });
      await onLogin();
      go('dashboard');
    } catch (err) {
      if (err.status === 409) setErr('รหัสนักศึกษานี้ถูกใช้แล้ว');
      else setErr('สมัครไม่สำเร็จ กรุณาตรวจสอบข้อมูลอีกครั้ง');
    } finally {
      setBusy(false);
    }
  }

  return (
    <div style={{minHeight:'calc(100vh - 88px)', display:'grid', gridTemplateColumns:'1fr 1fr', alignItems:'stretch'}}>
      {/* Left visual */}
      <div style={{background:'var(--ink)', color:'var(--bg)', padding:'56px 64px', position:'relative', overflow:'hidden'}}>
        <img src="/assets/img/campus-aerial-dawn.jpg" alt="" loading="lazy"
          style={{position:'absolute', inset:0, width:'100%', height:'100%', objectFit:'cover', filter:'brightness(.45) saturate(.7)'}}/>
        <div style={{position:'absolute', inset:0,
          background:'linear-gradient(135deg, rgba(26,37,71,.85) 0%, rgba(26,37,71,.55) 100%)',
          pointerEvents:'none'}}/>
        <div style={{position:'relative', maxWidth:480}}>
          <div className="crest" style={{width:56, height:56, fontSize:28, marginBottom:32}}>ท</div>
          <h1 className="serif" style={{fontSize:'clamp(36px, 4.4vw, 52px)', margin:'0 0 18px', fontWeight:600, lineHeight:1.15, color:'var(--paper)', letterSpacing:'-.005em'}}>
            ระบบการเรียนออนไลน์<br/>
            มหาวิทยาลัยทดสอบ
          </h1>
          <p style={{color:'rgba(245,239,226,.7)', fontSize:16, margin:'0 0 40px', lineHeight:1.7}}>
            เว็บไซต์นี้ใช้ในการทดสอบระบบ · เข้าสู่ระบบด้วยรหัสนักศึกษาหรือบัญชีของท่าน เพื่อเข้าถึงรายวิชา ตารางเรียน ผลการศึกษา และบริการนักศึกษาออนไลน์.
          </p>
          <div className="row" style={{gap:24, marginTop:48, paddingTop:28, borderTop:'1px solid rgba(245,239,226,.16)'}}>
            <div>
              <div className="serif" style={{fontSize:34, fontWeight:600, color:'var(--accent)', lineHeight:1}}>38,402</div>
              <div style={{fontSize:12, color:'rgba(245,239,226,.6)', marginTop:6}}>นักศึกษาในระบบ</div>
            </div>
            <div style={{width:1, alignSelf:'stretch', background:'rgba(245,239,226,.16)'}}/>
            <div>
              <div className="serif" style={{fontSize:34, fontWeight:600, color:'var(--accent)', lineHeight:1}}>1,247</div>
              <div style={{fontSize:12, color:'rgba(245,239,226,.6)', marginTop:6}}>รายวิชาออนไลน์</div>
            </div>
            <div style={{width:1, alignSelf:'stretch', background:'rgba(245,239,226,.16)'}}/>
            <div>
              <div className="serif" style={{fontSize:34, fontWeight:600, color:'var(--accent)', lineHeight:1}}>99.94%</div>
              <div style={{fontSize:12, color:'rgba(245,239,226,.6)', marginTop:6}}>ระบบพร้อมใช้งาน</div>
            </div>
          </div>
        </div>
      </div>

      {/* Right form */}
      <div style={{padding:'56px', display:'flex', alignItems:'center', justifyContent:'center'}}>
        <div style={{maxWidth:440, width:'100%'}}>
          <div className="row" style={{gap:0, marginBottom:28, borderBottom:'1px solid var(--line)'}}>
            <button onClick={()=>{setMode('login'); setErr('');}}
              style={{appearance:'none', border:0, background:'transparent', padding:'14px 0', marginRight:36,
                fontSize:14, color: mode==='login'?'var(--ink)':'var(--ink-3)', cursor:'default',
                borderBottom: '2px solid '+(mode==='login'?'var(--accent)':'transparent'),
                marginBottom:-1, fontWeight: mode==='login'?600:500}}>เข้าสู่ระบบ</button>
            <button onClick={()=>{setMode('register'); setErr('');}}
              style={{appearance:'none', border:0, background:'transparent', padding:'14px 0',
                fontSize:14, color: mode==='register'?'var(--ink)':'var(--ink-3)', cursor:'default',
                borderBottom: '2px solid '+(mode==='register'?'var(--accent)':'transparent'),
                marginBottom:-1, fontWeight: mode==='register'?600:500}}>ลงทะเบียนนักศึกษาใหม่</button>
          </div>

          {mode === 'login' ? (
            <form onSubmit={submit}>
              <h2 className="serif" style={{margin:'0 0 8px', fontSize:28, fontWeight:600}}>ยินดีต้อนรับกลับ</h2>
              <p style={{color:'var(--ink-3)', margin:'0 0 24px', fontSize:14}}>กรอกรหัสนักศึกษาและรหัสผ่านของท่าน</p>

              <div className="field">
                <label>รหัสนักศึกษา / Username</label>
                <input data-test="A07 cred stuff · enumeration"
                  value={stuId} onChange={e=>setStuId(e.target.value)}
                  placeholder="เช่น 64012345" autoComplete="off"/>
              </div>
              <div className="field">
                <label>รหัสผ่าน</label>
                <input data-test="A07 weak pwd · A02 plaintext transit"
                  type="password" value={pw} onChange={e=>setPw(e.target.value)}
                  placeholder="••••••••" autoComplete="off"/>
                <a className="hint" style={{textAlign:'right', cursor:'default', color:'var(--accent-2)', borderBottom:'1px solid transparent'}}>ลืมรหัสผ่าน?</a>
              </div>

              {err && (
                <div className="notice" style={{borderLeftColor:'var(--bad)', marginBottom:16, fontSize:13.5}}
                  dangerouslySetInnerHTML={{__html: escape(err)}}/>
              )}

              <button className="btn" style={{width:'100%', padding:'14px 22px'}} type="submit" disabled={busy}>{busy ? 'กำลังเข้าสู่ระบบ…' : 'เข้าสู่ระบบ'}</button>

              <div className="row" style={{gap:14, margin:'24px 0', color:'var(--ink-3)', fontSize:12}}>
                <div style={{flex:1, height:1, background:'var(--line)'}}/>
                <span>หรือเข้าสู่ระบบด้วย</span>
                <div style={{flex:1, height:1, background:'var(--line)'}}/>
              </div>

              <div className="grid g2" style={{gap:10}}>
                <button type="button" className="btn alt sm" style={{padding:'12px'}}>บัตรประชาชน (ThaID)</button>
                <button type="button" className="btn alt sm" style={{padding:'12px'}}>Microsoft 365</button>
              </div>

              <p style={{fontSize:12, color:'var(--ink-3)', marginTop:24, lineHeight:1.6}}>
                <b>บัญชีทดสอบ:</b> รหัสนักศึกษา <span className="mono">64012345</span> · รหัสผ่าน <span className="mono">demo1234</span>
              </p>
            </form>
          ) : (
            <form onSubmit={submitRegister}>
              <h2 className="serif" style={{margin:'0 0 8px', fontSize:28, fontWeight:600}}>สมัครสมาชิกใหม่</h2>
              <p style={{color:'var(--ink-3)', margin:'0 0 24px', fontSize:14}}>สำหรับผู้เรียนทั่วไปและศิษย์เก่า</p>
              <div className="grid g2">
                <div className="field"><label>ชื่อ</label><input name="firstName"/></div>
                <div className="field"><label>นามสกุล</label><input name="lastName"/></div>
              </div>
              <div className="field"><label>รหัสนักศึกษา</label><input name="studentId" placeholder="เช่น 64012346"/></div>
              <div className="field"><label>อีเมล</label><input name="email" type="email"/></div>
              <div className="field"><label>รหัสผ่าน</label><input name="regPassword" type="password"/><span className="hint">อย่างน้อย 8 ตัวอักษร</span></div>
              {err && (
                <div className="notice" style={{borderLeftColor:'var(--bad)', marginBottom:16, fontSize:13.5}}
                  dangerouslySetInnerHTML={{__html: escape(err)}}/>
              )}
              <label className="row" style={{gap:8, fontSize:13, color:'var(--ink-2)', margin:'6px 0 16px'}}>
                <input type="checkbox" required/>
                ยอมรับข้อกำหนดและนโยบายความเป็นส่วนตัวของมหาวิทยาลัย
              </label>
              <button className="btn" style={{width:'100%', padding:'14px'}} type="submit" disabled={busy}>{busy ? 'กำลังสร้างบัญชี…' : 'สร้างบัญชี'}</button>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}
window.LoginPage = LoginPage;
