// signup.jsx — Student registration

const { useState: useStateSU } = React;

function SignUpScreen({ onSignUp, onCancel, lang, setLang }) {
  const t = T[lang];
  const L = lang === 'th'
    ? {
        title: 'สร้างบัญชีนักเรียน',
        sub: 'สำหรับนักเรียนใหม่ที่ยังไม่เคยใช้งาน Bodin plus',
        firstName: 'ชื่อ',
        firstNamePh: 'ชื่อจริง',
        lastName: 'นามสกุล',
        lastNamePh: 'นามสกุล',
        studentId: 'รหัสประจำตัวนักเรียน',
        studentIdPh: 'เช่น 26142',
        grade: 'ระดับชั้น',
        gradePh: 'เลือกระดับชั้น',
        room: 'ห้องเรียน',
        roomPh: 'เช่น 1, 2, 3...',
        email: 'อีเมล',
        emailPh: 'name@bodin.ac.th',
        pw: 'รหัสผ่าน',
        pwPh: 'อย่างน้อย 8 ตัวอักษร',
        pwConfirm: 'ยืนยันรหัสผ่าน',
        pwConfirmPh: 'พิมพ์รหัสผ่านอีกครั้ง',
        agree: 'ยอมรับ',
        terms: 'ข้อตกลงและนโยบายความเป็นส่วนตัว',
        signup: 'ลงทะเบียน',
        signingup: 'กำลังลงทะเบียน...',
        haveAccount: 'มีบัญชีอยู่แล้ว?',
        signin: 'เข้าสู่ระบบ',
        forStaff: 'สำหรับครูและบุคลากร',
        forStaffSub: 'บัญชีของครูจะถูกสร้างโดยฝ่ายเทคโนโลยี กรุณาติดต่อ admin@bodin.ac.th',
        back: 'ย้อนกลับ',
        // errors
        pwMismatch: 'รหัสผ่านไม่ตรงกัน',
        pwShort: 'รหัสผ่านต้องมีอย่างน้อย 8 ตัวอักษร',
        needFields: 'กรุณากรอกข้อมูลให้ครบทุกช่อง',
        needAgree: 'กรุณายอมรับข้อตกลงก่อนลงทะเบียน',
        emailInvalid: 'รูปแบบอีเมลไม่ถูกต้อง',
        // password strength
        weak: 'อ่อน', medium: 'ปานกลาง', strong: 'แข็งแรง',
      }
    : {
        title: 'Create student account',
        sub: 'For new students who don\'t yet have a Bodin plus account',
        firstName: 'First name',
        firstNamePh: 'First name',
        lastName: 'Last name',
        lastNamePh: 'Last name',
        studentId: 'Student ID',
        studentIdPh: 'e.g. 26142',
        grade: 'Grade',
        gradePh: 'Select grade',
        room: 'Room',
        roomPh: 'e.g. 1, 2, 3...',
        email: 'Email',
        emailPh: 'name@bodin.ac.th',
        pw: 'Password',
        pwPh: 'At least 8 characters',
        pwConfirm: 'Confirm password',
        pwConfirmPh: 'Re-enter password',
        agree: 'I agree to the',
        terms: 'terms and privacy policy',
        signup: 'Create account',
        signingup: 'Creating account…',
        haveAccount: 'Already have an account?',
        signin: 'Sign in',
        forStaff: 'For teachers & staff',
        forStaffSub: 'Staff accounts are provisioned by IT. Please email admin@bodin.ac.th',
        back: 'Back',
        pwMismatch: 'Passwords don\'t match',
        pwShort: 'Password must be at least 8 characters',
        needFields: 'Please fill in all fields',
        needAgree: 'Please accept the terms',
        emailInvalid: 'Invalid email format',
        weak: 'Weak', medium: 'OK', strong: 'Strong',
      };

  const [f, setF] = useStateSU({
    firstName: '', lastName: '', studentId: '', grade: '', room: '',
    pw: '', pw2: '',
  });
  const [err, setErr] = useStateSU('');
  const [submitting, setSubmitting] = useStateSU(false);
  const [showPw, setShowPw] = useStateSU(false);

  const grades = lang === 'th'
    ? ['ม.1', 'ม.2', 'ม.3', 'ม.4', 'ม.5', 'ม.6']
    : ['M.1', 'M.2', 'M.3', 'M.4', 'M.5', 'M.6'];

  const pwStrength = (() => {
    const p = f.pw;
    if (!p) return 0;
    let s = 0;
    if (p.length >= 8) s++;
    if (/[A-Z]/.test(p) || /[ก-๙]/.test(p)) s++;
    if (/[0-9]/.test(p)) s++;
    if (/[^A-Za-z0-9]/.test(p)) s++;
    return s;
  })();
  const pwLabel = pwStrength <= 1 ? L.weak : pwStrength <= 2 ? L.medium : L.strong;
  const pwColor = pwStrength <= 1 ? 'oklch(0.62 0.22 25)' : pwStrength <= 2 ? 'oklch(0.70 0.16 75)' : 'oklch(0.55 0.16 155)';

  function update(k, v) { setF(prev => ({ ...prev, [k]: v })); setErr(''); }

  function submit(e) {
    e?.preventDefault?.();
    if (!f.firstName || !f.lastName || !f.studentId || !f.grade || !f.room || !f.pw) {
      setErr(L.needFields); return;
    }
    if (f.pw.length < 8) { setErr(L.pwShort); return; }
    if (f.pw !== f.pw2) { setErr(L.pwMismatch); return; }
    setSubmitting(true);
    const meta = { name: `${f.firstName} ${f.lastName}`, role: 'student', grade: `${f.grade}/${f.room}` };
    (SB_CONFIGURED
      ? sbSignUp(f.studentId, f.pw, meta)
          .then(({ user, profile }) => onSignUp({ id: f.studentId, name: meta.name, remember: true, userId: user.id, role: 'student', grade: meta.grade }))
          .catch(e => { setErr(e?.message || (lang === 'th' ? 'ลงทะเบียนไม่สำเร็จ กรุณาลองใหม่' : 'Sign-up failed, please try again')); })
          .finally(() => setSubmitting(false))
      : new Promise(r => setTimeout(r, 800)).then(() => {
          setSubmitting(false);
          onSignUp({ id: f.studentId, name: meta.name, remember: true });
        })
    );
  }

  return (
    <div style={{
      minHeight: '100vh', padding: 24, position:'relative',
      display:'flex', alignItems:'center', justifyContent:'center',
      background: `
        radial-gradient(70% 60% at 90% 10%, oklch(0.72 0.18 305 / 0.40) 0%, transparent 60%),
        radial-gradient(55% 50% at 10% 90%, oklch(0.65 0.20 250 / 0.32) 0%, transparent 60%),
        var(--bp-canvas)
      `,
    }}>
      {/* Lang toggle */}
      <div style={{ position:'absolute', top: 22, right: 22, display:'flex', gap: 6,
        background:'rgba(255,255,255,0.7)', padding: 4, borderRadius: 999,
        border:'1px solid rgba(255,255,255,0.6)', backdropFilter:'blur(20px)',
      }}>
        {['th', 'en'].map(l => (
          <button key={l} onClick={() => setLang(l)} style={{
            appearance:'none', border:0, cursor:'pointer',
            padding:'5px 12px', borderRadius: 999,
            background: lang === l ? 'var(--bp-grad)' : 'transparent',
            color: lang === l ? '#fff' : 'var(--bp-ink-3)',
            fontSize: 11.5, fontWeight: 600,
          }}>{l.toUpperCase()}</button>
        ))}
      </div>

      {/* Back link */}
      <button onClick={onCancel} style={{
        position:'absolute', top: 22, left: 22,
        appearance:'none', border:0, cursor:'pointer',
        background:'rgba(255,255,255,0.7)', backdropFilter:'blur(20px)',
        padding:'7px 14px 7px 10px', borderRadius: 999,
        display:'inline-flex', alignItems:'center', gap: 6,
        color:'var(--bp-ink-2)', fontSize: 12.5, fontWeight: 500,
        border:'1px solid rgba(255,255,255,0.6)',
        boxShadow:'var(--bp-shadow-sm)',
      }}>
        <Icon name="chev_l" size={14}/> {L.back}
      </button>

      <div style={{
        width:'100%', maxWidth: 540,
        background:'rgba(255,255,255,0.94)',
        backdropFilter:'blur(24px) saturate(180%)',
        border:'1px solid rgba(255,255,255,0.8)',
        borderRadius: 28, padding:'32px 32px 26px',
        boxShadow:'0 28px 70px -20px rgba(80,50,180,0.30), 0 0 0 1px rgba(45,30,110,0.04)',
        margin:'48px 0',
      }}>
        <div style={{ display:'flex', alignItems:'center', gap: 12, marginBottom: 18 }}>
          <Logomark size={40}/>
          <div>
            <div style={{ fontSize: 19, fontWeight: 700, letterSpacing:'-0.01em', color:'var(--bp-ink)' }}>{L.title}</div>
            <div style={{ fontSize: 12, color:'var(--bp-ink-3)', marginTop: 2, lineHeight: 1.4 }}>{L.sub}</div>
          </div>
        </div>

        <form onSubmit={submit} style={{ display:'flex', flexDirection:'column', gap: 12 }}>
          <div className="bp-su-row2" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap: 10 }}>
            <SuField label={L.firstName} icon="user">
              <input value={f.firstName} onChange={e => update('firstName', e.target.value)} placeholder={L.firstNamePh} style={authInputStyle}/>
            </SuField>
            <SuField label={L.lastName} icon="user">
              <input value={f.lastName} onChange={e => update('lastName', e.target.value)} placeholder={L.lastNamePh} style={authInputStyle}/>
            </SuField>
          </div>

          <SuField label={L.studentId} icon="user">
            <input value={f.studentId} onChange={e => update('studentId', e.target.value.replace(/\D/g, ''))} placeholder={L.studentIdPh} inputMode="numeric" style={authInputStyle}/>
          </SuField>

          <div className="bp-su-row2" style={{ display:'grid', gridTemplateColumns:'1.4fr 1fr', gap: 10 }}>
            <SuField label={L.grade} icon="layout">
              <select value={f.grade} onChange={e => update('grade', e.target.value)} style={{ ...authInputStyle, padding:'12px 0' }}>
                <option value="" disabled>{L.gradePh}</option>
                {grades.map(g => <option key={g} value={g}>{g}</option>)}
              </select>
            </SuField>
            <SuField label={L.room} icon="list">
              <input value={f.room} onChange={e => update('room', e.target.value.replace(/\D/g, '').slice(0, 2))} placeholder={L.roomPh} style={authInputStyle}/>
            </SuField>
          </div>

          <SuField label={L.pw} icon="cog" trailing={
            <button type="button" onClick={() => setShowPw(s => !s)} style={{
              appearance:'none', border:0, background:'transparent', cursor:'pointer',
              color: showPw ? 'var(--bp-blue)' : 'var(--bp-ink-3)', padding:'0 6px',
              display:'flex', alignItems:'center',
            }}><Icon name="eye" size={15}/></button>
          }>
            <input value={f.pw} onChange={e => update('pw', e.target.value)} placeholder={L.pwPh} type={showPw ? 'text' : 'password'} style={authInputStyle}/>
          </SuField>

          {f.pw && (
            <div style={{ display:'flex', alignItems:'center', gap: 8, marginTop: -4 }}>
              <div style={{ flex: 1, height: 4, borderRadius: 2, background:'var(--bp-soft)', overflow:'hidden' }}>
                <div style={{
                  width: `${(pwStrength / 4) * 100}%`, height:'100%',
                  background: pwColor, transition:'width .2s ease, background .2s ease',
                }}/>
              </div>
              <span style={{ fontSize: 10.5, color: pwColor, fontWeight: 600, minWidth: 56, textAlign:'right' }}>{pwLabel}</span>
            </div>
          )}

          <SuField label={L.pwConfirm} icon="check">
            <input value={f.pw2} onChange={e => update('pw2', e.target.value)} placeholder={L.pwConfirmPh} type={showPw ? 'text' : 'password'} style={authInputStyle}/>
          </SuField>

          {err && (
            <div style={{
              fontSize: 12, color:'oklch(0.45 0.20 25)',
              background:'oklch(0.96 0.05 25)', padding:'8px 12px', borderRadius: 10,
              display:'flex', alignItems:'center', gap: 8,
            }}>
              <Icon name="bolt" size={13}/> {err}
            </div>
          )}

          <button type="submit" disabled={submitting} style={{
            marginTop: 4, appearance:'none', border:0, cursor: submitting ? 'wait' : 'pointer',
            padding:'14px 18px', borderRadius: 14,
            background:'var(--bp-grad)', color:'#fff',
            fontSize: 14, fontWeight: 600,
            boxShadow:'0 10px 24px rgba(80,50,180,0.30)',
            display:'flex', alignItems:'center', justifyContent:'center', gap: 8,
            opacity: submitting ? 0.85 : 1,
          }}>
            {submitting ? <><Spinner/> {L.signingup}</> : <>{L.signup} <Icon name="arrow_r" size={16}/></>}
          </button>
        </form>

        <div style={{
          marginTop: 18, paddingTop: 16, borderTop:'1px solid var(--bp-line)',
          display:'flex', alignItems:'center', justifyContent:'space-between',
          fontSize: 12.5, color:'var(--bp-ink-3)',
        }}>
          <span>{L.haveAccount}</span>
          <button onClick={onCancel} style={{
            appearance:'none', border:0, background:'transparent', cursor:'pointer',
            color:'var(--bp-blue)', fontSize: 12.5, fontWeight: 600,
          }}>{L.signin} ›</button>
        </div>

      </div>
    </div>
  );
}

function SuField({ label, icon, trailing, children }) {
  return (
    <div>
      <div style={{ fontSize: 11.5, fontWeight: 600, color:'var(--bp-ink-2)', marginBottom: 5 }}>{label}</div>
      <div style={{
        display:'flex', alignItems:'center', gap: 10,
        padding:'0 12px', borderRadius: 11,
        border:'1px solid var(--bp-line)', background:'#fff',
      }}>
        <Icon name={icon} size={15} stroke="var(--bp-ink-3)"/>
        <div style={{ flex: 1, display:'flex' }}>{children}</div>
        {trailing}
      </div>
    </div>
  );
}

Object.assign(window, { SignUpScreen });
